message:
RGB fade program

I'm working on a function to fade RGB LEDs smoothly from one color to the next, so I thought I'd use a for loop  to increment each RGB value according with the set value. I've made the for loop as following:

    for (redFadeCurrent, greenFadeCurrent, blueFadeCurrent;
       ((redFadeCurrent != redFadeTarget)&&
       (greenFadeCurrent != greenFadeTarget)&&
       (blueFadeCurrent != blueFadeTarget));
       redFadeCurrent = redFadeCurrent + redStep,
       greenFadeCurrent = greenFadeCurrent + greenStep,
       blueFadeCurrent = blueFadeCurrent + blueStep) {

        analogWrite(ledRedPin, redFadeCurrent);
        analogWrite(ledGreenPin, greenFadeCurrent);
        analogWrite(ledBluePin, blueFadeCurrent);
        Serial.print("Red: ");
        Serial.print(redFadeCurrent);
        Serial.print(" Green: ");
        Serial.print(greenFadeCurrent);
        Serial.print(" Blue: ");
        Serial.println(blueFadeCurrent);
        delay(3000);

        if (redFadeCurrent>redFadeTarget) {
            redStep = -1;
        }
        else if (redFadeCurrent<redFadeTarget) {
            redStep = +1;
        }
        else {
            redStep = 0;
        }

        if (greenFadeCurrent>greenFadeTarget) {
            greenStep = -1;
        }
        else if (greenFadeCurrent<greenFadeTarget) {
            greenStep = +1;
        }
        else {
            greenStep = 0;
        }

        if (blueFadeCurrent>blueFadeTarget) {
            blueStep = -1;
        }
        else if (blueFadeCurrent<blueFadeTarget) {
            blueStep = +1;
        }
        else {
            blueStep = 0;
        }

Problem is, when one of the values hit the target the code leaves the for loop.
I'm guessing the condition `((redFadeCurrent != redFadeTarget)&&(greenFadeCurrent != greenFadeTarget)&&(blueFadeCurrent != blueFadeTarget))` does not work.

Is there any way to work around this?

Thanks is advance.

body:
You are correct, the problem is the condition inside the `for` statement.

Let's examine what happens when the *red* LED hits its fading target, which is, say, 100 (for the sake of the example, I will fabricate the other values):

    for (...; (100 != 100) && (90 != 100) && (80 != 100) ; ... )

   * (100 != 100) -> **FALSE**
   * (90 != 100) -> **TRUE**
   * (80 != 100) -> **TRUE**

**FALSE** && **TRUE** && **TRUE** -> **FALSE**

The condition inside the `for` evaluates to `FALSE`, therefor the loop will exit.

If you want the loop to continue as long as there is at least one LED which hasn't hit the fading target, you should change the `AND` to `OR`:

    ((redFadeCurrent != redFadeTarget) || (greenFadeCurrent != greenFadeTarget) ||
       (blueFadeCurrent != blueFadeTarget))

Let's examine what happens now with the same values:

    for (...; (100!=100) || (90 != 100) || (80 != 100) ; ...)

   * (100 != 100) -> FALSE
   * (90 != 100) -> TRUE
   * (80 != 100) -> TRUE

**FALSE** || **TRUE** || **TRUE** -> **TRUE** ==> The loop will continue.

And what will happen when all the colors hit the fading targets?

    for (...; (100!=100) || (100 != 100) || (100 != 100) ; ...)

   * (100 != 100) -> FALSE
   * (100 != 100) -> FALSE
   * (100 != 100) -> FALSE

**FALSE** || **FALSE** || **FALSE** -> **FALSE** ==> The loop will stop since the condition will not evaluate to `TRUE`.


sender: user

message:
Do addressable RGB's need to be programmed differently from normal RGB's?

I bought [these](https://www.sparkfun.com/products/12877) rgb's from Sparkfun, however I have no idea how to hook them up or how to program them. Obviously the [data sheet](https://cdn.sparkfun.com/datasheets/Components/LED/COM-12877.pdf) was somewhat helpful, however I have no idea how the IC's in the LED's work themselves or how to control them separately, or even how to string them together. My best guess is currently going for what the led's appear as in the example picture by connecting the first and last pins and putting the respective Vcc and ground pins to Vcc and ground.

Is there any good examples for hooking these up and coding them, or a basic understandable explanation for how they work?

Thanks, I can't find a great resource yet.

sender: assistant

body:
These are much different than "normal" RGB LED: they use the **[WS2812][1]** chip, which is the same as the chip used in famous Adafruit "neopixels" strips, rings...

Wiring is simple. For all LEDs:

- GND to 0V
- VDD to 5V

For the first LED (connected to Arduino):

- DIN to any Arduino logical output pin
- DOUT to the 2nd LED you want to address (on its DIN pin)

For all but the first LED:

- DIN to the previous LED DOUT
- DOUT to the next LED DIN (or left floating for the last LED)

Programming neopixel is quite hard because timing of sent commands must be very precise.

I highly suggest to use [Adafruit libraries][2] for that.

  [1]: http://www.adafruit.com/datasheets/WS2812.pdf
  [2]: https://github.com/adafruit/Adafruit_NeoPixel


message:
Why are LED 0 and 1 on as well?

I was just playing around a bit and ran into a strange problem. LED 3, 5, 6, 9 and 10 are on, as intended. For some reason LED 0 and 1 are on as well. Can someone explain why this is happening?

    int ledPins[] = {3, 5, 6, 9, 10};
    int pinCount = sizeof(ledPins);

    void setup(){
      for (int i = 0; i < pinCount; i++){
        pinMode(ledPins[i], OUTPUT);
      }
    }

    void loop(){
       for (int i = 0; i < pinCount; i++){
         digitalWrite(ledPins[i], 1);
       }
    }

body:
You haven't initialised the other pins at all; or included your circuit, but clearly you have LEDs on more pins than those defined (5 defined, 7 on).

The other LEDs are, therefore, in an undefined state - and may well be attached to pins set 'on' by default in your circuit. You probably need to either move 0/1 off the serial interface or explicitly set them 'off'.


body:
The behaviour of your program is undefined because you're reading past the end of your array.

In C/C++, the `sizeof` operator always gives you the size of something in **bytes**. It doesn't directly tell you the number of items in an array. Since `int` is usually 2 bytes for Arduino programming, the `pinCount` variable is actually being initialised to **10** (5 items x 2 bytes each).

The result is that each `for` loop is actually doing 10 iterations. The first 5 iterations are OK, reading correctly from the `ledPins` array. However, the rest of the iterations are reading whatever data happens to be in memory after that. This means it could be trying to initialise and switch on any pin, potentially including 0 and 1.

I can't guarantee that this is the source of the problem, but it's certainly very important to fix.

The solution is quite easy though. Divide the total size of the array by the size of a single element:

    int pinCount = sizeof(ledPins) / sizeof(int);


message:
Decoding a RS232 message in Arduino

I have an Arduino Mega with an MaxBotix (MB7066) sonar attached, the sonar has the ability to send serial data with it's reading. It uses a asynchronous RS232 format, except the voltages are 0-Vcc. The output should be a capital "R" (ASCII), followed by four digits(ASCII) and a carriage return (ASCII 13). The baud rate is 9600, 8 bits, no parity with one stop bit.
What I get from the device is as follows: (sonarSerial.read() while sonarSerial.available())

    43
    192
    6
    6
    179
    89
    30
    0

What do I have to get to the information? Or is my sensor just retuning garbage?
Please see the code below:

    #include <SoftwareSerial.h>

    #define pin1 3
    #define pin2 5 //pwm
    #define pin3 6 //analog
    #define pin4 10 //RX for sonar, TX for arduino
    #define pin5 11 //TX for sonar, RX for arduino

    SoftwareSerial sonarPort(pin5,pin4);

    void setup(){
       Serial.begin (9600);
       pinMode(pin1, OUTPUT);

       pinMode(pin4, OUTPUT);
       pinMode(pin5, INPUT);
       sonarPort.begin(9600);
    }

    void loop(){
      digitalWrite(pin1, HIGH);

      digitalWrite(pin4, LOW);
      digitalWrite(pin4, HIGH);
      delayMicroseconds(20);
      digitalWrite(pin4, LOW);

      long pulse = pulseIn(pin2, HIGH)/58;
      Serial.print("PM Result: ");
      Serial.println(pulse);

      String buffer = "";
      sonarPort.listen();
      while(sonarPort.available() > 0){
          int inByte = sonarPort.read();
          buffer += inByte; buffer += " ";
          if(!sonarPort.available()){
              Serial.print("Serial result: ");
              Serial.println(buffer);
          }
      }
      delay(500);
    }

body:
In the bitstream of your ASCII data the pattern for "R" (01010010b) does never occur.<br>
So obviously something is wrong in your system and/or setup.
Have you already considered the information given here http://www.maxbotix.com/articles/034.htm?

I would connect the sensor to a PC to check whether it's working correctly using a standard terminal software.


body:
I contacted MaxBotix with the problem and for my surprise their technical support is really great:

> The Arduino is set up to natively read TTL serial data.The MB7066 outputs its serial data in the RS232 format. Do not worry; this problem can easily be fixed. You can use an inverter such as the MAX232. You can also follow the following tutorial to make your own https://github.com/simonmonk/raspirobotboard/wiki/Rangefinder-Adapter.
>
> Another option would be to test using this code section SoftwareSerial
> sonarSerial(rxPin, txPin, true); //define serial port for recieving
> data, output from maxSonar is inverted requiring true to be set.


message:
Unable to connect to Linux Environment (Linino AR9331 Interface) in Arduino Yun

I was trying to reset my Arduino Yun (WLAN button pressed for more than 30 seconds), but it just kept on blinking for about 10 minutes. Then I finally got impatient and restarted the Yun. After the restart, there was no WLAN (blue) or USB (white) LED blinking or glowing anymore. I am unable to connect through the Wifi network, the Yun does not create it's own Wifi network and unfortunately when connected via Ethernet, I can still not navigate to arduino.local or 192.168.240.1.

So I have a feeling that somehow only the AVR is still functioning (because I can still upload sketches) and nothing else.

I have updated the firmware to the latest version (OpenWrt-Yun 1.5.3). Is there a way to connect or reset, if the Ethernet does not work? Can I upload a sketch to check in the console if the Linino interface still functions.

Thanks in advance!

body:
Try uploading YunSerialTerminal example, opening the serial monitor and pressing the YUN RST button. You should see the linux side starting.

If it starts but it looks somehow bricked, you could try following the http://arduino.cc/en/Tutorial/YunUBootReflash tutorial.


message:
Power consumption issue. I made project using atmel-328p

I made project using atmel-328p. I want to run it over a year. I am using power_down mode & 5500 mAh li-ion battery still battery discharges in 1 day. I am using standard code as explain on arduino site.
code is:

    String uniqueid;
    char value;
    volatile int NbTopsFan; //measuring the rising edges of the signal
    uint32_t Calc;
    int hallsensor = 2;    //The pin location of the sensor
    int power = 4;
    // ph sensor
    define SensorPin 0          //pH meter Analog output to Arduino Analog Input 0
    define Offset 0.00            //deviation compensate
    unsigned long int avgValue;    //Store the average value of the sensor feedback
    // temp sensor
    OneWire  ds(8);
    byte i;
    byte present = 0;
    byte data[12];
    byte addr[8];
    int HighByte, LowByte, SignBit, Whole, Fract, TReading, Tc_100, FWhole;

    int wakePin = 3;                 // pin used for waking up
    int sleepStatus = 0;             // variable to store a request for sleep
    int countsleep = 0;                   // counter

    void wakeUpNow()        // here the interrupt is handled after wakeup
    {// execute code here after wake-up before returning to the loop() function
     }
    void rpm ()     //This is the function that the interupt calls
    {
     NbTopsFan++;  //This function measures the rising and falling edge of the
    //hall effect sensors signal
    }
    void setup()
    {
     pinMode(hallsensor, INPUT); //initializes digital pin 2 as an input
    Serial.begin(9600); //This is the setup function where the serial port is
    pinMode(power, OUTPUT);
    //initialised,
     attachInterrupt(0, rpm, RISING); //and the interrupt is attached
    //initialised,
      //and the interrupt is attached
    // temp sensor pin 8
            if ( !ds.search(addr))
            {
               //       Serial.println("temp sensor is not connected");
            delay(1000);
            ds.reset_search();
            return;
            }
            if ( OneWire::crc8( addr, 7) != addr[7])
            {
           //      Serial.println("CRC not valid!");
           delay(1000);
           return;
            }
    pinMode(wakePin, INPUT);

      attachInterrupt(1, wakeUpNow, LOW); // use interrupt 1 (pin 3) and run function

    }

    void sleepNow()         // here we put the arduino to sleep
    {
      countsleep = 0;
    ADCSRA = 0;

       set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

        sleep_enable();          // enables the sleep bit in the mcucr register
                                 // so sleep is possible. just a safety pin
      // turn off brown-out enable in software
      MCUCR = bit (BODS) | bit (BODSE);  // turn on brown-out enable select
      MCUCR = bit (BODS);        // this must be done within 4 clock cycles of above

     sleep_cpu ();

        attachInterrupt(1,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                                           // wakeUpNow when pin 2 gets LOW

        sleep_mode();            // here the device is actually put to sleep!!
                                 // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

        sleep_disable();         // first thing after waking from sleep:
                                 // disable sleep...
        detachInterrupt(1);      // disables interrupt 0 on pin 2 so the
                                 // wakeUpNow code will not be executed
    }

    void loop()
    {

      countsleep++;
      delay(1000);                           // waits for a second
    // compute the serial input
      if (Serial.available())
      {
        String content = "";
        char character;
    // to read serial data coming
            while(Serial.available()>0)
              {
                  character = Serial.read();
                  content.concat(character);
              }
          String uniqueidread = content.substring(0,16);
          String parameter = content.substring(16,17);
          String checkuuid = content.substring(0,3);
          String putinsleep = content.substring(0,5);
           if (uniqueidread == uniqueid && parameter == "5")
    {         //    Serial.flush();
    digitalWrite(power,HIGH);
     NbTopsFan = 0;      //Set NbTops to 0 ready for calculations
     sei();            //Enables interrupts
     delay (1000);      //Wait 1 second
     cli();            //Disable interrupts
     Calc = (NbTopsFan * 60 / 7.5); //(Pulse frequency x 60) / 7.5Q, = flow rate

      digitalWrite(power,LOW);
              getTemp();
              delay(1000);
              getTemp();
              //   printTemp();
          Serial.print("Temp is: ");
               if (SignBit)
               {
                    Serial.print(" - ");
               }
               if( Whole == 0)
               {
                  Serial.print("temp sensor is not connected");
               }
               else
               {
                  Serial.print(Whole);
                  Serial.print(" C / ");
                  Serial.print(FWhole);
                  Serial.print(" F");
                }
                  Serial.print(", Current Reading = ");
         Serial.print (Calc, DEC); //Prints the number calculated above
                Serial.print(" L/hour");
       phvalue();
                Serial.println("S=m");
                  delay(100);
                  sleepNow();
    }

             if ( content == "sleep")
             {
              Serial.println("S=m");
              delay(100);     // this delay is needed, the sleep
              sleepNow();     // sleep function called here
             }
    }

      if (countsleep >= 10)
      {
          Serial.println("T=m");
          delay(100);     // this delay is needed, the sleep
                          //function will provoke a Serial error otherwise!!
          sleepNow();     // sleep function called here
      }
    }
          void getTemp()
              {
                  int foo, bar;

                  ds.reset();
                  ds.select(addr);
                  ds.write(0x44,1);

                  present = ds.reset();
                  ds.select(addr);
                  ds.write(0xBE);

                  for ( i = 0; i < 9; i++) {
                    data[i] = ds.read();
                  }

                  LowByte = data[0];
                  HighByte = data[1];
                  TReading = (HighByte << 8) + LowByte;
                  SignBit = TReading & 0x8000;  // test most sig bit

                  if (SignBit) {
                    TReading = -TReading;
                  }
                  Tc_100 = (6 * TReading) + TReading / 4;    // multiply by (100 * 0.0625) or 6.25
                  Whole = Tc_100 / 100;          // separate off the whole and fractional portions
                  Fract = Tc_100 % 100;
                  if (Fract > 49) {
                    if (SignBit) {
                      --Whole;
                    } else {
                      ++Whole;
                    }
                  }

                  if (SignBit) {
                    bar = -1;
                  } else {
                    bar = 1;
                  }
                  foo = ((Whole * bar) * 18);      // celsius to fahrenheit conversion section
                  FWhole = (((Whole * bar) * 18) / 10) + 32;
                  if ((foo % 10) > 4) {            // round up if needed
                       ++FWhole;
                  }
                }
    void printTemp(void)
    {
             Serial.println("");
             Serial.print("Temp is: ");
             if (SignBit)
             {
                  Serial.print(" - ");
             }
             Serial.print(Whole);
             Serial.print(" C / ");
             Serial.print(FWhole);
             Serial.print(" F");
    }
    void phvalue()
    {
        int buf[10];                //buffer for read analog
        for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
        {
          buf[i]=analogRead(SensorPin);
          delay(10);
        }
        for(int i=0;i<9;i++)        //sort the analog from small to large
        {
          for(int j=i+1;j<10;j++)
          {
            if(buf[i]>buf[j])
            {
              int temp=buf[i];
              buf[i]=buf[j];
              buf[j]=temp;
            }
          }
        }
        avgValue=0;
        for(int i=2;i<8;i++)                      //take the average value of 6 center sample
          avgValue+=buf[i];
        float phValue=(float)avgValue*5.0/1024/6; //convert the analog into millivolt
        phValue=3.5*phValue+Offset;                      //convert the millivolt into pH value
        Serial.print(" pH:");
        Serial.print(phValue,2);
        Serial.print(" ");
    }

![enter image description here][1]

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

body:
You need to first check the individual current consumption of all elements:

- pH sensor,
- temp sensor,
- water flow sensor
- xbee.

Since many of these just have an output pin in addition to +V & GND, this means those have a permanent current consumption that, overall, may possibly drain your battery.

You should then check the datasheets for all these components and see the minimum current consumption (and conditions for this consumption to be achieved).

If the total minimum current for these components is too high for your system, then you can possibly:

- use an available ATmel digital output pin to power them (and unpower them just before switching the ATmel to low power mode); that's possible only if you stay within current limitations of the MCU (there are current limitation per pin, 20mA IIRC, and total current for the whole MCU)
- if current consumption is above ATmel limits then you can still use the method above but add a MOSFET in-between so that you limit ATmel current consumption

I strongly advise you [this link from Nick Gammon][1], which is comprehensive and complete.

  [1]: http://www.gammon.com.au/power


message:
i2c of Atmega 328 on arduino uno not working

I am using Arduino uno board with Atmega 328 for i2c.
The ic is not showing any clock signal on its SCL line on oscilloscope, The same code when used with different new atmega 328, and same code. It is showing a good clock signal on oscilloscope.

The ic whose i2c is not working can be still programmed and can be used for other purposes like serial communication , adc etc.

So, is there any way by which i can confirm and surely say that i2c of my atmega 328 is fried up. And what can be the possible methods by which it can be fried up.

body: I2C (SDA-SCL) line needs to be pull up (place resistor on both to 5v input from master- the uno), it works with the arduino code for master-slave I2C (uno on master-severino on slave) using the code from arduino website (just be sure you set the address for the slave on the slave sketch (any number 1-126), it works for me that way, my pull up resistor is 10kohm, the same goes for my breadboard, if this is not doing the trick, maybe there's something wrong (I wouldn't know the answer to, just tried the i2c yesterday) update : on august5th (today) I just finished reading i2c's on atmel site, it is a complex one, there are several factors on why something is doing something on your twi comm, post your code, and maybe I have an answer


message:
What's taking up so much RAM in an almost empty sketch?

I wanted to check how much memory (RAM) is used by an "empty" sketch. Here is my code:

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

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

    void loop()
    {
    }

My result was that I have 1839 bytes of free RAM. I have an Arduino UNO, so there are 2048 bytes of RAM in total. Which means that 209 bytes are already taken. Wait, 209 bytes?! I started thinking and figured out that the Serial buffer must take some space. I've opened HardwareSerial.h and found this:

    #if (RAMEND < 1000)
      #define SERIAL_BUFFER_SIZE 16
    #else
      #define SERIAL_BUFFER_SIZE 64
    #endif

I've changed SERIAL_BUFFER_SIZE to 16 to see what will happen. (I've tried decreasing it to 1, but then the serial communication didn't work properly and I wasn't able to display the amount of free RAM). After this modification my result is 1935. So now "only" 113 bytes are taken. But what is taking this memory? HardwareSerial has 2 buffers:

    struct ring_buffer
    {
      unsigned char buffer[SERIAL_BUFFER_SIZE];
      volatile unsigned int head;
      volatile unsigned int tail;
    };

    ring_buffer rx_buffer = { { 0 }, 0, 0};
    ring_buffer tx_buffer = { { 0 }, 0, 0};

So when the SERIAL_BUFFER_SIZE is 16 they take exactly 40 bytes. What is taking the remaining bytes (113-40= **73 bytes**)? I'm aware that stack frames take some memory - calling main() which calls setup() whichs calls freeRam() probably take a few bytes, but 73 still seems too much.

body:
First off, a sketch that uses `Serial` **cannot really be considered an empty sketch** as `Serial` drags along a lot of function definitions, at least one `Serial` class instance (more on Arduino Mega, for instance), plus probably some more global variables...

`sizeof Serial` may be interesting to display as `Serial` is not limited to the TX and RX buffers, as you seem to believe. Its class also has a couple of **additional data members** on its own, plus members inherited from its superclasses, `Stream` and `Print`.

In addition, the Arduino IDE comes with the various "utilities" which you normally can't get rid of, like the **millisecond timer** that uses at least 9 bytes (see reference in `wiring.c` file).

So in the end, even an empty sketch (even without `Serial`) takes some SRAM space for global variables.

I think there is some way, with `avr-size`, to check out, with fine details, the size of data (not accounting for the runtime stack) after the sketch has been fully built.

Arduino IDE already displays some of this static memory information (at the end of "verification").

For example, on my IDE (1.5.8) for Arduino UNO, **a really empty sketch, once compiled is mentioned to use 9 bytes of SRAM**. Actually those 9 bytes are for 3 global variables, used by the millisecond timer. This number, of course, does not account for runtime memory usage, in particular the stack.

Then, **just adding `Serial.begin(9600);` makes it use 182 bytes** (ie 173 more bytes than an empty sketch). So you get the culprit.


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

I investigated this at some length a while back. On [this page about putting constant data into program memory](http://www.gammon.com.au/progmem) I obsessively tracked down every last byte of memory used in a small sketch. This was the sketch:

    #include "memdebug.h"

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      Serial.print (F("Free memory = "));
      Serial.println (getFreeMemory ());
      }  // end of setup

    void loop () { }

memdebug.h came from [Andy Brown - Debugging AVR dynamic memory allocation](http://andybrown.me.uk/wk/2011/01/01/debugging-avr-dynamic-memory-allocation/).

That particular sketch actually used even more RAM:

    Free memory = 1702

So where did the 346 bytes go? Here:

* 34 bytes for the HardwareSerial instance (Serial)
* 64 bytes for the Serial transmit buffer
* 64 bytes for the Serial receive buffer
* 4 bytes for the Serial transmit buffer head and tail pointers
* 4 bytes for the Serial receive buffer head and tail pointers
* 9 bytes for keeping track of millis / micros
* 4 bytes for memory allocation (__malloc_heap_start, __malloc_margin)
* 128 bytes for the heap safety margin
* 6 bytes for a few nested function calls (main -> setup -> getFreeMemory)
* 16 bytes for the compiler vtable for HardwareSerial
* 4 bytes for variables __brkval and __flp (used in memdebug)
* 2 bytes pushed onto the stack in main (to save registers)
* 2 bytes pushed onto the stack in setup (to save registers)
* 4 bytes pushed onto the stack in getFreeMemory (to save registers)
* 1 byte because the stack pointer starts at 0x8FF rather than 0x900

  (That's 346 bytes accounted for)


message:
Android <-> HC-05 <-> Arduino communication issue

My project involves Android (Samsung Galaxy 2) to Arduino (Uno) communication via HC-05.

HC-05 is connected to Arduino on pins 10,11 using SoftwareSerial lib.

I got this setup running for a while and was satisfied by the outcome - my bi-directional communication worked fine.

**Issue:**

I made a change to the communication protocol and now messages sent from Android to Arduino get corrupted. It happens under particular circumstances - when Arduino writes (streams) packets of data to Android and, at the same time, monitors the input from Android for a particular message which signals the end of communication. This message, when read from SoftwareSerial buffer, gets corrupted. This corruption is not consistent - it corrupts the packet in (seemingly) random way.

I've already run many tests and am pretty sure that this message is not corrupted on the Android side.

**Questions:**

 1. Is there anything about HC-05 or SoftwareSerial lib which prevents
    simultaneous bi-directional communication?
 2. Can it be that input/output buffers interfere in some way?
 3. How can I achieve reliable communication using the aforementioned HW and comm scheme?

P.S. I got pretty much code and am not sure what parts of it might be relevant to this issue. Will provide relevant parts per your request.

Thx

body:
Software serial ports are a hack and this is the result - random corruption, missed bytes, etc. The reason is that very precise timing is needed for both receive and transmit and it is very difficult to achieve this with the CPU, especially if you want to simultaneously receive and transmit. The problem is that the CPU has to either read the pin or update the pin at exactly the right moment, and the CPU can't do more than one thing at the same time. You can use interrupts, but it is still possible for the TX and the RX to conflict, and there is nothing you can do about it.

The solution is to either never run RX and TX at the same time, use a different serial protocol where this is not an issue (e.g. I2C), or use a hardware serial port. I would suggest using an Atmel XMEGA microcontroller - you can get these with 6 or more independent hardware serial ports.


body:
As mentioned by @alex.forencich, SoftwareSerial is not designed to support simultaneous bi-directional communication.

I found a link to [AltSoftSerial][1] library on Arduino site, and this lib seems to work properly in my setup.

To convert from SoftwareSerial to AltSoftSerial you need to change the pins that HC-05 is connected to (on Arduino Uno these are pins 8,9), and to make this minor change in the code:

    //#include <SoftwareSerial.h>
    //SoftwareSerial swSerial(10, 11);

    #include <AltSoftSerial.h>
    AltSoftSerial swSerial;

  [1]: https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html


body:
An alternative to software serial is to use hardware serial.

You can use hardware serial (i.e. supported in hardware by the chip) using pins 0 & 1. You will NOT! be able to do serial communications (e.g. programming your arduino) at the same time - I always make sure I have EITHER usb OR bluetooth serial connected at any given time. USB for power is ok.


body:
Another option is to use a separate chip to send and receive. An Attiny87 (picking a random example) has a UART and an SPI interface - it could receive the data via UART, send via SPI to the Arduino; then receive the data from the Arduino and send it via UART. Since the whole chain now has hardware support, you're going to have reliable communications. The data could be buffered on the AtTiny, and raise a signal to the Arduino to say when data is ready.

ATTiny chips are cut-down versions of the ATMega chips used on Arduinos, and they can be programmed over ISP. They can be had for a few dollars.

Yes, this is a lot of extra work.


message:
Resetting an Arduino with a timer

I want to run an Arduino autonomously - but although I apply a watchdog sometimes the systems hangs and can only be restarted by physically interrupting the power-supply (or hitting reset). So I need an external source to do that either after x hrs or based on a condition.

Instead of using another Arduino with a MOSFET or relay I am asking myself if this couldn't be done smarter with a pure electronic component like a timer or a capacitor. I could set a pin of the Arduino on high while it is active and let this charge a capacitor or something similar - if the time/energy exceeds a certain amount (because it hangs) this would connect the reset-pin of the Arduino to ground.

Any idea how this could be achieved and what component should be used?

body:
The following 555 circuit will produce a 170 ms low-going pulse every 24.2 hours.  You can adjust the values of the components using [this calculator][1] if you want different timing parameters.

![enter image description here][2]

Since the reset line of a microcontroller is configured for open-drain (meaning you can connect several inputs to it, which is a good thing since we are taking advantage of that), we need to drive it with a open-drain output.  That is what the buffer on the bottom of the circuit is for, to convert the push-pull output of the 555 to open-drain.  A typical buffer is one section of a 7407.

  [1]: http://www.csgnetwork.com/ne555timer2calc.html
  [2]: https://i.stack.imgur.com/OQj6h.jpg


body:
Here is the circuit I use which depends on a heartbeat from the arduino and resets the arduino if 8 pulses are missed and also enables the arduino code to know that an external watchdog reset occured
![enter image description here][1]

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

    and the Arduino code which can be incorporated into your sketch

    //Watchdog
    #define ResetDetect 8       // watchdog detect pin, HIGH if a watchdog reset has occured
    #define heartbeat 9         // heartbeat pin
    int pulseState = LOW;       // pulseState used to set the heartbeat pin
    long lastbeat = 0;          // will store last time the heartbeat pin was updated
    long HeartBeatFreq = 500;   // interval at which to blink (milliseconds)
    boolean ResetHappened;      // Set to true if a watchdog reset has occurred

    void setup(){
      pinMode(ResetDetect, INPUT);    // set Watchdog Reset sensing pin as input
      digitalWrite(ResetDetect, HIGH);// and turn on pullup
      pinMode(heartbeat, OUTPUT);     // set the heartbeat pin as output:

        // Check if Restarting after Watchdog Reset
        // NB must come before heartbeat resets external counter
        int ResetSet = digitalRead(ResetDetect);
        if (ResetSet == HIGH){
          ResetHappened = true;
        }
        else {
          ResetHappened = false;
        }
    }

    void loop(){

      // Heartbeat resets external watchdog when pin goes high
      if ((long)( millis() - (lastbeat + HeartBeatFreq)) >= 0) {
        lastbeat = millis();
        // if the LED is off turn it on and vice-versa:
        if (pulseState == LOW)
          pulseState = HIGH;
        else
          pulseState = LOW;
        // set the LED with the ledState of the variable:
        digitalWrite(heartbeat, pulseState);
      }
    }

If there are long running sections of code the 'heartbeat' could be put into a function and that function called in the appropriate places to avoid unintended timeouts/resets


body:
Why not use the in-ship watchdog timer ?

I found in the Atmel ATmega328 (used for example in the official Arduino Uno board) official datasheet some references :

    http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet.pdf

We can find on page #5 two blocks named "Watchdog Timer" and "Watchdog Oscillator" on the upper left corner. No need of additional circuits, soldering or any connections.

These blocks are bad documented on the Arduino official website but usable (I did it).

Some docs with code examples :

* http://sysmagazine.com/posts/189744/
* https://tushev.org/articles/arduino/item/46-arduino-and-watchdog-timer

Regards


message:
Concatenate two non constant char arrays in Arduino

I have two non constant char arrays. One is "buff" and other is "buffa". I get values in buffa via rf transmitter of other Arduino and I want to append those data to the data inside of buff. Then I will send all data to other Arduino. So I don't want to send two different char arrays. I want to send them all at once as just one array.

I TRIED SPRINTF BUT IT DOESNT WORK.

    char buffa[144];
        char buff[1000];

    void loop() {

      uint8_t buf[VW_MAX_MESSAGE_LEN];
      uint8_t buflen = VW_MAX_MESSAGE_LEN;

      sprintf(buff,"<status>\n");

        if (vw_get_message(buf, &buflen)) { // check to see if anything has been received
          int i;
          for (i = 0; i < buflen; i++) {
            buffa[i] = (char) buf[i];  // the received data is stored in buffer

          }
        }

      distance1 = getDistance(initPin1, echoPin1);
      sendData(3, distance1);

      sprintf(buff, "%s", buffa);

    delay(5000);
     const char *msg0 = buff;

     vw_send((uint8_t *)msg0, strlen(msg0)); // Send control character
     vw_wait_tx();

     Serial.print(msg0);

    }

body:
Assuming the data in buffa is a c-style string (i.e. null-terminated), replace

    sprintf(buff, "%s", buffa);

with

    strcat( buff, buffa );


message:
Variable current switch by human touch

Two goals:

 1. Make an LED turn on when a person touches two conductive pads (e.g. two square of aluminum foil)
 2. Make the RGB LED change color depending on how hard the pads are squeezed. I will figure out the color algorithm later. For now I just need to be able to sense variable conductivity/capacitance/current (one of those?).

I have an Arduino LilyPad. I know this can be done because I've seen it before (just don't remember the code or circuit). Example image:
![Example image][1]

I know the human body is conductive, so I'm not quite sure why the LED won't go on when I contact the conductive pads. My only hypothesis is that the resistance is too high, but that must mean *some* current is going through, no?

Thanks.

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

body: I am going to make this answer as simple as I can, the body is not THAT conductive, you gotta use something like a touch sensor.


body:
Okay; to start with, the Arduino Playground has a [how-to guide](http://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense), the components are commonplace - either recycle a high-resistance resistor from junk or buy one from eg [Maplin](http://www.maplin.co.uk/p/metal-film-06w-10m-ohm-resistor-m10m) at 38p.

This works as follows:
You charge the capacitor with one output, through a resistor. This charges the capacitor in RxC seconds - C is very small, typically 10^-11 or so, so a decent sized resistor helps make it slow, in computer terms. Ensure this is held on for long enough to charge fully. You can use one charge pin for many touch sensors.

You then drop the charge pin to 0, and see how fast the sense voltage drops; this will be affected by fingers etc, giving a time value reflecting the degree of contact; normally this is used as a threshold on/off, but does allow for some pressure sensitivity. You need one R/C/sense-pin per switch.


message:
Arduino and Raspberry Pi - 5V/3.3V I2C

This topic have been covered in various places, but I still think it hasn't been thoroughly explained anywhere. Doing google search on connecting Arduino to Raspberry Pi via i2c gives for example, this [page][1].

While apparently this should work, there is a factual error there: on arduino side, pins used for i2c do have internal pull ups, and they are activated by `Wire` library.

Digging [further][2], I've found following information:

> However, it turns out that these are weak (high-resistance) pull-ups;
> the Pi has strong pull-ups which dominate those on the Arduino, making
> direct connection safe.

What does safe mean? And how weaker are those pullups compared to raspberry pi ones?

Let's check:

* rpi i2c pullup: 1K8
* arduino i2c pullup: 20K-50K from datasheet (if I'm looking correctly, I'm using ATmega8), though the above page states 10K.

What can I make of those values? My (intuition rather than) basic knowledge hints me something along the lines:

If the i2c is floating, it means the 5V is connected with 3.3V and there are only those pullups along the way, so:

* calculate voltage drop between 5 and 3.3: 1.7V.
* calculate voltage drop across rpi pullup proportionally to voltage drop across arduino pullup:
  1800 / 30000 = 0.06, meaning 0.102V across rpi pullup and 1.598 across arduino pullup, so the actual pulled up voltage is gonna be 3.3V + 0.102V = 5V - 1.598V = 3.402V?

Though I'm pretty sure I'm doing some terrible math here and someone is gonna have good laugh:)

So, my question is not whether it's safe (as it's been proved), but rather *why* is it safe considering the internet resources are inaccurate on this matter.

  [1]: http://blog.oscarliang.net/raspberry-pi-arduino-connected-i2c/
  [2]: http://quick2wire.com/pi-and-arduino-linked-via-i2c/

body:
If you are sure to disable pull up on arduino side you are safe, as i2c works in open-drain mode, but the logic level "high" of arduino is about 3.2v, so it would be unstable.

Otherwise i2c pin of rasp are NOT 5v tolerant, so you must be sure the voltage on the bus does not exceed operative limit; as you calculated ~3.5v should be good on raspi, but please check on datasheet.

Also, you should check the total current on the bus, but as atmega resistor as so high,it should not pose a problem with raspi (but may give problem with passive i2c, that you can solve with a external pull up)


message:
Cannot control servo with button.

I am unable to get a button on my arduino board to control a servo. I'd like the servo to rotate 90 degrees on button push, but it is unresponsive.

Is there a flaw in my code or is it wiring?

    #include <Servo.h>  // servo library

    const int button1Pin = 2;  // pushbutton 1 pin
    Servo servo1; // servo control object

    void setup()
    {
      pinMode(button1Pin, INPUT);
      servo1.attach(9);

      // Set servo 1 to output?
    }

    void loop()
    {
      int button1State;
    int position;

    button1State = digitalRead(button1Pin);

    if (button1State == LOW);
    {
      servo1.write(90);  // move servo
    }

    }

body:
The problem is that `servo1.write(90)` does not do what you think it does.

`servo.write(angle)` tells the servo to go to that position, not to move by that many degrees. What you need is to set one angle when the button is not pressed, and a different angle when the button is pressed.

Normal hobby servos can move about 180 degrees. Where 0 is depends on how the servo horn is positioned. Which direction of rotation is positive depends on the manufacturer.

try something like this to set one position when the button is pressed and a different one when it is not:

    if (button1State == LOW);{
        servo1.write(45);  // move servo
    }
    else {
        servo1.write(135);
    }


message:
What is the best way to establish wireless communication between the Lilypad and a Mac?

I want to build a wearable device for a dancer using the Lilypad and I need to first send the programme from my Mac to the Lilypad board and then transfer the data read by sensors back to my Mac.

I want to know what is the best wireless solution to use here. I've seen various options such:

* the Xbee or Bluetooth modules (http://www.hobbytronics.co.uk/bluetooth-mate-silver)

body:
I have been using a hc-06 module very successfully. http://www.dx.com/p/hc-06-wireless-bluetooth-serial-pass-through-module-for-arduino-works-with-official-arduino-board-238364#.VLg153WjlIc

Connect pins to +5v, Gnd, and digital pins 0 and 1 (rx & tx).

Do not try to connect to USB and this at the same time, as communication will get garbled.


message:
Get the distance to non perpendicular surface

So I'm using the HC-SR04 modules to get the distance to objects, the problem is that if it's not a perpendicular surface I dont get any reading, and I assume that the reason is that the ultrasounds get reflected in another direction, so they don't come back to the sensor. What's the way to get over this issue?

Thanks in advance

body:
You mean to say that you get proper reading when the surfaces are FLAT?
Ultrasonic sensors have this property that the waves emitted from then are only 15 degree from the line of sight, but this means that you can surely calculate distance of objects having a curved shape. The only condition is the object should be directly in a straight line


body:
Coming in late but seeing no solutions offered yet, I'll take a stab at it:

Assume your vehicle is traveling obliquely toward the wall.
Assume you can find and measure the perpendicular distance to the wall.
Then you can calculate the travel distance from those two measurements:

![enter image description here][1]

Next we need to find the angle between the vehicle's heading (center-line) and the perpendicular. A rotating sensor that senses return-signal strength could probably give good results but is mechanically more complicated. Given that the ultrasonic sensors have a somewhat broad sensing angle, 3 or 5 fixed sensors (1 straight ahead and 1 or 2 to either side) may work well enough if you're just trying to avoid hitting the wall. In that case you could measure with all of the sensors, take the least distance measurement as 'p' and the known angle of that sensor as 'theta'.

What's left is to decide how to make the calculation and work with cosines. For the rotating sensor case, you'll have to find the angle of the sensor at the time of it's smallest reading, and look up in a table (or calculate) the cosine of that angle. For the multiple fixed sensors case, you already know the sensors' angles and therefore, their cosines.

If you have enough code memory it would easy to write your calculations in floating point, certainly for some quick and dirty testing. If not, or you need to speed up the calculations, you can do it in fixed point with less code. it's a little bit harder for the programmer but much easier and quicker for the MCU.

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


body:
Use a [Infrared Proximity Sensor][1]
![enter image description here][2]

or

Something like a [LidarLite][3]
![enter image description here][4]

They measures distance by measuring the offset ([parallax][5]) from a projected point of light. This will not suffer from echo restrictions, like Ultrasonic Sensors do.

  [1]: https://www.sparkfun.com/products/242
  [2]: https://i.stack.imgur.com/VWQT3.jpg
  [3]: https://www.sparkfun.com/products/13167
  [4]: https://i.stack.imgur.com/YKvmE.jpg
  [5]: https://en.wikipedia.org/wiki/Parallax


message:
Freeze with VCNL 4000 Proximity Sensor

I've the VCNL 4000 Proximity Sensor I use some sample code and at the very beginning

the following code hangs (never finishes)

     readVCNLByte(0x81); is called

Can this problem be caused because the contact of the pin isn't very good.

I only but the part with pins in the sensor without to solder it.

Is it likely that this may be the problem ? I have not many experince with solder and the sensor is really small so i'd like to avoid it for first tests ;)

Here the code. The last output in the Serial window is "pre product"

      Serial.println("VCNL");
      Wire.begin();
      Serial.println("pre product");
      uint8_t rev = read8(VCNL4000_PRODUCTID);
       Serial.println("post product");
      if ((rev & 0xF0) != 0x10) {
        Serial.println("Sensor not found :(");
        while (1);
      }

![Before][2]

![After][3]

![enter image description here][1]

  [1]: https://i.stack.imgur.com/prnZ1.jpg
  [2]: https://i.stack.imgur.com/jcIwU.jpg
  [3]: https://i.stack.imgur.com/2MBZ0.jpg

body: You really can't expect this to work unsoldered. The contacts will be at best intermittent, and poor contact. Even a 'dry joint' where the pin is mostly surrounded by solder doesn't work well, these are the ultimate examples! You could however use an edge-connector, if you can find one; not something you see often nowadays.


body:
Sorry .. my answer comes late ..
I had the same issue, this has nothing to do with bad connexion between wires (not only at least).
But by playing with some parameter (current value > 60mA) I noticed that the module begin to freeze more often.
To fix that :
You need to add a small delay within your readbyte function after a i2c.stop()

I found that an issue had been written about that : https://github.com/adafruit/VCNL4000/issues/1
They recommand a 170us delay

I'm testing myself at full current and max speed (an since 30min it didn't freeze)... Before it could freeze in a second.

Hope it helps ;)

----------------
EDIT :
In order to better understand where the freeze comes from, I re-write a simple I2C library. I could get rid of the freeze by simple add a small delay in the i2c_start function (that send the start condition along with the slave address)

    uint8_t i2c_start(uint8_t i2c_slave_address){
           //reset TWI control register
           TWCR = 0;
           //transmit start condition
           TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
           //wait for end of transmission
           while((TWCR & (1<<TWINT))==0){
                  _delay_us(75); // <-- here is the trick
           }
           if( (TWSR & 0xF8)!= TW_START ){
                  return -1;
           }
           // load slave address into data register
           TWDR = i2c_slave_address;
           //start address transmission
           TWCR = (1<<TWINT) | (1<<TWEN);
           //wait for transmission
           while ( (TWCR & (1<<TWINT))==0 );
           //check if the slave did acknoledge the Read/Write mode
           uint8_t twst = TW_STATUS & 0xF8;
           if ( (twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK) ){
                   return -1;
           }
           return 0;
    }

you will need to add these libraries :
util/twi.h (for the macro TW_STATUS .. TTW_MT_SLA_ACK and so on)

util/delay.h

stdlib.h (for the uint8_t way of typing variable ..not actually 100% sure)

I'm still not fully satisfy by this solution, but it is still more effective that the one that adafruit propose.

I suggest you write you own i2c library (5 functions : init / start / read / write / stop) you now have the start already .. so 4 left ;)

If you're still to much afraid : in twi.c ( .\arduino\avr\libraries\Wire\utility\twi.c) and twi_readFrom(...) function.
On line 155 and 159 you will see that arduino send the start condition, but do not wait / take care that the transmission as been done... you can add a while function as previously describe to ensure it.

------------------------------
MASTER EDIT :

My previous solution didn't solve the issue neither...
Actually reading the application note (Designing VCNL4000 into an Application : google that)
gives the solution (page 7) [![enter image description here][1]][1]

after you send the command to perform a single measurement, you need to wait.
I put a delay of 500ms and have none anywhere else. This works like a charm.

But for energy efficiency I recommend to put the uC in sleep mode for that period of time.

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


message:
DS3231 DTCXO and GPS

I am experimenting with this idea: keep a DTCXO in sync with some frequency standard. I have all the parts I can afford, but I cannot figure out a way to do it.

Parts I have: Arduino Leonardo, a `u-blox 6010` based GPS module with PPS output, and a proto shield with `DS3231` DTCXO chip mounted.

My big idea is that `DS3231` have aging registers that would affect the clock frequency. By keep counting the 8192Hz square wave output of `DS3231` and keep it in sync with the 1Hz signal from the GPS module, I can keep the DTCXO in sync with a reference clock. This, in turn, would give me a relatively good 32768Hz clock reference that I can build a frequency counter on.

Both 8192Hz and PPS are interrupt driven.

Anyone have an idea on how to do it? Does this spell Artificial Intelligence on AVR, as my instructor suggests?

body:
Hope you get this.  Trimming the aging compensation in the DS3231 is not worth the trouble.  You won't significantly improve the temperature accuracy or aging drift due to the crystal used, etc.
On the other hand, 10MHz Double Oven Reference Oscillators are available for under $50 on EBAY.  These are good to 2x10-12 short-term, or about 1x10-6 yearly drift.  For timekeeping purposes, you can ignore the short-term drift, could not measure it anyway :).  On the other hand, the aging drift will be large because you do not know how long these have been in service.  The good news is that aging drift is very stable if temperature is kept constant, the reason for the double ovens. So once you determine how far off frequency the OCXO is, you just periodically add a count to your divider during one period to keep it synched to the GPS signal.  For more info write mhuss103athotmaildotcom


message:
Emergency! INO file disappeared on computer. Still on Arduino!

For some reason, my Arduino program has disappeared from my computer, and it was a really long, complex program. It is currently still on my arduino, and I HAVE to get it back. Please, someone help me. Arduino UNO, Macbook Pro.

Edit: Perhaps I wasn't clear. I need the INO file back FROM MY ARDUINO.

body:
The .ino file is lost, however, your Arduino IDE uses your `%temp%` to store immediate data.

Look in `%temp%`, folders akin to `build116193871148509168.tmp` contain build files. The original ino is not there, but I remember the `cpp` files generated by IDE should be there.

Some info about how to find the `temp` on Mac: https://stackoverflow.com/questions/11607834/where-are-the-hex-files-compiled-by-arduino


body:
Your INO file is not (ever) on your Arduino.

When you "upload your sketch" to the Arduino, it is first compiled. Your Arduino cannot interpret a sketch directly, and there are various processes which convert your sketch into machine code. This process is not practically reversible.


message:
Multiple 7 segment displays blinking

i just set up 2 displays ( 3 digit 7 segments ), and the displays seems to be blinkin ( i know they are suppose to blink but so fast that the human eye cannot detect it ).

I'm using the SevSeg Library and this is how my code looks:

    void setup() {

       byte numDigits = 3;
       byte digitPins[] = {2, 3, 4};
       byte segmentPins[] = {5, 6, 7, 8, 9, 10, 11, 12};
       sevseg1.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);

       byte digitPins2[] = {14, 15, 16};
       byte segmentPins2[] = {17, 18, 19, 20, 21, 22, 23, 24};
       sevseg2.begin(COMMON_ANODE, numDigits, digitPins2, segmentPins2);

    }

    void loop() {

      while(true){
         sevseg1.setNumber(number,0);
         sevseg2.setNumber(number,1);
         sevseg1.refreshDisplay();
         sevseg2.refreshDisplay();
      }
    }

I need to add 2 more 3 digits 7 segment displays so i was wondering what is it that is causing the blinking.

Im using Arduino Mega.

body:
First of all, you have a `while(true)` in your loop, that makes no sense. The loop already loops for ever.

You are also changing the number every time the `loop()` is run, making it flicker. If you follow the Arduino library example, you can see they only use `setNumber` every so often and use `refreshDisplay` every time the code runs through the `loop()`.

Also, you didn't `setBrightness`, which shouldn't be a problem since the library probably sets a default value, but I'd advise on including it in your code to eliminate unforeseen problems.

Try this code and let me know if it works:

    #include "SevSeg.h"

    SevSeg sevseg1; //Instantiate a seven segment controller object
    SevSeg sevseg2;

    void setup() {
      byte numDigits = 4;
      byte digitPins1[] = {2, 3, 4, 5};
      byte segmentPins1[] = {6, 7, 8, 9, 10, 11, 12, 13};
      byte digitPins2[] = {14, 15, 16};
      byte segmentPins2[] = {17, 18, 19, 20, 21, 22, 23, 24};

      sevseg1.begin(COMMON_ANODE, numDigits, digitPins1, segmentPins1);
      sevseg1.setBrightness(90);

      sevseg2.begin(COMMON_ANODE, numDigits, digitPins2, segmentPins2);
      sevseg2.setBrightness(90);
    }

    void loop() {
      static unsigned long timer = millis();
      static int deciSeconds = 0;

      if (millis() >= timer) {
        deciSeconds++; // 100 milliSeconds is equal to 1 deciSecond
        timer += 100;
        if (deciSeconds == 10000) { // Reset to 0 after counting for 1000 seconds.
          deciSeconds=0;
        }
        sevseg1.setNumber(deciSeconds, 1);
        sevseg2.setNumber(deciSeconds, 1);
      }

      sevseg1.refreshDisplay(); // Must run repeatedly
      sevseg2.refreshDisplay(); // Must run repeatedly
    }


message:
Possible arduino burned (5V shorted to Vin), explanations and suggestions

Please apologize my english.
I am working in a project using an original arduino uno, one generic servo (no factory marks) and one HC-SR04 sensor.

I make a circuit like the one here: http://s24.postimg.org/43jra5l9h/mycircuit_bb.png ([url=http://postimg.org/image/lgu1p0gkh/][img]http://s24.postimg.org/lgu1p0gkh/mycircuit_bb.jpg[/img][/url], sorry, upload of image not allowed due reputation)

As you can see from the picture I accidentally connected green into Vin instead of GND. (If the image won't load, that means that my positive is connected to arduino 5V and the ground of the circuit is connected to arduino Vin)

Now my board turn on the lights but I am unable to execute the program already in the microcontroller as aslo I cannot upload a new program to it. (It gives some error message of failed to connect).

I think I burned the microcontroller(mc) by short circuiting 5V and Vin.

That said, I have three questions:

1 - Is there any way to find out if I really burned my board using just a low budget multimeter? And if I did, which parts I need to replace?
I have access to some spare ATMEL mc and I think I could replace and reprogram them by using another arduino board. However, I am affraid that I may have burned few other items and just by replacing the mc will not give me back all the funcionallities of a new board.

2 - I have basic knowledge of electronics, could someone explain to a beginner like me which impact did that mistake could/have make in all components of the circuit? (Arduino board, the servo and the sensor)

3 - Even before the accident, the circuit just work well for few minutes. I read tons of pages and tried a lot of suggestions, most of them related with power supply (capacitors to avoid flutuations, One battery just for the servo, one battery just for the sensor...) and none gave me good results.
I am wondering what are the alternatives to power up this simply circuit, in particular I am looking for this possibilities: Complete external power supply (by using AC to DC adapters), Complete internal power supply (Using just batteries) and a mix of those two (Using AC to DC and batteries). I have no access to a external DC power supply generator other than batteries.

body:
If you have another Uno then your best bet is either:

1) Swap the suspect processor into the known good board, test it.

2) to buy a replacement chip (ATMega 328-PU), use [this link](http://arduino.cc/en/Tutorial/ArduinoISP) to flash it, if it works you win, if not you can at least use the new processor again.

I have done this myself & it worked well, it isn't easy to be sure any other way as the chip needn't fail in a predictable manner. The chances are it will take a large current if it's dead, until it burns out & goes open circuit. Once the magic smoke has come out you know it's dead... the Arduino power supply is reasonably capable of looking after itself so your chances are good.


message:
Problems stacking Arduino Shields

I'm trying to stack the Adafruit Data Logger Shield https://learn.adafruit.com/adafruit-data-logger-shield/overview onto a CuteDigi Sim900 GPRS Shield so that I can upload data (collected eventually by a GPS breakout) to a server at certain intervals.

The problem is that I can't seem to get the two shields to play nicely together. I'm a beginner with the Arduino and electronics in general, so hopefully this is just a noob issue.

When I power on the GPRS Shield, the data logger stops outputting the Date/Time to the serial monitor. And when I turn the GPRS Shield off, the serial monitor continues again and shows the Date/Time from the data logger.

They don't share any pins that I'm aware of, and I've tried connecting a 7.4V li-po for external power with no success.

Any help is greatly appreciated!

body:
Make sure you are using a software serial port for the GPRS shield.

If you aren't using the software serial port, then you are probably running into an issue with trying to read data over the only UART (serial) port while two devices are tryiing to use it.

It looks like there are two jumpers next to D0/D1 on the GPRS shield, I can't tell but I think if you remove those, the shield will use software serial over D7/D8.  If you do this, you'll have to code your program to use a software serial.  [This wiki page on the GPRS shield][1] if you need help with that.

  [1]: http://linksprite.com/wiki/index.php5?title=SIM900_GPRS/GSM_Shield


message:
How to send data from a smartphone to Arduino

My goal is to build an extremely low cost quadcopter, by using the sensors of my smartphone (it will be mounted on the quadcopter). The arduino will only control the speed of each motor, as received from the smartphone. What methods exist to transfer data from a smartphone to arduino?

My first idea was to simply use USB, but it turns out that my smartphone doesn't support the USB host mode. Is it possible to send data over USB without USB host mode? What alternatives do I have? I thought of using the audio port: Can I directly connect an audio channel to analog in?

body:
I have been using a bluetooth module - they can be had for just a few dollars (depending on which country you're in). I've got an HC-06 which works great : http://www.dx.com/s/hc-05

It has 4 pins: VCC (connect to +5V on Arduino), GND, RX and TX (connected to RX and TX, digital pins 0 and 1 on the Arduino).

You will probably not be able to use Bluetooth and USB at the same time - both will be sending to the Arduino at the same time, and the communications will get garbled.

I have an app called "Bluetooth Serial Controller", which lets me send commands over bluetooth.

If using this, think carefully about what will happen if your phone goes out of range of your arduino.


message:
Simple word translator, return error: invalid array assignment

I know this is not a good question. But I am clueless with this error : invalid array assignment (at function convert). For extra information, I involved a lot of copying/pasting programs I haven't exactly understand from internet in the convert function (the strncpy ones) so.. yeah.

This is the program I've done (the menu/mn button currently not used):

    #include <LiquidCrystal.h>
    #define WORD 11
    #define LETTER 15
    LiquidCrystal lcd(7,6,5,4,3,2);
    int i=0;
    char input[] = "a";
    char output[15];
    const int dw = 8;
    const int ri = 9;
    const int le = 10;
    const int up = 11;
    const int ok = 12;
    const int mn = 13;
    int checker = 0;
    int bounceCk = 0;

    int bdw=0, bri=0, ble=0, beu=0, beo=0, bem=0;

    void setup()
    {
      pinMode(dw, INPUT);
      pinMode(ri, INPUT);
      pinMode(le, INPUT);
      pinMode(up, INPUT);
      pinMode(ok, INPUT);
      pinMode(mn, INPUT);
    }
    void intext()
    {
      int lim=16;
      lcd.setCursor(0,1);
      lcd.print(input);
      for(i=0; i<lim ; )
      {
        lcd.setCursor(0,1);
        lcd.print(input);
        if(digitalRead(dw)==HIGH)
        {
          checker=digitalRead(dw);
          delay(100);
          bounceCk=digitalRead(dw);
          if(checker==bounceCk)
          {
            if(input[i]>'z')
              input[i]='a';
            input[i]=input[i]+1;
          }
        }
        if(digitalRead(up)==HIGH)
        {
          checker=digitalRead(up);
          delay(100);
          bounceCk=digitalRead(up);
          if(checker==bounceCk)
          {
            if(input[i]<'a')
              input[i]='z';
            input[i]=input[i]-1;
          }
        }
        if(digitalRead(ri)==HIGH && i<16)
        {
          checker=digitalRead(ri);
          delay(100);
          bounceCk=digitalRead(ri);
          if(checker==bounceCk)
          {
            i=i+1;
          }
        }
        if(digitalRead(le)==HIGH && i>0)
        {
          checker=digitalRead(le);
          delay(100);
          bounceCk=digitalRead(le);
          if(checker==bounceCk)
          {
            i=i-1;
          }
        }
        if(digitalRead(ok)==HIGH)
        {
          checker=digitalRead(ok);
          delay(100);
          bounceCk=digitalRead(ok);
          if(checker==bounceCk)
          {
            lim=i;
          }
        }
      }
    }
    void convert()
    {
       char sumber[WORD][LETTER] = {{0}};  /* declare a progmem unsigned static array of kata x huruf */
       char dasar[WORD][LETTER] = {{0}};  /* declare a progmem unsigned static array of kata x huruf */

      /* copy various strings to statically declared storage SUMBER */
      strncpy (sumber[0],"memakan", strlen("memakan")+1);
      strncpy (sumber[1],"makanan", strlen("makanan")+1);
      strncpy (sumber[2],"menyuci", strlen("menyuci")+1);
      strncpy (sumber[3],"perubahan", strlen("perubahan")+1);
      strncpy (sumber[4],"penulisan", strlen("penulisan")+1);
      strncpy (sumber[5],"tercampurkan", strlen("tercampurkan")+1);
      strncpy (sumber[6],"pengelompokan", strlen("pengelompokan")+1);
      strncpy (sumber[7],"pengembangan", strlen("pengembangan")+1);
      strncpy (sumber[8],"kehebatan", strlen("kehebatan")+1);
      strncpy (sumber[9],"memotret", strlen("memotret")+1);
      strncpy (sumber[10],"melakukan", strlen("melakukan")+1);

      /* copy various strings to statically declared storage DASAR*/
      strncpy (dasar[0],"makan", strlen("makan")+1);
      strncpy (dasar[1],"makan", strlen("makan")+1);
      strncpy (dasar[2],"cuci", strlen("cuci")+1);
      strncpy (dasar[3],"ubah", strlen("ubah")+1);
      strncpy (dasar[4],"tulis", strlen("tulis")+1);
      strncpy (dasar[5],"campur", strlen("campur")+1);
      strncpy (dasar[6],"kelompok", strlen("kelompok")+1);
      strncpy (dasar[7],"kembang", strlen("kembang")+1);
      strncpy (dasar[8],"hebat", strlen("hebat")+1);
      strncpy (dasar[9],"potret", strlen("potret")+1);
      strncpy (dasar[10],"laku", strlen("laku")+1);

        /* mencari input pada sumber */
      int k=0, search=0, sel=9;

      while(search==0)
      {
        sel=strcmp(input, sumber[k]);
        if(sel==0)
        {
          output[]=dasar[k]; //!!!!THE ERROR IS HERE!!! happen to either this or output=dasar[k]
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Base Word:");
          lcd.setCursor(0,1);
          lcd.print(output);
          search=1;
        }
        else
        {
          k=k+1;
          if(k>=11)
          {
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Error:NF");
            lcd.setCursor(0,1);
            lcd.print("word n found");
            search=1;
          }
        }
      }
        /*
        //print the values
        while (*sumber[i])
         printf ("  %s\n", sumber[i++]);
        */

    }
    void loop()
    {
      lcd.begin(16,2);
      lcd.setCursor(0,0);
      lcd.print("Type your word:");
      intext();
      convert();
      delay(15000);
    }

I found more errors before, I've fixed those, but can't fix this one. I think this problem is caused by the wrong instruction or wrong format. But can't found solution...yet.

The program is converting words to its basic word in Bahasa, you can compare it to English like this. You type "eaten" and it will return "eat". You type "understood" it will return "understand". When you type "stunk" it will return "stink". Or something like that.

Example in bahasa :

"memakan" (eating) -> "makan" (eat)

"makanan" (food) -> "makan" (eat)

"pengembangan" (development) -> "kembang" (becoming bigger/better)

etc

I hope someone will give me a clear hint or two (I'm not too bright, but I still need to learn how not just copying things around),
Thank you very much!

body:
Just replace the line in error with:

    strcpy(output, dasar[k]);


body:
It looks like you're trying to copy the contents of a particular sub-array in `dasar` across to the `output` array. However, this isn't valid in C/C++:

    output[]=dasar[k];

To copy data from one array to another, you either need to copy each element one-by-one (e.g. in a loop), or use a block memory operation like `memcpy`.

Here's how I would do it:

    memcpy(output, dasar[k], sizeof(output));

This should work because arrays are basically just pointers in C/C++. It uses the start of `output` as the destination of the copy, and uses the start of `dasar[k]` as the source. The number of bytes it copies is taken from the total size of the `output` array.


message:
Reading the audio signal from a smartphone

i want to read the audio signal from my smartphone.
Can i just cut a headphonewire and connect it to the analog in? (Arduino uno)
I sadly dont know much about electronics.

greetings

body:
No. It partly depends on the phone, but most put out a low voltage AC signal. This would drive the Arduino inputs negative. You can do this by biassing the input at the mid point (+2.5V) and feeding audio in via a capacitor. There are many projects which use similar to record audio.

PS I would not recommend cutting a headphone cord. The wires are very fine, and almost impossible to solder. If you want to do this make a custom cable.


message:
How can Arduino source code be tested automatically (continuous integration)?

I'd like manage my Arduino source code (projects and libraries) under source control with continuous testing. How can I automatically compile the code with continuous integration tools, to make sure each version compiles cleanly? In the best case one should be able to configure builds for multiple processors, optionally run unit tests and check for maximum binary size.

body:
Newest version of Arduino ide has a command line interface to build and upload code. But you can obviously do it by makefile and avrdude.
Now, you have compiled your code BUT you need testing.
As simulator are complex,incomplete, expansive and.. Just a simulation, and because the chip are relatively cheap, building a board witch will make HW interaction AND check the results its the fastest and easiest way.
On that "special" board you may upload something like an interpreter witch take a test from the PC and execute it, something similar to firmata for arduino.
At least that is how I would build it.
And as far as I know there are no know implementation of this, even if I'm quite sure many industries should and probably do that.


body:
One example of setting up Jenkins continuous integration for Arduino project can be found here: [Continuous integration for embedded systems][1]

The example shows how to build and upload image to Arduino and execute Selenium web tests (the system under test is Arduino-based web-server).

  [1]: http://jperala.fi/2015/02/20/setting-up-continuous-integration-for-embedded-systems/


body:
As the creator of [PlatformIO][1] I would recommend you to look into it. It's a cross-platform code builder and missing library manager. It can build the same code for the many popular embedded development platforms and boards.

PlatformIO can be be integrated with many popular [Continuous Integration (CI)][2] systems (or your own). See [documentation with examples][2].

Let's look into ``.travis.yml`` config/template for Travis CI:

    language: python
    python:
        - "2.7"

    env:
        - PLATFORMIO_CI_SRC=path/to/source/file.c
        - PLATFORMIO_CI_SRC=path/to/source/file.ino
        - PLATFORMIO_CI_SRC=path/to/source/directory

    install:
        - python -c "$(curl -fsSL https://raw.githubusercontent.com/platformio/platformio/master/scripts/get-platformio.py)"

    script:
        - platformio ci --board=TYPE_1 --board=TYPE_2 --board=TYPE_N

Example
-------

Integration for `USB_Host_Shield_2.0` project. The `.travis.yml` configuration file:

    language: python
    python:
        - "2.7"

    env:
        - PLATFORMIO_CI_SRC=examples/acm/acm_terminal
        - PLATFORMIO_CI_SRC=examples/Bluetooth/WiiIRCamera PLATFORMIO_BUILD_FLAGS="-DWIICAMERA"
        - PLATFORMIO_CI_SRC=examples/ftdi/USBFTDILoopback
        - PLATFORMIO_CI_SRC=examples/Xbox/XBOXUSB
        # - ...

    install:
        - python -c "$(curl -fsSL https://raw.githubusercontent.com/platformio/platformio/master/scripts/get-platformio.py)"

        # Libraries from PlatformIO Library Registry
        # http://platformio.org/#!/lib/show/416/TinyGPS
        # http://platformio.org/#!/lib/show/417/SPI4Teensy3
        - platformio lib install 416 417

    script:
        - platformio ci --board=uno --board=teensy31 --board=due --lib="."

* Configuration file: https://github.com/felis/USB_Host_Shield_2.0/blob/master/.travis.yml
* Build History: https://travis-ci.org/felis/USB_Host_Shield_2.0

  [1]: http://platformio.org
  [2]: http://docs.platformio.org/en/latest/ci/index.html


body:
I would advice to use the arduino eclipse plugin named sloeber [sloeber.io][1] of which I'm the project lead.
It integrates with version control and allows building on multiple platforms as it supports multiple configurations.
Though it is not yet idiot proof I have documented and demonstrated using unit testing of arduino code on the local pc using the google test framework.
Here is a link to a blog containing a presentation of how you can do it. [http://blog.baeyens.it/#post25][2]

  [1]: http://sloeber.io
  [2]: http://blog.baeyens.it/#post25


body:
I wrote this test [unittest][1] framework for Arduino, since i could not find proper existing. While i did not write it for CI, it would be good fit for CI job, since it requires no hardware but can be ran on PC.

Running the CI jobs without the hardware has good sides and bad sides, good sides beeing that

 - No flashing, no hardware needed -> can be runned in parallel -> fast to check for example for every commit
 - No hardware issues influencing the tests -> no need to worry did this test just fail because my XYZ-hardware component is not stable

On the downside there is:

 - Its not testing the actual target code, for example your 'int' is 32 bits in your PC and 16bits in AVR.

[1]: https://github.com/susundberg/arduino-simple-unittest "arduino simple unittest"


body:
I've just put together [a decent size writeup as an answer to this related question](https://stackoverflow.com/a/49161903/2063546) about [an Arduino CI/unit testing framework I wrote](https://github.com/ifreecarve/arduino_ci) that's finally mature enough to start talking publicly about.

The `arduino_ci` ruby gem supports both local testing and Travis CI integration (e.g. [this build job for the Adafruit FONA library](https://travis-ci.org/adafruit/Adafruit_FONA/builds/350489990)).

Some examples of how it integrates:

* The [DoSomething example library](https://github.com/ifreecarve/arduino_ci/tree/master/SampleProjects/DoSomething) shown above, used to test arduino_ci itself
* A practical example, [testing a Queue implementation](https://github.com/sdesalas/Arduino-Queue.h/pull/1/files)
* A complex example, simulating a library that controls an interactive device over a SoftwareSerial connection as part of the [Adafruit FONA library](https://github.com/adafruit/Adafruit_FONA/pull/91/files)

I have [an issue created for reporting sketch size](https://github.com/ifreecarve/arduino_ci/issues/14) but no work has been done on that.  It's also possible that I could parallelize the builds someday, but at the moment I'm not precisely sure how I'd do that.  Right now, the  most time consuming build step on Travis CI is downloading the Arduino IDE... parallel testing won't put much of a dent in that if every job needs to do that step.


message:
Op Amp Understanding + Holiday Lights Tutorial

I am following Jeremy Blum's tutorial for Holiday Lights: http://www.jeremyblum.com/2011/12/25/tutorial-14-for-arduino-holiday-lights-and-sounds

I am just trying to set up the circuit for one of the audio channels. I believe I followed the breadboard schematic. However, when I connect the Arduino the power, but without any audio input, the LED lights up. I would've thought that would not be the case.

Can someone help me correct my understanding here? Thanks.

Image of my breadboard: http://postimg.org/image/ibqfvezqp/

body:
Per Jeremy Blum:

>If the input doesn’t have a audio input plugged in, then it’s said to be “floating” and you >can’t really count on the circuit to do what you would expect. The audio input connection >introduces a known voltage (0 when no sound is playing) connection between the positive op->amp input and GND that we then amplify. Try connecting the input to GND and you should see >the LED turn off.

Source: http://www.jeremyblum.com/2011/12/25/tutorial-14-for-arduino-holiday-lights-and-sounds/comment-page-2/#comment-1373392


message:
Question about viability of building a Bill Counter machine

I have a need for a bill counter at my current job, but besides counting bills we also could use a machine to count admission cards.

The idea is to either buy a bill counter machine (like those that the Banks have), or make one from scratch by buying the parts.
Besides the bill counting feature i wanted to make it so that it also counts the certain number of cards, and check if they are either stamped or not.

My question is:

Is this possible?

If so, is it easier to just buy a arduino and use it with other parts (sensors, moving gears etc etc), or to buy a bill counter and just "crack" the OS?

Any insight would be appreciated!

PS: I am a 1st year Computer Science student, but i have 0 experience in programming in Arduino

body:
There are many more things to consider than just put some parts together if you try to build a counter from scratch. Automated currency handling has come a long way to today's bill counters or any vending machines. You may perfectly handle the computing part of task with an embedded system like the arduino, but paper handling is an art of itself.

If you think of this task as a challenge to acquire and hone engineering skills, go ahead. It may be one of the best training tasks one can think of. But while you may learn a lot from this conundrum, you will propably end up without an usabale device. :)

You have to consider, there are subtasks in

 - mechanics
 - electronics
 - programming

which may include

 - paper handling (separation, traction, alignment)
 - pattern recognition
 - motor control
 - high speed sensors
 - signal detection and processing
 - error and fault processing and handling
 - motor and gear connection
 - bearings and mechanical substructure
 - user interface

and many more.

To modify an existing device solves a lot of mechanical problems in advance. But it may still be difficult to change the firmware of a bill counter to your needs.

You will have to

 - break into the system (may be impossible)
 - reverse engineer the firmware
 - understand the mechanical constraints
 - find a way to adapt the system to your needs.

A third way, which in my eyes is rather intriguing, is to take an existing bill counter, rip out the controller and try to plug in your own controller, e.g. an arduino. This gives you a real chance to reach your goal while still having the opportunity to learn a lot.


message:
Serial Data through Pin 13 LED

I am looking to utilize Pin 13 and an external LED to flicker as either the Rx or Tx LEDs do when Serial data is transferred through the Arduino. The existing code is all in real time to function with external buttons, so there can't be any delay.

I came across this link which seems useful, but I can't quite get it to read from Serial:

http://arduino.cc/en/Tutorial/BlinkWithoutDelay

Thanks in Advance

body:
If you are going to use an external LED, then using software to make the LED blink when the RX or TX line is busy is a waste of your CPU.

Instead, simply connect the LED to the RX or TX line using a transistor as a buffer to prevent the current draw from messing with the serial signal.

To borrow an image from [this answer][1] to [a similar question][2]:

![enter image description here][3]

You can try omitting the transistor buffer, but the serial waveform will be altered, possibly to the point where data becomes corrupted. The transistor prevents the current draw of the LED and resistor from loading down the RX or TX lines.

  [1]: https://electronics.stackexchange.com/a/42589
  [2]: https://electronics.stackexchange.com/questions/42581/attaching-a-led-to-pics-rx-pin
  [3]: https://i.stack.imgur.com/boiiA.gif


message:
Serial.write and Serial.println return different values? Cannot use correct ones

I have a text file on an SD card, and I am trying to print the lines to the serial monitor.

This Code Works:

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

    File myFile;

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

      Serial.print("Initializing SD card...");

      pinMode(10, OUTPUT);

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        return;
      }
      Serial.println("initialization done.");

      myFile = SD.open("c.txt");
      if (myFile) {
        Serial.println("c.txt:");

        while (myFile.available()) {
          Serial.write(myFile.read());  //THIS LINE RIGHT HERE
        }
        myFile.close();
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening c.txt");
      }
    }

    void loop()
    {
    }

However, if I replace the line `Serial.write(myFile.read());` with `Serial.println(myFile.read());`, then the code doesn't return the correct lines.

It should return numbers similar to this (albeit 3000 of them):

    564
    564
    564
    564
    564
    564
    564
    464
    564
    664
    564

If I use `Serial.println` it returns numbers like this (and it doesn't stop at 3000 lines):

    13
    10
    54
    54
    52
    13
    10
    53
    54
    52

And if I try to do `int(myFile.read())` then the integer becomes the wrong numbers (returned by `println`), not the right ones (returned by `write`).\

How do I get a number returned by `Serial.write(myFile.read());` to be an integer?

body:
The text file contains the sequential ascii values that spell out the data, not binary data. `println` in printing the numerical value of each byte. For example, the 10's `println` prints are '\n' characters. `write` is printing the ascii character associated with the binary value (the new line). You need to parse the ascii characters into numbers.

Luckily for you the SD library inherits from the `Stream` class, so it will have the same `parseInt` function most often used to parse ints from the serial monitor.

You probably want to set `myFile.setTimeout(0)` first because the file isn't slowly getting characters from the serial bus, so the timeout would just slow you down.

Then you should be able to parse and print out the ascii integers with something like this:

    int val = myFile.parseInt();
    Serial.println(val);


message:
Where can I find a better pinout diagram for "Arduino Ethernet" board?

I'm looking for a complete pinout of the [Arduino Ethernet R3][1].
I've found one [here][2] which is low quality, and seems not complete (where are the digital I/O pins?).

![enter image description here][3]

BTW, it was not a good idea for Arduino to name this board "Arduino Ethernet", as this is pretty useless for searching online :-(

  [1]: http://arduino.cc/en/Main/arduinoBoardEthernet
  [2]: http://f1mvp.perso.sfr.fr/Robotic/arduino.htm
  [3]: https://i.stack.imgur.com/9mk4A.jpg

body:
The [formal Arduino.cc website][1] mentions, somewhat obscurely, that the Arduino Ethernet is pin compatible with Arduino Uno:

> The Revision 3 of the board introduces the standardized 1.0 pinout

Except for pins 10-13:

> Pins 10, 11, 12 and 13 are reserved for interfacing with the Ethernet
> module and should not be used otherwise. This reduces the number of
> available pins to 9, with 4 available as PWM outputs.

The other difference is the onboard LED is connected to pin 9 rather than the Uno's pin 13:
>On most other arduino boards, this LED is found on pin 13. It is on pin 9 on the Ethernet board because pin 13 is used as part of the SPI connection.

You can use any Arduino Uno pinout diagram as a reference, the [one you have found][2] seems to be pretty elaborated.

  [1]: http://arduino.cc/en/Main/arduinoBoardEthernet
  [2]: http://marcusjenkins.com/wp-content/uploads/2014/06/ARDUINO_V2.png


body:
That's a better one from :

https://pinoutguide.com/images/arduino/ethernet.png

This one also presents the Arduino Ethernet R3 board and
has the extra I2C pins (SCK=A5,SDA=A4) next to the AREF pin.

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

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


message:
Can I replace Atmega8 with Atmega328 in my freeduino board?

If so, let me know the steps needed.

body:
Shouldn't be a problem. Some later versions already have a ATMega168 instead of the ATMega8. All three are pin-compatible.

In the arduino IDE you should however select a different board (one with a 328, like the UNO). That way the compiler knows the target MCU is the 328, and not the 8.


message:
data type error on sensor data to ethernet client

I'm having a hard time debugging this piece of code, and i'm hoping someone can point out where i am making the mistake.

My serial output is:

    connected
    GetData()
    got data...
    next stage...

I've tested with a simple network client that loops sending a hello world, and it works fine. Every time this code halts after attempting to send a value to the `client`. I know that  `getData()` is causing the issue, but i cannot work out why, or how to best resolve it.
(apologies for the code dump, i want to be thorough)

    #include <LiquidCrystal.h>
    #include <dht11.h>
    #include <SPI.h>
    #include <Ethernet.h>
    dht11 DHT11;
    #define DHT11PIN 8

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    IPAddress server(192,168,1,100);
    IPAddress ip(192,168,1,50);
    EthernetClient client;

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    const int trigPin = 6;
    const int echoPinOne = 7;
    const int echoPinTwo = 8;
    const int echoPinThree = 9;
    const int echoPinFour = 10;

    void setup() {
      lcd.begin(16, 2);
      Serial.begin(9600);
      delay(1000);

      //Network
     if (Ethernet.begin(mac) == 0) {
        Serial.println("DHCP FAIL");
        Ethernet.begin(mac, ip);
      }
      delay(1000);
      Serial.println("connecting...");
      lcd.setCursor(0, 0);
      lcd.print("connecting");
      connect();
    }

    void connect(){

        if (client.connect(server, 8080)) {
        Serial.println("connected");
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("connected");

        client.println("hello server");
        client.println();
        delay(500);
        lcd.clear();
      }
      else {
        Serial.println("connection failed");
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Connection Failure");
      }
      delay(500);
    }

    void loop() {

       //network
      if(!client.available()){
        Serial.println("lost connection!-restart");
        lcd.println("Disconnection");
        client.stop();
        connect();
      }
      else {

        int inp[5];
        getData(inp);
        Serial.println("next stage...");
        char *output = (char *) &inp[0];
        client.println(output);

        client.println("first");

        Serial.println("sent first...");

        //here repeats the same process for the other sensors - omitted for clear reading

      }
       //end network

       delay(500);
    }

    void getData(){

    Serial.println("GetData()");
    long durationThree, inchesThree, cmThree = 0;
    long durationOne, inchesOne, cmOne = 0;
    long durationTwo, inchesTwo, cmTwo = 0;
    long durationFour, inchesFour, cmFour = 0;

    //SENSOR ONE
    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    pinMode(echoPinOne, INPUT);
    durationOne = pulseIn(echoPinOne, HIGH);

    delay(100);

    //SENSOR TWO
    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    pinMode(echoPinTwo, INPUT);
    durationTwo = pulseIn(echoPinTwo, HIGH);

    delay(100);

    //SENSOR THREE
    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    pinMode(echoPinThree, INPUT);
    durationThree = pulseIn(echoPinThree, HIGH);

    delay(100);

    //SENSOR FOUR
    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    pinMode(echoPinFour, INPUT);
    durationFour = pulseIn(echoPinFour, HIGH);

    //DISTANCE CALCULATION
    cmOne = microsecondsToCentimeters(durationOne);
    cmTwo = microsecondsToCentimeters(durationTwo);
    cmThree = microsecondsToCentimeters(durationThree);
    cmFour = microsecondsToCentimeters(durationFour);
    //Serial.println("sending...");
    //char *out = (char *) &cmOne;
    //Serial.println(out);
    //client.println(out);
    //Serial.println("sent!");      used this to test - same issue

    Serial.println("got data...");
    inputBuf[0] = cmOne;
    inputBuf[1] = cmTwo;
    inputBuf[2] = cmThree;
    inputBuf[3] = cmFour;

    }

    long microsecondsToCentimeters(long microseconds)
    {
    return microseconds / 29 / 2;
    }

body:
The code you posted is performing incompatible casts and by thus is sending garbage to `client.println`.

There is no automatic conversion in C/C++ from an array of integers (`int inp[]`) or longs, to a C style string `char *`. A C Style string should end with null terminator `\0`, and the one in your code doesn't. For example, in this line:

    char *output = (char *) &inp[0];

The `inp[0]` contains the first integer. The expression `&inp[0]` contains the address of that integer in memory.

Thus the cast to `(char *)` will yield a malformed C style string, since it will not end with a null terminator, and more important, will not contain the data you expect it would (this cast is saying - "hey, compiler, note that the *address* of that `int` is actually the address of a C style string").

You can, however, utilize the `String` type constructor that receives int/long, and send the duration in order, something similar to:

            void getData()
            {
                ... // rest of the code here
                client.println(String(cmOne));
                client.println(String(cmTwo));
                ... // etc.
            }


message:
Multiple upload/ Synchronization problem

I am trying to do an experiment with Arduino Uno r3 board plus a 2-channel relay shield. What I need to do is to alternatively turn on and off the relay shields. So, it requires multiple compile and upload of the program to assign values to corresponding pins. What I have seen by now is that uploading the program to Arduino is a kind of painful process and it requires nothing to be connected to pins 0 and 1 to prevent synchronization errors. So, I was wondering how I can do my experiment without having to mount/unmount relay shield each time I want to upload a new program into it.

Thanks in advance

body:
Well, you can write a program that takes numbers out of Serial input.

    int pin1 = Serial.parseInt();
    int pin2 = Serial.parseInt();
    // etc., etc.

Simple.


message:
Why doesn't this motor turn?

When I upload the code, the DC motor makes a humming noise, but doesn't turn.

    //2-Way motor control

    int motorPin1 =  5;    // One motor wire connected to digital pin 5
    int motorPin2 =  6;    // One motor wire connected to digital pin 6

    // The setup() method runs once, when the sketch starts

    void setup()   {
      // initialize the digital pins as an output:
      pinMode(motorPin1, OUTPUT);
      pinMode(motorPin2, OUTPUT);
    }

    // the loop() method runs over and over again,
    // as long as the Arduino has power
    void loop()
    {
      rotateLeft(150, 500);
      rotateRight(50, 1000);
      rotateRight(150, 1000);
      rotateRight(200, 1000);
      rotateLeft(255, 500);
      rotateRight(10, 1500);
    }

    void rotateLeft(int speedOfRotate, int length){
      analogWrite(motorPin1, speedOfRotate); //rotates motor
      digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
      delay(length); //waits
      digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
    }

    void rotateRight(int speedOfRotate, int length){
      analogWrite(motorPin2, speedOfRotate); //rotates motor
      digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
      delay(length); //waits
      digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
    }

    void rotateLeftFull(int length){
      digitalWrite(motorPin1, HIGH); //rotates motor
      digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
      delay(length); //waits
      digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
    }

    void rotateRightFull(int length){
      digitalWrite(motorPin2, HIGH); //rotates motor
      digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
      delay(length); //waits
      digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
    }

  ![][1]

Why doesn't this work?

***Update:***

I plugged it into a different port (5v) as it is a 5v motor, but now it only turns left, not right. It just hums when it goes right.

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

body:
The IO drivers of most common logic chips or microprocessors such as the ATmega on your Arduino are nowhere near strong enough to drive typical electromagnetic motors.

To drive a motor, you should use a higher current switching device - a standard solution for bidirectional control being an H bridge part such as a TB6612FNG, L293D, L298, etc.

These are commonly sold on "motor shields" which you can plug into your Arduino, if you want to experiment with the concept before building something (and if you do want to build something, reviewing such a working schematic first would be a good idea).

You can in theory put an L293D or its DIP-packaged work-alikes on your breadboard, but you will need some care to get it right, especially if you use one of the other parts which requires external catch diodes.

Finally, you should not be powering most motors from the Arduino's onboard regulator or a USB port, but rather should use an external power supply.

=============

Responding to your edit, by  changing connections to place the the motor between one pin and the 5v supply, you have done two things:

1) You have made it so that the voltage difference across the motor can be applied in one direction only, therefore it can only rotate in one direction.

2) You have made it so that only the N-channel MOSFET in an output driver is involved in powering the motor.  That change is *almost* a useful idea, as N-channel devices are in fact much more capable than P-channel devices of similar dimension (and practical capacitance, voltage rating, and other tradeoffs) due to the greater mobility of negative charger carriers.

But this is still not really a solution, as it is unlikely that your motor's current rating is within even the current sink rating of the N-channel side of the ATmega output.

If you want a simple, unidirectional motor control, you could pursue this idea using one external N-channel MOSFET (or even a biploar NPN power transistor, which will be less efficient but also less delicate) to connect the unpowered side of the motor to ground.

If you want bidirectional control, you will need either + and - power supplies, or four external switching devices taking the roles of the low current N-FET and P-FET totem poles inside each of the two on-chip IO pin drivers you started with.


body:
This is a huge simplification of @Chris Stratton's post, for beginners.

To put it simply, the power that runs your motor is going through your arduino. Your arduino is not made to carry that sort of power.

What you want is an H-Bridge - see https://itp.nyu.edu/physcomp/labs/motors-and-transistors/dc-motor-control-using-an-h-bridge/ - the H Bridge is specially made to carry the power needed.

Note that this page is for a 9v motor, not a 5v motor like yours - you will need to find a more appropriate power supply than a 9v battery (or, you need to find a 9v motor). If you try to power it through USB, you will be drawing the power through your computer - you may damage it!


message:
Powering Infrared and Sonar sensors using BEC

I'm new to Arduino. I'm using Arduino Mega 2560 board & MATLAB Simulink-Arduino support package and trying to integrate Maxbotix Sonar and Sharp IR sensor for my class project. When I powered single US sensor from Arduino 5V output, the readings are fine. However, when I tried to power IR sensor in parallel with US sensor, IR readings are fine but US readings fluctuate.

So, I tried powering the sensors using BEC (5V-3A). The readings for both sensors are fluctuating(extremely noisy). From the specification mentioned by manufacturers, Maxbotix US sensor draws 2mA of current, whereas IR sensor averagely draws 20mA. Is there any way to solve this problem?

Thank you.

body:
I've managed to solve the problem. When external power supply is used to power multiple sensors, connect the GND of that supply with that of the Arduino GND input. For more details, refer to the link below.

http://www.thebox.myzen.co.uk/Tutorial/Power_Supplies.html


message:
What do these pins on the Uno do?

I've been wondering for a long time what these pins, labeled `ICSP` and blank, do.

![arduino][1]

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

I can't seem to find a diagram that explains them, so I've been wondering:

 - What are they for?
 - Are they GPIO, or do they do something special?
 - How can you use them?

Thanks for the help.

body: They're for programming, as well as carrying the non-select signals for SPI. The right one is for programming the main MCU, the left for the USB communication MCU. You should almost never need to use them unless you need to write a bootloader to a new chip or change the fuse or lock settings on them.