body: I am in grade 6. I have a very nice pet dog in my house but it often enters Mom's kitchen to spoil all the foods. So I am thinking of a device to attach with him which can locate its position. But I am totally new to arduino programming. I have found some tutorials of arduino UNO to locate position with GPS. But I don't know how to set up the alarm when my dog reaches the position of our kitchen and what will be the code for it. If I wanna set alarm for different position, like kitchen and two toilets, what would be the code then? I know Java a very little bit. C too. Nothing else. Is there any altruist to help me out, please?

title: What would be the code for using Arduino UNO to alert by sound or LED when it detects a certain position through GPS?

Answers: 2

body:
First things first: do you know that a GPS can locate your dog accurately enough in your home?

Basically, even with a good GPS receiver, the best accuracy you can expect (using off-the-shelf receivers, non-military or DGPS) is maybe 3 m. Typical performance is maybe 4 m, and indoors it will be even worse. The point is, your dog could be 5 m away from your intended location, and you will get an alarm. 5 m in a house might be the room over, two rooms over, or outside the house!

However, if you want to go forward with this, get yourself a GPS module, connect it to your Arduino, install the [TinyGPS++](http://arduiniana.org/libraries/tinygpsplus/) library (one of the better Arduino GPS libs IMO), and play with it. It's easy to figure out how to perform an action when the GPS coordinates are in range of a given coordinate set.

You might have better luck using a different form of dog location detection.

body:
A more low-tech solution might be better. For example, a couple of light beams across the doorway to the kitchen. An human would block both of them as they passed, and a dog only the lower one. You could sound an alarm if the lower one is broken, and the upper one is not broken (within a second).

---

Or do something with infra-red transmitters / receivers. There are lots of Arduino projects using those. You could have a transmitter in the kitchen pointing towards the doorway, sending some code (eg. 1234). Mount on the dog an Arduino with an IR decoder sketch. When the dog enters the kitchen it will get the code, and then you could sound a beeper. The beeper alone might make the dog change its mind about going in, especially if you go after it yelling "bad dog!" every time the beeper goes off.

Since the IR beam is just light, it would only go in a straight line, and if properly positioned would flood the kitchen, but not hit anywhere else.

---

## Proof of concept

I made up a test of my idea of the IR transmitter.

*(Please don't report me to the moderators for being off-topic. I know the question was about a GPS, but the **real** question is how to detect that the dog has come into the kitchen).*

You can get IR (infra-red) LEDs cheaply at any electronics supplier (or eBay). They are like normal LEDs except that they transmit in the IR light range. They can also usually handle higher currents, like 80 mA.

---

## Sender

So, to drive that from the Arduino we need a transistor to boost the output from the Arduino pin, like this:

[![IR driver][1]][1]

Note that the positive pin of the LED will have a longer lead. The positive pin goes to the 39 ohm resistor, and the negative (shorter) lead goes to the transistor collector. In the schematic the negative pin (cathode) is at the bottom and has a horizontal line (think of the horizontal line as a minus sign).

The 39 ohm resistor limits current through the LED to 74 mA. Assuming a LED forward voltage of 2.1V we have:

     (5V - 2.1V) / 39Ω = 74 mA

The 470 ohm resistor limits current through the transistor base.

---

## Sender code

Then some simple code to send a IR code (using PWM modulation like TV remotes do). There is a library for that, so the code is very simple:

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

    #include <IRLib.h>

    IRsend My_Sender;

    const unsigned long DOG_ALERT_CODE = 0xBADA;

    void setup()
      {
      }

    void loop()
      {
      My_Sender.send (NEC, DOG_ALERT_CODE, 20);
      delay (1000);
      }

That sends the code 0xBADA (which I just picked at random) every second using the NEC IR protocol.

The objective would be to have this plugged into the power somewhere in the kitchen, and aimed at the doorway. The IR library uses digital pin 3 (on the Uno at least). That happens to be the Timer 2 "B" output to send 38 kHz PWM (pulse-width-modulated) signal, which it interrupts from time to time to encode the code into it.

---

## Receiver

Now we need something on the dog to detect the IR code. The objective is to notice the code above (eg. 0xBADA) and if found, sound a tone on a speaker, otherwise ignore it. That way we can still use remotes in the kitchen, and the speaker won't sound.

[![IR Receiver][2]][2]

The code for the receiver is a bit more complex, but not much:

    #include <IRLib.h>
    #include <TonePlayer.h>

    const byte SPEAKER = 9;  // output pin is fixed (OC1A)
    const byte IR_READER = 11;
    const unsigned long BEEP_WIDTH = 50;
    const int BEEP_FREQUENCY = 880;  // Hz
    const unsigned long DOG_ALERT_CODE = 0xBADA;

    // pin D9 (Uno), D11 (Mega)
    TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);

    IRrecv My_Receiver(IR_READER);
    IRdecode My_Decoder;

    void setup()
      {
      My_Receiver.enableIRIn(); // Start the receiver
      pinMode (SPEAKER, OUTPUT);
      }

    unsigned long lastTone;

    void loop()
      {
      if (My_Receiver.GetResults(&My_Decoder))
        {
        My_Decoder.decode();
        if (My_Decoder.decode_type == NEC)
          {
          if (My_Decoder.value == DOG_ALERT_CODE)
            {
            tone1.tone (BEEP_FREQUENCY);
            lastTone = millis ();
            }  // end of wanted code
          }  // end of NEC type
          My_Receiver.resume();
        }  // end of if we got a result

        // if time up, stop the beep
        if (millis () - lastTone >= BEEP_WIDTH)
          tone1.noTone ();

      } // end of loop

This also uses the IR library, this time to detect an incoming code. You wire the "Data" pin of the IR detector to digital pin 11 on the Arduino (Uno or similar). The other two pins of the IR detector go to Ground and +5V as marked.

To play a sound get a small piezo speaker and wire that to digital pin 9 (one side) and Ground (other side).

Because of the way that the IR library uses interrupts, I had to use my own Tone library to generate a tone. You can download that from:

  <http://www.gammon.com.au/Arduino/TonePlayer.zip>

---

## Testing

How well did it work? Certainly at short distances (like three feet or one metre) we got a positive result. There could be variance based on the light conditions in the room, and the exact parts you get.

You might want to read the [design notes for TV B Gone](https://learn.adafruit.com/tv-b-gone-kit/design-notes) where they discuss the technicalities of sending IR beams. In particular for their design they used **four** IR LEDs to give adequate range. You could add more LEDs by duplicating the transistor driver shown above a few times. In other words, duplicate the transistors, LEDs and resistors. They could all be driven from the same output pin.

As mentioned in the TV B Gone article, you can get different IR LEDs. Some have a narrow beam, but go further, others have a wider beam, but go less far.

Also you could arrange them to point in slightly different directions to cover more of the room.

You could also change the length of the beep when the code is detected (BEEP_WIDTH) in milliseconds. And also the frequency (BEEP_FREQUENCY) which I had at 880 Hz. A higher frequency might annoy the dog more but be less audible to humans. I suppose it depends if you want the dog to hear it or the people in the house.

---

## Hardware size and power

You probably want a small Arduino (like a Nano) which is physically quite small. Also powering it could be an issue. You could get 3 x AA batteries, which would nominally output around 4.5V, and connect them directly to the +5V pin of the Arduino.

To save battery power you could have the Arduino sleep for (say) a second, wake and eheck for a code, and then sleep again. See [my post about power savings](htp://www.gammon.com.au/power) for more details about that sort of thing.

---

## Hardware photos

[![IR Transmitter and receiver][3]][3]

[![Piezo speaker][4]][4]

  [1]: https://i.stack.imgur.com/ZF3ps.png
  [2]: https://i.stack.imgur.com/6WURi.png
  [3]: https://i.stack.imgur.com/CSEqi.jpg
  [4]: https://i.stack.imgur.com/slBY3.jpg


body:
Ive recently bought my self a arduino Mega 2560 and managed to get a sort of RANDOM function to work with different cases which go of by the number selected.
My question is is there a way to also make a PWM sequence in such a case? so that the LED is fully light to dark and then the the next case starts?  IS there a more random sequence wich i could then also expand if neccesary?

Mark.

    int ledcolor = 0;
     int a = 500; //this sets how long the stays one color for
    int b = 2000;
    int brightness = 255;    // how bright the LED is
    int fadeAmount = 25;    // how many points to fade the LED by

     void setup() { //this sets the output pins

     pinMode(11, OUTPUT);
     pinMode(10, OUTPUT);
     pinMode(9, OUTPUT);
     pinMode(8, OUTPUT);
     }

     void loop() {
     int ledcolor = random(1,16); //this randomly selects a number between 1 and 15

     switch (ledcolor) {

     case 1: //if ledcolor equals 1 then the led on pin 11 will turn on etc.
     analogWrite(11, brightness);
     brightness = brightness - fadeAmount;     break;
     case 2:
     digitalWrite(10, HIGH);
     delay(a);
     digitalWrite(10, LOW);
     break;
     case 3:
     digitalWrite(9, HIGH);
     delay(a);
     digitalWrite(9, LOW);
     break;

title: how to implement PWM LED fading into a random case switch?

Answers: 2

body:
In order to fade in and fade out LEDs you need to use [PWM][1] feature. And, specifically you need to use the [analogWrite()][2] function call. Also, you need to make sure all your LEDs are connected to PWM port pins.  Port pins which support the PWM feature for various Arduinos are listed in the above link.

In your code you might try replacing your 500ms delay with a count up followed by a count down loop.  Each loop should contain the appropriate delay and count up or down to the appropriate value.

For instance, you might try a 1ms delay and a count from 0 to 255 followed by a count from 255 to 0.  In both loops just before or just after calling the delay() function, place the call to the analogWrite() function and pass the counter value as the PWM duty cycle (LED brightness setting).

added later...

For example, you might try to see if this code works for the 1st case statement:

    int brightness_level;

    case 1: //if ledcolor equals 1 then the led on pin 11 will turn on etc.
      for(brightness_level = 0 ; brightness_level < 255 ; brightness_level++)
      {
        analogWrite(11, brightness_level);
        delay(1);
      }
      for(brightness_level = 255 ; brightness_level >= 0 ; brightness_level--)
      {
        analogWrite(11, brightness_level);
        delay(1);
      }
    break;

  [1]: https://www.arduino.cc/en/Tutorial/PWM
  [2]: https://www.arduino.cc/en/Reference/AnalogWrite

body:
To make a completely "non blocking" system you need to change your thinking somewhat. Instead of thinking "A need to fade from X to Y" you instead need to start thinking "I am at brightness X at the moment. I want to get to brightness Y. What do I need to do to get there?".

For instance, you might have a `loop()` than contains a structure like:

* My target brightness is Y
* My current brightness is X
* Is X equal to Y?
  * Yes:
     * Select a different target brightness to get to
  * No:
     * If my current brightness is below my target brightness then make it brighter.
     * Otherwise make it dimmer.

You can introduce a small delay to slow the fading down, or use `millis()` to only run that structure at pre-defined intervals (like BlinkWithoutDelay does) to get your desired fade speed.


body:
my group is doing a project which call automatic bed maker. we want to use a servomotor to pull the sheet of the bed. can we possibly make the servomotor stop rotate when the speed of rotation decrease? or is there any way to make the servo motor automatically stop beside using timer.
sorry for broken english.

title: is it possible to code microservo automatically stop when the speed of rotation getting slower?

Answers: 0


body:
Hardware newbie here and I need to know how to connect my TSL 1401 line scan camera to an Arduino Mega so that I can send it the needed impulses. The Mega has a hundred different sockets and the Schema just scared me when I looked at it.

I just want to know which socket I can connect to the CLK and SI ports of my camera so that I can get and an analog output of pixels.

title: How would you send clock impulses to a camera with an Arduino Mega?

Answers: 1

body:
It depends on the camera that you're using but you send in impulse just sending digital write signal, waiting a little bit and then turning it off. You do this over and over again until you have all the pixels. Here is an example where I send 128 impulses:

      for(int i = 0; i < 128; i++)
      {
        digitalWrite(CLK, HIGH);
        delay(1);
        digitalWrite(CLK, LOW);
        delay(1);
      }
Depending on the hardware you are using you might have to send a SI (signal impulse) prior to the CLK impulses and the delay in between them will vary. The best thing to do is to read the documentation to find these figures.


body:
I have an ATtiny hooked up to two line scan modules. I'm sending digital signals to the line scan modules then receiving the analog output and storing it in an array. I have an if statement that will make the LED on the ATtiny programmer blink when the number are below a certain range (meaning that lens is covered).

Here is my code:

    #include <SoftwareSerial.h>
    const int rx=0;
    const int tx=1;

    SoftwareSerial mySerial(rx,tx);
    int CLK = 2;
    int SI = 1;
    int Aout = A3;
    int Aout1 = A2;

    int LED = 0;

    int pixelsArray[128];   //Array to hold the values of the individual pixles.
    int pixelsArray1[128];

     void outputPixels()
    {
      for(int j = 0; j < 128; j++)
      {
        digitalWrite(LED, LOW);

        if(pixelsArray[j] < 100)
        {
          digitalWrite(LED, HIGH);
          delay(500);
          digitalWrite(LED, LOW);
          delay(500);
        }
      }
    }

The problem that I am having is that when I test my code with one line scan module it works just fine. You will notice that in the `readPixels()` I have the statement `pixelsArray1[i]=analogRead(Aout1);` commented out. However, when I try to use it with two the LED start blinking regardless of how much light is hitting the line scanner.

The strange thing is that EVEN when I comment out the `digitalWrite(LED, HIGH);` statement in the `outputPixels()` method...THE LED STILL BLINKS!!!

Since the ATtiny does not support URT and can't use the console in Arduino I have no idea how to debug this. Does anyone here have any clue what is wrong?

Here is the datasheets

ATtiny: http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf

ATtiny Programmer: https://learn.sparkfun.com/tutorials/tiny-avr-programmer-hookup-guide/?_ga=1.59946280.467360091.1464906372

title: Debugging with an ATtiny?

Answers: 2

body:
According to the Specs of the Attiny, this microcontroller only has 128 bytes of memory (RAM).

In the code you declare two arrays:

    int pixelsArray[128];   //Array to hold the values of the individual pixles.
    int pixelsArray1[128];

which will occuppy much more memory than the available on this microcontroller.
Try to reduce the size of the array. Each int entry occupies 2 bytes according to the [link][1].

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

body:
Since you do not have enough RAM for your arrays, something has to
give. A few options:

1. Do you really need the 10-bit precision of the ADC? If you can live
   with 8 bits, then use 8-bit arrays (type `uint8_t`) and store only
   the 8 most significant bits of each reading
   (`pixelsArray[i]=analogRead(Aout)>>2`). This will make the arrays
   half as big.
2. If you really need 10-bit precision, maybe you do not need 128-pixel
   resolution? Then you could store only every other pixel. This will
   also halve the array sizes.
3. If you do need both the full precision and the full resolution, then
   you will have to pack the bits tight. You can pack up to 4 readings
   in 5 bytes. But this will increase the complexity of your program.

**Addendum**: To declare the arrays as being made of 8-bit integers,
just replace

    int pixelsArray[128];
    int pixelsArray1[128];

by

    uint8_t pixelsArray[128];
    uint8_t pixelsArray1[128];

Here “uint8\_t” means “unsigned 8-bit integer”, whereas “int” is a
regular integer, i.e. signed and, on the AVRs, 16-bits long.


body: I want to control 2 dc motors using the arduino board directly. One motor must rotate clockwise and the other counter clockwise. The directions  doesn't change only the speed of each motors. Can this be done without any shield? Them motors may need a higher voltage than the arduino can provide. If I link the arduino board to a power source of about 15 V (the board is arduino mega limits between 6 and 20 ) and I use "analog.write()" function can I output more than 5 volts(the internal voltage)?

title: Motor control using arduino board

Answers: 1

body:
Simplest way to do this is two MOSFETs (one per motor, because you don't need to change direction), and some miscellaneous passives, and a flyback diode for each motor.

See [this tutorial](http://bildr.org/2012/03/rfp30n06le-arduino/) for wiring diagrams and details.


body:
First of all, let me be clear: I'm a total noob, I have close to zero programming experience and I know i'm out of my league, but I want to learn and understand.
Here's the issue. The following code has been made to control heat pads using 4 relays that turn off/on depending on the temperature that 4 lm35 Temp sensors pick up. Because these sensors can be jumpy sometimes, I want to get the average temperature from, let's say, 50 readings, and make the code check THAT data instead of the raw temp reading.
I have the code for the arduino (I wrote some code and guys over other forums took it and modified it to make it shorter (and that kind of lost me, but the code works)
and then I searched smoothing data and got a piece of code that does exactly what I want: make an array, calculate the average temp, and keep deleting and adding new data.

I tried to join both codes together and I got all different kind of errors, lol
So here I am.

**The Code that works without average data is this one:**

    const byte tempPin[] = {A1, A2, A3, A4};
    const byte relayPin[] = {6, 7, 8, 9};

    // hysteresis = upperLimit - lowerLimit
    const byte lowerLimit = 24;
    const byte upperLimit = 31;

    float tempC[4];
    word reading[4];

    word printInterval = 1000; // 1 second
    unsigned long printCheck = 0, lastPrintTime = 0;

    void setup()
    {
      analogReference(INTERNAL);
      Serial.begin(115200);
      for (int i = 0; i < 4; i++) {
        pinMode(relayPin[i], INPUT_PULLUP);
        pinMode(relayPin[i], OUTPUT); // defaults HIGH, relay OFF
      }
    }

    void loop()
    {
      // readings and control
      for (int i = 0; i < 4; i++) {
        reading[i] = analogRead(tempPin[i]);
        tempC[i] = reading[i] / 9.31;

        if (tempC[i] < lowerLimit) {
          digitalWrite(relayPin[i], LOW);   //relay OFF
        }
        else if (tempC[i] > upperLimit) {
          digitalWrite(relayPin[i], HIGH);  // relay ON
        }
      }
      printCheck = millis() - lastPrintTime;
      if (printCheck >= printInterval) {
        for (int i = 0; i < 4; i++) {
          Serial.print("tempC");
          Serial.print(i + 1);
          Serial.print(" ");
          Serial.println(tempC[i]);
        }
        Serial.println();
        lastPrintTime = millis(); // reset print timer
      }
    }

**The average code I got from Arduino Learning center is this one:**

    /*

      Smoothing

      Reads repeatedly from an analog input, calculating a running average
      and printing it to the computer.  Keeps ten readings in an array and
      continually averages them.

      The circuit:
        * Analog sensor (potentiometer will do) attached to analog input 0

      Created 22 April 2007
      By David A. Mellis  <dam@mellis.org>
      modified 9 Apr 2012
      by Tom Igoe
      http://www.arduino.cc/en/Tutorial/Smoothing

      This example code is in the public domain.

    */

    // Define the number of samples to keep track of.  The higher the number,
    // the more the readings will be smoothed, but the slower the output will
    // respond to the input.  Using a constant rather than a normal variable lets
    // use this value to determine the size of the readings array.
    const int numReadings = 10;

    int readings[numReadings];      // the readings from the analog input
    int readIndex = 0;              // the index of the current reading
    int total = 0;                  // the running total
    int average = 0;                // the average

    int inputPin = A0;

    void setup() {
      // initialize serial communication with computer:
      Serial.begin(9600);
      // initialize all the readings to 0:
      for (int thisReading = 0; thisReading < numReadings; thisReading++) {
        readings[thisReading] = 0;
      }
    }

    void loop() {
      // subtract the last reading:
      total = total - readings[readIndex];
      // read from the sensor:
      readings[readIndex] = analogRead(inputPin);
      // add the reading to the total:
      total = total + readings[readIndex];
      // advance to the next position in the array:
      readIndex = readIndex + 1;

      // if we're at the end of the array...
      if (readIndex >= numReadings) {
        // ...wrap around to the beginning:
        readIndex = 0;
      }

      // calculate the average:
      average = total / numReadings;
      // send it to the computer as ASCII digits
      Serial.println(average);
      delay(1);        // delay in between reads for stability
    }

**The monster I created joining both codes is this one:**

    const byte tempPin[] = {A1, A2, A3, A4};
    const byte relayPin[] = {6, 7, 8, 9};

    // hysteresis = upperLimit - lowerLimit
    const byte lowerLimit = 24;
    const byte upperLimit = 31;

    float tempC[4];
    word reading[4];

    const int numReadings = 50;
    int readings[numReadings];
    int readIndex = 0;
    int total = 0;
    float average[4];

    word printInterval = 1000; // 1 second
    unsigned long printCheck = 0, lastPrintTime = 0;

    void setup()
    {
      analogReference(INTERNAL);
      Serial.begin(115200);
      for (int i = 0; i < 4; i++) {
        pinMode(relayPin[i], INPUT_PULLUP);
        pinMode(relayPin[i], OUTPUT); // defaults HIGH, relay OFF
      }
      for (int thisReading = 0; thisReading < numReadings; thisReading++){
        readings[thisReading] = 0;
      }
    }

    void loop()
    {
      // readings and control
      for (int i = 0; i < 4; i++) {
        reading[i] = analogRead(tempPin[i]);
        tempC[i] = reading[i] / 9.31;
        total[i] = total[i] - readings[readIndex];
        readings[readIndex] = tempC[i]
        total[i] = total[i] + readings[readIndex]
        readIndex[i] = readIndex[i] + 1 ;
        if (readIntex[i] >= numReadings) {
          readIndex = 0;
        }
        average[i] = total[i] / numReadings;

        if (average[i] < lowerLimit) {
          digitalWrite(relayPin[i], LOW);   //relay OFF
        }
        else if (average[i] > upperLimit) {
          digitalWrite(relayPin[i], HIGH);  // relay ON
        }
      }
      printCheck = millis() - lastPrintTime;
      if (printCheck >= printInterval) {
        for (int i = 0; i < 4; i++) {
          Serial.print("tempC");
          Serial.print(i + 1);
          Serial.print(" ");
          Serial.println(tempC[i]);
        }
        Serial.println();
        lastPrintTime = millis(); // reset print timer
      }
    }

**These are the errors that I got:**

    Arduino: 1.6.8 (Windows 7), Board: "Arduino/Genuino Uno"

    \temprelayfinal2.ino: In function 'void loop()':

    temprelayfinal2:40: error: invalid types 'int[int]' for array subscript

         total[i] = total[i] - readings[readIndex];

                ^

    temprelayfinal2:40: error: invalid types 'int[int]' for array subscript

         total[i] = total[i] - readings[readIndex];

                           ^

    temprelayfinal2:42: error: expected ';' before 'total'

         total[i] = total[i] + readings[readIndex]

         ^

    temprelayfinal2:44: error: 'readIntex' was not declared in this scope

         if (readIntex[i] >= numReadings) {

             ^

    temprelayfinal2:47: error: invalid types 'int[int]' for array subscript

         average[i] = total[i] / numReadings;

                             ^

    exit status 1
    invalid types 'int[int]' for array subscript

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

title: Help with getting Sensor Average using Arrays

Answers: 2

body:
    total[i] = total[i] - readings[readIndex];

`total` is of type `int`. That is, it is a scalar integer. You cannot index into it, `total[i]` doesn't make sense. That is why the compiler is complaining.

body:
Using the exponential moving average filter suggested by Gerben, things
become quite simpler:

    const byte tempPin[] = {A1, A2, A3, A4};
    const byte relayPin[] = {6, 7, 8, 9};

    // hysteresis = upperLimit - lowerLimit
    const byte lowerLimit = 24;
    const byte upperLimit = 31;

    const int numReadings = 64;
    const word printInterval = 1000; // 1 second

    float tempC[4];
    unsigned long lastPrintTime = 0;

    void setup()
    {
      analogReference(INTERNAL);
      Serial.begin(115200);
      for (int i = 0; i < 4; i++) {
        digitalWrite(relayPin[i], HIGH);
        pinMode(relayPin[i], OUTPUT);
      }
    }

    void loop()
    {
      // readings and control
      for (int i = 0; i < 4; i++) {
        float raw_temp = analogRead(tempPin[i]) / 9.31;
        tempC[i] += (raw_temp - tempC[i]) / numReadings;  // filter
        if (tempC[i] < lowerLimit) {
          digitalWrite(relayPin[i], LOW);   //relay OFF
        }
        else if (tempC[i] > upperLimit) {
          digitalWrite(relayPin[i], HIGH);  // relay ON
        }
      }
      if (millis() - lastPrintTime >= printInterval) {
        for (int i = 0; i < 4; i++) {
          Serial.print("tempC");
          Serial.print(i + 1);
          Serial.print(" ");
          Serial.println(tempC[i]);
        }
        Serial.println();
        lastPrintTime = millis(); // reset print timer
      }
    }


body:
guys.

I'm writing here because I cannot find an obvious error, so I'm stuck. Could you please help me?

Here's the code:

    int arrayAAA[] = {6, 8, 10, 12};
    int arrayBBB[] = {9, 15, 27, 41};

    const int arrayAAALength = sizeof(arrayAAA)/sizeof(int);
    const int arrayBBBLength = sizeof(arrayBBB)/sizeof(int);

    int newArrayLength = 0;

    void setup() {

        Serial.begin(9600);

    }

    void loop() {

      String dir = "AAA";

      if (dir == "AAA"){

          //Copy existing array to the new one...
          newArrayLength = arrayAAALength;              //Get the size of source array
          int newArray[newArrayLength];                 //Make the new array of the same size
          memcpy(newArray, arrayAAA, sizeof(arrayAAA)); //Copy content of the source array to the new one

          /*
          for (int i = 0; i < newArrayLength; i++){
              Serial.print(newArray[i]); //Here everything works just fine...
              Serial.print("   ");
          }
           */
      }

      for (int i = 0; i < newArrayLength; i++){
          Serial.print(newArray[i]); //But here I see this error: 'newArray' was not declared in this scope
          Serial.print("   ");
      }

      Serial.println();
      Serial.println();

    }

What I'm trying to do is to copy the array to a new one, but depending on the circumstances I need to take different source arrays (AAA or BBB).

The problem is in checking the values of an newly crreated array:

    'newArray' was not declared in this scope

if I try to check its valus outside of if statment.

It seems my stupid mistake, but I can't find it.

title: Variable scope error

Answers: 3

body:
The clue is in the indenting:

      if (dir == "AAA"){

          //Copy existing array to the new one...
          newArrayLength = arrayAAALength;              //Get the size of source array
          int newArray[newArrayLength];                 //Make the new array of the same size <<<==== DEFINED IN THE SCOPE OF "IF"
          memcpy(newArray, arrayAAA, sizeof(arrayAAA)); //Copy content of the source array to the new one

          /*
          for (int i = 0; i < newArrayLength; i++){
              Serial.print(newArray[i]); //Here everything works just fine...
              Serial.print("   ");
          }
           */
      }

      for (int i = 0; i < newArrayLength; i++){
          Serial.print(newArray[i]); //But here I see this error: 'newArray' was not declared in this scope <<=== USED IN THE SCOPE OF "FOR"
          Serial.print("   ");
      }

As you can see by the indenting the definition of `newArray` is in a different block of code which you come right out of before you use it.

You must define `newArray` at a scope that is *outside* where you use it.

From that code you don't actually need to copy the contents of one array into another - you can just *point* to the array you want to use with a pointer.  Alternatively, if you do need to clone the array contents (for some other purpose we don't know of) then you should pre-create an array that is big enough to hold *either* of your other arrays.

    int newArray[max(arrayAAALength, arrayBBBLength)];

body:
*Made corrections per @Majenko's comment*

The following will **not** work on real Arduinos, but it did work for me on the ESP8266 and the Teensy3, which are what I use mostly, and the only ones I tested the code for: https://github.com/jayeye/jardino/tree/master/esp8266/ase25017

    #include <vector>
      ...
      size_t vector_size = 42;
      std::vector<int> foo(vector_size);  // foo is a vector of 42 integers

**Another correction:** Exceptions do not work even on the aforementioned platforms, so do not access the vector with `.at(n)`

If you *must* have an array, use a unique_ptr with an array allocator:

    #include <memory>
      ...
      size_t vector_size = 42;
      std::unique_ptr<int[]> arr(new int[vector_size]);

When `arr` goes out of scope, the array will be automatically freed.

You can always use malloc(), but you'll have to remember to free() it, and that's always a source of bugs.

body:
After a careful study of C/C++ documentation, I finally managed to use pointers in Arduino :)

So, the final code became like this:

    int arrayAAA[] = {6, 8, 10, 12};
    int arrayBBB[] = {9, 15, 27, 41};

    //Create a pointer, which will point to any of your arrays of your choice
    int *newArray;

    const int arrayAAALength = sizeof(arrayAAA)/sizeof(int);
    const int arrayBBBLength = sizeof(arrayBBB)/sizeof(int);

    void setup() {

        Serial.begin(9600);

        //Uses the address of arrayAAA (i.e. inherits the content of arrayAAA).
        //&: points to address of a chosen array.
        //[0]: is a must to grab all values!
        newArray = &arrayAAA[0];

        Serial.print("arrayAAA:");
        for (int i = 0; i < arrayAAALength; i++){
            Serial.print("   ");
            Serial.print(arrayAAA[i]);
        }
        Serial.println();

        Serial.print("newArray:");
        for (int i = 0; i < arrayAAALength; i++){
            Serial.print("   ");
            Serial.print(newArray[i]);
        }
        Serial.println();
    }

    void loop(){
        //Left empty
    }

And it works perfectly, just what I expected!


body:
My final project goal is to make Brushless gimbal for drones using only Arduino MEGA 2560 and 9DOF IMU for control. On Instructables I found two excellent tutorials. Both are different than mine in selected components.

I use the following components:

Arduino MEGA2560

Motors - Quanum 2208 Precision Brushless Gimbal Motor ( httpx://goo.gl/RDBvJL)

Motor Driver - H bridge L298n (httpx://goo.gl/A4ZQi5)

9DOF Razor IMU (httpx://goo.gl/myg9oj )

I'm stuck with 9DOF Razor IMU. Surfing on the internet I found a great tutorial and  github repository (httpx://goo.gl/jh2pfU). This tutorial is excellent and AHRS works great with the FTDI Basic Breakout 3.3V. They gave me a good starting point, but my goal is use only Arduino MEGA2560 and sensors.

I want to connect the Arduino and 9DOF IMU directly and use the accelerometer data (Yaw, Pitch, Roll) for directly control the engines. On the website of the manufacturer Sparkfun (httpx://goo.gl/myg9oj ) I can’t find any datasheet exclusively for 9DOF IMU that could help me to connect Arduino and IMU. There are only datasheet of sensors that are on IMU ( ITG-3200 (MEMS triple-axis gyro), ADXL345 (triple-axis accelerometer), and HMC5883L (triple-axis magnetometer)  which are useless for me.

That's why I decided to use code from this site ( httpx://goo.gl/zOnYjN ) and he works great. I connected everything as is in tutorial and  Arduino SerialMonitor show me the desired values YPR. Values load very quickly directly from IMU and printed on SerialMonitor.

Values on SerialMonitor looks like this:

# YPR=72.13,1.74,-16.38
# YPR=72.14,1.72,-16.39
# YPR=72.12,1.71,-16.39
# YPR=72.13,1.71,-16.37
# YPR=72.13,1.70,-16.40 …

**HELP ME**

This is my first solo Arduino project and I have a lot of questions about it.
How could I parse the data that appears on SerialMonitor to get new variables eg. Yaw = 72.12, Pitch = 1.74, Roll = -16.39?

Is it possible to do that?

Does anyone have any experience with 9DOF razor IMU and maybe know  better way to collect information from the accelerometer 9DOF razor IMU?

I want to achieve three separate variables which i will use to control the brushless motor. I think this should be an easier method as it is just comma separated numbers but then again i am new to arduino serial communication so i would appreciate any help with this. Even if it's only how to parse and extract the values.

title: How to get data from 9DOF razor IMU directly to arduino mega

Answers: 1

body:
<!-- language-all: c -->

[sscanf](http://www.cplusplus.com/reference/cstdio/scanf/) should be enough. There is also other options, String class for example with substring method.

Take a look at the example:

    #include <stdio.h>

    char myString[] = "#YPR=72.13,1.74,-16.38";

    void setup() {
      // put your setup code here, to run once:
      float yaw = 0;
      float pitch = 0;
      float roll = 0;

      sscanf(myString, "#YPR=%f,%f,%f", &yaw, &pitch, &roll);
      Serial.println(yaw);
      Serial.println(pitch);
      Serial.println(roll);
    }

    void loop() {

    }


body:
Looking at [the Sparkfun comparison][1], it seems that the Due is by far the fastest of the Arduinos and has I/O capabilities similar to the Mega. So why was it retired with no obvious successor?

  [1]: https://learn.sparkfun.com/tutorials/arduino-comparison-guide "Sparkfun comparsion"

title: Why was the Due retired?

Answers: 2

body:
Because, basically (in my opinion, anyway) it was rubbish.

Yes, it has grunt. Yes, it has IO, but the chips themselves are pretty rancid.

There are far better options than the SAM3X from other manufacturers.

Also, since all the in-fighting began between the two Arduino factions (.org / .cc) the majority of actual progress and innovation has been by third parties (Intel mostly).

body:
"Why was the Due retired?" - It is quite interesting that Arduino.CC never explained that. One would think, that a professional company or organisation places a notice in advance with at least a short explanation as to why.

Most of the Arduinos, that have been available on both projects (CC and ORG) have suddenly and without further notice or explanation been retired on CC (the exceptions being Uno and Mega 2560, the cash-cows), but are still alive on ORG.
It would seem, that either the "divorce" is proceeding or that the copyright case at the US court is not going as smoothly as Banzi hoped. Well, he could repeatedly "bend the truth" by claiming Arduino being completely his idea and design in front of the press (that never bothered to check the obvious facts), but laying such a claim at court is borderline criminal. (see also: arduinohistory.github.io and make your own opinion)
CC has still the biggest chunk of the overall community and also serves as the central nexus for developers. But it seems there is a lot of movement... some people move to Wiring (from which the Arduino IDE was forked), others to 3rd Party sites and yet others try out different  and newly emerging products (eg. Adafruits MCUs and Pi or the Renesas GR series).
ORG on the other hand seems to become the bigger (Arduino branded) hardware supplier and developer. CC has apparently out-sourced this to Intel and tries to live of royalties and "certification" fees (which is the central point where Banzi and Martino started to heavily and openly disagree).

"Why was the Due retired?" - Unless CC doesn't give an explanation, there is no real answer. A lack of interest is certainly not the reason.


body:
I have simple code working on Serial Communication asn below. With Same data i would impliment Modbus protocol> I have Used Modbus library for arduino earlier which works fine with 9600 baudrate and wont work with higher baudrates.And also have restriction In library ,They directly storing values into Buffers SO i cant able to fig out weather request send proper or improper.
I never Worked on EMbeded c Chip level code.Is there any way to Implement without library for arduino

In below code I would Like Serial value into register and when function called i could read value. Similarly the **function CODE** for Modbus should be implemented.

I am looking for simple c code or implement c code Where i can perform the operation this way.

I am trying to Send modbus Request <DeviceID><Modbus function COde><length of request><CRC check>

I found CRC error calculation like in one of forum

     unsigned int crc_fn(unsigned char *dpacket,unsigned int len)  // CRC 16 Function(Error calculation)
        {
         unsigned int crc = 0xffff,poly = 0xa001;
         unsigned char i=0,j=0;

         for(i=0;i<len;i++)
         {
          crc^= dpacket[i];
          for(j=0;j<8;j++)
          {
           if(crc & 0x01)
           {
            crc >>= 1;
            crc ^= poly;
           }
           else
           crc >>= 1;
          }
         }
         return (crc);
        }

**I would like to See my code in arduino Like this With CRC check**

    void Serial_access(void)
    {
     unsigned char i=0,len=0,ser_data[60],crc_data[60],j=0;
     unsigned int crc1=0,crc2=0;
     crc1 = crc_fn(&rxbuf[0],6);
     _delay_ms(100);
     if((rxbuf[6] == (unsigned char)(crc1))&&(rxbuf[7] == (unsigned char)(crc1>>8)))
     {
      if(rxbuf[0]==DEVICE_ID)
      {
       if(rxbuf[1] == Function_code)
       {
        if((rxbuf[5]>=1)&&(rxbuf[5]<30))
        {
         //Address = ((unsigned int)(rxbuf[2]<<8)+((unsigned int)(rxbuf[3])));
         len = (rxbuf[5]*2);
         _delay_ms(10);
         ser_data[0] = 0;
         ser_data[1] = 0;
         ser_data[2] = 0;
         ser_data[3] = 0;
         ser_data[4] = 0;
         ser_data[5] = 0;
         ser_data[6] = 0;
         ser_data[7] = 0;
         ser_data[8] = 0;
         ser_data[9] = 0;
         ser_data[10] = 0;
         ser_data[11] = 0;
         ser_data[12] = 0;
         ser_data[13] = 0;
         ser_data[14] = 0;
         ser_data[15] = 0;
         ser_data[16] = 0;
         ser_data[17] = 0;
         ser_data[18] = 0;
         ser_data[19] = 0;
         ser_data[20] = 0;
         ser_data[21] = 0;
         ser_data[22] = 0;
         ser_data[23] = 0;
         ser_data[24] = 0;
         ser_data[25] = 0;
         ser_data[26] = 0;
         ser_data[27] = 0;
         ser_data[28] = 0;
         ser_data[29] = 0;
         ser_data[30] = 0;
         ser_data[31] = 0;
         ser_data[32] = 0;
         ser_data[33] = 0;
         ser_data[34] = 0;
         ser_data[35] = 0;
         ser_data[36] = 0;
         ser_data[37] = 0;
         ser_data[38] = 0;
         ser_data[39] = 0;
         ser_data[40] = 0;
         ser_data[41] = 0;
         ser_data[42] = 0;
         ser_data[43] = 0;
         ser_data[44] = 0;
         ser_data[45] = 0;
         ser_data[46] = 0;
         ser_data[47] = 0;
         ser_data[48] = 0;
         ser_data[49] = 0;
         ser_data[50] = 0;
         ser_data[51] = 0;
         ser_data[52] = 0;
         ser_data[53] = 0;
         ser_data[54] = 0;
         ser_data[55] = 0;
         ser_data[56] = 0;
         ser_data[57] = 0;
         ser_data[58] = 0;

         crc_data[0] = DEVICE_ID;
         crc_data[1] = Function_code;
         crc_data[2] = len;

         j=3;
         for(i=0;i<len;i++)
         {
          crc_data[j++] = ser_data[i];
         }
         crc2 = crc_fn(&crc_data[0],(len+3));
         _delay_ms(100);
         serial_send(DEVICE_ID);
         serial_send(Function_code);
         serial_send(len);
         for(i=0;i<len;i++)
         {
          serial_send(ser_data[i]);
         }
         _delay_ms(10);
         serial_send((unsigned char)(crc2));
         serial_send((unsigned char)(crc2>>8));
        }
       }
      }
     }
     index = 0;
     for(i=0;i<16;i++)
      rxbuf[i] = 0;
     rec_flag = 0;
     check_flag = 1;
    }

Here code written in C++, How can we convert these to C

    int8_t Modbus::query( modbus_t telegram ) {
      uint8_t u8regsno, u8bytesno;
      if (u8id != 0) return -2;
      if (u8state != COM_IDLE) return -1;

      if ((telegram.u8id == 0) || (telegram.u8id > 247)) return -3;

      au16regs = telegram.au16reg;

      // telegram header
      au8Buffer[ ID ]         = telegram.u8id;
      au8Buffer[ FUNC ]       = telegram.u8fct;
      au8Buffer[ ADD_HI ]     = highByte(telegram.u16RegAdd );
      au8Buffer[ ADD_LO ]     = lowByte( telegram.u16RegAdd );

      switch ( telegram.u8fct ) {
      case MB_FC_READ_COILS:
      case MB_FC_READ_DISCRETE_INPUT:
      case MB_FC_READ_REGISTERS:
      case MB_FC_READ_INPUT_REGISTER:
        au8Buffer[ NB_HI ]      = highByte(telegram.u16CoilsNo );
        au8Buffer[ NB_LO ]      = lowByte( telegram.u16CoilsNo );
        u8BufferSize = 6;
        break;
      case MB_FC_WRITE_COIL:
        au8Buffer[ NB_HI ]      = ((au16regs[0] > 0) ? 0xff : 0);
        au8Buffer[ NB_LO ]      = 0;
        u8BufferSize = 6;
        break;
      case MB_FC_WRITE_REGISTER:
        au8Buffer[ NB_HI ]      = highByte(au16regs[0]);
        au8Buffer[ NB_LO ]      = lowByte(au16regs[0]);
        u8BufferSize = 6;
        break;
      case MB_FC_WRITE_MULTIPLE_COILS:
        u8regsno = telegram.u16CoilsNo / 16;
        u8bytesno = u8regsno * 2;
        if ((telegram.u16CoilsNo % 16) != 0) {
          u8bytesno++;
          u8regsno++;
        }

        au8Buffer[ NB_HI ]      = highByte(telegram.u16CoilsNo );
        au8Buffer[ NB_LO ]      = lowByte( telegram.u16CoilsNo );
        au8Buffer[ NB_LO + 1 ]    = u8bytesno;
        u8BufferSize = 7;

        u8regsno = u8bytesno = 0; // now auxiliary registers
        for (uint16_t i = 0; i < telegram.u16CoilsNo; i++) {

        }
        break;

      case MB_FC_WRITE_MULTIPLE_REGISTERS:
        au8Buffer[ NB_HI ]      = highByte(telegram.u16CoilsNo );
        au8Buffer[ NB_LO ]      = lowByte( telegram.u16CoilsNo );
        au8Buffer[ NB_LO + 1 ]    = (uint8_t) ( telegram.u16CoilsNo * 2 );
        u8BufferSize = 7;

        for (uint16_t i = 0; i < telegram.u16CoilsNo; i++) {
          au8Buffer[ u8BufferSize ] = highByte( au16regs[ i ] );
          u8BufferSize++;
          au8Buffer[ u8BufferSize ] = lowByte( au16regs[ i ] );
          u8BufferSize++;
        }
        break;
      }

      sendTxBuffer();
      u8state = COM_WAITING;
      return 0;
    }

    int8_t Modbus::poll() {
      // check if there is any incoming frame
      uint8_t u8current = port->available();

      if (millis() > u32timeOut) {
        u8state = COM_IDLE;
        u16errCnt++;
        return 0;
      }

      if (u8current == 0) return 0;

      // check T35 after frame end or still no frame end
      if (u8current != u8lastRec) {
        u8lastRec = u8current;
        u32time = millis() + T35;
        return 0;
      }
      if (millis() < u32time) return 0;

      // transfer Serial buffer frame to auBuffer
      u8lastRec = 0;
      int8_t i8state = getRxBuffer();
      if (i8state < 7) {
        u8state = COM_IDLE;
        u16errCnt++;
        return i8state;
      }

      // validate message: id, CRC, FCT, exception
      uint8_t u8exception = validateAnswer();
      if (u8exception != 0) {
        u8state = COM_IDLE;
        return u8exception;
      }

      // process answer
      switch ( au8Buffer[ FUNC ] ) {
      case MB_FC_READ_COILS:
      case MB_FC_READ_DISCRETE_INPUT:
        // call get_FC1 to transfer the incoming message to au16regs buffer
       // get_FC1( );
        break;
      case MB_FC_READ_INPUT_REGISTER:
      case MB_FC_READ_REGISTERS :
        // call get_FC3 to transfer the incoming message to au16regs buffer
        get_FC3( );
        break;
      case MB_FC_WRITE_COIL:
      case MB_FC_WRITE_REGISTER :
      case MB_FC_WRITE_MULTIPLE_COILS:
      case MB_FC_WRITE_MULTIPLE_REGISTERS :
        // nothing to do
        break;
      default:
        break;
      }
      u8state = COM_IDLE;
      return u8BufferSize;
    }

    int8_t Modbus::poll( uint16_t *regs, uint8_t u8size ) {

      au16regs = regs;
      u8regsize = u8size;

      // check if there is any incoming frame
      uint8_t u8current = port->available();
      if (u8current == 0) return 0;

      // check T35 after frame end or still no frame end
      if (u8current != u8lastRec) {
        u8lastRec = u8current;
        u32time = millis() + T35;
        return 0;
      }
      if (millis() < u32time) return 0;

      u8lastRec = 0;
      int8_t i8state = getRxBuffer();
      if (i8state < 7) return i8state;

      // check slave id
      if (au8Buffer[ ID ] != u8id) return 0;

      // validate message: CRC, FCT, address and size
      uint8_t u8exception = validateRequest();
      if (u8exception > 0) {
        if (u8exception != NO_REPLY) {
          buildException( u8exception );
          sendTxBuffer();
        }
        return u8exception;
      }

      u32timeOut = millis() + long(u16timeOut);

      // process message
      switch ( au8Buffer[ FUNC ] ) {
      case MB_FC_READ_COILS:
      case MB_FC_READ_DISCRETE_INPUT:
        return process_FC1( regs, u8size );
        break;
      case MB_FC_READ_INPUT_REGISTER:
      case MB_FC_READ_REGISTERS :
        return process_FC3( regs, u8size );
        break;
      case MB_FC_WRITE_COIL:
        return process_FC5( regs, u8size );
        break;
      case MB_FC_WRITE_REGISTER :
        return process_FC6( regs, u8size );
        break;
      case MB_FC_WRITE_MULTIPLE_COILS:
        return process_FC15( regs, u8size );
        break;
      case MB_FC_WRITE_MULTIPLE_REGISTERS :
        return process_FC16( regs, u8size );
        break;
      default:
        break;
      }
    }

    void Modbus::init(uint8_t u8id, uint8_t u8serno, uint8_t u8txenpin) {
      this->u8id = u8id;
      this->u8serno = (u8serno > 3) ? 0 : u8serno;
      this->u8txenpin = u8txenpin;
      this->u16timeOut = 1000;// intially set for 1000
    }

    int8_t Modbus::getRxBuffer() {
      boolean bBuffOverflow = false;

      if (u8txenpin > 1) digitalWrite( u8txenpin, LOW );

      u8BufferSize = 0;
      while ( port->available() ) {
        au8Buffer[ u8BufferSize ] = port->read();
        u8BufferSize ++;

        if (u8BufferSize >= MAX_BUFFER) bBuffOverflow = true;
      }
      u16InCnt++;

      if (bBuffOverflow) {
        u16errCnt++;
        return ERR_BUFF_OVERFLOW;
      }
      u32timeOut=500;
       // u32timeOut = millis() + (unsigned long) u16timeOut;
      return u8BufferSize;
    }

    void Modbus::sendTxBuffer() {
      uint8_t i = 0;

      // append CRC to message
      uint16_t u16crc = calcCRC( u8BufferSize );
      au8Buffer[ u8BufferSize ] = u16crc >> 8;
      u8BufferSize++;
      au8Buffer[ u8BufferSize ] = u16crc & 0x00ff;
      u8BufferSize++;

      // set RS485 transceiver to transmit mode
      if (u8txenpin > 1) {
        switch ( u8serno ) {
    #if defined(UBRR1H)
        case 1:
          UCSR1A = UCSR1A | (1 << TXC1);
          break;
    #endif

    #if defined(UBRR2H)
        case 2:
          UCSR2A = UCSR2A | (1 << TXC2);
          break;
    #endif

    #if defined(UBRR3H)
        case 3:
          UCSR3A = UCSR3A | (1 << TXC3);
          break;
    #endif
        case 0:
        default:
          UCSR0A = UCSR0A | (1 << TXC0);
          break;
        }
        digitalWrite( u8txenpin, HIGH );
      }

      // transfer buffer to serial line
      port->write( au8Buffer, u8BufferSize );

      // keep RS485 transceiver in transmit mode as long as sending
      if (u8txenpin > 1) {
        switch ( u8serno ) {
    #if defined(UBRR1H)
        case 1:
          while (!(UCSR1A & (1 << TXC1)));
          break;
    #endif

    #if defined(UBRR2H)
        case 2:
          while (!(UCSR2A & (1 << TXC2)));
          break;
    #endif

    #if defined(UBRR3H)
        case 3:
          while (!(UCSR3A & (1 << TXC3)));
          break;
    #endif
        case 0:
        default:
          while (!(UCSR0A & (1 << TXC0)));
          break;
        }

        // return RS485 transceiver to receive mode
        digitalWrite( u8txenpin, LOW );
      }
      port->flush();
      u8BufferSize = 0;

      // set time-out for master
    //  u32timeOut = millis() + (unsigned long) u16timeOut;
     u32timeOut=500;
      // increase message counter
      u16OutCnt++;
    }

    uint16_t Modbus::calcCRC(uint8_t u8length) {
      unsigned int temp, temp2, flag;
      temp = 0xFFFF;
      for (unsigned char i = 0; i < u8length; i++) {
        temp = temp ^ au8Buffer[i];
        for (unsigned char j = 1; j <= 8; j++) {
          flag = temp & 0x0001;
          temp >>= 1;
          if (flag)
            temp ^= 0xA001;
        }
      }
      // Reverse byte order.
      temp2 = temp >> 8;
      temp = (temp << 8) | temp2;
      temp &= 0xFFFF;
      // the returned value is already swapped
      // crcLo byte is first & crcHi byte is last
      return temp;
    }

    uint8_t Modbus::validateRequest() {
      // check message crc vs calculated crc
      uint16_t u16MsgCRC =
        ((au8Buffer[u8BufferSize - 2] << 8)
        | au8Buffer[u8BufferSize - 1]); // combine the crc Low & High bytes
      if ( calcCRC( u8BufferSize - 2 ) != u16MsgCRC ) {
        u16errCnt ++;
        return NO_REPLY;
      }

      // check fct code
      boolean isSupported = false;
      for (uint8_t i = 0; i < sizeof( fctsupported ); i++) {
        if (fctsupported[i] == au8Buffer[FUNC]) {
          isSupported = 1;
          break;
        }
      }
      if (!isSupported) {
        u16errCnt ++;
        return EXC_FUNC_CODE;
      }

      // check start address & nb range
     // uint16_t u16regs = 4000;
     uint16_t u16regs = 0;
      uint8_t u8regs;
      switch ( au8Buffer[ FUNC ] ) {
      case MB_FC_READ_COILS:
      case MB_FC_READ_DISCRETE_INPUT:
      case MB_FC_WRITE_MULTIPLE_COILS:
        u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]) / 16;
        u16regs += word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ]) / 16;
        u8regs = (uint8_t) u16regs;
        if (u8regs > u8regsize) return EXC_ADDR_RANGE;
        break;
      case MB_FC_WRITE_COIL:
        u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]) / 16;
        u8regs = (uint8_t) u16regs;
        if (u8regs > u8regsize) return EXC_ADDR_RANGE;
        break;
      case MB_FC_WRITE_REGISTER :
        u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]);
        u8regs = (uint8_t) u16regs;
        if (u8regs > u8regsize) return EXC_ADDR_RANGE;
        break;
      case MB_FC_READ_REGISTERS :
      case MB_FC_READ_INPUT_REGISTER :
      case MB_FC_WRITE_MULTIPLE_REGISTERS :
        u16regs = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ]);
        u16regs += word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ]);
        u8regs = (uint8_t) u16regs;
        if (u8regs > u8regsize) return EXC_ADDR_RANGE;
        break;
      }
      return 0; // OK, no exception code thrown
    }

    uint8_t Modbus::validateAnswer() {
      // check message crc vs calculated crc
      uint16_t u16MsgCRC =
        ((au8Buffer[u8BufferSize - 2] << 8)
        | au8Buffer[u8BufferSize - 1]); // combine the crc Low & High bytes
      if ( calcCRC( u8BufferSize - 2 ) != u16MsgCRC ) {
        u16errCnt ++;
        return NO_REPLY;
      }

      // check exception
      if ((au8Buffer[ FUNC ] & 0x80) != 0) {
        u16errCnt ++;
        return ERR_EXCEPTION;
      }

      // check fct code
      boolean isSupported = false;
      for (uint8_t i = 0; i < sizeof( fctsupported ); i++) {
        if (fctsupported[i] == au8Buffer[FUNC]) {
          isSupported = 1;
          break;
        }
      }
      if (!isSupported) {
        u16errCnt ++;
        return EXC_FUNC_CODE;
      }

      return 0; // OK, no exception code thrown
    }

    void Modbus::buildException( uint8_t u8exception ) {
      uint8_t u8func = au8Buffer[ FUNC ];  // get the original FUNC code

      au8Buffer[ ID ]      = u8id;
      au8Buffer[ FUNC ]    = u8func + 0x80;
      au8Buffer[ 2 ]       = u8exception;
      u8BufferSize         = EXCEPTION_SIZE;
    }

The functionality Check

    void Modbus::get_FC3() {
      uint8_t u8byte, i;
      u8byte = 3;

      for (i = 0; i < au8Buffer[ 2 ] / 2; i++) {
        au16regs[ i ] = word(
        au8Buffer[ u8byte ],
        au8Buffer[ u8byte + 1 ]);
        u8byte += 2;
      }
    }

    int8_t Modbus::process_FC1( uint16_t *regs, uint8_t u8size ) {
      uint8_t u8currentRegister, u8currentBit, u8bytesno, u8bitsno;
      uint8_t u8CopyBufferSize;
      uint16_t u16currentCoil, u16coil;

      // get the first and last coil from the message
      uint16_t u16StartCoil = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
      uint16_t u16Coilno = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );

      // put the number of bytes in the outcoming message
      u8bytesno = (uint8_t) (u16Coilno / 8);
      if (u16Coilno % 8 != 0) u8bytesno ++;
      au8Buffer[ ADD_HI ]  = u8bytesno;
      u8BufferSize         = ADD_LO;

      // read each coil from the register map and put its value inside the outcoming message
      u8bitsno = 0;

      for (u16currentCoil = 0; u16currentCoil < u16Coilno; u16currentCoil++) {
        u16coil = u16StartCoil + u16currentCoil;
        u8currentRegister = (uint8_t) (u16coil / 16);
        u8currentBit = (uint8_t) (u16coil % 16);

        bitWrite(
        au8Buffer[ u8BufferSize ],
        u8bitsno,
        bitRead( regs[ u8currentRegister ], u8currentBit ) );
        u8bitsno ++;

        if (u8bitsno > 7) {
          u8bitsno = 0;
          u8BufferSize++;
        }
      }

      // send outcoming message
      if (u16Coilno % 8 != 0) u8BufferSize ++;
      u8CopyBufferSize = u8BufferSize +2;
      sendTxBuffer();
      return u8CopyBufferSize;
    }

    int8_t Modbus::process_FC3( uint16_t *regs, uint8_t u8size ) {

      uint8_t u8StartAdd = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
      uint8_t u8regsno = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );
      uint8_t u8CopyBufferSize;
      uint8_t i;

      au8Buffer[ 2 ]       = u8regsno * 2;
      u8BufferSize         = 3;

      for (i = u8StartAdd; i < u8StartAdd + u8regsno; i++) {
        au8Buffer[ u8BufferSize ] = highByte(regs[i]);
        u8BufferSize++;
        au8Buffer[ u8BufferSize ] = lowByte(regs[i]);
        u8BufferSize++;
      }
      u8CopyBufferSize = u8BufferSize +2;
      sendTxBuffer();

      return u8CopyBufferSize;
    }

    int8_t Modbus::process_FC5( uint16_t *regs, uint8_t u8size ) {
      uint8_t u8currentRegister, u8currentBit;
      uint8_t u8CopyBufferSize;
      uint16_t u16coil = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );

      // point to the register and its bit
      u8currentRegister = (uint8_t) (u16coil / 16);
      u8currentBit = (uint8_t) (u16coil % 16);

      // write to coil
      bitWrite(
      regs[ u8currentRegister ],
      u8currentBit,
      au8Buffer[ NB_HI ] == 0xff );

      // send answer to master
      u8BufferSize = 6;
      u8CopyBufferSize = u8BufferSize +2;
      sendTxBuffer();

      return u8CopyBufferSize;

    }

    int8_t Modbus::process_FC6( uint16_t *regs, uint8_t u8size ) {

      uint8_t u8add = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
      uint8_t u8CopyBufferSize;
      uint16_t u16val = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );

      regs[ u8add ] = u16val;

      // keep the same header
      u8BufferSize         = RESPONSE_SIZE;

      u8CopyBufferSize = u8BufferSize +2;
      sendTxBuffer();

      return u8CopyBufferSize;
    }

    int8_t Modbus::process_FC15( uint16_t *regs, uint8_t u8size ) {
      uint8_t u8currentRegister, u8currentBit, u8frameByte, u8bitsno;
      uint8_t u8CopyBufferSize;
      uint16_t u16currentCoil, u16coil;
      boolean bTemp;

      // get the first and last coil from the message
      uint16_t u16StartCoil = word( au8Buffer[ ADD_HI ], au8Buffer[ ADD_LO ] );
      uint16_t u16Coilno = word( au8Buffer[ NB_HI ], au8Buffer[ NB_LO ] );

      // read each coil from the register map and put its value inside the outcoming message
      u8bitsno = 0;
      u8frameByte = 7;
      for (u16currentCoil = 0; u16currentCoil < u16Coilno; u16currentCoil++) {

        u16coil = u16StartCoil + u16currentCoil;
        u8currentRegister = (uint8_t) (u16coil / 16);
        u8currentBit = (uint8_t) (u16coil % 16);

        bTemp = bitRead(
        au8Buffer[ u8frameByte ],
        u8bitsno );

        bitWrite(
        regs[ u8currentRegister ],
        u8currentBit,
        bTemp );

        u8bitsno ++;

        if (u8bitsno > 7) {
          u8bitsno = 0;
          u8frameByte++;
        }
      }

      // send outcoming message
      // it's just a copy of the incomping frame until 6th byte
      u8BufferSize         = 6;
      u8CopyBufferSize = u8BufferSize +2;
      sendTxBuffer();
      return u8CopyBufferSize;
    }

    int8_t Modbus::process_FC16( uint16_t *regs, uint8_t u8size ) {
      uint8_t u8func = au8Buffer[ FUNC ];  // get the original FUNC code
      uint8_t u8StartAdd = au8Buffer[ ADD_HI ] << 8 | au8Buffer[ ADD_LO ];
      uint8_t u8regsno = au8Buffer[ NB_HI ] << 8 | au8Buffer[ NB_LO ];
      uint8_t u8CopyBufferSize;
      uint8_t i;
      uint16_t temp;

      // build header
      au8Buffer[ NB_HI ]   = 0;
      au8Buffer[ NB_LO ]   = u8regsno;
      u8BufferSize         = RESPONSE_SIZE;

      // write registers
      for (i = 0; i < u8regsno; i++) {
        temp = word(
        au8Buffer[ (BYTE_CNT + 1) + i * 2 ],
        au8Buffer[ (BYTE_CNT + 2) + i * 2 ]);

        regs[ u8StartAdd + i ] = temp;
      }
      u8CopyBufferSize = u8BufferSize +2;
      sendTxBuffer();

      return u8CopyBufferSize;
    }

title: Modbus Protocol RTU

Answers: 0


body:
I'm fairly new to arduino programming and C/C++. I would like to read a .csv file element wise, and send each element via. a nRF24L01 tranceiver to a raspberry pi. Right now I'm able to read the .csv file with `Serial.write(<file>.read())`. I was wondering if there's a way to read each element one at a time, if so how would i do that?

My thoughts (Pseudo code-ish):

    loop through every element in .csv file {
        save the current element to X.
        send X to raspberry pi (I already have a function for sending)
    }

I hope someone can help. Thanks in advance.

title: Reading a .csv file element wise

Answers: 1

body:
The `read()` method works character-wise, not element-wise. Then you
have to rethink your algorithm to loop over characters:

* store each character in a buffer
* send the whole buffer (i.e. a single element) when you see a delimiter

Example:

    const size_t BUFFER_SZ = ...;
    char buffer[BUFFER_SZ];
    size_t pos = 0;    // current write position in buffer
    int c;

    // While we can read a character:
    while ((c = <file>.read()) != -1) {

        // If we get a delimiter, then we have a complete element.
        if (c == ',' || c == '\n') {
            buffer[pos] = '\0';         // terminate the string
            raspberry.println(buffer);  // send to the RPi
            pos = 0;                    // ready for next element
        }

        // Otherwise, store the character in the buffer.
        else if (pos < BUFFER_SZ-1) {
            buffer[pos++] = c;
        }
    }

Here the buffer is sent as a string. If you want to parse it into a
number, you can use `sscanf`.

This code assumes Unix text-file conventions, i.e. each line of the file
(including the last one) being terminated by an LF character. You may
have to adapt if your file is different.


body:
I am building a IR-based laser tag system. The basics are working fine. One feature, that I want to have, is different weapon modes with different ranges.

How can I change the range of an IR transmitter with as little hardware as possible, or at best, completely in software?

title: Change range of IR programatically

Answers: 3

body:
Consider using a Sharp Distance Sensor in addition to your shoot / confirm-hit inferred LED & receiver.

[This Sharp distance sensor][1] is specified to detect objects that reflect IR light from 100 cm-500 cm.

> How can I change the range of an IR transmitter with as little
> hardware as possible, or at best, completely in software?

I believe the sensors produce an analog output that can feed into an Arduino's ADC.  So software (by itself) can be used to adjust the threshold distance.

Similar devices I have used have a narrow sensing field.  They only reported the distance to objects directly in front of them.  Also, I found they were effected by defective (burning out?) florescent light sources.  We assumed failing florescent light sources produced IR radiation similar in frequency as used by the sensor's IR emitter.  Also, the analog output is slightly stair stepped in the unit we tested.  I say this in case you were expecting to use increase relative accuracy of several readings if not precision of any given reading.

  [1]: https://www.adafruit.com/products/1568?gclid=CLOo8qn-ms0CFZM6gQodhnYIPg

body:
Instead of modifying the TX power, why not make the receiver read the light level. You just need to transmit some data, like the weapon ID.

If it works you could send more information, including how stable the weapon that hit the target was, during the shoot, using an accelerometer.

body:
Let us assume you are using an ordinary inferred LED and a type of inferred detector used in remote control entertainment equipment.

[Inferred LED modulation is simple and is well documented on the web][1].

[The inferred receiver is a complex device][2].  It contains, among other features, an Automated Gain Control (AGC) circuit and a Phase Locked Loop (PLL) circuit.  The AGC adjusts the gain and makes it impossible to gauge the power of one IR source relative to another. The PLL "locks onto" the signal.

Consider using and adjusting the power of a secondary inferred LED transmitter transmitting at the same time as the primary LED transmitter is being received. The secondary inferred LED transmitter is local to the inferred LED receiver and transmits a unique code.  The primary inferred LED transmitter is part of the opponent's equipment and transmits a unique code.  Slowly reduce the power of the secondary inferred LED source until the code switches from the secondary source to the primary source.  The power used by the secondary inferred LED when the switch occurs should be proportional to the distance to the primary inferred LED.

In the above scenario we have used the AGC to "hide" the primary source until we reduced the power of the secondary source to just below that of the primary source.  And we used the PLL to "lock onto" the strongest signal.

  [1]: https://learn.adafruit.com/using-an-infrared-library/sending-ir-codes
  [2]: http://www.vishay.com/docs/80069/circuit.pdf


body:
I am intended to use Gas Sensors (MQ series) on protoboard so I connect it to Arduino and perform analogue read.
I would like to request if possible to get the interfacing circuit (resistors, amplification.. etc.) or if there are schematics available.

Also, when I read the data digitized into 10bits ADC value, how can I convert it into units (ppm)?

Thank you so much in advance.

title: Gas Sensors with Arduino + Interfacing Circuit

Answers: 2

body:
You can connect the directly to the Arduino +5, Gnd and Signal.

I don't know of any calibration data for the sensors that I have.  I suppose you could take the maximum concentration the sensor can measure and divide this by 1024, but I don't know if the value returned is linear or logarithmic.
The data sheet does have some info on, but this page may be more helpful
http://forum.arduino.cc/index.php?topic=230945.0

Oh and don't forget the warm up time on the sensors!

body:
I would suggest checking out one of the gas sensors that comes with a breakout board. I've found the pins don't quite match the spacing of a protoboard and make it a little difficult to set up. Seeed Studio sells some of the sensors with a breakout board and has some nice examples of how to convert the values to PPM.

http://www.seeedstudio.com/wiki/Grove_-_Gas_Sensor(MQ5)


body:
I am a newbie..  I am integrating Arduino controller with Matlab

I have connected my arduino DUE board in COM7. And I have also connected a DC Motor in one of the digital output pins (D3)

So when I just execute the matlab built in arduino function to initialise or establish a connection my motor runs for a second and then stops. I dont want my motor to run initially. Is there a solution or an alternative to do this.

    a = arduino('COM7', 'Due');

Thanks in advance.

title: initial power output in the digital io pins of an Arduino controller

Answers: 0


body:
I am trying to use a VL6180X distance sensor and an Arduino Uno board for individual sensor doing individual distance sensing. This sensor follows the I2C protocol. Since for the same type of sensor, the I2C protocol says that they would all have the same address, I am thinking about using the chip enable pin (`GPIO00`) on the sensor chip to toggle sensor when doing the distance measuring.

I am able to update the address of the sensor group now. But I think to obtain individual results from different sensors on the Arduino serial monitor, right now I can only do one time setup sensor thing (like I couldn't update and toggle around different sensors). Once I started to do that, the results from the serial monitor were wrong. Any advice how I can continue to toggle around the sensor and make them work using the GPIO00 pin?

The code I'm using is:

    #include <Wire.h>
    #include <VL6180X.h>
    #define Address1 0x20
    #define Address2 0x22
    #define Address3 0x24

    VL6180X sensor;

    int pin2 = 2;
    int pin3 = 3;
    int pin4 = 4;

    void setup() {
      Serial.begin(9600);
      Wire.begin();
      pinMode(pin2,OUTPUT);
      pinMode(pin3,OUTPUT);
      pinMode(pin4,OUTPUT);
      digitalWrite(pin2,HIGH);
      digitalWrite(pin3,HIGH);
      digitalWrite(pin4,HIGH);
      sensor.init();
      sensor.configureDefault();
      sensor.writeReg(VL6180X::SYSRANGE__MAX_CONVERGENCE_TIME, 30);
      sensor.writeReg16Bit(VL6180X::SYSALS__INTEGRATION_PERIOD, 50);
      sensor.writeReg16Bit(VL6180X::INTERLEAVED_MODE__ENABLE,0);
      sensor.setTimeout(500);
      sensor.stopContinuous();
      delay(300);
      sensor.startInterleavedContinuous(100);
    }

    void loop() {
      hello2();
      delay(1000);
    }

    void hello1(){
      sensor.setAddress(0x29);
      Serial.println(sensor.readReg(0x212),HEX);
      sensor.setAddress(Address1);
      sensor.writeReg(0x212,Address1);
      Serial.println(sensor.readReg(0x212),HEX);
      Serial.println();
      digitalWrite(pin2,HIGH);
      digitalWrite(pin3,LOW);
      digitalWrite(pin4,LOW);
      Serial.print("Ambient 1: ");
      Serial.print(sensor.readAmbientContinuous());
      if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
      Serial.print("\tRange 1: ");
      Serial.print(sensor.readRangeContinuousMillimeters());
      if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
      Serial.println();
      sensor.writeReg(0x212,0x52);
      digitalWrite(pin2,HIGH);
      digitalWrite(pin3,HIGH);
      digitalWrite(pin4,HIGH);
    }

    void hello2(){
      sensor.setAddress(0x52);
      Serial.println(sensor.readReg(0x212),HEX);
      sensor.setAddress(Address2);
      sensor.writeReg(0x212,Address2);
      Serial.println(sensor.readReg(0x212),HEX);
      Serial.println();
      digitalWrite(pin2,LOW);
      digitalWrite(pin3,HIGH);
      digitalWrite(pin4,LOW);
      Serial.print("Ambient 2: ");
      Serial.print(sensor.readAmbientContinuous());
      if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
      Serial.print("\tRange 2: ");
      Serial.print(sensor.readRangeContinuousMillimeters());
      if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
      Serial.println();
      sensor.writeReg(0x212,0x52);
    }

    void hello3(){
      sensor.setAddress(0x52);
      Serial.println(sensor.readReg(0x212),HEX);
      sensor.setAddress(Address3);
      sensor.writeReg(0x212,Address3);
      Serial.println(sensor.readReg(0x212),HEX);
      Serial.println();
      digitalWrite(pin2,LOW);
      digitalWrite(pin3,LOW);
      digitalWrite(pin4,HIGH);
      Serial.print("Ambient 3: ");
      Serial.print(sensor.readAmbientContinuous());
      if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
      Serial.print("\tRange 3: ");
      Serial.print(sensor.readRangeContinuousMillimeters());
      if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
      Serial.println();
      sensor.writeReg(0x212,0x52);
    }

Any help would be appreciated!

title: Multiple VL6180X distance sensors interactive problem

Answers: 3

body:
You are using only one VL6180 object and then changing its address repeatedly. In your setup(), since all the sensors are enabled and have the same address, you're sending init commands to all of them; I'm not sure what will happen (multiple ACK/NACKs?), but it's probably not a good thing. Your hello() functions actually changes the address of all the sensors (twice?), if the commands even work, and then enables only one to read from. A host of undefined problems is expected.

To fix this, you have to do all the config and address changes in setup():

 - Before setup(), create 3 VL6180 objects: `sensor1`, `sensor2`, `sensor3`
 - In setup(), enable ONLY ONE sensor, and call all the sensor initialization commands on one of the objects you created (sensor1, maybe), as usual. Then call `setAddress()` on that sensor object to change its address to a unique one. This object is now tied to the physical sensor which has been enabled; all future operations related to that sensor, must be done on this object.
 - Then, disable this first sensor, and enable another and repeat the same steps as before on another object (sensor2), making sure to make each sensor's address unique. This way, you configure only one sensor at a time.
 - After configuring all three, you can now use their respective objects to get readings in loop().

body:
I believe, if I have read this [Multiple VL6180x in a design][1] right, then you can change the I2C addresses of the sensors.  You need to hold all the sensors in reset then send it the change ID message.  I'm not sure if it is permanent or you have to do it each power up.

Does that help?

  [1]: http://www.st.com/content/ccc/resource/technical/document/application_note/b4/f0/79/ec/ca/54/45/07/DM00114403.pdf/files/DM00114403.pdf/jcr:content/translations/en.DM00114403.pdf

body:
You can use an I2C multiplexer ([TCA9548A][1]). One I2C input can be output to one of the eight I2C outputs.

It has 8 configurable addresses, so you can connect 64 I2C devices with the same address by using 8 multiplexer chips.

  [1]: http://www.ti.com/lit/ds/symlink/tca9548a.pdf


body: I am trying to make a RBB Arduino based project and I only need 3 pins. In the future I may use one to two more. I wanted to use an ATtiny85 however my code is 13,270 bytes and it would not fit. So I decided to use an ATtiny84 but it also would not fit, it will fit on an ATmega328p but I do not want to use one because i want to keep the project relatively small and I for sure do not need that many pins. Does anyone know of a chip that has a lot of memory but not many pins, or some other solution. Thank you, any help is appreciated.

title: I need more memory!

Answers: 2

body:
There are a few ways to optimize your code and reduce the size. Have a look on this document from Atmel. I've used some tips to reduce the size of my bootloader once.

[http://www.atmel.com/images/doc8453.pdf][1]

For the AVR family I'm not familiar with any option. You could use a small QFN package for the atmega328p as well... You might find some small ARM with much more memory and small size.

  [1]: http://www.atmel.com/images/doc8453.pdf

body:
AFAIK, 8 KiB of flash is the most you can have on an AVR in a DIP
package with less than 28 pins. If you do not mind soldering
surface-mount parts, the 328P is available in TQFP and VQFN packages,
significantly smaller than the DIP version.

Otherwise you could try to optimize your program to fit in 8 KiB.
The Arduino libraries are often inefficient size-wise, and in many
instances you can save quite a lot by rewriting the parts that you need
on top of just [avr-libc](http://www.nongnu.org/avr-libc/). Note that
this libc is always linked to your program by the Arduino IDE.


body:
I have connected to EL wire, 12v EL Inverter to SparkFun EL Sequencer but it does not work (no battery is connected). The connections are the same like in Hookup Guide (https://cdn.sparkfun.com/assets/learn_tutorials/3/6/9/ELSequencerHookUp_bb.png). Furthermore, there is no light indicating that it works but I hear a noise/whistle from the Inverter.

Do I have to program the EL Sequencer or does it automatically turn the EL wire on?

title: SparkFun EL Sequencer does not work

Answers: 1

body:
It looks like Sparkfun probably only put the bootloader on the board. The [tutorial][1] is written in a way that suggests the need to flash the board.

Also the board does not imediatly work with the 12V inverter. If you have the battery you should attach it and see the `PWR` LED turn on.

 *The inverter only provides voltage to the EL wire* and **not the Microcontroller**, power to the microcontroller is provided by way of a regulator(`U2`), ***not** the LM317* the last quote from the one comment shows how you can connect to the 12V inverter.

What you should do instead of having to go the route of all the wiring is to connect both the battery to `BATT IN` and the inverter, but ensuring that the microcontroller is programmed before hand.

> Arduino Code
>
> Once you have all of your hardware hooked up properly, it’s time to
> program your Sequencer to run the EL Wire display as you want. You
> will need to download the Arduino code in order to follow along with
> the example.
>
> You can also download the most up-to-date code from the EL Sequencer
> [GitHub repository][2].
>
> We will be working with the “SparkFun_EL_Example.ino” example. If you
> need a review on how to upload Arduino code to your board or using the
> Arduino IDE, please check our tutorial [here][3]. Also, if you are unsure
> about installing the FTDI drivers, please check out [this tutorial][4].

Also from one of the [Tech support notes][5]:

> Using 12V to Power Both the EL Inverter & Microcontroller
>
> If you are using a 12V wall adapter to power the 12V Inverter, you
> would still need to provide power to the microcontroller side. One
> solution with your 12V wall adapter to provide power to the 12V
> inverter and Atmega328P is to get a barrel jack adapter to 2 pin JST
> adapter [ https://www.sparkfun.com/products/8734 ], thus connecting
> the 12V wall adapter to the “BATT IN.” This is assuming that your wall
> adapter is using a center positive barrel jack.
>
> From there you can connect the 2 pin JST labeled “DC Out” to the 12V
> inverter’s input voltage. To connect, I recommend using the male DC
> barrel jack adapter [ https://www.sparkfun.com/products/10287 ] and a
> 2pin JSt jumper wire [ https://www.sparkfun.com/products/8670 or
> https://www.sparkfun.com/products/8671 ]. You will need to wire strip
> the cable to be able to connect it to the screw terminals.
>
> Lastly, you would need to add a solder jumper to SJ1 so that you
> bypass the voltage regulator between your external power (“BATT IN”)
> to provide power to the inverter’s “DC OUT”. This will provide power
> to your 12V inverter’s input.

**Warning: if SJ1 is closed, inverter will see 5V with FTDI plugged in and switch at USB**

  [1]: https://learn.sparkfun.com/tutorials/el-sequencerescudo-dos-hookup-guide
  [2]: https://github.com/sparkfun/EL_Sequencer
  [3]: https://learn.sparkfun.com/tutorials/installing-arduino-ide
  [4]: https://learn.sparkfun.com/tutorials/how-to-install-ftdi-drivers
  [5]: https://learn.sparkfun.com/tutorials/el-sequencerescudo-dos-hookup-guide/discuss


body:
I have a question about connecting a Arduino with Raspberry Pi.

What is the benefit of connecting the two?

title: Why connect arduino with Rasberry pi?

Answers: 3

body:
Interfacing hardware is easier with the Arduino: more available I/O pins
capable of sourcing and sinking more current, 5 V I/O, analog
inputs, very predictable timings, etc. The Raspberry, on the other hand,
is a real computer with a real OS, has **a lot** more computing power
and memory, has Internet connectivity, can easily run “standard” web
servers like Apache or nginx... or mostly any Linux software for that
matter.

Some projects can benefit from using both. E.g. if you want to make a
web interface for some low-level hardware sensors.

body:
**Why add an Raspberry Pi to an Arduino?**

There are some things that simply are beyond the possibilities of Arduino. The first thing that would cross my mind is video processing, HDMI output, decent sound etc.

A Raspberry Pi can be used to add some features to your project aswell. If you make an Arduino controlled robotic arm, you could add an "user interface" to it, using a Raspberry Pi.

**Why add an Arduino to an Raspberry Pi?**

Some may argue that the Raspberry Pi is much more capable as an Arduino, in every form.
Though, the strengths of Arduino are:

 - Ease of use. (For GPIO on Raspberry Pi you'll likely need to install something, to make it work with your favorite programming language.)
 - Real time / deterministic timing, this is one of the best things of Arduino. Given that an Arduino has no "operating system" that can induce random (tiny) delays in your program (other than the millis()/micros() interrupts).

**Why do any of this? You could choose an Arduino OR Raspberry Pi**

One thing you might not think about is, that by joining an Arduino and a Raspberry Pi, you're joining two important parts of Embedded Systems. Which you can learn a lot from.

Microcontrollers and Single-board computers. This really has a good educational effect. Since you'll not limit yourself to one device or "way of thinking".

Moreover, the interfacing between two devices is often important and will bring some extra problems. (And solving them gives extra knowledge/experience)

body: I prefer to use arduino type boards as data acquisition units then transfer the data to an actual computer (or raspberry pi) in most of my projects. Arduinos are, in my experience, much more tolerant of fault and accidental crossed circuits than the R pi.  Thus is especially true of the ruggedized or industrial arduino versions.


body:
https://www.arduino.cc/en/Tutorial/RowColumnScanning

This code really confused me because I don't know if the `pixels[x][y]` is HIGH or LOW in `void refreshScreen()`.

As you look at the code, `pixels[x][y]` is HIGH and then LOW in `void setup()`, and then `pixels[x][y]` is HIGH again in `void loop()`. Could anyone explain this to me, please？

title: Row-column scanning to control an 8x8 LED matrix

Answers: 1

body:
The pixels array in initialized to all HIGH in `setup()`. Then one element of the pixel array is set to LOW in `readSensors()`  which turns on one LED.

The tricky bit is you have to remember to turn off the previous LED. That is why in `readSensors()` there is the line where an element of pixels is set HIGH while the pixels' array pointers are still pointing at the former (already lit) LED.


body:
I want to power my motor shield without my UNO. I have connected the `+ve` and `-ve` terminals resulting in lighting up of the LED.

Is there any way to control the motors in this arrangement from the Arduino?

title: how do I power my motor shield without an arduino uno?

Answers: 1

body:
Welcome!

I'm not sure I understand what you are asking because what you are trying to do doesn't make much sense.

The motors connected to the motor shield are controlled by the output pins of the Arduino that the motor shield is plugged in to.

You could run jumper leads from an separate Arduino into your unplugged motor shield, but that's just extending what you already have.  You really do need some form of controller, not necessary a microprocessor, otherwise how can you go forwards and backwards?

Is the problem you have put the Arduino into a plastic case and you can't plug the motor shield in any more?  If so get a set of long male to female connectors (they look like the Arduino connectors) and use them as extensions.

Is the problem you have a different format of board and can't plug it in? If so use the wires method to form the correct connections.

I hope that answers your question, if not please try and explain what I'm misunderstanding.


body:
I’m constructing an arduino based sytem that uses a SD card and I’m looking for a way to safely remove the card from the system during operation. One way would probably be to turn of the arduino before removal of the SD card, but that is not acceptable in this context.

The library I’m using:
https://www.arduino.cc/en/Reference/SD

Is it possible to safely remove the SD card during operation? If no, how can I minimize the risk of damage to the SD card while inserting and removing it?

title: How to remove SD card safely

Answers: 3

body:
The physical construction of the card and socket are designed such that power to the card is cycled properly when the card is inserted and removed. The only thing the firmware has to do is to stop writing to the card before it is removed.

Unexpected removal can cause a problem in "larger" systems (e.g. cellphones or PCs) because they may have structures open on the card that are not yet complete, but small embedded systems typically do not have the capability to do so and so once all writes are completed the card can be removed.

Detection of non-presence of a card is another issue though, and the firmware will have to be designed to not fail in such a situation.

body:
An SDCard is very much like a hard disk drive.  Both in how it is made and how it is treated by the host.  As such there are critical times where interrupting the communication to the SDCard can cause corruption.

To avoid problems it is advisable to finish all transaction before removing the SDCard.  In a perfect situation all data will be flushed from the host's buffers (cache) and the files being accessed closed.  So research the flush() and the close() function calls in the library you are using.

In order to accomplish the above, it is obvious the host device needs to be told the SDCard is about to be removed.  In most cases this is accomplished using a switch (human interface) and some code to flush and close any open files.

All this said, often people pull SDCards with out any obvious problems.  This is likely because SDCard transactions are fast and completed in fractions of a second.  Also pulling an SDCard when periodically reading a file is far safer then when writing to a file or altering any information on the SDCard (for example the name of a file).  If you can suffer the possibility of corruption, it may be that the added effort is not worth it.  However if you stand lose a great deal, I would advise you to do some research into the best ways to avoid SDCard corruption.

body:
In my early days of computing, the computer used to turn on a led when writing to cassette tape or floppy disk. If you wanted to remove the tape or disk, you had to wait for the led to turn off.
I think that could be your easiest solution.


body:
I'm attempting to reduce the amount of RAM being used by my program by writing some values to the EEPROM of my micro controller. I'm currently programming on the ATtiny85 which has 512 Bytes of EEPROM. According to the documentation this is how you write to EEPROM:

    #include <EEPROM.h>

    void setup() {
      EEPROM.write(0, 1);
      EEPROM.write(1, 0);
      EEPROM.write(2, 3);
      EEPROM.write(3, 2);
      EEPROM.write(4, 1);

    }

For some reason this isn't working for me and I can't seem to find the error. Am I programming this wrong or can the EEPROM of the ATtiny simply NOT be accessed with Arduino Code?

Here is the Datasheet: http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet-Summary.pdf

Here is the second sketch I'm using to test the EEPROM:

        #include <EEPROM.h>

    void setup() {
      EEPROM.write(0, 1);
      EEPROM.write(1, 0);
      EEPROM.write(2, A3);
      EEPROM.write(3, A2);
      EEPROM.write(4, A1);

    byte CLK = EEPROM.read(0);

    }

    void loop() {

      if(CLK == 1)
      {
        for(int i = 0; i < 3; i++)
        {
        digitalWrite(0, HIGH);
        delay(1000);
        digitalWrite(0, LOW);
        delay(1000);
        }
        exit(0);
      }
      else
      {
        for(int i = 0; i < 100; i++)
        {
        digitalWrite(0, HIGH);
        delay(1000);
        digitalWrite(0, LOW);
        delay(1000);
        }
        exit(0);
      }

      exit(0);

    }

title: Can you access the EEPROM of an ATtiny with Arduino Code?

Answers: 4

body:
When you upload a new sketch with the default settings, the EEPROM will be cleared.

"The -e option instructs avrdude to perform a chip-erase before programming; this is almost always necessary before programming the flash."

If you're using the Arduino IDE, the -e option is enabled by default. This is probably why it's not working for you.

See also the question [Is there a way to preserve EEPROM contents in AVR Atmega when burning a new firmware to flash with avrdude?][1]

  [1]: https://electronics.stackexchange.com/questions/98891/is-there-a-way-to-preserve-eeprom-contents-in-avr-atmega-when-burning-a-new-firm

body:
The Arduino EEPROM library is compatible with the ATTiny range of AVR microcontrollers as the library itself is built on the standard Atmel AVR avr/eeprom.h 'library' so it is compatible with all the AVR microcontrollers.

The EEPROM also doesn't take to being written or read to often as EEPROM can wear very quickly. Reading though does not cause much damage though.

Also note that using `exit(0);` **will stop the ATTiny from doing anything else** after it is called so I hope your intention is to only run the loop once, if not this would account for either not seeing anything or it only ever running the blinking cycle once.

To answer your follow up question. Yes you can run one sketch to set you values in EEPROM and then use another sketch to read those. That us usually the point of EEPROM it is a memory type that "keeps its value while there is no power".

Also you need to make sure the ATTiny is set to preserve EEPROM during upload with the ISP, this is done with the fuse settings. You need to look for a tutorial on fuse calculators for the AVRs. To set the `EESAVE` you need to set the High fuse to `0xD7`, you can change this in the `boards.txt` file. [Here is a fuse calculator.][1]

If the code that is on your question at the moment is being used you won't be seeing anything as it needs the pins to be set with `pinMode`. That's a note for others that see this.

Next what you can do is run a basic test code which blinks the LED without anything else going on.

Basically:

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

    void setup(){

     pinMode(0, OUTPUT);

    }

    void loop(){

     digitalWrite(0, HIGH);
     delay(1000);
     digitalWrite(0, LOW);
     delay(1000);

    }

Below is the code you have written, it works I have it running in front of me.
I have commented it and changed a few things to make it work as intended, although the intention is not clear.

    #include <EEPROM.h>

    byte CLK = 0; //This is a global variable with an initial value

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

      EEPROM.write(0, 1); //set the pin to D1
      delay(5);

      //read from EEPROM address 0
      //this sets the value of the global variable CLK
      CLK = EEPROM.read(0); //place this inside a function

      //just to give an example...
      byte PIN = CLK;   //PIN variable is a local variable

      pinMode(PIN ,OUTPUT); //using that local variable

    }

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

      // Note: the below if() will always be true as the value
      // of CLK is never change and shouldn't be changed as
      // it will change the pin number of the output

      if (CLK == 1) {
        for (int a = 0; a < 3; a++) {
          digitalWrite(CLK, HIGH);  //this uses the global variable
          delay(1000);
          digitalWrite(CLK, LOW);
          delay(1000);
        }
        //putting exit(0); will actually stop the program
        //remove it
    //    exit(0);
      }
      else {
        for (int a = 0; a < 100; a++) {
          digitalWrite(0, HIGH);  //this has a predefined pin no.
          delay(500);
          digitalWrite(0, LOW);   //this has a predefined pin no.
          delay(500);
        }
        //putting exit(0); will actually stop the program
        //remove it
    //    exit(0);
      }
    }

  [1]: http://eleccelerator.com/fusecalc/fusecalc.php?chip=attiny85&LOW=E2&HIGH=D7&EXTENDED=FF&LOCKBIT=FF

body:
Not sure if things have changed so significantly since the question was asked originally but I'll answer using the Atmel AVR libraries.

Don't assign the EEPROM value to a variable as then you are wasting precious SRAM again. EEPROM has unlimited read cycles.

I can't find any current references to `EEPROM.read()` as a Macro or function in the Arduino IDE. Instead there is the AVR EEPROM library which uses `eeprom_read_byte()` as shown below.

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

    #include  <avr/eeprom.h>

    // the setup routine runs once when you press reset:
    void setup() {
    /* The "131" value is used to prevent damaging excess EEPROM writes on every restart.
       If you want to try setting a different GPIO pin for LED blink change the test value in
       both the read and following write to EEPROM address 511 */

        if (eeprom_read_byte((uint8_t*)511) != 131) {
           eeprom_write_byte((uint8_t*)511,131);
    // Store the GPIO pin number in EEPROM address 1
           eeprom_write_byte((uint8_t*)1,1);
        };
    // initialize the digital pin as an output.
        pinMode(eeprom_read_byte((uint8_t*)1), OUTPUT); // LED pin value stored in EEPROM address 1
    }

    // the loop routine runs over and over again forever:

    void loop() {
        digitalWrite(eeprom_read_byte((uint8_t*)1), HIGH);
        delay(1000);               // wait for a second
        digitalWrite(eeprom_read_byte((uint8_t*)1), LOW);

        delay(1000);               // wait for a second
    }

body:
It is now very common to read from EEPROM in an ATTiny, particularly an OSCCAL value. It has also been the case for some embedded devices to perform a superfluous write and read back to external EEPROM during POST. Every boot.

    > ---snip---
    >     current tick:1 sec
    >     EEPROM Init...
    >     Write EE_TEST ==0x7cf u8EEData1=0xaa
    >     Read EE_TEST ==0x7cf u8EEData1=0xaa
    >     [EEPROM 24c16 found!]
    >     EEPROM: Data valid
    >     Restore Configuration from EEPROM to Device...
    >     Show MY MAC Address(from 24c16): (0x00:92:58:01:45:4d)
    >     _24c16_eeprom_word_read: EE_DHCPEN: (01)
    > --- end snip ---

In addition, available cores include options to suppress EEPROM erase in programming, this is fuseable.

In ancient times AVRDUDE would write flash counts to the four bytes terminated by E2END. (the -y option).

You need to include the header.  You can check, peek and poke, the contents with a sketch or by using avrdude in terminal mode (-t) with "dump ee".

And yes, it is normal for Arduino work to have a dedicated temporary sketch to load EEPROM data.
So SRAM (or FLASH) does not matter, there is a lot of FLASH compared to EEPROM.

Keep it simple and test your results. Depending upon the library or core, it is best to avoid crossing page boundaries as addressing may wrap around to the beginning of the page due to 6 bit truncation as for I2C external EEPROM. Don't trust, verify.


body:
I have several sensors (Grove multichannel gas sensor, Air Pressure Sensor MPX4115A, Temperature and Humidity Sensor DHT11) where most of them uses I2C communication.
I wonder if it is possible to read all of them using the I2C communication on a single Arduino board?

title: I2C multi sensors reading on Arduino

Answers: 2

body:
Should be easy enough.  Do you already know how to connect and communicate with one I2C device?  If so, connecting multiple should be simply a case of connecting them in parallel.

If you don't know how to communicate with a single I2C device, then...

For the Arduino software you can use [Wire][1] to talk to devices over I2C.

For the hardware, connect the I2C clock and data lines from the Arduino to the I2C devices.  More on that [here][2].

  [1]: https://www.arduino.cc/en/Reference/Wire
  [2]: https://learn.sparkfun.com/tutorials/i2c/why-use-i2c

body:
It is possible to use multiple I²C devices, all is needed is for each one to have a different address and the ability to set up the wiring(the [other answer][1] points to wriring info).

Of the sensors you listed only one is an I2C device(Grove sensor).

The DHT11 uses a single digital wire to communicate and the air pressure sensor is an analog device. Although you do mention having several devices, the only thing you need to be sure of is if there are no address conflicts, i.e. there being two devices with the same address on the I²C bus.

If address conflicts are an issue most devices provide a way of changing that address, often there are solder jumpers on the board. This allows you to change a devices address to a unique one.

  [1]: https://arduino.stackexchange.com/a/25087/2944