body:
There are a couple of alternative solutions to the question that I think are worth mentioning.

1. Use a data only USB cable or manually cut  the VCC and GND wires of the cable.

2. Remove the USB poly fuse from the arduino board.

3. Connect external power to one of the input pins to measure the voltage. This measurement can then be used to determine if the external power is connected and is providing sufficient voltage.
If it does the USB power should not be use anyways, otherwise an if statement can be used to disable the code that turns devices that draw power.
USB power will still be used to power the arduino board itself. It also has a limitation in that because the power supply could provide insufficient current it could draw the remaining required current from USB.


sender: user

message:
How to stop Arduino from drawing power through USB

I'm working on an embedded project, where I use arduinos as a "sensor shield" for RaspberryPi (I have model B).

The problem is, that the RaspberryPi's USB port is not powerfull enough to drive WiFi adapter and arduino with sensors. The solution is easy, I will power the sensors externally, not through the RPi.

But I was wondering, **is it possible to power whole Arduino externally (through Vin) and use the USB only for serial communication.**

To clarify, I know how to solve my problem - use some other mean of communication, than USB - GPIO serial, I2C, wireless, etc... I'm just interested if the whole thing will work, with USB cable which has 5V lead cut, for example.

The main issue I can see with this is, that the USB<->Serial chip is powered through USB only, then it will now work.

sender: assistant

body:
**Just cut the *`VCC`* line (usually *red*) in the USB cable.**

---

There are four wires in a USB cable:

- Ground
- VCC
- Data +
- Data -

You cannot send data along without a reference ground as you need a potential difference. Hence you must keep the ground connected and just snip the power line (red *`VCC`*).

---

Note that this is **not** usually necessary as **_`VIN`_ is favoured over _USB_ power**.


message:
Problem with fading LEDs

I got a breadboard with 10 LEDs, 4 of them fade, to be specific:
3, 5, 6 and 9 are working. 0, 1, 2, 4, 7, 8 are not working.

I'm using LEDs and resistors on all spots, they're all the same. Tried changing things around but the problem doesn't seem to be the resistors or the LEDs.

I'm using the following code (I'll highlight the parts for the fading, by marking it between `//**` comments).

Does anyone know a way to fix this? Or see any problem?

    const int inButton = 13;
    int buttonPushCounter = 0;
    int buttonState = 0;
    int lastButtonState = 0;
    int delayTime = 100;
    int brightness = 0;
    int fadeAmount = 5;

    void setup() {
      //**
      pinMode(inButton, INPUT);
      for (int out = 0; out < 10; out++){
        pinMode(out, OUTPUT);
      }
      //**

      pinMode(testLed, OUTPUT);
    }

    void loop() {
      buttonState = digitalRead(inButton);
      if (buttonState != lastButtonState){
        if (buttonState == 1){
          buttonPushCounter++;
        }
      }

      lastButtonState = buttonState;

      if (buttonPushCounter % 5 == 0){
        for (int i = 0; i < 10; i++){
          digitalWrite(i, 1);
          delay(delayTime / 2);
          digitalWrite(i, 0);
        }
      }
      else if (buttonPushCounter % 5 == 1){
        for (int i = 0, j = 9; i < 10, j >= 0; i++, j--){
          digitalWrite (i, 1);
          digitalWrite (j, 1);
          delay(delayTime / 2);
          digitalWrite (i, 0);
          digitalWrite (j, 0);
        }
      }
      else if (buttonPushCounter % 5 == 2){
        for (int i = 0; i < 10; i+=2){
          digitalWrite(i, 1);
        }
        delay(delayTime);
        for (int i = 0; i < 10; i+=2){
          digitalWrite(i, 0);
        }
        delay(delayTime);
        for (int i = 1; i < 10; i+=2){
          digitalWrite(i, 1);
        }
        delay(delayTime);
        for (int i = 1; i < 10; i+=2){
          digitalWrite(i, 0);
        }
      }
      else if (buttonPushCounter % 5 == 3){
        for (int i = 0 ; i < 10 ; i++){
          analogWrite(i, brightness);
        }
        brightness = brightness + fadeAmount;
        if (brightness == 0 || brightness == 255){
          fadeAmount = -fadeAmount;
        }
        delay(25);
      }
      else {
        int R1 = random(10);
        int R2 = random(10);
        int R3 = random(10);
        int R4 = random(10);
        digitalWrite(R1, 1);
        digitalWrite(R2, 1);
        digitalWrite(R3, 1);
        digitalWrite(R4, 1);
        delay(delayTime);
        digitalWrite(R1, 0);
        digitalWrite(R2, 0);
        digitalWrite(R3, 0);
        digitalWrite(R4, 0);
      }
    }

body: Only pins that support PWM support `analogWrite()` fully. 3, 5, 6, 9, 10, and 11 do. The rest do not.


body: To add to @ignacio-vazquez-abrams answer, the pins that support `analogWrite()` have `~` sign next to their number (on my Uno board they are `9~`, `10~`, `11~` e.g.);


message:
AnalogRead too slow... Faster alternative?

For a program that I'm working on, I want to get an accurate reading from a noisy pressure sensor.  So, the idea that I have is to do a thousand AnalogRead commands on the same port very quickly and then average them.  The pressure readings become very precise, however, the program that I am running becomes very slow.  I need my program to be orders of magnitude faster.

I'm sure that there's a faster way to do AnalogRead commands, especially because I am requesting the same port over and over.  Maybe there's a way that I can take lower resolutions of readings and then average those?  I don't know.  Can anyone help me?  I am an amateur Arduino user looking to learn.

I have done a little bit of research on my own and had trouble finding concrete examples.

body:
Ignacio's proposal is surely a good one if you really need higher sample rates, but I would try another approach:

Average your signal before sampling it! This can be done by connecting a simple [RC lowpass][1] to your AD input.

With that you get rid off those high frequency noise you don't need, but without wasting CPU time.

  [1]: http://hyperphysics.phy-astr.gsu.edu/hbase/electric/filcap2.html#c2


body:
The ADC is rated at up to 15K samples per second.  So reading a 1000 is not a problem.
However, care must be taken in the Vcc used for the ADC (AVcc).  It must be noise free otherwise it will introduce noise into the digital readings, when it actually isn't there in the analogue signal.

See page 256 on the Atmel 328 datasheet for further information.

The RC Lowpass filter should also be used on the AVcc supply, as well as the pressure sensor signal.

I just thought!   Are you using a Serial.print() after each analogRead()???
If so, the serial port will drastically slow down the sample rate.
If this is the case perform a number of analogRead()s then use Serial.print() after some form of processing.


message:
Convert Arduino Pro Mini 5v to use 3.3v

Id like to make my 5v pro mini use 3.3 v instead of 5 because i want to use it in an existing piece of electronics that uses 3v throughout.

Looking at the specs for the pro mini it says the 3.3v version can accept higher voltages.

So is there a regulator i can bypass/bridge that will convert my 5v version to a 3.3v version? or am i wasting my time?

body:
I have good news, and I have bad news.

The good news is that only **two changes** to the board are required to change it from a 5V board to a 3.3V (or any voltage within spec) board.

The bad news is that there's *no way in hell* you'll be able to do them.

So, we work around them and get the board up and running.

The first is obvious: a 3.3V board should be running off of 3.3V. Since we can't replace the SOT23-5 regulator on the board (the little 5-pin device towards the end) we need a voltage regulator to supply this, directly to the VCC pin. Find yourself a linear or switching regulator that provides this voltage.

The second is that the microcontroller, an Atmel ATmega168/P, is not specced to run at 16MHz when the supply voltage is only 3.3V; the maximum speed is 12MHz. Since we can't replace the crystal on the board (the little silver package next to the MCU itself) we need to perform some trickery to tell the MCU divide the frequency down to something way below safe, and then boost it up after. Use a programmer (see some of my other answers for more info about this) to set the CKDIV8 fuse and then use the routines in <a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__power.html">`avr/power.h`</a> in your code to "reduce" the divisor to 2, bringing the clock speed back up to 8MHz. While you're at it, check the BOD fuses to make sure they're not set to something useless like 0b100.

As always, see the datasheet.


body:
See [this nice article][1] by Adafruit, which explains how to run an Arduino **Uno** at 16Mhz with 3.3v. Both the Arduino Pro Mini and the Uno use the same ATmega328p chip, and they claim that even though running at 16Mhz is out of specs, it *should* work.

As **Ignacio** mentioned in [his answer][2], there will be no alternative to downclocking the Mini Pro if you want to play it safe and stay **within the specs**. If you are willing to take the chance, remove the 5v regulator as suggested, and connect a regulated 3.3v to Vin. Consider the hazards; they might include device resets, misbehaving code or malfunctioning I/O pins.
If you are using an unregulated 3v voltage source, you will need to step up the voltage - using DC DC step up converter such as [this one][3]. (By the way - you could also find a [step up converter to 5v][4] - hence problem solved...)

In addition, see [this SO answer][5] for more details. The *safe* clock speed for the ATmega328p operating at 3.3v would be **13.33Mhz**. For reference, here is the Safe Operating Area graph from the datasheet supplied in the answer:

![enter image description here][6]

  [1]: https://learn.adafruit.com/arduino-tips-tricks-and-techniques/3-3v-conversion
  [2]: https://arduino.stackexchange.com/a/5413/630
  [3]: http://www.ebay.com/itm/DC-DC-Input-0-8-3-3V-Output-3-3V-Step-UP-Boost-Voltage-Converter-Module-/171569922743?pt=LH_DefaultDomain_0&hash=item27f25d42b7
  [4]: http://www.ebay.com/itm/DC-DC-Boost-Converter-Step-Up-Module-1-5V-to-5V-500mA-Power-Module-New-TR-/400819011062?pt=AU_Gadgets&hash=item5d52acbdf6
  [5]: https://electronics.stackexchange.com/questions/58818/programming-3-3v-atmega328-running-at-16mhz
  [6]: https://i.stack.imgur.com/98hvi.jpg


message:
Convert long to char array and back

I'm trying to store a state in my data logger. I can read/write fine to SD, but I can't wrap my head around reading/writing a `long` value correctly - I've build it down to converting it to char array and back.

My best try so far has been

    long temp = 1418172669L;
    unsigned char buf[4];
    buf[0] = temp         & 0xFF;
    buf[1] = (temp >>  8) & 0xFF;
    buf[2] = (temp >> 16) & 0xFF;
    buf[3] = (temp >> 24) & 0xFF;

    long  l = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);

But `l` is very different from `temp` - currently the output is `-26371`. Am I making an obvious mistake?

body:
I think the last expression is performed exclusively as an `int` expression and converted to `long` only at the end, i.e. before assignment to `l`.

    long  l = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);

Here the compiler calculates `buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24)` as an `int` only.

If you give a hint to the compiler by telling it you want `long` expressions used, then it should work. The easiest way to do so is to replace the number of bits to be shifted as **long literals**:

    long  l = buf[0] | (buf[1] << 8L) | (buf[2] << 16L) | (buf[3] << 24L);

That should be enough for the compiler to perform the whole operation as `long` and not loose precision.


body:
I suggest using a union:

    union {
        char myByte[4];
        long mylong;
    } foo;

**Char to Long:**

Then you can just add the bytes:

    foo myUnion;
    myUnion.myByte[0] = buf[0];
    myUnion.myByte[1] = buf[1];
    myUnion.myByte[2] = buf[2];
    myUnion.myByte[3] = buf[3];

Then you can access the long as:

    myUnion.myLong;

**Long to Char:**

The same if you want to go the other way from long to char array:

    foo myUnion
    myUnion.myLong = 1234L;

To access bytes:

    myUnion.myByte[0];
    myUnion.myByte[1];
    myUnion.myByte[2];
    myUnion.myByte[3];


body:
Just for completeness, after posting this, I've found another way around it, but @Phataas solution is much more elegant.
Using the `ltoa` and `atol` functions, long to char array and vice-verse can be done like this:

    char temp[10];
    ltoa(669L,temp,10);
    long result = atol(temp);


message:
Unable to retrieve heart rate reading and send to JY-MCU Bluetooth

Hello Arduino Community,

I am encountering an issue trying to retrieve a heart rate reading from an op-amp and instrumentation amplifier and sending it via Bluetooth.  I used this website as a basis of my design:  http://www.instructables.com/id/Electrocardiograph-Heart-Rate-Monitor/?ALLSTEPS.  I would appreciate it if you could take a look at that.  Here are a couple of pictures of my design.
![1](https://i.stack.imgur.com/CkH3w.jpg)
![2](https://i.stack.imgur.com/j9rFB.jpg)
![3](https://i.stack.imgur.com/y91vh.jpg)
Here is the code that I used:

        const int  signal = 7;    // Pin connected to the filtered signal from the circuit
        unsigned long time;
        unsigned long frequency;

        // Internal variables
        int period = 2000;
        int starttime = 2000;
        int input = 0;
        int lastinput = 0;
        unsigned long death = 0;

             void setup() {
               pinMode(signal, INPUT);
               Serial.begin(9600);
             }

         void loop() {
           delay(1000);

           time = millis();
           input = digitalRead(signal);

           if ((input != lastinput)&&(input == HIGH)) {
           // If the pin state has just changed from low to high (edge detector)
           period = time - starttime; // Compute the time between the previous beat and the one that has just been detected
           starttime = time; // Define the new time reference for the next period computing
           death = time;
          }
          lastinput = input; // Save the current pin state for comparison at the next loop iteration

          if (period < 0) {
          frequency = 0;
          }
          else {
          frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
          }

          if ((time - death) > 2000) { // Detect if there is no beat after more than 2 seconds
          Serial.println("dead");
          }

          else {
          char freq[3];

          if (frequency/100 == 0) {
           freq[0] = 32; // Print a space to the first character if the frequency is below 100 bpm
          }
          else {
           freq[0] = frequency/100+48; // Sort the hundreds character and convert it in ASCII
          }
           freq[1] = (frequency/10)+48; // Sort the thents character and convert it in ASCII
           freq[2] = frequency+48; // Sort the units character and convert it in ASCII

          Serial.print(freq);
          Serial.print("alive! ");
          }

          }`

But all I'm getting as output is 'dead'.  I am really starting to lose it here since I am a complete amateur with Arduino and circuitry.  For reference, I copied the design from this image from the website (this is just an enlarged version): http://www.instructables.com/file/FVBC6TYHOW0HQ7H/?size=ORIGINAL.  I would appreciate it if anyone could provide some extra guidance.

body:
![enter image description here][1]assuming your circuit works, your code has some serious issues. I rewrote the code for you and also provided a simplified circuit that I have tested and know works.  Instead of getting the pulse from the heartbeat detector circuit, we will simulate it on the Arduino by pulsing pin 2 periodically.

    const int  signal = 7;    // Pin connected to the filtered signal from the circuit
    unsigned long currentBeatTime;
    unsigned long previousBeatTime;

    unsigned long frequency;

    unsigned long myBeatFreq;
    unsigned long myBeat;

    // Internal variables
    unsigned long period = 0;
    int input = 0;
    int lastinput = 0;

    void setup() {
        pinMode(signal, INPUT);
        pinMode(2, OUTPUT);
        Serial.begin(9600);

        previousBeatTime = millis();
        myBeat = previousBeatTime;
    }

    void loop() {
        if ( millis()-myBeat > myBeatFreq )
        {
          digitalWrite(2, HIGH);
          myBeat=millis();
        }
        else
        {
          digitalWrite(2, LOW);
        }

        input = digitalRead(signal);

        if ((input != lastinput) && (input == HIGH)) {
         // If the pin state has just changed from low to high (edge detector)
            currentBeatTime = millis();

         period = currentBeatTime - previousBeatTime; // Compute the time between the previous beat and the one that has just been detected
         previousBeatTime = currentBeatTime; // Define the new time reference for the next period computing
        }

        lastinput = input; // Save the current pin state for comparison at the next loop iteration

        // Detect if there is no beat after more than 2 seconds
        if ( (millis() - previousBeatTime) > 2000 )
        {
         Serial.println("dead");
        }
        else
        {
            if (period <= 0)
            {
             frequency = 0;
            }
            else
            {
             frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
            }

            Serial.print(frequency);
            Serial.println(" : alive! ");
        }
    }

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


message:
3.5 inch TFT LCD connection diagram with mega r3

[Forum post](http://forum.arduino.cc/index.php?topic=257168.0)

I would like to ask if someone has this shield fully working.

My biggest problem is the touch screen that i couldn't manage to make it work.

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

    // ic: ili9327
    #define LCD_RD   A0
    #define LCD_WR   A1
    #define LCD_RS   A2
    #define LCD_CS   A3
    #define LCD_REST A4

    void Lcd_Writ_Bus(char VH)
    {
     unsigned char i,temp,data;
     data=VH;
     for(i=8;i<=9;i++)
     {
       temp=(data&0x01);
       if(temp)
         digitalWrite(i,HIGH);
       else
         digitalWrite(i,LOW);
       data=data>>1;
     }
     for(i=2;i<=7;i++)
     {
       temp=(data&0x01);
       if(temp)
         digitalWrite(i,HIGH);
       else
         digitalWrite(i,LOW);
       data=data>>1;
     }

     digitalWrite(LCD_WR,LOW);
     digitalWrite(LCD_WR,HIGH);
    }

    void Lcd_Write_Com(char VH)
    {
     digitalWrite(LCD_RS,LOW);
     Lcd_Writ_Bus(VH);
    }

    void Lcd_Write_Data(char VH)
    {
     digitalWrite(LCD_RS,HIGH);
     Lcd_Writ_Bus(VH);
    }

    void Lcd_Write_Com_Data(int com,int dat)
    {
     Lcd_Write_Com(com);
     Lcd_Write_Data(dat);
    }

    void Address_set(unsigned int x1,unsigned int y1,unsigned int x2,unsigned int y2)
    {
     Lcd_Write_Com(0x2a); // Set_column_address 4 parameters
     Lcd_Write_Data(x1>>8);
     Lcd_Write_Data(x1);
     Lcd_Write_Data(x2>>8);
     Lcd_Write_Data(x2);

     Lcd_Write_Com(0x2b); // Set_page_address 4 parameters
     Lcd_Write_Data(y1>>8);
     Lcd_Write_Data(y1);
     Lcd_Write_Data(y2>>8);
     Lcd_Write_Data(y2);

     Lcd_Write_Com(0x2c); // Write_memory_start
    }

    void Lcd_Init(void)
    {
     digitalWrite(LCD_REST,HIGH);
     delay(5);
     digitalWrite(LCD_REST,LOW);
     delay(15);
     digitalWrite(LCD_REST,HIGH);
     delay(15);

     digitalWrite(LCD_CS,HIGH);
     digitalWrite(LCD_WR,HIGH);
     digitalWrite(LCD_CS,LOW);  //CS

     Lcd_Write_Com(0xE9);
     Lcd_Write_Data(0x20);

     Lcd_Write_Com(0x11); //Exit Sleep
     delay(100);

     Lcd_Write_Com(0xD1);
     Lcd_Write_Data(0x00);
     Lcd_Write_Data(0x71);
     Lcd_Write_Data(0x19);

     Lcd_Write_Com(0xD0);
     Lcd_Write_Data(0x07);
     Lcd_Write_Data(0x01);
     Lcd_Write_Data(0x08);

     Lcd_Write_Com(0x36);
     Lcd_Write_Data(0x48);

     Lcd_Write_Com(0x3A);
     Lcd_Write_Data(0x05);

     Lcd_Write_Com(0xC1);
     Lcd_Write_Data(0x10);
     Lcd_Write_Data(0x10);
     Lcd_Write_Data(0x02);
     Lcd_Write_Data(0x02);

     Lcd_Write_Com(0xC0); //Set Default Gamma
     Lcd_Write_Data(0x00);
     Lcd_Write_Data(0x35);
     Lcd_Write_Data(0x00);
     Lcd_Write_Data(0x00);
     Lcd_Write_Data(0x01);
     Lcd_Write_Data(0x02);

     Lcd_Write_Com(0xC5); //Set frame rate
     Lcd_Write_Data(0x04);

     Lcd_Write_Com(0xD2); //power setting
     Lcd_Write_Data(0x01);
     Lcd_Write_Data(0x44);

     Lcd_Write_Com(0xC8); //Set Gamma
     Lcd_Write_Data(0x04);
     Lcd_Write_Data(0x67);
     Lcd_Write_Data(0x35);
     Lcd_Write_Data(0x04);
     Lcd_Write_Data(0x08);
     Lcd_Write_Data(0x06);
     Lcd_Write_Data(0x24);
     Lcd_Write_Data(0x01);
     Lcd_Write_Data(0x37);
     Lcd_Write_Data(0x40);
     Lcd_Write_Data(0x03);
     Lcd_Write_Data(0x10);
     Lcd_Write_Data(0x08);
     Lcd_Write_Data(0x80);
     Lcd_Write_Data(0x00);

     Lcd_Write_Com(0x2A);
     Lcd_Write_Data(0x00);
     Lcd_Write_Data(0x00);
     Lcd_Write_Data(0x00);
     Lcd_Write_Data(0xeF);

     Lcd_Write_Com(0x2B);
     Lcd_Write_Data(0x00);
     Lcd_Write_Data(0x00);
     Lcd_Write_Data(0x01);
     //  Lcd_Write_Data(0x3F);
     Lcd_Write_Data(0x8F); // on internet

     Lcd_Write_Com(0x29); //display on

     Lcd_Write_Com(0x2C); //display on

     digitalWrite(LCD_CS,HIGH);
    }

    void H_line(unsigned int x, unsigned int y, unsigned int l, unsigned int c)
    {
     unsigned int i,j;
     Lcd_Write_Com(0x02c); //write_memory_start
     digitalWrite(LCD_RS,HIGH);
     digitalWrite(LCD_CS,LOW);
     l=l+x;
     Address_set(x,y,l,y);
     j=l*2;
     for(i=1;i<=j;i++)
     {
       Lcd_Write_Data(c);
     }
     digitalWrite(LCD_CS,HIGH);
    }

    void V_line(unsigned int x, unsigned int y, unsigned int l, unsigned int c)
    {
     unsigned int i,j;
     Lcd_Write_Com(0x02c); //write_memory_start
     digitalWrite(LCD_RS,HIGH);
     digitalWrite(LCD_CS,LOW);
     l=l+y;
     Address_set(x,y,x,l);
     j=l*2;
     for(i=1;i<=j;i++)
     {
       Lcd_Write_Data(c);
     }
     digitalWrite(LCD_CS,HIGH);
    }

    void Rect(unsigned int x,unsigned int y,unsigned int w,unsigned int h,unsigned int c)
    {
     H_line(x  , y  , w, c);
     H_line(x  , y+h, w, c);
     V_line(x  , y  , h, c);
     V_line(x+w, y  , h, c);
    }

    void Rectf(unsigned int x,unsigned int y,unsigned int w,unsigned int h,unsigned int c)
    {
     unsigned int i;
     for(i=0;i<h;i++)
     {
       H_line(x  , y  , w, c);
       H_line(x  , y+i, w, c);
     }
    }

    void LCD_Clear(unsigned int j)
    {
     unsigned int i,m;
     Lcd_Write_Com(0x02c); //write_memory_start
     digitalWrite(LCD_RS,HIGH);
     digitalWrite(LCD_CS,LOW);
     Address_set(0,0,479,399);

     for(i=0;i<480;i++)
       for(m=0;m<400;m++)
       {
         Lcd_Write_Data(j);
       }
     digitalWrite(LCD_CS,HIGH);
    }

    void setup()
    {
     for(int p=2;p<10;p++)
     {
       pinMode(p,OUTPUT);
     }
     pinMode(A0,OUTPUT);
     pinMode(A1,OUTPUT);
     pinMode(A2,OUTPUT);
     pinMode(A3,OUTPUT);
     pinMode(A4,OUTPUT);
     digitalWrite(A0, HIGH);
     digitalWrite(A1, HIGH);
     digitalWrite(A2, HIGH);
     digitalWrite(A3, HIGH);
     digitalWrite(A4, HIGH);
     Lcd_Init();
     LCD_Clear(0x00);
    }

    void loop()
    {

     for(int i=0;i<1000;i++)
     {
       Rect(random(300),random(300),random(300),random(300),random(65535)); // rectangle at x, y, with, hight, color
     }
     LCD_Clear(0x00);
    }

Here are some pictures:

![1](http://imageshack.com/a/img908/7546/YEctM8.jpg)
![3](http://imageshack.com/a/img537/5378/GIWz2x.jpg)

Any suggestions?

body:
Try to use [MCUFriend kbv library][1] I used this library for a 3.5 inch display and the driver on it was ILI9486 this library includes all the function and I have tested the touch also this library works good for it also

  [1]: https://www.arduinolibraries.info/libraries/mcufriend_kbv


message:
Sniffing RF signals

I am using an Arduino UNO and an [RXb6][1] (I would link to the data sheet if I could find one) to try to decode a RF Signal that controls a remote outlet. I have the devices connected as you would assume 5V+ to 5v, Gnd to Gnd, Antenna is not connected as I think it would only exacerbate my problem, and data is connected to the A0 pin on my UNO.

The problem I am having is with all the noise that I am getting with my signal.I hooked it up to my o-scope to give a better idea of whats happening. When no signal is being transmitted this is the noise I am seeing:
![enter image description here][2]

Just lots of static. When I press the remote button I can see a clean signal come through (note that it is cutoff):![enter image description here][3]

I was able to export a CSV of the wave and manually clean it up but it was just such a pain trying to translate it back to highs and lows for the arduino to send.

**How can I reduce signal noise on my 433MHz receiver so the arduino can read the actual signal instead of noise?**

  [1]: http://i.ebayimg.com/00/s/NzUwWDc1MA==/z/wucAAOxy0x1TRKey/$_57.JPG
  [2]: https://i.stack.imgur.com/1Qvs8.png
  [3]: https://i.stack.imgur.com/u3V1n.png

body:
I'm adding another answer, because I don't think the core thing to grasp is mentioned, and others might benefit :)

The noise you are seeing, is actually the result of a feature of the RXB6, KSA6, and similar modules. When they see no signal, they increase gain/sensitivity until they do see a signal. The upside of this is they are very sensitive, and can operate well over quite long ranges. The downside is that if there really is no signal, they will start picking up anything that remotely looks like a signal, the noise you see :)

Dealing with this noise is the job of the software/protocol and other electronics built around the receiver.
A common way to solve it, which the VirtualWire library also uses, is to send some unimportant 'data' first, which makes the receiver decrease it's sensitivity, and then send the  important data.
Another common way is to just repeat the data several times, this is also what your wall sockets most likely do.

In software you can usually find the 'important' parts by looking at pulse lengths, the noise is usually short high pulses, most protocols use far longer pulses, which also have a predictable/defined length.

What I did in exactly your case was to dump the sound recording as a raw signed pcm 16 bit file, which I could then easily read into a bit of software I wrote, which find's the high/low transitions, filters out any short pulses, and then writes out the output (like a csv) you want :)


message:
How to update a variable in an ISR using Timers

I'm trying to check the frequency of Timer3 using a counter. The value of the counter, declared as volatile, is incremented in the ISR and every second the sum is shown in the main loop and the value reset to zero.

The timer has been set up correctly. (If I choose a 3Hz timer I can see the led blinking)

**The problem**

The counter isn't incremented. Here is the output:

    Setup Completed
    tick: 1
    tick: 0
    tick: 0
    tick: 0

**CODE**

    volatile int cont = 0;

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

      pinMode(13, OUTPUT);

      // Initialize Timer
      cli();          // disable global interrupts
      TCCR3A = 0;     // set entire TCCR3A register to 0
      TCCR3B = 0;     // same for TCCR3B

      // set compare match register to desired timer count: 800 Hz
      OCR3B = 20; // 800Hz 5; // 3 Hz
      // turn on CTC mode:
      TCCR3B |= (1 << WGM12);
      // Set CS10 and CS12 bits for 1024 prescaler:
      TCCR3B |= (1 << CS30) | (1 << CS32);
      // enable timer compare interrupt:
      TIMSK3 |= (1 << OCIE3B);
      // enable global interrupts:
      sei();

      Serial.println("Setup completed");
    }

    void loop()
    {
      if (millis() % 1000 == 0)
      {
        Serial.print(" tick: ");
        Serial.println(cont);
        cont = 0;
      }
    }

    ISR(TIMER3_COMPB_vect)
    {
      //digitalWrite(13, digitalRead(13) ^ 1);
      cont++;
    }

**EDIT**
This timer is used to read an anlog value from an accelerometer and store it in an array of float. But at the moment I'm stuck on this update issue.

**SOLUTION 1**
Thanks to Gerben

    volatile int cont = 0;

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

      // Initialize Timer
      cli();          // disable global interrupts
      TCCR3A = 0;     // set entire TCCR3A register to 0
      TCCR3B = 0;     // same for TCCR3B

      // set compare match register to desired timer count: 800 Hz
      OCR3A = 20; // 20; //800Hz 5; // 3 Hz
      // turn on CTC mode:
      TCCR3B |= (1 << WGM32);
      // Set CS10 and CS12 bits for 1024 prescaler:
      TCCR3B |= (1 << CS30) | (1 << CS32);
      // enable timer compare interrupt:
      TIMSK3 |= (1 << OCIE3B);
      // enable global interrupts:
      sei();
      Serial.println("Setup completed");
    }

    void loop()
    {
      delay(1000);
      Serial.println(cont);
      cont = 0;
    }

    ISR(TIMER3_COMPB_vect)
    {
      cont++;
    }

**SOLUTION 2**
Thanks to BrettM

    volatile int cont = 0;

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

      // Initialize Timer
      cli();          // disable global interrupts
      TCCR3A = 0;     // set entire TCCR3A register to 0
      TCCR3B = 0;     // same for TCCR3B

      // set compare match register to desired timer count: 800 Hz
      OCR3B =  20; //800Hz 5; // 3 Hz
      // turn on CTC mode:
      //TCCR3B |= (1 << WGM32);
      // Set CS10 and CS12 bits for 1024 prescaler:
      TCCR3B |= (1 << CS30) | (1 << CS32);
      // enable timer compare interrupt:
      TIMSK3 |= (1 << OCIE3B);
      // enable global interrupts:
      sei();
      Serial.println("Setup completed");
    }

    void loop()
    {
      Serial.println(cont);
      cont = 0;
      delay(1000);

    }

    ISR(TIMER3_COMPB_vect)
    {
      TCNT3 = 0;
      cont++;
    }

body:
In CTC mode the top is `OCR3A`, not `OCR3B`!

After that `TIMSK3 |= (1 << OCIE3B);` should also be changed to `TIMSK3 |= (1 << OCIE3A);`, and `ISR(TIMER3_COMPB_vect)` to `ISR(TIMER3_COMPA_vect)`

For 3Hz, `OCR3A` should be 5208, not 20.

Technically `TCCR3B |= (1 << WGM12);` should be `TCCR3B |= (1 << WGM32);`


body:
It seems my answer to [this question][1] was previously incomplete, thanks for pointing out that CTC mode only works with OCR3A Gerben. I apologize for not testing an answer before I post it.

Given the information only in this question Gerben's answer is complete, but since your other question implies that you cannot use OCR3A due to the Servo library I'll add a bit. (I've also edited that answer)

you can emulate the behavior of CTC mode by setting TCNT3 to 0 in your interrupt routine. Remember to remove the line that turns on CTC mode in your code.

I've tested your code with this ISR:

    ISR(TIMER3_COMPB_vect)
    {
      TCNT3 = 0;
      cont++;
    }

and this configuration of the timer registers

    OCR3B = 5208; // 800Hz 5; // 3 Hz
    // Set CS10 and CS12 bits for 1024 prescaler:
    TCCR3B |= (1 << CS30) | (1 << CS32);
    // enable timer compare interrupt:
    TIMSK3 |= (1 << OCIE3B);

This might be a bit less accurate at high frequencies than CTC, I'm not sure, but at 3Hz it worked perfectly. Notice that 5208 was the correct OCR value, not 20 (again thanks to Gerben).

  [1]: https://arduino.stackexchange.com/questions/5396/setting-timer3-in-ctc-mode-conflict-with-servo-library/5432#5432


message:
Why can this color sensor not recognize green?

I got this [color sensor][1] last week, I've been able to get the sensor to recognize blue and red, but not green. still working on this.
I use the code in the product page.

so anybody have any idea about this issue? Pretty thanks.
![enter image description here][2]

  [1]: http://www.icstation.com/product_info.php?products_id=1503
  [2]: https://i.stack.imgur.com/f69jM.jpg

body:
Check that you've connected all the Arduino pins correctly to the sensor. In particular, make sure pin 4 on the Arduino is connected to S2 on the sensor.

It's the combination of signals on S2 and S3 which determines which colour is being detected:

    S2    S3    Colour
    ----  ----  ------
    Low   Low   Red
    Low   High  Blue
    High  Low   Clear
    High  High  Green

If S2 is always low then you can only detect red and blue.

If the connections are definitely correct, then ensure you haven't made any code modifications which could interfere with it. You may also want to test pin 4 on your Arduino (e.g. using a multimeter) to make sure it's working properly. If necessary, you could use a different pin instead. However, you'll need to modify the `#define S2` line in the code to match.


message:
How to detect high/low signal from a DC servo motor using arduino?

I am a newbie to Arduino.

What I am going to do is to change my roll to roll printer to flatbed printer.
Rather using print roller, I decided to move the bed from a stepper motor.I know how to run the stepper motor for specific distance using arduino.

So I need to cheat printer to think that its roller is working and media is going through it.But actually what I am going to do is to monitor the printer motor running or not from arduino input and if the printer motor is running stepper motor will turn or if motor stops stepper motor must stop.

What my problem is how can I read that the dc servo motor status? How would I need to wire arduino input to servo motor to get the status.

Please show me some light on this.Sorry if this is a newbie question.

Thank you.

body:
Do you need to check if it is stalled? Or simply running?

Either way, you could check the voltage with an analogue input, compare against a threshold (empirically set) & use that. Take the voltage reading from the non-commoned side of the motor, after any driver circuit.

If you want stalled, a small resistance would help, if just running then you could get away with a digital input.

If the voltages aren't matched then a resistance divider chain would be necessary.


body:
I would definitely use an Opto-Isolator between the motor and the Arduino for these reasons.

You will have a problems with the grounds as the motor reverses.
The 24V supply.  If you get something slightly wrong then it will take out the Arduino and the PC connected to it.
The motor will generate large voltage spikes( circa 50..300Volts) under certain condions.  The Arduino and the PC connected to it will complain, but not for long!


message:
How to delay so that LED stays on a bit longer?

I have a circuit with a shift register which controls 8 LEDs: http://node-ardx.org/exercises/5. In code, I created a function `cycle()` cycle through each LED one at a time, but this occurs too quickly on the board. How can I add a delay inside the loop so that each LED stays on for 500ms?

Here's my code:

    var five = require("johnny-five"), board, shiftRegister;

    board = new five.Board();

    board.on("ready", function() {
      shiftRegister = new five.ShiftRegister({
        pins: {
          data: 2,
          clock: 3,
          latch: 4
        }
      });

      var bytes = [
        00000001,
        00000010,
        00000100,
        00001000,
        00010000,
        00100000,
        01000000,
        10000000,
        00000000
      ];

      function cycle() {
          for ( var i = 0; i < bytes.length; i++ ) {
              console.log(bytes[i]);
              shiftRegister.send(bytes[i]);
          }
        }

      this.repl.inject({
        sr: shiftRegister
      });

      cycle();

    });

body:
Insert a delay of 500ms?

    function cycle() {
        for ( var i = 0; i < bytes.length; i++ ) {
            console.log(bytes[i]);
            sr.send(bits[i]);
            delay(500);
        }
      }


body:
The answer is already provided in the article.

      var i = 0;
      function cycle() {
        console.log(bytes[i]);
        sr.send(bits[i]);
        i++;
        if( i<bytes.length )
          setTimeout(cycle, 300);
      }


message:
Source Code for strcpy and strcat

Does anyone know the location of the assembler file for strcpy and strcat for the Arduino?  I wish to modify it.

body:
The Arduino IDE doesn't ship with the source/assembly for a lot of the core functionality. It comes pre-compiled in object/library files.

However, you could download the source code for AVR Libc from this site:

 * http://www.nongnu.org/avr-libc

Obviously there's no guarantee that the files you download will exactly match what comes with the Arduino IDE, but it's useful if you're interested in how they're implemented.

When you've downloaded and extracted the source code, look in the `libc/string` folder. you should find assembly files called `strcat.S` and `strcpy.S`.

As jfpoilpret says in the comments, attempting to modify core library functions is generally not a good idea. They may be getting called by other parts of the core, so any changes you make could break something else.


message:
Are my arrays stored in sram or in Flash?

I have the following memory allocation:

    unsigned char g1[]={
      0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ....0x00 ,0x00 ,0x00 ,0x00 ,0x00 };
    g2[]={
      0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ....0x00 ,0x00 ,0x00 ,0x00 ,0x00 };
    ...

     unsigned char* index[10] = {g1,g2,g3,g4,g5,g6,g7,g8,g9,g0};

This is accessed in the following way:

    unsigned char* getMatch(int input){
      return index[input];
    }

This is then futher acces using the method of

    unsigned char store[1024]
    unsigned char* temp = getMatch(n);
    for(int i=0;i <50;i++){
     store[i]=temp[i];
    }
and store is then modified and send to an external device.

As my program is randomly failing I think it might be running low on SRAM and was wondering if there is any way to force this memory to be placed in flash. Anybody got an idea?

body:
It's stored in both the FLASH and SRAM because it's initialized array. To store in FLASH only you need use PROGMEM attribute.

    const unsigned PROGMEM char g1[]= ...

You cannot access directly but using *memcpy_P()* function.


message:
Arduino - Progamming issue

my first post here.

Anyway I'm working on a Simon Says game.
I have a weird bug with the function that reads button input.

This is the code:

    int deBounce(int count){
      int pressed=-1;
      int laastButtons[3]; // save the previous deBounce read.
      for(int x; x<4; x++)
      {
        laastButtons[x] = lastButtons[x];
        lastButtons[x] = !digitalRead(button[x]);
        if(lastButtons[x] == true)
        {
          delay(50);
          lastButtons[x] = !digitalRead(button[x]);
          if(lastButtons[x] == 1){ pressed = x;}
          nt("Pressed!, Button ID: ");nt(x); nt(" pressed:  ");nt(pressed); nt(" state "); ntln(lastButtons[x]);
        }
      }
      if((lastButtons[0] + lastButtons[1] + lastButtons[2] + lastButtons[3]) > 1)
      {
        ntln("ERROR: dont press more than one button at a time. ");
      }
      if( ((lastButtons[0] + lastButtons[1] + lastButtons[2] + lastButtons[3]) == 1 ) && !laastButtons[pressed] && (pressed != -1) ) {
        pressButtons[count] = pressed;
        nt("Pressed!, ID: ");nt(count); nt(" Button ID ");ntln(pressed);
        return count++;
      }else return count;
    }

This is what I recieve in the Serial Monitor if I press one of the buttons.

> Pressed!, Button ID: 3 pressed: -1 state 1

How is that possible? Note the lines where that line is printed and the line above it.
Seems like that if should run, but the line pressed = x; doesn't function.
Note that, nt and ntln are just a short for Serial.print.
I have this weird bug and sometimes it seems like the chip is glitching!

Another question is- I tried attaching interrupt and it didn't worked,
Is it possible that my board is not compatiable with them? (It's not original).

Thanks.

EDIT:

After Majenko helped me figure it out,
The thing that created the bug was that I expected a x==0, but I didn't define it in the for loop.

Before:

    for(int x; x<4; x++)

After:

    for(int x=0; x<4; x++)

Thanks again Majenko!

body:
    int laastButtons[3]; // save the previous deBounce read.
    for(int x; x<4; x++)
    {
       laastButtons[x] = lastButtons[x];

Well, there's a common bug right away.  An array with three slices, numbered 0, 1 and 2, and you're accessing them with a loop that counts from 0 to 3.

Spot the error.

Also, in the for loop, what number does it start counting from?

And now for your "bug".  This block of code:

    if(lastButtons[x] == true)
    {
      delay(50);
      lastButtons[x] = !digitalRead(button[x]);
      if(lastButtons[x] == 1){ pressed = x;}
      nt("Pressed!, Button ID: ");nt(x); nt(" pressed:  ");nt(pressed); nt(" state "); ntln(lastButtons[x]);
    }

I think you have it slightly wrong.  Let's convert it into plain english:

* If button is pressed:
   * Delay 50 ms
   * Read button again
   * If button is pressed:
      * Set *pressed* to the button number
   * Print the button message

Note the indenting, which highlights what gets executed for what IF statement.  The print is going to happen regardless of the setting of the *pressed* variable.

I think the structure you wanted is:

* If button is pressed:
   * Delay 50 ms
   * Read button again
   * If button is pressed:
      * Set *pressed* to the button number
      * Print the button message

In that layout the second If is controlling both the setting of the *pressed* variable as well as whether or not to print the Pressed! message.

    if(lastButtons[x] == 1){ pressed = x;}

That line is saying "If last buttons X is 1, then set pressed to X. That is all it is doing. Nothing more, nothing less.


message:
Delay on multiple NRF24L01+ (RF24.h) and Arduino nodes

I have set up a system using 4 arduino clones, each wired to an NRF24L01+ radio. I am using the RF24 library by maniacbug (https://github.com/maniacbug/RF24) and have set-up the nodes with 1 base node as a receiver and 3 child nodes that transmits continuously to the receiver.

What I want to do is to send the read and analog value wirelessly from the child nodes to the base node as fast as possible. I used the starping example as a guide and it looks almost realtime when only 1 child node is active. When I turn on another child node, most of the time the update stops for a while then continue on, with randomly updating either child 1 or child 2.

I'm guessing there's a collision that's causing the delays. How do I lessen these delays? I'm thinking of having some sort of scheduling system for the children to send their messages (like, child2 will send only after child1, etc.) I also tried `radio.setAutoAck(false)` in an attempt to lessen the delays but that made all my readings stop altogether.

**base node**:

  #include "Timer.h"
  #include <SPI.h>
  #include "nRF24L01.h"
  #include "RF24.h"
  #include "printf.h"

  RF24 radio(9,10);
  Timer t;

  const uint64_t pipes[5] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL, 0xF0F0F0F0B4LL, 0xF0F0F0F0A5LL, 0xF0F0F0F096LL };
  unsigned int values[3] = {0,0,0};
  void setup(void)
  {

    Serial.begin(115200);
    printf_begin();
    //printf("Receiver Node Active\n\r");

    radio.begin();

   radio.openReadingPipe(1,pipes[0]);
   radio.openReadingPipe(2,pipes[1]);
   radio.openReadingPipe(3,pipes[2]);
   radio.openReadingPipe(4,pipes[3]);
   radio.openReadingPipe(5,pipes[4]);

    radio.startListening();
    radio.printDetails();
    t.every(1, print_values); //call print_values() every 1ms

  }

  void loop(void)
  {
   int sender_id;
   uint8_t pipe_num;
   if ( radio.available(&pipe_num) )
   {
     unsigned int message;
     bool done = false;
    while (!done)
    {
     done = radio.read( &message, sizeof(message) );
    }
     sender_id = pipe_num - 1;
     values[sender_id-1] = message;
   }
   delay(1);
   t.update();

   }

   void print_values(){
     //formatted for arduinoscope
     printf("%d %d %d 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n", values[0], values[1], values[2]);
   }
  // vim:ai:ci sts=2 sw=2 ft=cpp

**child node:**

  #include <SPI.h>
  #include "nRF24L01.h"
  #include "RF24.h"

  RF24 radio(0,1);

  const int SW01 = 18;
  const int SW02 = 19;

  const uint64_t pipes[5] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL, 0xF0F0F0F0B4LL, 0xF0F0F0F0A5LL, 0xF0F0F0F096LL };
  int node_id;

  void setup(void)
  {
    node_id=3; //hard coded id
    radio.begin();
    radio.openWritingPipe(pipes[node_id]);
  }

  void loop(void)
  {
   unsigned int val = analogRead(A0);
   radio.write( &val, sizeof(val) );
   //delay(1);
  }

body:
I can think of 3 ways:

 1. You could have the Base polling for updates to each node
    sequentially, or
 2. If all child nodes see each other, node2 can hear when node1
    finished transmitting so it can transmit and so on. Or
 3. You can punch through collisions setting random delays between each
    retry


body:
1) Since these are all one-way communication, disable AutoAck on all NRFs (setAutoAck(false)). You're not doing Ack anyway which will cause retransmission when not acknowledged.

2) Change the address to something better.

Addresses where the level shifts only one time (that is, 000FFFFFFF) can often be detected in noise and can give a false detection, which may give a raised Packet Error Rate. Addresses as a continuation of the preamble (hi-low toggling) also raises the Packet Error Rate

3) Put a capacitor between ground and Vcc on all NRFs.


body:
I am too building a RF24 based network there were two issues I encountered:

1) Update your libraries, use [TMRh20 fork of RF24][1] (to make your life easier, use [RF24Mesh][2] too)

2) Add a decoupling cap to the NRF24L01+ power pins.

  [1]: http://tmrh20.github.io/RF24/
  [2]: http://tmrh20.github.io/RF24Mesh/


message:
How to prevent Arduino compiler from merging changing of port pin outputs into a single operation

I want to set one pin's output value, and then set a different pin's output value so that the two pins change value one after the other.
However, the compiler optimises the two calls to change both pins in one go.

```
PORTD |= _BV(0);    //set pd0 to high
PORTD |= _BV(1);    //set pd1 to high
PORTD &= ~(_BV(1)); //set pd1 to low
```

The two pins go high simultaneously. I tried inserting a NOP between these but it doesn't change behaviour.

(I originally intended to include an oscilloscope screengrab to show what was happening - that's how I knew (or got the wrong impression) that the two pins were changing at the same time. But the photo wasn't shifting from my Nexus 7 for me to access it from my laptop.)

body:
I certainly can't duplicate what you are saying.  The small code snippet:

    void setup() {
     PORTD |= _BV(0);
     PORTD |= _BV(1);
     PORTD &= ~(_BV(1));
    }

    void loop() {
    }

compiles into:

    000000a6 <setup>:
      a6: 58 9a        sbi 0x0b, 0 ; 11
      a8: 59 9a        sbi 0x0b, 1 ; 11
      aa: 59 98        cbi 0x0b, 1 ; 11
      ac: 08 95        ret

    000000ae <loop>:
      ae: 08 95        ret

That is clearly two separate bit sets followed by a bit clear.

I am using UECIDE that is set to use GCC 4.3.2

If I switch to GCC 4.8.1 instead, the code generated is identical.

Even turning on full -O3 optimization I still get the same results.

So how are you determining that it's happening at the same time?


message:
Difference between void setup() and void setup(void)

As it says in the title. I have been searching but I cant seem to find the answer.

What is the difference between void setup() and void setup(void) as well as void loop() and void loop(void)?

body:
Absolutely nothing, in modern versions of C and C++. Specifying no arguments is the same as specifying `void`.

In old versions of C a function with no arguments took a single implicit `int` argument or allowed you to specify the arguments on a separate line, but no one uses anything like that nowadays.


message:
Arduino software won't open in Mac OSX 10.10.1

I am having trouble opening the Arduino software on my mac, since I have updated Java to version 8 the Arduino software won't open. It does not give an error just closes instantly.

I have tried getting the newest version of the Arduino.cc site but no change.

Can anyone tell me how to open Arduino using an older version of Java?

body:
Download and install the Apple version of Java (6): http://support.apple.com/kb/DL1572

If you need Java 8 SDK for some reason, the two can coexist because the Arduino IDE will explicitly ask for the (Apple Version) of Java 1.6 using 'JavaApplicationStub':

    $ ./JavaApplicationStub
    [JavaAppLauncher] Requested [1.5*], launching in [1.6] instead.
    Experimental:  JNI_OnLoad called.
    Stable Library
    =========================================
    Native lib Version = RXTX-2.1-7
    Java lib Version   = RXTX-2.1-7

Note however that if you have both Apple Java and Oracle installed, running 'java' or 'javac' form the command line will run the Oracle version.

    $ java -version
    java version "1.8.0_25"

If you need to switch the 'command line' version, change the symlinks in:

    /System/Library/Frameworks/JavaVM.framework/Versions/

'JavaApplicationStub' will use the Apple version located in /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java.

As such, 'normal' java programs will generally use the Oracle version, while applications running in your browser or using JavaApplicationStub explicitly (like Arduino) will use the 'Apple' version.


body:
I just clicked on the apple icon => about this Mac => software update => Mac Sierra update.

now to get the USB port to work

numbatmark


message:
Feeble click in relay but it doesn't get activated when connected to Arduino circuit

I have an Arduino uno board and I have a soil moisture sensor

1. connected the digital output pin of the sensor to Arduino input pin
1. connected an output pin of Arduino to the INPUT pin of the relay board
1. programmed the Arduino such that if input is HIGH then the OUTPUT should be HIGH as well
1. connected 5 v pin of Arduino to vcc of the relay board
1. connected gnd pin of Arduino to gnd of the relay board

When my sensor outputs a HIGH DO (digital output), the relay only creates a feeble click sound and does not get activated. The Relay board LED does light up but the relay itself does not work (NC remains closed and NO remains open).

Do I need to supply an external VCC to the relay board? If yes then how should I set up the circuit?

A picture of the relay board is attached. You are right ... it is a 12 v relay. Do I need a 12 v external power source with IN1 coming from Arduino? Any help will be much appreciated.

![Relay][1]

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

body:
You need to join the ground of the external supply to the ground being supplied from the Arduino.  The 12V supply must be capable of at least 100ma

There appears to be a transistor and resistor on the board.  This is probably to drive the relay coil from the Arduino.  However, I would need to look at the circuit diagram of the board to be certain.  Can you supply images of the copper side and component side of the board to see what the connections are.

Ideally the circuit diagram from the manufacturer would be even better.


message:
AVR ATmega328p-pu operating circuit?

I used to work with PIC micro-controller so i know what it needs to work from operating circuit to crystal oscillators needed and other components to power it up , my question here where can i find the operating circuit for ATmega32p-pu and other AVR models . or all i need to do is to give it +5v and gnd and it will work ?

body: You're looking for [this](http://arduino.cc/en/main/standalone) I think? How to set up an Arduino on a breadboard.


message:
What's the difference between different Ethernet Shields?

I am working on a project with Arduino and I need an Ethernet shield. but after searching in some electronics shops I found there isn't only one but a lot. I don't know which one is better and what are the differences.

[Arduino Ethernet with PoE module](http://www.dfrobot.com/index.php?route=product/product&product_id=502&search=ethernet+&description=true)

[Ethernet Pro](http://www.dfrobot.com/index.php?route=product/product&search=ethernet &description=true&product_id=497)

Ethernet Shield for Arduino - W5200

Arduino Ethernet Rev3 Without PoE Module

Ethernet Shield W5100 For Arduino

in DFRobot Online Shop.

body:
Clearly the 'best' one is the one that meets your requirements (or is the most expensive - that's always the best, right?).

You say you need an ethernet shield - can you explain why? Without that information, it's almost impossible to tell you which is the most suitable.

If you are looking at IoT applications, it may be that an Ethernet shield isn't the 'best' thing for you. If you just want access to the local IP network, you could use any of those. If you want the 'best' library of functions to support your application, that may affect which module you use.

For me, I think the best module is the cheapest one that gives me connectivity: http://www.aliexpress.com/item/Hot-Sale-ENC28J60-Ethernet-LAN-Network-Module-For-Arduino-51-AVR-STM32-LPC/32254842414.html

The W5100 is also a good choice, but only if it is under $7


body:
What one that is the best is highly subjective.

Though my **personal** experience is that arduinos original is the one with the best support. Where you can find alot of documentation about the other ones, you might need to do some legwork updating the code to the latest version of the arduino ide or use an older ide.

Be aware that some Arduinos has integrated ethernet, and others are SHIELDS, you recognize the arduinos with ethernet by the power-connector, and the shields by the distinct name containing "Shield", though shields require an arduino to work. The arduino with integrated ethernet does not.

Also be aware that not all shields fits arduinos boxes if you want to encase it. And of cause, buying arduinos original products, cost a bit more - but you support the arduino foundation, and further development of the products.


message:
74HC595N in series error

I want have 2 74HC595N shift registers in series.

I built this schematic

![][1]

When I send a value to the first register, it is sent to the second one. I have same value on both. I change them (master/slave) but the result is the same.

I connected pin 9 on the first SR first with pin 14 on the second. I am using Johnny Five on Galileo Gen 1 with `shiftRegister.send(25)` to send the data.

What am I doing wrong because several days ago I made it and it worked?

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

body:
If you had it working and it has changed, I would suggest trying a few changes to track down the issue. The schematic seems OK so assuming that all connections are sound, I would look towards proving the code. Maybe try a simple pure Arduino sketch designed for the 74HC595N and see if the results are the same. If not, the culprit is almost certainly Johnny Five.

Perhaps try [this sketch](http://arduino.cc/en/Tutorial/ShftOut22) which should work with your schematic (remap the I/O though to your 2,3,4 configuration). If the problem persists, throughly examine your connections because there is very little else which would prevent it from working - especially given that it did work a few days ago. Also, have you got another Leonardo to test with?

Finally, the schematic for the Arduino-only example shows a cap on the latch line - presumably for debouncing - which is missing from your schematic. I don't think you've damaged your registers but I wouldn't rule it out.


message:
How to pass value of a function from the RFID-RC522 library into a variable then be sent into either serial or ethernet?

I'm using an RC522 RFID reader with an Arduino UNO. There is a function?? (or whatever it's called :)) in Miguel Balboa's new MFRC522.h library which is mfrc522.uid.uidByte[i] that prints the bytes of the unique ID. The repetition of the function results in 8 piece of HEX digits that are from the 2 numbers that each function outputs (2+2+2+2=8). Whenever I use the line of codes that are commented out, the serial monitor outputs them successfully. So for example, 12345678 is the unique id, each array displayed 12, then 34, then, 56, then 78 which is 12345678 in the serial. which is fast and unnoticeable besides that there are no spaces included when on output. The thing is, I want to output all of these into a single variable.(Please help me also on how to concatenate) How can I do this? An attempt was done below (not commented out) but it outputs only the number 16, consistently, which is I think due to a data type problem. The variables are initialized as int. The "function" which I found in the library is initialized as byte (correct me If I'm wrong). But when the variables are initialized as byte, I cannot upload the sketch since there are errors. Please help. :( (The reason I need it to be saved into a single variable is because I am placing it in the GET method of an Ethernet Client. I don't think the bare function can do that. (Or if it can, can you please help with the code? :)) Thanks

<pre> <code>
// Dump UID
        //Serial.print("Card UID:");

                //Serial.print(mfrc522.uid.uidByte[0], HEX);
                //Serial.print(mfrc522.uid.uidByte[1], HEX);
                //Serial.print(mfrc522.uid.uidByte[2], HEX);
                //Serial.print(mfrc522.uid.uidByte[3], HEX);

                serNum0={mfrc522.uid.uidByte[0], HEX};
                serNum1={mfrc522.uid.uidByte[1], HEX};
                serNum2={mfrc522.uid.uidByte[2], HEX};
                serNum3={mfrc522.uid.uidByte[3], HEX};
                Serial.print(serNum0);
                Serial.print(serNum1);
                Serial.print(serNum2);
                Serial.print(serNum3);

body:
 As far as I can understand, you expect to receive byte data from the RFID reader, you would like to store this data into a single variable, and eventually print its content, or manipulate it in some way. You could do this maintaining a byte array (or uint8_t array).

Let's suppose, for example, to receive a unique ID of length 4 from the RFID reader. In this case you could simply store it into a **serNum[serNum_size]** array, where **serNum_size** is just the number of data you are expecting to receive, and later access its content for whatever manipulation you would like to do.

    int serNum_size = 4;        // reader data size
    byte serNum[serNum_size];   // reader data content

    for(int i = 0; i < serNum_size; i++){
     serNum[i] = mfrc522.uid.uidByte[i]; // store reader data block
     Serial.print(serNum[i], HEX);       // hexadecimal form
    }

As far as the print is concerned, you can simply print the byte entry and apply the HEX format. In this way, the stored value will be considered as its hexadecimal value.


message:
Using multiple timers and avoiding conflicts

I would like to use three timers in CTC mode to launch three Interrupt Service Routines at different frequencies.

In this application I need to use the servo library, millis() and micros() functions.

**Timer3** (Working)

Thanks to this [question][1], Timer3 has been set up in the following way:

      cli();          // disable global interrupts
      TCCR3A = 0;     // set entire TCCR3A register to 0
      TCCR3B = 0;     // same for TCCR3B

      // set compare match register to desired timer count:  @~744 Hz
      OCR3A = 20;
      // turn on CTC mode:
      TCCR3B |= (1 << WGM32);
      // Set CS10 and CS12 bits for 1024 prescaler:
      TCCR3B |= (1 << CS30) | (1 << CS32);
      // enable timer compare interrupt:
      TIMSK3 |= (1 << OCIE3B);
      // enable global interrupts:
      sei();

      ISR(TIMER3_COMPB_vect)
      {
         cont++;
      }

**Timer4**
I've tried with this configuration:

    cli();          // disable global interrupts
    TCCR4A = 0;     // set entire TCCR3A register to 0
    TCCR4B = 0;     // same for TCCR3B

    // set compare match register to desired timer count: @ ~744 Hz
    OCR4A = 20;
    // turn on CTC mode:
    TCCR4B |= (1 << WGM42);
    // Set CS10 and CS12 bits for 1024 prescaler:
    TCCR4B |= (1 << CS40) | (1 << CS42);
    // enable timer compare interrupt:
    TIMSK4 |= (1 << OCIE4B);
    //TIMSK4 |= (1 << OCIE4A); same issue
    // enable global interrupts:
    sei();

    ISR(TIMER4_COMPB_vect) //TIMER4_COMPA_vect same issue
    {
      cont++;
    }

But the compiler returns an error caused by the servo library conflict:

> Servo\Servo.cpp.o: In function '__vector_42': C:\Program Files
> (x86)\Arduino\libraries\Servo/Servo.cpp:117: multiple definition of
> '__vector_42' Timer4B_800Hz.cpp.o:C:\Program Files
> (x86)\Arduino/Timer4B_800Hz.ino:49: first defined here c:/program
> files
> (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.3.2/../../../../avr/bin/ld.exe:
> Disabling relaxation: it will not work with multiple definitions

As Gerben suggested in a comment in this [question][2]:

> They are just hogging all timers. I guess you have to alter the
> library slightly by removing the #define _useTimer3 line, or try
> putting a #undef _useTimer3 right after the include. –  Gerben

I would avoid changing the servo library since motors play a critcal role in the application.

**Timer 5** Same issue

Which timers and output compare registers can I use to set up the three ISR correctly?

  [1]: https://arduino.stackexchange.com/questions/5431/how-to-update-a-variable-in-an-isr-using-timers/6447#6447
  [2]: https://arduino.stackexchange.com/questions/5396/setting-timer3-in-ctc-mode-conflict-with-servo-library/5432#5432

body:
The problem is the Servo library. This library is claiming all the timers, so you can't use them yourself. What I do to fix this is edit the Servo.h (or ServoTimers.h) file.

    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    //#define _useTimer5
    #define _useTimer1
    #define _useTimer3
    //#define _useTimer4
    //typedef enum { _timer5, _timer1, _timer3, _timer4, _Nbr_16timers }   timer16_Sequence_t;
    typedef enum { _timer1, _timer3, _Nbr_16timers } timer16_Sequence_t;

This will remove the 2 timers (4 and 5) for the Mega boards, but you can still attach 24 servo's. If you need more, you should edit this file again.


message:
Comparing a char with the symbols '.-'

I'm using the Arduino software to create a Morse code decoder using the  serial monitor.

I enter a Morse code such as `.-` as a text string and it's displayed in the LCD as a alphanumeric text. So if I enter `.-` into the serial Monitor, `A` is displayed on the LCD. But it only works for single symbols, not the dot and dash together.

Is there a way to make the if statement as seen below accept both the dots and dashes together?

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup()
    {
      lcd.begin(16, 2);

     Serial.begin(9600);
    }

    void loop()
    {
      char schar;

      if (Serial.available())
      {
        schar = Serial.read();

        Serial.write(schar);

        if (schar== '.-' ){
          Serial.write('A');
          lcd.print('a');
        }
      }
    }

body: `schar` is a `char` variable of size 1. It makes no sense to compare it with `'.-'`, which is supposed to be a string. Declare a `char[3]` array, fill it as string and use the `strcmp` function. It's elementary C knowledge.


body:
Your first problem is that there is no way for schar to contain two characters in the first place; Since schar is declared as a char, it can only contain one character.

You need to make a String out of the serial input. `Serial.read()` only returns one character at a time, so you will need to make sure you iterate over all the input. Then you can compare the whole String with another, and see if both characters match at once. Just look at this code to see different ways of manipulating Strings: http://arduino.cc/en/Tutorial/StringComparisonOperators

Notice that string literals use double quotes, not single quotes like characters.

Also, be aware of the fact that `string` and `String` are different things. lowercase 's' is an array of characters, capitol 'S' is the class that has those useful string comparison member functions. The class is more resource intensive, but I think in your case the readability and convenience are worth it.


body:
You could use C strings, (type `char*`) or C++ String objects (type `String`). Both would work.

If you use C strings, you'll need to use functions like `strcmp()` from the C library to see if your input string matches a particular morse sequence.

If you use C++ String objects, you'll need to use the methods of that class. I'm less familiar with that class.

If you have single Morse characters, matching them up is pretty easy. If you have a continuous stream of dots and dashes, though, it's a much thornier problem. You need a way to figure out the boundary between characters. Morse characters can be sequences of between 1 and 5 dots and dashes.

Unless there are extra delays between the dots/dashes for a character, I'm not sure how you figure out where the boundaries are. There are already computer Morse code readers, though, so this must be a "solved problem". I'd do some googling.


message:
Sweep with two shift registers

I am working with 8 dual color LED's and 2 shift registers. My connections are in place. But I do not understand how to work with 2 shift registers.

So I am trying to make this: turn the first led on, turn the first led of, go to the next led, turn it on, turn in off, etc...

I do not know how to jump from the first shift register to the second shift register when the last LED of the first shift register is turned off.

body:
Exactly the same as when you're trying to keep them dark when lighting an LED with the first register: shift two bytes.

The first byte shifts into the first register to begin with, and then *out* of the first register and *into* the second register when you shift the second byte into the first register. Just make sure only the appropriate bits are set in both bytes and you're good to go.


message:
Oil Pressure / Water Pressure / Boost Pressure ( Turbo Engine )

I'm an automotive enthusiast and I want to build some gauges by myself using Arduino.

I was taking a look at this [pressure transducer or sender, 100 psi, stainless steel, for oil, fuel, air, water][1] and I was thinking if I can use this sensor to do all of the these tasks: Water, Boost and Oil Pressure.

Look at the Signal output vs read PSI chart of the sensor

![ Signal output vs read PSI chart of the sensor][2]

I came out with this equation for the PSI calculation:

Since it is a `Y = bx + a`, where:

    a = 0.5
    b = y2 - y1 / x2 - x1 = (4.5 - 0.5 ) / (100 - 0) = 4/100 = 0.04
    x = PSI
    y = Signal's Voltage

This means that

Voltage Reading = 0.04PSI + 0.5

So we have :

PSI = (Voltage Reading - 0.5 ) / 0.04

Am I correct? Can I use this sensor?

  [1]: http://www.ebay.com/itm/Pressure-transducer-or-sender-100-psi-stainless-steel-for-oil-fuel-air-water-/271576977896?pt=Motors_Car_Truck_Parts_Accessories&hash=item3f3b3fd1e8&vxp=mtr
  [2]: https://i.stack.imgur.com/6Yy1T.png

body:
You math checks you to me.

When you code it, You will probably read a voltage using an analog pin (or external ADC) that will return an integer between 0 being 0 volts, and 1024 = vin volts. vin will be 5 if you don't wire up the vin pin, and 1024 could be different if you use an external ADC.

Anyway you should be aware that the raw readings will probably not be 0-5, and they dont have decimal points. You will need to first convert the reading into the voltage with something like this:

    float voltage = ((float)reading)/1024.f;

notice that the datatype float is used (enables decimal points) and that the constant being divided by is also a float so that the calculations will definitly happen between floating point numbers.


body:
I'd add code to test for voltage between 0.0 to less than or near 0.5 volts. Disconnected pressure transducer won't present 0.5v, 0 PSI transducer voltage; not output 0.5 v @0 PSI shows a lower voltage indicated a fault or open circuit in transducer wiring. My experiences, too many times other engineers "borrowed" hardware and I wound up troubleshooting a non-fault but theft ;} Only a few lines of code to ensure connections are correct.
The floating point vs integer arithmetic compute time is outweighed by settling time of A/D converter and transducer. The auto part was my solution to show HOA board stats for my wildly varying water pressure at Condo Assn,  very cost effective too.


message:
Get the uploaded code from arduino by using arduino IDE 1.0.6

Recently bought a arduino device which already have program,

it is model AR-293D and I have already connect it with my PC(windows 7) through usb

when I open the IDE , It seems there is no function that read the uploaded program?

And after searching a while , like some beginner tutorial , it only tell you how to upload the program but not how to get the uploadded program

http://www.forefront.io/a/beginners-guide-to-arduino

So, I wonder how to get the code? Thanks a lot for helping, I worried erase the uploadded program so I need to take caution about this

body:
<!-- language-all: lang-none -->

You can download the **hex machine code** from the Arduino by using an ISP programmer, like this one:

[![ISP programmer][1]][1]

A command like this could be used to read the flash memory and save it into `myfile.hex`:

    avrdude -c avrisp -p m328p -U flash:r:myfile.hex:i

However be warned that this file will look like this:

    :100000000C945C000C946E000C946E000C946E00CA
    :100010000C946E000C946E000C946E000C946E00A8
    :100020000C946E000C946E000C946E000C946E0098
    :100030000C946E000C946E000C946E000C946E0088
    :100040000C9488000C946E000C946E000C946E005E
    :100050000C946E000C946E000C946E000C946E0068
    :100060000C946E000C946E00000000080002010069
    :100070000003040700000000000000000102040863
    :100080001020408001020408102001020408102002
    :10009000040404040404040402020202020203032E
    :1000A0000303030300000000250028002B000000CC
    :1000B0000000240027002A0011241FBECFEFD8E043
    :1000C000DEBFCDBF21E0A0E0B1E001C01D92A930AC
    :1000D000B207E1F70E94F1010C9401020C940000B8

As you can see, you haven't really got "the program" back.

---

As Mikael Patel points out, you can at least turn it into assembler by doing this:

    avr-objdump -j .sec1 -d -m avr5 myfile.hex

However the output is still not C code like you see in the IDE:

      d4: 0e 94 f1 01  call 0x3e2 ;  0x3e2
      d8: 0c 94 01 02  jmp 0x402 ;  0x402
      dc: 0c 94 00 00  jmp 0 ;  0x0
      e0: 61 e0        ldi r22, 0x01 ; 1
      e2: 8d e0        ldi r24, 0x0D ; 13
      e4: 0c 94 81 01  jmp 0x302 ;  0x302
      e8: 61 e0        ldi r22, 0x01 ; 1
      ea: 8d e0        ldi r24, 0x0D ; 13
      ec: 0e 94 ba 01  call 0x374 ;  0x374
      f0: 68 ee        ldi r22, 0xE8 ; 232
      f2: 73 e0        ldi r23, 0x03 ; 3
      f4: 80 e0        ldi r24, 0x00 ; 0
      f6: 90 e0        ldi r25, 0x00 ; 0
      f8: 0e 94 f5 00  call 0x1ea ;  0x1ea
      fc: 60 e0        ldi r22, 0x00 ; 0
      fe: 8d e0        ldi r24, 0x0D ; 13
     100: 0e 94 ba 01  call 0x374 ;  0x374
     104: 68 ee        ldi r22, 0xE8 ; 232
     106: 73 e0        ldi r23, 0x03 ; 3
     108: 80 e0        ldi r24, 0x00 ; 0
     10a: 90 e0        ldi r25, 0x00 ; 0
     10c: 0c 94 f5 00  jmp 0x1ea ;  0x1ea

Unless you are an assembler expert, making sense of that would be pretty hard, and the time taken to do it would be better spent simply rewriting the code from scratch.

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


message:
How to return the value in Arduino function (that can be read by the connected device)?

Right now I have an RC car program for Arduino. The code is like this:

    void loop() {
      distance = Dist.getDistanceCentimeter();
      if(distance<=5 & distance>1)
      if(Serial.available()) {
        lkf = Serial.read();
      switch(lkf) {
      case 'a':
         forward();
         servoX.write(90);
         lkf=0;
         break;
      }
    }

I wrote a TCPclient that can order the RC car to move forward by connecting through TCP and sending the message "a" to the Arduino board.

The problem is how to return the distance to the cilent? Is it simply `return distance;` or something like `system.println(distance);`? Thanks for helping.

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

You are using the USB interface, right? So you just use Serial to send data back. For example, this would send the distance every second:

    unsigned long lastSent;
    void loop() {
      distance = Dist.getDistanceCentimeter();
      if (millis () - lastSent >= 1000)  // every second
      {
        lastSent = millis ();
        Serial.println (distance);
      }

      if (distance <= 5 & distance > 1)
      {
        if (Serial.available()) {
          command = Serial.read();
          switch (command) {
            case 'a':
              forward();
              servoX.write(90);
              command = 0;
              break;
          }  // end of switch
        }
      }
    }


message:
Button reading not going off

I made a circuit which in my intentions would allow me to toggle a LED dimming loop.

Problem is that once I push the button the first time pushing it a second time doesn't toggle the LED loop off.

Here is the code:

    const int LED = 9; // the pin for the LED
    const int BUTTON = 7;

    int val = LOW;

    int old_val = LOW;
    int state = 0;
    int i = 0;

    void setup()
    {
      pinMode(LED, OUTPUT);
      pinMode(BUTTON, INPUT);

    }

    void loop()
    {
      val = digitalRead(BUTTON);

      if ((val == HIGH) && (old_val==LOW))
      {
        state = 1 - state;
        delay(10);
      }

      old_val = val;

      if (state == 1)
      {
        for (i = 0; i < 255; i++)  // loop from 0 to 254 (fade in)
        {
          analogWrite(LED, i); // set the LED brightness
          delay(10);           // Wait 10ms because analogWrite
          // is instantaneous and we would
          // not see any change
        }

        for (i = 255; i > 0; i--) // loop from 255 to 1 (fade out)
        {
          analogWrite(LED, i); // set the LED brightness
          delay(10);           // Wait 10ms
        }
      } else
      {
        analogWrite(LED, 0);
      }

      if ((val == LOW) && (old_val == HIGH))
      {
        delay(10);
      }
    }

Here is the circuit scheme:

![circuit schematics][1]

I would be interested both in learning what the problem is AND learning any mental methods I can apply to debug in such situations.

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

body:
While the led is fading in and out (which takes 5 seconds), the state of the button is never checked. So you'd need to have the button released for at least 5 seconds (so old_val becomes LOW), and then pressed exactly we the led is faded out (again, 5 seconds later). So try keeping the button pressed for at least 5 seconds.

You probably want to rewrite your code, so the button is more 'responsive'. Below I added an example of how to do this.

    const int LED = 9; // the pin for the LED
    const int BUTTON = 7;

    int val = LOW;
    int old_val = LOW;

    bool fadeLed = false;
    int brightness = 0;//current pwm value
    int direction = 1;// 1 is brightness is increasing, -1 if brightness is decreasing

    void setup()
    {
      pinMode(LED, OUTPUT);
      pinMode(BUTTON, INPUT);
    }

    void loop()
    {

      /* check the button */
      val = digitalRead(BUTTON);
      if ((val == HIGH) && (old_val==LOW))
      {
        // button pressed ( called only once per press )
        fadeLed = !fadeLed;// invert boolean
      }
      old_val = val;

      /* update the leds brightness */
      if( fadeLed )
      {
        // fade led in and out
        if( brightness==0 )
          direction = 1;//change direction is minimum value reached
        if( brightness==255 )
          direction = -1;//change direction is maximum value reached
        brightness += direction;// increase/decrease brightness
      }
      else
      {
        // fadeLed is disabled, so only decrease brightness till it reaches zero
        if( brightness>0 )
          brightness--;
      }

      analogWrite(LED, brightness); // set the LED brightness
      delay(10);           // Wait 10ms because analogWrite
                           // is instantaneous and we would
                           // not see any change

    }

Any questions about the code; just let me know.


message:
how to block Arduino code until a certain event?

i am tring to enter a series of numbers using "keypad" to different variables..when simulate the code on proteus it only took the first "getkey()" function and ignored the rest ..
SO,
How can i block an arduino code until a key is pressed by keypad, in other words prevent the rest of code from being executed before a key is pressed

body:
It depends on how the "keypad" is implemented. If you've got it hooked up to a hardware interrupt, then you only need to add an interrupt handler for that event.

On the other hand, the more "straight-forward" implementation is that you have to poll the pins to see if a key was pressed.  Simply do that in a loop until you see a key press, call your event-handler method, and then continue to loop.


message:
Newbie needing help with debounce errors in arduino

So I found a code I would like to use and not sure how to edit the code properly.

    #include <Debounce.h>

    void matrix(char matrix[7]) {
      int map[10];
      map[0] = 2;
      map[1] = 3;
      map[2] = 4;
      map[3] = 5;
      map[4] = 6;
      map[5] = 7;
      map[6] = 8;
      map[7] = 9;

      int i=0;
      for(i=0;i<=7; i++) {
       if(matrix[i] == 0x30) { // 0x31=1, 0x30=0
          Serial.println(map[i]);
          digitalWrite(map[i],LOW);
       }
       else digitalWrite(map[i],HIGH);
      }
    }

    void show(int number) {
      switch(number) {
        case 0:
          matrix("11111100");
          break;
        case 1:
          matrix("01100000");
          break;
        case 2:
          matrix("11011010");
          break;
        case 3:
          matrix("11110010");
          break;
        case 4:
          matrix("01100110");
          break;
        case 5:
          matrix("10110110");
          break;
        case 6:
          matrix("10111110");
          break;
        case 7:
          matrix("11100000");
          break;
        case 8:
          matrix("11111110");
          break;
        case 9:
          matrix("11110110");
          break;
        default:
          matrix("00000010");
          break;
      }
    }

    #define t1 13
    #define t2 12

    Debounce debouncert1 = Debounce( 20 , t1 );
    Debounce debouncert2 = Debounce( 20 , t2 );

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

      // initialize the digital pin as an output:
      pinMode(13, INPUT);
      pinMode(12, INPUT);
      pinMode(2, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);
      pinMode(6, OUTPUT);
      pinMode(7, OUTPUT);
      pinMode(8, OUTPUT);
      pinMode(9, OUTPUT);
    }

    int setCountPlus(int count){
      if(count == 9){
        count = 1;
      }
      else{
        count++;
        count %= 10;
      }
      return count;
    }

    int setCountMinus(int count){
      if(count==1){
        count = 9;
      }
      else{
      count--;
      count %= 10;
      }
      return count;
    }

    void loop()
    {
      int i=-1;
      show(i);
      while(1){
        debouncert1.update();
        debouncert2.update();
        if(debouncert1.read()){
          i=setCountPlus(i);
        }
        if(debouncert2.read()){
          i=setCountMinus(i);
        }
        if(i==10){
          i=1;
        }
        show(i);
        delay(250);
      }
    }

as for the errors.

sketch 65: error: 'Debounce' does not name a type

sketch 66: error: 'Debounce' does not name a type

sketch .ino: In function 'void loop()':

sketch 108: error: 'debouncert1' was not declared in this scope

sketch 109: error: 'debouncert2' was not declared in this scope

Any help would be great on fixing the code to stop getting errors.

body:
In the description of [Debounce](http://playground.arduino.cc/Code/Debounce), you'll find the hint that this library is **outdated** and no longer maintained.

Its successors, **Bounce1** and, more recently, **Bounce2** are available from a **github** repository by Thomas Fredericks, [Bounce-Arduino-Wiring](https://github.com/thomasfredericks/Bounce-Arduino-Wiring).

Instead of simply downloading and unzipping the archive to `${HOME}/sketchbook/libraries`, you might want to consider that this is the right moment to get familiar with git repositories as an easily updatable source for third-party libraries.

Supposed that you're on a GNU/Linux system with `git` installed, you would

    cd /${HOME}/sketchbook/libraries
    git clone https://github.com/thomasfredericks/Bounce-Arduino-Wiring.git

to obtain a clone of the necessary data.

If the name of the directory of the library contains dashes (`-`), you'll have to change this name: remove the dashes or replace them with underscores (`_`). Names with dashes aren't valid!

Once in a while, you would change to the directory of the respective library and simply run `git pull` to update your local copy to the latest version of the repository.


body:
Depending on the switch type:
-SPDT (SIngle Pole Double Throw) - You would use a Cross Coupled NAND Gates (Flip Flop, Set Reset) This will set true to the side it sees power at from the switch and if it bounces it can't change state until the switch touch the other contact.

-SPST (Single Pole Single Throw) - You can use a software debounce where you would detect a signal and then wait for 10ms then read again and if there is a signal still, it is a debounced signal.  --OR--  You can use capacitors to help extend the life of a signal.

so debounce code

    bool sw13=false;
    bool sw12=false;
    while(1){
    if(digitalRead(13)==HIGH && !sw13){
      delay(20); //Delay For 20ms
      if(digitalRead(13)==HIGH){
        i=setCountPlus(i);
        sw13=true;
      }
    }else{
        sw13=false;
    }
    if(digitalRead(12)==HIGH && !sw12){
      delay(20);
      if(digitalRead(12)==HIGH){
        i=setCountMinus(i);
        sw12=true;
      }
    }else{
        sw12=false;
    }
    if(i==10){
      i=1;
    }
    //show(i);
    delay(250);
    }


message:
How can I tell which pins I will have left available by looking at a shield?

I'm very new to Arduino and came to a point where I'm interested in playing with shields, such as LCDs.

For example, I really like the looks of "LCD 1602 with keypad" module, but it seems to be using a lot of pins.

 - By looking at a module / shield, how can I tell (or at least estimate) which pins will be used and which ones I will have left if I stack them with my Uno or Mega without printed schematics?

body:
If you look in the 'Tutorials' section of [this page](http://www.sainsmart.com/sainsmart-1602-lcd-keypad-shield-for-arduino-duemilanove-uno-mega2560-mega1280.html) you can see the pins used. All of the buttons come through in one analogue input and you'll need a further 7 digital I/O pins. So 8 in total which would leave 5 analogue and 4 digital (I think) pins on an Uno.

As for how to tell which ones, does it matter in advance? I would just map the I/O in the sketch to suit. If you need to plan that far in advance though, it seems that J5 in this [schematic](http://sainsmart.com/zen/documents/20-011-901/schematic.pdf) shows which pins travel through the shield (i.e. are available to use in conjunction with the shield). Also J6 shows the 5 remaining analogue pins.


body:
why dont you use an i2c adapter for this type of display?
search for i2c display module.
i2c only needs 2 wires for data and clock and 2 for power.
you can also easily locate the SDA and SCL pins on your arduino


message:
Where can I see the output of printf?

I would like to know where I can see the output when I use the command `printf`. I am programming using the Arduino interface.

Update
-

I'll add a few lines of code for better understanding:

    #include <stdio.h>

    int main(void)
    {
        printf("Hello World");

        return 0;
    }

body:
In `setup()`, start serial and choose your speed:

    Serial.begin(9600);

Wherever you want to write to serial:

    Serial.write("write this");

Wherever you want a newline:

    Serial.println();

## example

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

    }

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

    }


body:
If you're working with the standard Arduino environment and libraries then `printf()` won't display anything anywhere. The reason is that microcontrollers could be connected to any number of different output/communication devices in any way. `stdio` would have no idea how or where to send the data.

The most common approach to outputting text from an Arduino (particularly during development) is to send it to the primary UART port using [`Serial.begin()`][1] and [`Serial.print()`][2]. If the Arduino is connected to your computer via USB then the Arduino IDE's serial monitor should display the result.

If you *really* want to use `printf()` though then it is possible to make it work (or implement similar functionality). A full explanation is on this page:

 * http://playground.arduino.cc/Main/Printf

  [1]: http://arduino.cc/en/Serial/Begin
  [2]: http://arduino.cc/en/Serial/Print


message:
Why my RTC module doesn't return the right date/time?

I have a RTC module DS1307 (MR005-001.2) on my Arduino Uno.
I use the Wire.h / Time.h / DS1307RTC.h libraries.

The date and time returned is completely wrong ("17:18:9 2 4 2036") ... What do I do wrong ??

Thanks !

Here is my partial code for setup() :

        setSyncProvider(RTC.get);
      if(timeStatus()!= timeSet)
         Serial.println("Unable to sync with the RTC");
      else
         Serial.println("RTC has set the system time");

This writes "RTC has set the system time", so I guess something is happening right...

Here is my partial code for loop() :

        Serial.print(hour());
      Serial.print(":");
      Serial.print(minute());
      Serial.print(":");
      Serial.print(second());
      Serial.print(" ");
      Serial.print(day());
      Serial.print(" ");
      Serial.print(month());
      Serial.print(" ");
      Serial.print(year());
      Serial.println();

Just as in the example ... and the date/time returned is "17:18:9 2 4 2036"

body:
You setup interpretation should be more like:

     setSyncProvider(RTC.get);
     if(timeStatus()!= timeSet)
       Serial.println("RTC has never been set");
     else
        Serial.println("RTC has a time");

To conditionally sync the clock to the compilation time if the clock is not running:

    if (! RTC.isrunning()) {
       Serial.println("RTC is NOT running!");
       // following line sets the RTC to the date & time this sketch was compiled
       // uncomment it & upload to set the time, date and start run the RTC!
       RTC.adjust(DateTime(__DATE__, __TIME__));
    }
    // following line unconditionally resets the RTC to the date & time this sketch was compiled
    // uncomment it & upload to set the time, date and start run the RTC!
    // RTC.adjust(DateTime(__DATE__, __TIME__));

To unconditionally sync it to the compilation time, uncomment the last line and reload for one cycle, then re-comment it and reload to let the clock run itself.


message:
Going from one shift register to two shift registers

I am able to control one shift register with this shift function:

    void shift (int pin) {
      shiftOut(ds,shcp,MSBFIRST,pin);
      digitalWrite(stcp,HIGH);
      delay(100);
      digitalWrite(stcp,LOW);
    }

but when I move to 2 shift registers it does not add up.. how do I need to adapt this method to make it work with 2 shift registers when I am going from 8 leds to 16 leds?

My second register now just copies the first register.. I want the second register to continue instead of repeat

body:
- Configure SPI
  - Hook up your shift registers
    * common `SS`
    * common `CLK`
    * `QH*` of the first shift register to `SER` of the next

In order to transfer the bytes

  * Pull `SS` low
  * `ShiftOut` first byte
  * `ShiftOut` next byte
  * Pull `SS` high again to finish the SPI transfer

**UPDATE**

*This is untested, just out of memory!*

    #include<SPI.h>
    // note that the pins for CLK and MOSI are defined here

    unsigned int ledPattern = 0b1111000011110000;
    // store the state for 16 LEDs here

    void setup(void)
    {
        pinMode(SS, OUTPUT);
        digitalWrite(SS, HIGH);
        SPI.setDataMode(3);
        SPI.setClockDivider(4);
        SPI.setBitOrder(MSBFIRST);

        // let's transfer 2 bytes
        digitalWrite(SS, LOW);
        SPI.transfer(ledPattern & 0xff00;) // high byte
        SPI.transfer(ledPattern & 0x00ff;) // low byte
        digitalWrite(SS, HIGH);
    }

**UPDATE II**

You are by no means limited to 2 shift registers! In 2013, we did a 8x11 LED display for an upcycling art project. Eleven 74HC595 were chained to display some patterns. Each 'pixel' consisted of 3 12V SMD LEDs on a stripe. Consequently, each shift register was connected to an `ULN2803`.

I just uploaded a [video](https://www.youtube.com/watch?v=jObemcticOo) from the construction phase, showing a test pattern.


body:
It sounds like the primary issue is how you've connected the two shift registers.  You just need the bit shifting out of the first one to shift into the second one so they act, together, as one longer shift register.

![Two serial shift registers][1]

The example pictured is described in full here, under the heading "Example 2":
[http://arduino.cc/en/tutorial/ShiftOut][2]

As Klaus mentioned, you want to first `ShiftOut` the byte you intend to wind up in the second resister, then `ShiftOut` the byte for the first register.  This will push your first byte through to the second register.

  [1]: https://i.stack.imgur.com/VEEl6.gif
  [2]: http://arduino.cc/en/tutorial/ShiftOut


body:
split the data into 2 bytes, and then send those, one after the other

    void shift (int pin) {
      byte data1 = 0;//shift register 1
      byte data2 = 0;//shift register 2
      if( pin<8 )
        data1 = (1<<pin);
      else
        data2 = (1<<(pin-8));
      shiftOut(ds,shcp,MSBFIRST,data2);//note that you send the data for shift register 2 first
      shiftOut(ds,shcp,MSBFIRST,data1);
      digitalWrite(stcp,HIGH);
      delay(100);//why wait this long?
      digitalWrite(stcp,LOW);
    }


body:
    void shift(int pin) {
      digitalWrite(stcp, LOW);

      // shift the bits out:
      shiftOut(ds, shcp, MSBFIRST, pin >> 8);
      shiftOut(ds, shcp, MSBFIRST, pin);
      // turn on the output so the LEDs can light up:
      digitalWrite(stcp, HIGH);

      delay(100);
    }


message:
Homemade soil moisture analog value reading jumping from 0 to max

I made a soil moisture sensor out of two metal poles, adjustable resistor, for a project I am making. The first run with the project the sensor worked amazing and gave clear and concise readings, 0-800 depending on water. I then unhooked the sensor and left it in the soil while I fine tuned the code (added warnings to the areas that would read to low), and while testing the code without the sensor being hooked up my arduino uno (Sparkfun Pro Mini) would read a value of 330(area). I thought this strange but didnt worry about it.

Well I hooked up my sensor (just power, ground, and to the A1 pin) and now my readout for the readings jump from 0 to 800, 0 to 512, 0 to another random number. I commented out everything in the code BUT the part that sets up the pin and displays the analog reading and its still the same issue. I also checked all my wires, changed the resistor setting, changed to a 10k single resistor, nothing changed.

Does anyone have any idea on what could be wrong?

body:
You are constantly running .5mA through 2 nails in wet earth. What are they made of, that won't undergo some electrolysis in 1/2 hour? Gerben appears to have hit the, er, nail on the head in one, above.

You can avoid this to an extent by using a.c. drive to the probes, which reverses the effect so they only tarnish at about the normal rate for metal X in soil.


message:
RTC MCP7940M not counting up

I'm able to set a time and to read it back without any problems but it doesn’t tick up. It stays the same. Even if I restart the serial monitor and thereby resets the buffer(?). So it seems to me that I'm able to set the registers but somehow the oscillator isn't working, do I have to tell it to use the external oscillator? [Datasheet][1].
Using Uno Rev3.

I've connected it like this:![Schematic][2]

Never mind the BAT54 diode and the "RTC+MCU_VCC" node, its all just backup power from a capacitor. The supply voltage is alright.

The code I've been using is a modified version of [this][3].

    // SDA analog pin 4
    // SCL analog pin 5

    #include <Wire.h>
    const int MCP7940 = 0x6F; // Address of MCP7940 see data sheets
    const char* days[] =
    {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    const char* months[] =
    {"January", "February", "March", "April", "May", "June", "July", "August","September", "October", "November", "December"};

    // Initializes all values:
    byte second = 0;
    byte minute = 0;
    byte hour = 0;
    byte weekday = 0;
    byte monthday = 0;
    byte month = 0;
    byte year = 0;

    void setup() {
      Wire.begin();
      Serial.begin(9600);
      delay(2000); // This delay allows the MCU to read the current date and time.

      Serial.print("The current date and time is: ");
      printTime();
      Serial.println("Please change to newline ending the settings on the lower right of the Serial Monitor");
      Serial.println("Would you like to set the date and time now? Y/N");

      while (!Serial.available()) delay(10);
      if (Serial.read() == 'y' || Serial.read() == 'Y')

      // This set of functions allows the user to change the date and time
      {
        Serial.read();
        setTime();
        Serial.print("The current date and time is now: ");
        printTime();
      }

      Serial.println("Thank you.");
    }

    // Continuous function for converting bytes to decimals and vice versa
    void loop() {
    }
    byte decToBcd(byte val) {
      return ((val/10*16) + (val));
    }
    byte bcdToDec(byte val) {
      return ((val/16*10) + (val));
    }

    // This set of codes is allows input of data
    void setTime() {
      Serial.print("Please enter the current year, 00-99. - ");
      year = readByte();
      Serial.println(year);
      Serial.print("Please enter the current month, 1-12. - ");
      month = readByte();
      Serial.println(months[month-1]);
      Serial.print("Please enter the current day of the month, 1-31. - ");
      monthday = readByte();
      Serial.println(monthday);
      Serial.println("Please enter the current day of the week, 1-7.");
      Serial.print("1 Sun | 2 Mon | 3 Tues | 4 Weds | 5 Thu | 6 Fri | 7 Sat - ");
      weekday = readByte();
      Serial.println(days[weekday-1]);
      Serial.print("Please enter the current hour in 24hr format, 0-23. - ");
      hour = readByte();
      Serial.println(hour);
      Serial.print("Please enter the current minute, 0-59. - ");
      minute = readByte();
      Serial.println(minute);
      second = 0;
      Serial.println("The data has been entered.");

      // The following codes transmits the data to the RTC
      Wire.beginTransmission(MCP7940);
      Wire.write(byte(0));
      Wire.write(decToBcd(second));
      Wire.write(decToBcd(minute));
      Wire.write(decToBcd(hour));
      Wire.write(decToBcd(weekday));
      Wire.write(decToBcd(monthday));
      Wire.write(decToBcd(month));
      Wire.write(decToBcd(year));
      Wire.write(byte(0));
      Wire.endTransmission();
      // Ends transmission of data
    }

    byte readByte() {
      while (!Serial.available()) delay(10);
      byte reading = 0;
      byte incomingByte = Serial.read();
      while (incomingByte != '\n') {
        if (incomingByte >= '0' && incomingByte <= '9')
          reading = reading * 10 + (incomingByte - '0');
        else;
        incomingByte = Serial.read();
      }
      Serial.flush();
      return reading;
    }

    void printTime() {
      char buffer[3];
      const char* AMPM = 0;
      readTime();
      Serial.print(days[weekday-1]);
      Serial.print(" ");
      Serial.print(months[month-1]);
      Serial.print(" ");
      Serial.print(monthday);
      Serial.print(", 20");
      Serial.print(year);
      Serial.print(" ");

      Serial.print(hour);
      Serial.print(":");

     Serial.print(minute);
     Serial.println();
    }

    void readTime() {
      Wire.beginTransmission(MCP7940);
      Wire.write(byte(0));
      Wire.endTransmission();
      Wire.requestFrom(MCP7940, 7);
      second = bcdToDec(Wire.read());
      minute = bcdToDec(Wire.read());
      hour = bcdToDec(Wire.read());
      weekday = bcdToDec(Wire.read());
      monthday = bcdToDec(Wire.read());
      month = bcdToDec(Wire.read());
      year = bcdToDec(Wire.read());
    }

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/20002292B.pdf
  [2]: https://i.stack.imgur.com/VbAhL.png
  [3]: http://www.instructables.com/id/Setting-the-DS1307-Real-Time-Clock-using-the-Seria/

body: Okey, I've been very tired when doing this but I think the problem was with bit 7 at adress 00h. The "seconds byte". That bit is called ST and turns on or off the oscillator. Doing a bitwise OR like this: `Wire.write(decToBcd(second) | 128);` sets it to "1" (128 = B10000000) and it's running now.


body:
you have a small flaw in your readTime function. If you don't want very strange seconds from the device you should combine the two nibbles packed into the seconds byte. Like this:

    void readTime() {
      Wire.beginTransmission(MCP7940);
      Wire.write(byte(0));
      Wire.endTransmission();
      Wire.requestFrom(MCP7940, 7);

      int rawsecond = Wire.read();
      second = bcdToDec( rawsecond & 112) + bcdToDec(rawsecond & 15);
      minute = bcdToDec(Wire.read());
      hour = bcdToDec(Wire.read());
      weekday = bcdToDec(Wire.read());
      monthday = bcdToDec(Wire.read());
      month = bcdToDec(Wire.read());
      year = bcdToDec(Wire.read());
    }

Thanks for the sample - helped me quite a bit.