body:
I was wondering if I can use the Rx and Tx Hardware on the Arduino Uno and also add another Rx/Tx pins using SoftwareSerial at the same time ? cause I need two to communicate with two motor Controllers (Roboclaw controller)
Thx

title: Arduino Uno Rx/Tx + Arduino Serial

Answers: 2

body:
Yes, you can.  That's the purpose of the SoftwareSerial - to allow you to complement the hardware TX/RX with other pins defined by software.

One thing to note with SoftwareSerial - it's half duplex. It can either send or receive, it can't receive while it's sending.

body:
You can, but be aware that SoftwareSerial can cause problems if you need strict timing, as it will keep the Arduino stuck while it is receiving, as it polls in interrupt context.

I would recommend to check which one of the two serial channels is more likely to receive data and use the real HW Serial port for it.

The duration of the polling of the SoftwareSerial library is also influenced by the bitrate used on the port: the higher the bitrate, the shorter the duration of the lockups, so try to use the highest bitrate you can afford, on the Software Serial port.

In case you find out that you cannot afford letting SW handle one of the 2 serial ports, you can try the [Arduino Mega 250][1], which has several UART HW blocks.

About the specific use case: if either of your motor controllers supports I2C or SPI, you could consider using that, as alternative to the SoftwareSerial.

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560


body:
I want to calculate the number of pulses coming from motor1 encoder pin2 (Int0) as input , and motor 2 encoder pin3 (Int1), I am working now for the first motor (just for the first motor ) so I set timer 2 to count 50 ms then throw flag in this moment I have to send the number of pulses to my screen, but not succeeded cause i see   on my screen zeros and ascii caracters but not the  number of pulses.:this my code .

     volatile int  pulses = 0;

     int flag=0;
     int setbit = 0;
     int encoder_in = 2;
     void count() {

           pulses++;
         }

      void setup()
       {

     Serial.begin(115200);
     pinMode(encoder_in, INPUT);
    digitalWrite(2, HIGH); //Enable pullup

    // initialize timer2
     noInterrupts();           // disable all interrupts

    TCCR2A = 0x00;
     TCCR2B = 0x07;
    TCNT2 = 0x64;
    //EIMSK = 0x03;     // Enable external interrupt INT0
    //EICRA = 0x0f;    // Trigger INT0 on falling edge

     TIMSK2 |= 0x01;  // enable timer compare interrupt
    interrupts();             // enable all interrupts
    attachInterrupt(0,count,RISING);

     }
      ISR(TIMER2_OVF_vect)
    {
    TCNT2 = 0x64;            // preload timer
     setbit=setbit+1;
      if(setbit==5)
      {
      flag=1;
     setbit=0;

       }
    }

     //ISR(EXT_INT0_vect)
     //{ pulses++; }

     void loop()
    {

     if (flag==1)
     {

       Serial.println(pulses);
        pulses=0;

      }
      }

title: counting pulses from encoder on interrupt 0 pin every 50 ms

Answers: 2

body:
Check the Baud Rate in Serial Monitor. If baud rate is not correct i.e. 9600 bps then it will show garbage.

Remove the Timer and Wire Libs

add this code in void setup()

    attachInterrupt(0,void_counter,RISING);

the above is for the the external interrupt input.

and attach your sensor/incoming pulse wire on Pin 2 on arduino.

make a new function like this

    void_counter(){
    pulses++;
    }

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

Your technique looks convoluted to me. How about this?

    volatile bool counting;
    volatile unsigned long events;

    unsigned long startTime;
    const unsigned long INTERVAL = 50;  // ms

    void eventISR ()
      {
      if (counting)
        events++;
      }  // end of eventISR

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      pinMode (2, INPUT_PULLUP);
      attachInterrupt (0, eventISR, RISING);
      }  // end of setup

    void showResults ()
      {
      Serial.print ("I counted ");
      Serial.println (events);
      }  // end of showResults

    void loop ()
      {
      if (counting)
        {
        // is time up?
        if (millis () - startTime < INTERVAL)
          return;
        counting = false;
        showResults ();
        }  // end of if

      noInterrupts ();
      events = 0;
      startTime = millis ();
      EIFR = bit (INTF0);  // clear flag for interrupt 0
      counting = true;
      interrupts ();
      }  // end of loop

---

### Explanation

Using a timer to detect when 50 ms is up isn't particularly helpful in this case. You can't do printing inside an ISR, so you would have to set a flag that can be checked in the main loop.

If you are going to check a flag anyway, you may as well just check if the time is up, as my code does.

Inside the ISR, I stop adding to `events` if the flag `counting` is false. This is to stop `events` being changed at the exact moment it is being printed.


body:
I want to add the following boards:

[https://redbearlab.github.io/arduino/package_redbearlab_index.json][1]

Which I can add in the Arduino IDE by going to File -> Preferences -> Additional Boards Manager URLs and just pasting it there

Where is the equivalent function in Eclipse, or how do I configure Eclipse to allow me to develop for those boards?

From Eclipse, I have tried Window-> Properties -> Arduino and from there "Private Library Path" and "Private hardware path", and I have tried pointing them to "C:\Program Files (x86)\Arduino\hardware" and "C:\Program Files (x86)\Arduino\libraries", but that didn't seem to change anything (i.e. no new board options, even after running Eclipse as admin) - while the boards show up (examples and all) in the Arduino IDE

  [1]: https://redbearlab.github.io/arduino/package_redbearlab_index.json

title: How can I add additional boards to Eclipse with the Arduino add-on with only a URL, not a zip file

Answers: 1

body:
With arduino eclipse plugin 2.4 you simply install the boards with the arduino ide -like you described- and you can use then in the arduino eclipse plugin.

Version 3.0 (that is the nightly as 3.0 still needs to be released) contains it's own boards and library manager in windows->preferences->arduino.


body:
I have an **Arduino Uno** *(a SainSmart model, actually)*. I intend to power it with three 1.5V batteries. I measured them and they yield 4.67V in total. The Arduino requires 5V.

# The question is, if the arduino will work this way.

I'm not powering complicated microcontroller components here. These components are used:

* A buzzer
* An LED
* A unit of 4 seven segment displays
* A couple of buttons as input elements

If the volume or brightness of these components is slightly decreased, it doesn't matter at all. But I would like to know if it will work in the first place.

# And also...

Where exactly do I plug the power source in? The power jack, the USB jack, pins, somewhere else?

---

**The schematic looks like this**, just to illustrate it. I'm not a good drawer, but you'll get the idea...

[![schematic][1]][1]

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

title: How to power an Arduino Uno with 3 1.5V batteries?

Answers: 4

body:
The Arduino doesn't *require* 5V.

The Atmel chip on the board *requires* somewhere between 1.8V and 5.5V, the Arduino just happens to have chosen 5V as a good common widely used voltage to run at.

If you provide a voltage within that range to the +5V pin the board will operate.  There's a couple of caveats though:

* Anything below about 4V will mean the 3.3V regulator won't be working right, so the 3.3V pin won't be functioning properly
* At lower voltages the Atmel chip can't operate reliably at higher frequencies, which is why 3.3V Arduino boards operate at 8MHz instead of 16Mhz.

So 3 x AA batteries is a perfect power source for running the Arduino, direct into the 5V pin.  Just make sure that you don't power it any other way at the same time or you'll be pumping 5V into your batteries.  You may want to add a Schottky diode in series with your battery + (between battery + and the 5V pin) to stop that ever causing a problem.  Choose one with a very low forward voltage drop though, otherwise you could end up dropping too much of your precious voltage over the diode.

By the way, when you're powering it from USB the 5V could be anywhere between 4.75V and 5.25V.

body:
As per @Majenko's answer, yes, this will work fine.

Some caveats: the Atmel chip at the center of the Arduino has brown-out detection - if it drops below a certain voltage, the chip will shut down. This voltage is selectable: 4.3v, 2.7v, 1.8v, or off. The factory default for the chip is "off", I found a reference that the Uno sets this at 2.7V.

Also, if you are powering anything else with your battery, e.g. a motor, the voltage is will drop - if it drops below the brownout, the arduino will shut down (usually also shutting down the external device, causing the voltage to rise again, causing it to power up again). An LED (with a correct resistor) should be fine.

body:
You can power the Arduino via the 5V pin - but you need make sure you disconnect it when you are connected via USB - ie. don't power both the 5V pin and via the USB.

Any even better way is to power it from the USB socket - I use those emergency Phone battery packs, but you could cut up a usb cable and use that - this is a much better socket fit to use than the 5v pin and more energy efficient than passing a higher voltage through the 9V supply.

body:
For battery-operated Arduino Uno's I recommend thinking bigger (in terms of power, not physical size).

I power several by using 3x 18650 batteries in series, (providing about 14 Volts, connected to a 4x USB 5 Volt module.

The Unos are connected to power by a standard USB cable (into the programming port), and then you also have 3 other 5V USB charging or power ports available.

Or you can get a small converter unit that provides just one 5V USB.

Either way, bringing the power to the UNO is as simple as using the programming cable that comes with the board.

Or you can use any other converter and use wires to bring in Vin and GND.

You don't need to use 3 of the 18650s.  2 will do fine.  Or 4 in series/parallel for longer battery life.  No converter would be needed but again you would need wires to bring the voltage into the Unos.

18650s are very common, and are inexpensive.  They pack a whole lot more mAh than any AA battery you will find.

One warning about buying 18650s:  There are Chinese companies that advertise 9,800 mA batteries.  Don't believe it.  3,000 is about the max any reputable manufacturer will claim.


body:
I have a Adafruit Pro Trinket. I'm having issues getting GPS and and SD card working together. The trinket can be connected via USB but there is no serial connection do debugging my program is hard.

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

I purchased an FTDI connector from sparkfun, installed the FTDI software and connected to the trinket. My code complies but it won't flash. The error is confusing:

Can anyone please help me figure out how to get it to flash?

    Arduino: 1.6.4 (Mac OS X), Board: "Pro Trinket 3V/12MHz (FTDI)"

    Sketch uses 19,896 bytes (69%) of program storage space. Maximum is 28,672 bytes.
    Global variables use 1,476 bytes of dynamic memory.
    avrdude: ser_open(): can't open device "/dev/cu.usbmodem1a21": No such file or directory
    ioctl("TIOCMGET"): Inappropriate ioctl for device
    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Here is the "verbose" version of the error:

    Arduino: 1.6.4 (Mac OS X), Board: "Pro Trinket 3V/12MHz (FTDI)"

    Using library SPI in folder: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SPI
    Using library Adafruit GPS Library in folder: /Users/futurebird/Documents/Arduino/libraries/Adafruit-GPS-Library-master
    Using library SoftwareSerial in folder: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial
    Using library SdFat in folder: /Users/futurebird/Documents/Arduino/libraries/SdFat (legacy)

    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=12000000L -DARDUINO=10604 -DARDUINO_AVR_PROTRINKET5FTDI -DARDUINO_ARCH_AVR -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/variants/eightanaloginputs -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SPI -I/Users/futurebird/Documents/Arduino/libraries/Adafruit-GPS-Library-master -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial -I/Users/futurebird/Documents/Arduino/libraries/SdFat /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp -o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.o
    Using previously compiled file: /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SPI/SPI.cpp.o

    (^^repeats many times for different files)

    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc -Wall -Os -Wl,--gc-sections -mmcu=atmega328p -o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.elf /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SPI/SPI.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/Adafruit GPS Library/Adafruit_GPS.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SoftwareSerial/SoftwareSerial.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/MinimumSerial.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdFatBase.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdFatUtil.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiCard.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiSAM3X.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiSTM32F1.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/SdSpiTeensy3.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFile.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFileLFN.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFilePrint.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatFileSFN.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FatVolume.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/FmtNumber.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/fstream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/istream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/ostream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/SdFat/utility/StdioStream.cpp.o /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/core.a -L/var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp -lm
    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.elf /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.eep
    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy -O ihex -R .eeprom /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.elf /var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.hex

    Sketch uses 19,896 bytes (69%) of program storage space. Maximum is 28,672 bytes.
    Global variables use 1,476 bytes of dynamic memory.
    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbmodem1a21 -b115200 -D -Uflash:w:/var/folders/r9/t7hwvgjx1kz18v8j60_kp_vh0000gn/T/build4892553004123204558.tmp/little_GPS.cpp.hex:i

    avrdude: Version 6.0.1, compiled on Apr 14 2015 at 16:30:25
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/Users/futurebird/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/cu.usbmodem1a21
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: ser_open(): can't open device "/dev/cu.usbmodem1a21": No such file or directory
    ioctl("TIOCMGET"): Inappropriate ioctl for device

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

---------------------------
UPDATE
---------------------------
I looked in the /dev/ directory and found these which match the menu in Arduino.

cu.Bluetooth-Incoming-Port
cu.Bluetooth-Modem
cu.JabraREVOa400-SPPDev
cu.LightBlue-Bean

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

The above files are int the dev folder but not cu.usbmodem1a21. How can I get it? Or is it looking for the wrong file?

This is what my board selection looks like. I think the issue is the port?

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/p0OBI.jpg
  [2]: https://i.stack.imgur.com/WKYpG.jpg
  [3]: https://i.stack.imgur.com/u2wsB.jpg

title: I can upload via USB but not FTDI

Answers: 1

body:
Things to check:

 - Does the file exist? check with `ls` if the file that avrdude tries to open is actually there

 - Do you have the right to open it? Opening a serial port requires having the appropriate rights, iow you user belongs to the same group that the device belongs to.
On linux this is usually wheel or dialout, depending on the distro. Again, `ls -la` is your friend.

 - Is your device identified correctly? Meaning that you are not trying to have avrdude address the device wit the wrong protocol.


body:
Lets say I have something that sends a command to the Arduino (for example, a PC sending through serial, Ethernet, etc). I want the Arduino to "check" what command it is and run a specific function linked to that command.

I don't need a very explanatory answer, just give me something so I can learn from. A sketch that shows a similar idea would be good, I can try to interpret it and adapt/remake for me.

The idea is to use the Arduino for a lot of different things. Let's say:

1. Turn a bunch of leds on/off;

2. Read data from a sensor and send it through Ethernet/I2C/Serial;

3. Control a servo.

But I want the Arduino to do that when I tell it to (in this case, sending the command through serial, etc). So let's say I send it 1, I'll want it to run the 1 function (turning the LEDs on/off).

I already took a [tutorial course on Arduino programming](http://sheepdogguides.com/arduino/FA1main.htm), but I'm clueless on how to do this job.

title: Run a part of code upon call

Answers: 2

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

If you just want some example code, here is a smallish sketch I wrote that controls some LEDs via a shift register. Exactly how the shift register works isn't important, but you can see the basic idea for taking input from the serial port and decoding it:

    #include <SPI.h>

    const byte LATCH = 10;

    const byte numberOfChips = 4;
    const byte maxLEDs = numberOfChips * 8;

    byte LEDdata [numberOfChips] = { 0 };  // initial pattern

    void refreshLEDs ()
      {
      digitalWrite (LATCH, LOW);
      for (int i = numberOfChips - 1; i >= 0; i--)
        SPI.transfer (LEDdata [i]);
      digitalWrite (LATCH, HIGH);
      } // end of refreshLEDs

    // how much serial data we expect before a newline
    const unsigned int MAX_INPUT = 10;

    void setup ()
    {
      Serial.begin(115200);
      SPI.begin ();
      refreshLEDs ();
    } // end of setup

    // here to process incoming serial data after a terminator received
    void process_data (char * data)
      {
      Serial.print ("Got command: ");
      Serial.println (data);

      // C: clear all bits
      switch (toupper (data [0]))
        {
         case 'C':
            {
            for (int i = 0; i < numberOfChips; i++)
              LEDdata [i] = 0;
            Serial.println ("All bits cleared.");
            refreshLEDs ();
            return;
            }

        // S: set all bits
        case 'S':
            {
            for (int i = 0; i < numberOfChips; i++)
              LEDdata [i] = 0xFF;
            Serial.println ("All bits set.");
            refreshLEDs ();
            return;
            }

        // I: invert all bits
        case 'I':
            {
            for (int i = 0; i < numberOfChips; i++)
              LEDdata [i] ^= 0xFF;
            Serial.println ("All bits inverted.");
            refreshLEDs ();
            return;
            }
        } // end of switch

      // otherwise: nnx
      //   where nn is 1 to 89 and x is 0 for off, or 1 for on

      // check we got numbers
      for (int i = 0; i < 3; i++)
        if (!isdigit (data [i]))
          {
          Serial.println ("Did not get 3 digits.");
          return;
          }

      // convert first 2 digits to the LED number
      byte led = (data [0] - '0') * 10 + (data [1] - '0');

      // convert third digit to state (0 = off)
      byte state = data [2] - '0';  // 0 = off, otherwise on

      if (led > maxLEDs)
          {
          Serial.println ("LED # too high.");
          return;
          }

       led--;  // make zero relative

       // divide by 8 to work out which chip
       byte chip = led / 8;  // which chip

       // remainder is bit number
       byte bit = 1 << (led % 8);

       // turn bit on or off
       if (state)
         LEDdata [chip] |= bit;
       else
         LEDdata [chip] &= ~ bit;

      Serial.print ("Turning ");
      Serial.print (state ? "on" : "off");
      Serial.print (" bit ");
      Serial.print (led & 0x7, DEC);
      Serial.print (" on chip ");
      Serial.println (chip, DEC);

      refreshLEDs ();
      }  // end of process_data

    void loop()
    {
    static char input_line [MAX_INPUT];
    static unsigned int input_pos = 0;

      if (Serial.available () > 0)
        {
        char inByte = Serial.read ();

        switch (inByte)
          {

          case '\n':   // end of text
            input_line [input_pos] = 0;  // terminating null byte

            // terminator reached! process input_line here ...
            process_data (input_line);

            // reset buffer for next time
            input_pos = 0;
            break;

          case '\r':   // discard carriage return
            break;

          default:
            // keep adding if not full ... allow for terminating null byte
            if (input_pos < (MAX_INPUT - 1))
              input_line [input_pos++] = inByte;
            break;

          }  // end of switch

      }  // end of incoming data

      // do other stuff here like testing digital input (button presses) ...

    }  // end of loop

---

Example of commands understood by the above code:

    C    <-- clear all LEDs
    S    <-- set (turn on ) all LEDs
    I    <-- invert all LEDs (turn off if on, and vice-versa)
    021  <-- turn LED 02 on
    020  <-- turn LED 02 off
    161  <-- turn LED 16 on

This code processes a 3-digit string as:

    nnS

Where "nn" is the LED number and S is the new state (1 = on, 0 = off).

---

### Other examples

* There is a more elaborate example on my page about [using a 74HC595 output shift register as a port-expander](http://gammon.com.au/forum/?id=11518)

* [How to process incoming serial data without blocking](http://gammon.com.au/serial)

* [State machines](http://gammon.com.au/statemachine)

body:
If you want it really barebones and easy, you can checkout the Arduino "Dimmer" example sketch.

Instead of changing the brightness of an attached pin, you could take the input you send it over the serial console and execute various functions, depending on what you receive.

Something like this:

    boolean newCommand = false;
    void setup()
    {
      // initialize the serial communication:
      Serial.begin(9600);

      // other setup stuff here
    }

    void loop()
    {
      byte command;

      // check if data has been sent from the computer:
      if (Serial.available())
      {
        // read the most recent byte (which will be from 0 to 255):
        command = Serial.read();
        // say that you received a new command
        newCommand = true;
      }

      // is there a new command?
      if (newCommand == true)
      {
        // do something depending on what command you received
        switch(command)
        {
          // if you receive command "1", do something
          case 1: functionWhatever();
                  break;  // "break" out of the switch. otherwise it would continue executing the following commands as well
          case 2: functionWhatever2();
                  break;
          //for cases that are not caught, send out an error
          default: Serial.write("invalid command");
                  break;
        }
      }
    }

---

If you want to use an existing library, you might want to check out:
[EasyTransfer][1].

It can be used for communication between two Arduinos, which you then can use to execute functions on the other side of the line.

The code itself is relatively simple, so you might be able to adapt it to communicate with a processing script on your computer for example.

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


body:
I have an Arduino Uno and a Texas Instruments CC3000 WiFi shield. I need to connect the Arduino to a local network which has no Internet access so that it can send information to a computer also connected to the same local network. I am using a Linksys WRT120N for the local network.

I can't use the Internet access WiFi because it is WPA2 Enterprise which is why I created the local network. Currently the computer is connected to the local network via WiFi.

I have downloaded and installed the correct library but when I run the connection test, it searches for Internet access which doesn't exist and sends back errors.

How do I verify that it is connecting to the local network?

Btw, I have almost no experience coding an Arduino but I have access to people who are proficient; However, they have no experience with a WiFi shield.

title: Can wifi shield connect to local network without internet?

Answers: 1

body: If you have created your own local network, you may need a DHCP server to give it an IP address, or you will have to configure your Arduino with a static ip. I can't think of a reason why it would need internet access, but it is not uncommon for devices to refer (incorrectly) to connectivity issues on the local network as "internet" issues.


body:
I learned, that SPI-code uses interrupts. So is it true then, that I can't use SPI related code inside an ISR?

Background: I want to capture one or more revolution speeds with an MCP23S17. I rewired the interrupt lines to INT1 and INT2 accordingly to get the interrupts at the Arduino.

I thought it was good to fetch the port registers from the MCP23S17 inside the ISR, but this apparently doesn't work.

Is the only thing I can do in my ISR set a flag for another test in the main loop? And let a routine called from lood() then poll the registers from the port expander? This opposes the idea to fetch the relevant data which issued the interrupt ASAP.

title: Usage of SPI inside an ISR

Answers: 1

body:
SPI doesn't use interrupts.  It references the interrupt flag to know if a transfer has been completed, but it doesn't actually have interrupts enabled:

    SPDR = data;
    asm volatile("nop");
    while (!(SPSR & _BV(SPIF))) ; // wait
    return SPDR;

It should be perfectly possible to use SPI within the interrupt - indeed there is portions of the SPI API that deal specifically with this - see https://www.arduino.cc/en/Reference/SPIusingInterrupt for instance.


body:
I'm trying to connect my Arduino Mega via Wifi to my XAMPP server. My main objective is get a value from my database and store it on a variable in Arduino code. With this new variable I'll be able to control the rest of the program... So I need your help. Can someone give me advice?

I already tried every thing that I found on the internet but it just doesn't work.

I think that the simple way is to send a GET request to the server and read its response... But for some reason I can't send a GET request through...

I tested it on the browser directly and the value shows up, so I think that the server side is all right.

Here is my Arduino code:

    #include <Arduino.h>
    #include <SoftwareSerial.h>
    #include "WiFly.h"
    #include "HTTPClient.h"

    #define SSID      "mySSID"
    #define KEY       "myKEY"
    #define AUTH      WIFLY_AUTH_WPA2_PSK
    #define HTTP_GET_URL "http://192.168.1.80/xampp/training/send_data_db.php/?temp=0"

    // Pins' connection
    // Arduino       WiFly
    //  2    <---->    TX
    //  3    <---->    RX
    SoftwareSerial uart(10, 11);
    WiFly wifly(uart);
    HTTPClient http;
    char get;

    void setup() {
      Serial.begin(9600);
      Serial.println("------- WIFLY HTTP --------");
      uart.begin(9600); // WiFly UART Baud Rate: 9600
      // Wait WiFly to init
      //  delay(3000);

      // check if WiFly is associated with AP(SSID)
      if (!wifly.isAssociated(SSID)) {
        while (!wifly.join(SSID, KEY, AUTH)) {
          Serial.println("Failed to join " SSID);
          Serial.println("Wait 0.1 second and try again...");
          delay(100);
        }
        wifly.save(); // save configuration,
      }
      Serial.println("\r\nTry to get url - " HTTP_GET_URL);
      Serial.println("------------------------------");
      while (http.get(HTTP_GET_URL, 10000) < 0) {
      }
      while (wifly.receive((uint8_t *)&get, 1, 1000) == 1) {
        Serial.print(get);
      }
      if (wifly.commandMode()) {
        Serial.println("\r\n\r\nEnter command mode. Send \"exit\"(with \\r) to exit command mode");
      }
    }

    void loop() {
      int c;
      while (wifly.available()) {
        c = wifly.read();
        if (c > 0) {
          Serial.write((char)c);
        }
      }
      while (Serial.available()) {
        c = Serial.read();
        if (c >= 0) {
          wifly.write((char)c);
        }
      }
    }

And here is my PHP code:

    <? php
    include("./connection/database_connect.php");
    include("./top_table.php");

    if ((isset($_SESSION["ID"])) AND (isset($_GET["temp"]))) {
      $id = $_SESSION["ID"];
      $sql = "SELECT temp FROM perfil, client WHERE perfil.ID ='$id'";
      $consult = mysqli_query($connect, $sql);
      $result = mysqli_num_rows($consult);
      if (($result == 1)) {
        $person_data = mysqli_fetch_array($consult, MYSQLI_ASSOC);
        $temp = $person_data["temp"];
        header("HTTP/1.1" . " " . 200 . "OK");
        header("Content-Type: text/html; charset=UTF-8");
        header("Content-Length: 1112");
        header("Connection: close");
        header("/r/n");
        echo $temp;
      } else {
        //se user dosen't exist on data base
        header("Location: http://192.168.1.80/xampp/training/login.php");
        exit;
      }
    } else {
      header("Location: http://192.168.1.80/xampp/training/login.php");
      exit;
    }
    ?>

title: How can an Arduino Mega 2560+Wifi Shield 2.0 (SeeedStudio) receive data from database in a XAMPP server on my PC?

Answers: 2

body:
You should forget about the $_SESSION["ID"]; on PHP side, because you are working stateless without any session!
You should give a parameter for identifying your variable from arduino to php script - is this the temp=0? If so you need to exchange

    $sql="SELECT temp FROM perfil, client WHERE perfil.ID ='$id'";

with

    $sql="SELECT temp FROM perfil, client WHERE perfil.ID =" . $_GET["temp"];

assuming that perfil.id is only an integer - if it is a string, then add "'".

body:
Yes you are right!

Meanwhile i finished this project.

The problem was with the Wi-Fi shield that I was using. The Http request wasn't in a right format.


body:
I was having an issue very similar to this one:

https://arduino.stackexchange.com/questions/3324/arduino-compatibles-serial-port-not-showing-mac-osx

Basically I have a clone (VISduino) and it's made with a different USB chip so it needed a driver. Installing the driver didn't help.

http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

Running:

     sudo nvram boot-args="kext-dev-mode=1"

didn't help. So I decided to delete Arduino and reinstall. Then I went through all of the steps again.

Well.... now nothing works. Before doing this I could use:

 - Adafruit metro
 - An uno clone
 - My genuine uno
 - lightBlue Bean
 - adafruit trinket and trinket pro
 - adafruit trinket pro via USB
 - digikey

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

I've reinstalled the drivers for these but NOTHING is working now. They were all working before. It just says Arduino Uno on COM1, or digikey on COM1 etc.

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

And of course my clone (vis duino) isn't working either.

How can I fix this?

[![enter image description here][3]][3]

The com ports just are not there.

  [1]: https://i.stack.imgur.com/TSdpy.jpg
  [2]: https://i.stack.imgur.com/c6Z1i.jpg
  [3]: https://i.stack.imgur.com/2VQUA.jpg

title: Tried to fix ports on Mac OS X Yosemite. Now nothing works

Answers: 1

body:
I solved this issue by deleting all of the Arduino files and the Arduino app. I put my sketched folder aside but deleted all libraries.

Restarted the computer.

Installed Arduino fresh.

Restarted the computer.

Installed the drivers.

Ran the command.

Restarted the computer.

Restarted the computer.

Restarted the computer.

Then it worked.


body:
I'm very new to Arduino, and I'm trying to read data from a LaCrosse TX23 V02(X) anemometer. It's supposed to behave like this https://www.john.geek.nz/2012/08/la-crosse-tx23u-anemometer-communication-protocol/, but it's not...

I don't have an oscilloscope, so I made this code, using micros() to try to trace the output from the TX23:

    void loop() {
      collectData();
    }

    int collectData(void){
       if (bitLength < 0){
          bitLength = 1200;// length of bit is equal to approx 1230 micro seconds;
       }
      // init sequence
      pinMode(dataPin, OUTPUT);
      Serial.print("Send LOW\n");
      digitalWrite(dataPin, LOW );
      Serial.print("Send HIGH\n");
      digitalWrite(dataPin, HIGH);
      delay(100);
      Serial.print("Send LOW\n");
      digitalWrite(dataPin, LOW );
      delay(500);

      Serial.print("Begin input mode\n");
      pinMode(dataPin, INPUT);

      int state = 0;
      int oldstate = 0;
      unsigned long oldmicros = micros();
      for (int i = 1; i<5250 ; i++) {
        state = (digitalRead(dataPin) == LOW)? 0:1;
        if (i != 0) {
          Serial.print("-");
        } else {
          Serial.print("+");
        }

        delayMicroseconds(10);
        if (state != oldstate) {
          oldstate = state;
          i = 1;
          Serial.print(oldstate);
          Serial.print(" @");
          Serial.print(micros() - oldmicros);
          oldmicros = micros();
          Serial.print("\n");
        }
      }
      Serial.print(state);
      Serial.println(micros()-oldmicros);
    }

Does it have a chance to provide a quite accurate monitoring of the TX23 output? (eg is using micros() or delayMicroseconds(10) accurate ?)

title: Can I use micros() to analyze TX23 anemometer signal?

Answers: 3

body:
You should really make use of `pulseIn()` to work out the bit rate of the signal.  The first HIGH pulse in the header is there for timing so you know how often to poll the input.

Step one, after sending your outgoing initiation pulse, should be to wait for that first pulse (you might need a slight delay first before it starts transmitting - wait for the line to be low first):

    while (digitalRead(dataPin) == HIGH); // Wait for TX start
    uint32_t pulseWidth = pulseIn(dataPin, HIGH); // Get first pulse

That gives you the width of the first pulse in microseconds.

Now you can read 45 times at that period.  If you first delay by half that amount before your first sample you will be roughly in the middle of the bit so you can cope with a slight amount of drift.

    // Wait for the middle of the first bit
    delayMicroseconds(pulseWidth / 2);

    uint32_t highBlock = 0;
    uint32_t lowBlock = 0;
    for (int i = 0; i < 45; i++) {
        // Shift the high 32-bits left one bit
        highBlock <<= 1;
        // Place in the highest bit of the low block as the lowest
        // bit of the high block
        highBlock |= (lowBlock & 0x80000000UL ? 1 : 0);
        // Shift the low 32-bits left one bit
        lowBlock <<= 1;
        // Add in the value of the bit from the data pin
        lowBlock |= digitalRead(dataPin);
        // Wait for the next bit
        delayMicroseconds(pulseWidth);
    }

You should now have two 32-bit words which, when put together, form the entire datagram.  You can now use bitwise operators to pull out the parts you are interested in.

A better, though more complex, method of doing it would be to employ a timer with an overflow period equal to the pulse width. That will afford you much more accurate timing than a simple loop with delays.

body:
Majenko showed a method for digitally recording the waveform, after measuring `pulseWidth` at the outset, and mentioned use of a timer for delays.   I'll address the part of your question about using `micros()` while tracing TX23 output:  “Does it have a chance to provide a quite accurate monitoring of the TX23 output?”

Some of the serial output that your method produces as it goes along will affect evenness of timing.  For example, the `Serial.print()` of + after every tenth reading introduces a small timing irregularity (the two branches of the `if` may differ a few cycles in execution time).

More seriously, your double-read of `micros()` (after you print `oldstate`, you print `micros() - oldmicros` and then read `micros()` again) introduces a few cycles of timing error.  It probably amounts to a few microseconds total over the course of recording the pulse train.  Instead of reading `micros()` twice, say something like `newmicros = micros()` directly after detecting a state change, before doing any serial printing, then use `newmicros` in place of other `micros()` calls.  Having serial prints before `oldmicros = micros();` causes an offset error, which will be microseconds or milliseconds depending on the data rate you set in `setup()`.  It mostly affects the reported length only of the first pulse.

What I would do for debug monitoring of the pulse train is along the following lines:

    enum { timelen=44, maxpause=50000 };
    unsigned long int times[timelen];

    int collectData() {
      byte ntimes = 0, state=LOW;
      unsigned long int prevtime;
      pinMode(dataPin, OUTPUT);
      digitalWrite(dataPin, LOW ); // Pull DTR low to trigger conversion
      delay(500);
      pinMode(dataPin, INPUT_PULLUP); // Release DTR and set pullup
      delay(1);     // Let TX23U pull DTR low
      prevtime = micros();
      while (micros() - prevtime < maxpause && ntimes < timelen) {
        if (digitalRead(dataPin) != state) {
          times[ntimes++] = prevtime = micros();
          state = 1-state;
        }
      }
      return ntimes;
    }

This code is intended to record times at which state changes occur.  After `loop()` calls `collectData()`, it can call a `reportData()` routine that will print out pulse lengths by subtracting adjacent entries of `times[]`.  Even-indexed array entries are times of rising edges in the pulse train; odd-indexed entries are times of falling edges.  Because the `if (digitalRead(dataPin) != state) {...}` statement isn't executed atomically, the data pin can change after being tested but before being recorded a couple of lines later.  Using `state = 1-state;` instead of `state = digitalRead(dataPin);` guarantees that even indexes are for rising edges, but does not guarantee that adjacent entries correspond to the same pulse edge.  That is, a noisy signal can produce misleading results.

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

I'm going to present a third way of working on this. :)

First, since I don't have a TX23 I wrote a TX23-simulator:

    const byte TESTPIN = 2;

    const byte test [6] = {
        0b00000011,
        0b01111011,
        0b01010100,
        0b00010100,
        0b01001010,
        0b10111111 };

    void setup ()
      {
      pinMode (TESTPIN, INPUT);
      delay (100);
      }  // end of setup

    void loop ()
      {
      // wait for host to pull pin low
      while (digitalRead (TESTPIN) == HIGH)
        { }
      // wait for host to release it
      while (digitalRead (TESTPIN) == LOW)
        { }
      digitalWrite (TESTPIN, HIGH);
      pinMode (TESTPIN, OUTPUT);
      for (byte i = 0; i < 6; i++)
        for (byte j = 0; j < 8; j++)
          {
          delayMicroseconds (1100);
          digitalWrite (TESTPIN, test [i] & bit (7 - j));
          }
      pinMode (TESTPIN, INPUT);
      }  // end of loop

Based on your [linked page about the TX23](https://www.john.geek.nz/2012/08/la-crosse-tx23u-anemometer-communication-protocol/) it outputs a series of low/high pulses corresponding to the example on that page, like this:

[![TX23 simulator][1]][1]

Note that you need a 10 k pull-up resistor for this to work properly.

---

Now the reading code uses interrupts to detect state changes:

    const byte READ_PIN = 2;
    const byte NUMBER_OF_CHANGES = 48;

    volatile unsigned long bitTime [NUMBER_OF_CHANGES];
    volatile byte state [NUMBER_OF_CHANGES];
    volatile byte count;

    void stateChange ()
      {
      unsigned long now = micros ();
      if (count >= NUMBER_OF_CHANGES)
        return;  // array full
      state [count] = digitalRead (READ_PIN);
      bitTime [count++] = now;
      } // end of stateChange

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      }  // end of setup

    void takeReading ()
      {
      count = 0;
      digitalWrite (READ_PIN, LOW);  // start reading
      pinMode (READ_PIN, OUTPUT);
      delay (20);  // pulse width
      pinMode (READ_PIN, INPUT);     // release line
      EIFR = bit (INTF0);  // clear flag for interrupt 0
      attachInterrupt (0, stateChange, CHANGE);
      delay (55);  // let readings fill up array
      detachInterrupt (0);
      }  // end of takeReading

    void loop ()
      {
      takeReading ();
      if (count == 0)
        return;  // nothing!

      delay (500);
      for (byte i = 0; i < count; i++)
        {
        Serial.print ("count: ");
        Serial.print ((int) i);
        Serial.print (" = ");
        Serial.print (bitTime [i]);
        Serial.print (", state = ");
        Serial.print (state [i]);
        if (i > 0)
          {
          Serial.print (", width = ");
          unsigned long width = bitTime [i] - bitTime [i - 1];
          Serial.print (width);
          Serial.print (" (");
          int bits = width / 1000;
          for (byte k = 0; k < bits; k++)
           Serial.print (state [i - 1]);
          Serial.print (")");
          }
        Serial.println ();
        }
        Serial.println ();
      }  // end of loop

---

Results were:

    count: 0 = 10952804, state = 1
    count: 1 = 10953928, state = 0, width = 1124 (1)
    count: 2 = 10960616, state = 1, width = 6688 (000000)
    count: 3 = 10962844, state = 0, width = 2228 (11)
    count: 4 = 10963960, state = 1, width = 1116 (0)
    count: 5 = 10968412, state = 0, width = 4452 (1111)
    count: 6 = 10969524, state = 1, width = 1112 (0)
    count: 7 = 10971752, state = 0, width = 2228 (11)
    count: 8 = 10972876, state = 1, width = 1124 (0)
    count: 9 = 10973988, state = 0, width = 1112 (1)
    count: 10 = 10975104, state = 1, width = 1116 (0)
    count: 11 = 10976216, state = 0, width = 1112 (1)
    count: 12 = 10977328, state = 1, width = 1112 (0)
    count: 13 = 10978440, state = 0, width = 1112 (1)
    count: 14 = 10984012, state = 1, width = 5572 (00000)
    count: 15 = 10985124, state = 0, width = 1112 (1)
    count: 16 = 10986244, state = 1, width = 1120 (0)
    count: 17 = 10987356, state = 0, width = 1112 (1)
    count: 18 = 10990700, state = 1, width = 3344 (000)
    count: 19 = 10991812, state = 0, width = 1112 (1)
    count: 20 = 10994040, state = 1, width = 2228 (00)
    count: 21 = 10995156, state = 0, width = 1116 (1)
    count: 22 = 10996268, state = 1, width = 1112 (0)
    count: 23 = 10997380, state = 0, width = 1112 (1)
    count: 24 = 10998500, state = 1, width = 1120 (0)
    count: 25 = 10999616, state = 0, width = 1116 (1)
    count: 26 = 11000728, state = 1, width = 1112 (0)

This seems to agree with the test data.

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


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

Now the code I'm writing in Arduino (Using Arduino) uses multiple 2-dimensional arrays. Now when I print some thing using the Serial Monitor it prints it correctly but when I declare and initialize the 2-dimentional array it won't print it.

Code:

    void setup()
    {
      Serial.begin(9600);
      int image_width = 56;
      int image_height = 96;

      int image_result[image_width][image_height];
      for (int i=0; i<image_height; i++) {
        for (int j=0; j<image_width; j++) {
          image_result[j][i] = 5;
        }
      }

      Serial.print("code works");
    }

Now in this case "code works" does not print but when I remove the array declaration and initialization code works is printed. What is the problem?

Do 2 dimensional arrays work differently in Arduino or is it a space issue?

title: Arduino Uno not able to handle 2-dimensional array

Answers: 6

body:
2D arrays work fine on arduino, but you run out of space very quickly.

An uno has 2 kilobytes of ram; your array has 56*96 = 5376 2-byte elements.

I would guess that you are writing over some critical memory value with a 5 at some point causing the program to fail.

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

This is what I fed my Uno:

    #define IMAGEWIDTH 56
    #define IMAGEHEIGHT 96

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

      int i, j;
      int image_result[IMAGEWIDTH][IMAGEHEIGHT];

      for (i = 0; i < IMAGEWIDTH; i++) {
        Serial.print("\nIMAGEWIDTH ");
        Serial.print(i + 1);
        Serial.println(":");
        for (j = 0; j < IMAGEHEIGHT; j++) {
          image_result[i][j] = i + j;
          Serial.print("image_result[");
          Serial.print(i + 1);
          Serial.print("][");
          Serial.print(j + 1);
          Serial.print("]: ");
          Serial.println(image_result[i][j]);
        }
      }
      Serial.println(F("\nDone!"));
    }

    void loop() {
    }

This will run over the whole array, while printing progress over Serial, which then print "Done!" once it is. I suggest changing:

    #define IMAGEWIDTH 56
    #define IMAGEHEIGHT 96
To lesser values, unless you have a few good minutes at hand.

body:
You are trying to use more memory than you have available: 96 * 56 * 2 = 10.752KBytes. Not much that the MCU can do when this happens.

If you look into the [datasheet][1], you'll see that your microcontroller (ATmega328p) only has 2KBytes of RAM.

I guess the question then, is to ask yourself if you really need that large an array. You may consider getting an external flash chip or an SDcard shield. If you only need it for read-only purposes (such as a lookup table), you can use some of your [flash program memory][2] (you have 32KBytes).

  [1]: http://www.atmel.com/Images/doc8161.pdf
  [2]: https://www.arduino.cc/en/Reference/PROGMEM

body: Indeed, this is an issue of RAM available. If you do not need 8 bits per piece of data (if you are perhaps willing to reduce image quality, for example), consider compacting your data such that you have multiple piece of data per bit. For example, hex values or BCD (binary coded decimals) could work, depending on the size of each piece of data.

body:
As others have noted, your array is larger than the available RAM in your Arduino. Others mentioned Flash memory which could be a solution for you. Your Arduino has 32 KB of memory which could hold your array. See the following reference for more info about Flash memory. Keep in mind that Flash and EEPROM have a limited number of write cycles before becoming unreliable.

[Hidden Powers - storing data in Flash and EEPROM][1]

  [1]: http://playground.arduino.cc/Code/EEPROM-Flash

body:
In case the matrix is mostly empty or anyway has values that can be calculated programmatically, [sparse arrays][1] might come to the rescue. It requires memory allocation and hopping, so the access time to individual elements is not deterministic, but you can calculate the worst-case scenario.

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


body:
On an Arduino you can have several different interrupt types, two of them being RISING and FALLING. Looking past that RISING is from LOW to HIGH, and FALLING is the opposite, what are the benefits of using one or the other?

To clarify; why would you use a RISING interrupt or a FALLING interrupt?

title: What's the benefits between different interrupts on Arduino

Answers: 3

body:
Imagine that you have the circuit below:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/RFd8S.png)

<!-- End schematic -->

Let's say that you wanted to catch the user pressing the button. The input signal will go from high to low, which is a falling edge. So you would use a FALLING interrupt to catch this event. Easy, right?

Now let's say you wanted to catch a user releasing the button instead. This time the inverse is true, so you want to use a RISING interrupt.

You should note that since these interrupts are edge triggered, the simple circuit below would not be ideal. Without any debouncing, there may be several edges to trigger from, resulting in repeated interrupts. Also, given the analogue nature of the design, we can't be sure that the rise / fall times will be fast enough to trigger the edge interrupt. We can get around this by adding a 100nF capacitor across the switch and following by a Schmitt trigger (which I can't find a symbol for in the circuit editor!).

So to answer your question, you use the interrupt that is correct for the event you are trying to catch. The Arduino MCU implements both edges for completeness and flexibility in your design, so if this interrupt was coming from an external IC you have no control over the design of, you can easily match the interrupt to its behaviour without having to add in an inverter.

body: Suppose you have a pushbutton that connects Arduino pin to the ground. The pin is also pulled up  to VCC (may be internally in Atmega chip, or through external resistor). Now, when the switch is open, Arduino sees HIGH, and when you press the button it sees LOW. If you would like to perform an action when the button is pressed, you would use FALLING interrupt. If you would like to know when the button is released, you would use RISING. There are no general benefits of using one over another.

body: The interrupt will be generated by an external circuit.  In many cases, you have the control over the design of the external circuit, and you can choose whether it will be generating low-to-high edges or high-to-low edges.  But in some cases you don't have the control over the design of the external circuit which generates the interrupt.  Then you have to adapt your firmware code to the interrupt source.


body: I am in the process of developing an Arduino application that can read keystrokes from a PS/2 keyboard. I was wondering if it would be possible to upload a C# program onto the Arduino to interpret the keystrokes from the keyboard and write an Arduino program to perform operations based on the keystrokes.

title: Using C# Program to Interpret Keystrokes

Answers: 2

body:
The answer is actually, surprisingly, yes! C# requires `.NET CLR` for execution, I had assumed that `.NET` exists only in microsoft desktop land, but it has in fact been ported to [microcontrollers and released open source](https://msdn.microsoft.com/en-us/library/jj610646.aspx) as `.NET micro`, it can even run baremetal with no OS.

However this is not possible on an 8 bit regular arduino, it requires one of the larger 32 bit models. There is a prebuilt clone that has the `.NET micro CLR` framework ported to it on an STM32F4 cpu called the [netduino](http://www.netduino.com/)

Unfortunately the footprint for .Net Micro is too large to run on a regular 8bit arduino and probably hasn't been built for 8bit systems. It is possible with the arduino Due (in theory) and on other micrcontroller platforms that support `.NET micro` to run C# code outside of the windows platform.

body:
I hope this answer doesn't get voted down just because it addresses the generic need (do something upon input from a PS/2 keyboard), rather than the (too) specific question that was asked (use c# on Arduino), but here it comes ...

If you use a PS/2 to USB adapter for the keyboard, you can select a much easier solution, based, for example, on raspberry PI (or anything that runs linux and has a USB master port) and use any simple scripting language - even shell. The overall cost would not be much higher and the ease of implementation would be definitely more likely to succeed. And in a short time.


body:
I want to "connect" two Arduinos, without using wires. The range is ~0.2 miles (300 meters). Using Google, I saw too many options.

The idea is to build something like a beacon, so the bandwidth can be small. I want to send 32 or 64 bits/second of data (32 bits for the application + 32 bits for checksum if the module does not guarantee consistency of data).
The communication between Arduinos is bi-directional, and I'm looking for something cheaper than 50 US dollars per module.

Can I use a serial WiFi module for this, without using a router? Do you recommend a 2.4GHz module? Or a RF module?

title: Wirelessly communicate between two Arduinos without router

Answers: 2

body:
I can highly recommend [these cheap little 433Mhz radios][1].  You can get them on amazon, ebay, etc. and they work pretty well for me. Your distances are a bit longer than my situation but I have to go through several walls.

  [1]: http://smile.amazon.com/gp/product/B00INTI8R2/ref=ox_sc_sfl_title_6

body:
It's a bit unorthodox solution, but have you considered toy walkie-talkies?
They cover the distance you reported, even if some obstacles are in the path and they are relatively cheap, if you go for some sales.
It requires a bit of hacking to connect the arduino to the mic/speaker and the push button, but it shouldn't be too difficult.


body:
There are all sorts of Arduino and Arduino-compatible boards out there. They come in all form factors and they come with all sorts of different I/O. They even come with memory specs and different kinds of microcontrollers, from the ATmega328P to [Intel-based][1].

So what is it that imbues a board to become "Arduino Compatible" ? Must it be pin-compatible? Must it be possible to compile Arduino source code for the board? Or must the board be binary-compatible? Must it emulate some specific processor instruction set?

Very curious. Please reference specifications if possible. Thank you.

  [1]: https://www.arduino.cc/en/ArduinoCertified/IntelGalileo

title: What makes a board "Arduino Compatible"?

Answers: 3

body:
I think the practical answer is: it is not defined.

In practice:

For peripherals, it seems to mean that it can interact with an Arduino compatible board.

For boards, as far as I can tell, it has to be: instruction-set compatible, OR pin (layout) compatible with another board which was previously defined as Arduino compatible.

body:
I think you could say it is **Arduino-compatible** if it contains a processor found on an Arduino board. For example:

* The Atmega328P (found on the Uno, Duemilanove, Pro Mini, amongst others)
* The Atmega32U4 (found on the Leonardo, Micro, amongst others)
* The Atmega2560 (found on the Mega2560)
* Other processors used by Arduinos such as the Atmel SAM3X8E ARM Cortex-M3 CPU used on the Arduino Due.

With a processor used on an Arduino, you will find that you can almost certainly compile code using the Arduino IDE, and the Arduino libraries, that will work on such chips.

---

You could say it is **Arduino-Uno-compatible** if the board physically was compatible with the Arduino Uno (ditto for other boards). In other words, if it was possible to plug a shield, designed for the Uno, onto such a board. That could be called "plug compatible" I suppose.

---

As for other boards, like sensors, relay boards, etc., I have seen a lot of those on eBay advertised as "Arduino compatible", but of course they would also be compatible with other micro-controllers as well. I'm waiting for the day someone advertises "Arduino compatible" resistors.

body:
The problem here is that "compatible" can mean so many things in different contexts and to different people.  For instance, it may mean any of the following:

1. Can be used with the Arduino IDE without any need for additional board installation of other modifications
2. Can be used with the Arduino IDE after modification (boards installed)
3. Uses the same (or very similar) API to the Arduino system
4. Has the same footprint as an existing official Arduino board
5. Is a device which will work with an Arduino board and has software available to operate it

All very different meanings.

Point 1 could be a board that is based on the design of an existing Arduino board (say the Uno) but built into a new form factor, maybe with additional hardware and peripherals added.  It is still treated as if it was the board the design was based on though.

Point 2 would be a board that is similar, though not the same, as an existing board.  A different board definition may be required to map the IO pins properly, for instance.  It could use a slightly different chip in the same supported family. You still use it as an Arduino, but it's not the same as an existing Arduino board.

Point 3 may mean it's based on a completely different chip.  The programming environment may be almost the same, but it's hard to get 100% API compatibility.  Arduino sketches and libraries *may* work out of the box, or may not.

Point 4 could be a board that, internally, is completely different to the Arduino, uses a different programming language, IDE, etc, yet the layout of the board is the same as, say, an Arduino Uno.  A good example is the Mecanique Firewing - an Uno footprint, but a PIC32 chip instead of an Atmel, and Basic instead of C++.  Most Arduino shields would just plug in and work though, software permitting.

Point 5 is from the completely opposite direction.  This is a device which "is compatible with" in that "it will work with" and Arduino.  That could be on an electrical level (it's a 5V device and will connect to the Arduino) or that it has full software support (*"Download our Arduino library..."*).  It has nothing to do with how the device works or what it is though.

I prefer to use specific terms, respectively:

1. Based on the Ardino UNO
2. Programmable with the Arduino IDE
3. Compatible with the Arduino API
4. Footprint compatible with the Arduino UNO
5. Suitable for use with Arduino boards

That way it states exactly in what way this device relates to the official Arduino boards.


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

I am using an Arduino Due to collect a large amount of data from an encoder (about 1kb). Afterwards I need to send the collected data to a C# application I wrote over the serial port. I serialized my tx data into a byte buffer and simply used this code to transmit:

    void sendEncoderData()
    {
      byte buffer[1024];

      /*** some code that populates buffer ***/

      int bytesToSend = 1024;
      Serial.write(buffer, bytesToSend);
    }

When I run the code, nothing seems to get received by the C# application. In fact, I never see the Tx LED light up. However, if I change `bytesToSend` to a value smaller than 64 bytes everything works. Is this a limitation of `Serial.write()` or is it something else? What are ways I can work around this limitation?

More information： `sendEncoderData()` is called by an interrupt service routine. However prior to the call, I made sure to 'detachInterrupt()` on all pins including the pin associated with said ISR.

title: Arduino Serial.write sending more than 64 bytes

Answers: 1

body:
Here's the problem:

> sendEncoderData() is called by an interrupt service routine.

There is an internal 64 byte serial transmit buffer that is filled by Serial.write().  That buffer is empted by sending the data a byte at a time using an interrupt.

If you are in an interrupt (at a higher priority than the serial interrupt) then the interrupt that sends the data can never happen, so the buffer just fills up and stops when it gets to 64 bytes.  It will hang until there is room for more bytes in the buffer, and that will never happen because you're not allowing the data to be sent.

The answer (as I and others have said many times in the past): **Never use Serial in an interrupt.**


body:
**Increase the number of digital pins**

There are many post that explain how to use more than just the standard pins on the various arduinos but none of them explain the limitations and the proplems properly.

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

Arduino Uno:

**1.You can** use the analog pins

    Pin 14 = Analog in 0
    Pin 15 = Analog in 1
    Pin 16 = Analog in 2
    Pin 17 = Analog in 3
    Pin 18 = Analog in 4
    Pin 19 = Analog in 5

    digitalWrite(14,HIGH);
    or
    digitalWrite(A0,HIGH);

**2.You can't** use both SDA , SCL & A4 , A5 as they are basically the same (18,19).

**3.You can** also use the TX/RX.

> "Don't do it, you break the serial communication..."

> "Never use pins 0 and 1"

> "you can't use the TX/Rx Pins"

**You can... but you need to take precautions. Which ones?**

It should have software serial over USB, right?

Or do i break the USB serial?

Are there internal Chip problems if i use TX/RX?

As i use those TX/RX pins in the code i probably should not use `Serial.print()`?

What happens if i forget to remove `Serial.print()` after uploading the code that use pins 0,1?

How to hardware reset the arduino/bootloader if something goes wrong?

As there are various other Arduino's that use different chips, is the above valid for all Atmel chips?

**So, what shuold i know before using those TX/RX or also maybe the other analog pins?**

> There are cheap shiftregisters, pwm drivers, led drivers, spi, i2c and
> more ic's to expand your I/O

----------

But if there are not to big problems it means that the arduino has 20 I/O pins...

*You could theoretically control:*

    17x3 = 51 = 17 RGB leds (multiplexing, pwm sourcing&sinking);
    14x6 = 84 leds (multiplexing, pwm on 6 rows/colums );
    10x10 = 100 leds (multiplexing, high low);
    20x(20-1) = 380 leds (charlieplexing, high low);
    // yes it would flicker

Correct me if i'm wrong. That means you are able to control 380 "Whatever" using diodes and one arduino.

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

title: Use all pins As digital I/O

Answers: 3

body:
The main issue is with pins 0 and 1.

Many pins have multiple functions assigned to them, such as A4 and A5 are also the I2C pins, pins 10/11/12/13 are also the SPI pins, etc.  But pins 0 and 1 are the only multi-function pins that actually have something attached to them on the board.

All the other pins, while being multi-function, have their function defined basically by what you attach to them.  Since the pins 0 and 1 are already attached on the board to the USB interface chip their usage possibilities are somewhat more limited.

* As soon as you enable Serial in your sketch (`Serial.begin()`) those two pins can no longer be reliably used for digital IO.

That means that you can *either* use the hardware serial port *or* you can use the pins for digital IO, but not both.

* Devices connected to pins 0 and 1 can interfere with the serial connection

That includes uploading of sketches.  You have serial data coming in from the PC while the same pins are being affected by other things connected to them.  The most common one is things like GPS modules which connect to those pins and constantly send serial data.  That serial data will conflict with the PC's serial data and neither will arrive right.

* How do you upload sketches if the serial is being interfered with by your sketch? How do you "reset" the board?

You don't.  It's not your sketch that's interfering with the serial, it's what is physically connected to those two IO pins that are interfering.  Just disconnect those two pins from whatever is connected and you will be able to upload sketches again.  Many shields now are starting to add a small switch on them to disconnect those pins so you can upload sketches without unplugging the shield.  You can also use the same trick with other devices you wire up to those pins - add a double-pole-single-throw or double-pole-double-throw (and not use one position) to easily isolate both pins from the rest of your hardware when you need to.

* Does this affect all Arduino boards?

No, only those that use a USB to Serial bridge chip - that's things like the Uno, Due, Mega, etc.  Boards that have a direct USB connection don't use the TX and RX pins for uploading sketches - they use the dedicated USB D+ and D- pins.  That's boards like the Leonardo, some of the smaller (mini? micro? I forget which) boards, etc.

body:
> 20x(20-1) = 380 leds (charlieplexing, high low);
> Correct me if i'm wrong. That means you are able to control 380 "Whatever" using diodes and one Arduino.

First, the figure of 380 is correct for 20 pins (202 - 20) however pins 0 and 1 are connected to pull-up resistors on the Atmega16U2, so they are never really at 0V. If you load a blank sketch, you will measure 5 V on pins 0 and 1.

Second, you can't drive 380 "whatevers" you can drive 380 **LEDs** via Charlieplexing. The property of the LED, that current only flows one way through it, is important to the way it works.

Related question <https://arduino.stackexchange.com/questions/117/is-there-a-way-to-have-more-than-14-output-pins-on-arduino>

body:
I can't comment due to insufficient reputation but I want to point out that the OP pinout has at least one pin wrong!

**PB6 should be PB5**

I spent quite a lot of time trying to figure out why I couldn't see SCK on scope (SPI bus). I was working low level, not with the IDE.

As this is the first picture that comes up when googling I wanted to avoid the same trouble to others...


body:
I want to make a game of [Tic-tac-toe][1] using an Arduino, LEDs and bouncy buttons. Hence I need nine inputs and nine outputs. But you see that an Arduino only has 13 I/O pins. So is there a way I can use the analog pins or a way to reduce the number of I/O pins using an ingenious way?

  [1]: https://en.wikipedia.org/wiki/Tic-tac-toe

title: Increasing the numbers of I/O pins on Arduino Uno

Answers: 2

body:
Yes, just use the analog pins. The analog pins are both analog inputs and digital I/O pins. The functions happen to be shared on the pins, in the same way that the interrupt pins are shared with digital I/O, the TX and RX pins are shared with digital I/O and the SPI pins are shared with digital I/O.

Every I/O pin (analog or digital, etc.) can be used as digital I/O.

You can also reduce your required number of I/O pins by using a technique known as *multiplexing*.

For instance, to read nine buttons you could have them arranged (as in Tic-tac-toe) in three rows of three buttons. You then have three I/O pins for the columns and three I/O pins for the rows - that's just six I/O pins for nine buttons.

The technique is widely used for keypads, but they are just buttons, so the same technique can be applied to any buttons.

* *[The Matrix Keypad how-to][1]*

The same can go for LEDs. There are various specialist LED multiplexing techniques that allow for many LEDs to be driven from just a handful of I/O pins.

* *[How to Multiplex an LED Grid...][2]* (YouTube)
* *[Charlieplex Library for Arduino][3]*

  [1]: http://playground.arduino.cc/Main/KeypadTutorial
  [2]: https://www.youtube.com/watch?v=MmCGDJ90Qt4
  [3]: http://playground.arduino.cc/Code/Charlieplex

body:
If multiplexing is too complicated for you, you can wire all buttons to one analog pin using resistors. This way you only need 9 pins for LEDs and 1 analog pin for buttons.

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

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


body:
I noticed something unusual using the Low Power library today.
When printing text in the loop and using `LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);` to sleep for one second, all the text in the loop gets messed up in the Serial Monitor as if you chose the wrong baud rate.

Example code:

<!-- language: c -->

    #include "LowPower.h"

    void setup() {
      Serial.begin(9600);
      Serial.println(F("HELLO"));
      Serial.println(F("HELLO"));
    }

    void loop() {
      Serial.println(F("HELLO"));
      LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);
    }

This code just prints

    ����11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=

even when using different baud rates. (I used the same baud rate on both the arduino and the monitor).
Replacing the low power command with `delay(1000);` works fine

title: Low Power library messing up serial text

Answers: 1

body:
The problem is most likely that the system is going to sleep *while* it's still sending the serial data.

Forcing all the serial data to be sent before you go to sleep should fix the problem (serial data is sent in the background using an interrupt so as to keep sketch slowdown to a minimum):

    Serial.flush();
    LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);


body: Has someone experience with interfacing the AS3935 lightning sensor using I2C? I found a library but it only works with SPI as far as I can tell. I really don't want to give up 4 pins for SPI as I need those for other things. I2C would be great as I use a couple more sensors with I2C so no extra pins only for AS3935.

title: Use AS3935 with I2C?

Answers: 1

body:
Just use these functions to read/write AS3935 registers, replacing the SPI ones (_devAddr is the device address, usually 0x03) :

    // read/write functions for I2C mode
    uint8_t AS3935::_i2cRead(uint8_t addr)
    {
     // send register number
     Wire.beginTransmission(_devAddr);
     Wire.write(addr);
     Wire.endTransmission(false); // <<<--- THE 'false' here is mandatory!

     // request register data
     Wire.requestFrom(_devAddr, (uint8_t)1);

     // read data
     return Wire.read();
    }

    void AS3935::_i2cWrite(uint8_t addr, uint8_t data)
    {
     Wire.beginTransmission(_devAddr);
     Wire.write(addr);
     Wire.write(data);
     Wire.endTransmission();
    }

The "trick" is to use Wire.endTransmission(false) inside the read routine; this avoid to send the stop bit, which is mandatory for AS3935 read operation.


body:
I have a small light metal platform about 30 cm square mounted on horizontal rails. It is well lubricated and slides easily from side to side. I would like to build a device to connect to the underside of the platform that will allow me to programatically move the platform left or right by a defined distance at the touch of a button.

While I've never used an Arduino, I've been aware of its existence for a while and felt this might be a good project to begin experimenting with it. For context, I'm a computer programmer by trade, but have limited exposure to electronics in general.

Where would be a good place to start?  Are there books that are considered the "bible" of Arduino development? Are there existing projects that  basically do what I'm hoping to achieve? Am I barking up the wrong tree and shouldn't be attempting to find a solution for this with an Arduino? Any input would be greatly appreciated.

title: Controlling a sliding tray - beginners project

Answers: 1

body:
> Am I barking up the wrong tree and shouldn't be attempting to find a solution for this with an Arduino?

Not at all. For example see [Reprap](http://reprap.org/) - a 3D printer using an Atmega1280 as the controller. As it says [here](http://reprap.org/wiki/Generation_2_Electronics):

> Arduino is an open source project that has created an easy and powerful microcontroller board based on the Atmel ATmega168. It is the brain of the RepRap electronics.

If you can make a 3D printer with an Arduino, then you can make your sliding platform gadget, which sounds simpler if anything.

---

> Are there existing projects that basically do what I'm hoping to achieve?

Reprap, for one.

---

>  Are there books that are considered the "bible" of Arduino development?

This is a broad question, and your original question already has a couple of "flags" that it is *too* broad. I suggest you narrow it down a bit.

There are a number of books about learning Arduino. My advice is to start doing some simple projects (simpler than the platform initially) to get the hang of compiling, uploading, and generally working with microcontrollers.

---

Also try Google and YouTube. There are a **lot** of Arduino projects out there.


body: I have two devices connected to my Arduino using the SoftwareSerial library. However, it seems that they cannot communicate at the same time. I can only communiate with both by switching between which one I am listening to every 1000ms (they poll for 1500ms), but this slows down overall communication significantly. Is there anyway to communiate with both at the same time? Could this be achieved by using SoftwareSerial with one and the hardware serial port with the other?

title: Serial communication with two devices

Answers: 1

body:
See <https://arduino.stackexchange.com/questions/14179/softwareserial-write-to-return-read-in-serial-monitor/14180#14180> - SoftwareSerial cannot both read and write at the same time.

However HardwareSerial can.

> Could this be achieved by using SoftwareSerial with one and the hardware serial port with the other?

Yes.

---

> So, likewise, there is no way to read from both devices using only SoftwareSerial?

That is correct. Not at the same time. SoftwareSerial uses an interrupt to detect the start bit of incoming data. So far so good. But once it gets it, it leaves interrupts disabled while it goes into a timed loop to read all the bits.

Thus, it is impossible for it to react to another incoming byte on another pin at the same time.

Still, you could receive on SoftwareSerial on one pin, and HardwareSerial on another. With HardwareSerial the hardware will run in the background, receiving the byte.


body:
I'm using an Adafruit NRF8001 Low Energy Bluetooth module and a Real Time Clock module with my Arduino board. I want to connect to the BLE module using UART to set the clock. I'll also be using UART to set alarms.

I'm not sure which is the best way to take a string from the UART receiver and pull it apart into the hours, minutes, second, etc.

Any ideas? I did look at the Arduino JSON library but it seems a little buggy, and possibly overkill.

Any help would be very much appreciated :)

title: Using UART to Set RTC

Answers: 1

body:
The simplest method is to keep it as a fixed format string with line termination.

Read one line in from serial into a character array (aka C string) and then chop it up.  As long as the string is in the correct format you can easily chop it around.

For instance, assume you chose the format `YYYY-MM-DD HH:MM:SS\n` which is quite common and easy to use, you may have data like this:

    char *indata = "2015-08-22 17:23:48\n";

(`\n` is the new-line character)

Using simple char pointers you can get each substring quite easily:

First slice the string up into the component parts by replacing the separator tokens with character 0:

    indata[4] = 0;
    indata[7] = 0;
    indata[10] = 0;
    indata[13] = 0;
    indata[16] = 0;

Then you can assign pointers to each segment:

    char *year = indata;
    char *month = indata + 5;
    char *day = indata + 8;
    char *hour = indata + 11;
    char *minute = indata + 14;
    char *second = indata + 17;

Or if you want it as integers, you can pass it straight to `atoi`:

    int year = atoi(indata);
    int month = atoi(indata + 5);
    int day = atoi(indata + 8);
    int hour = atoi(indata + 11);
    int minute = atoi(indata + 14);
    int second = atoi(indata + 17);

In fact, if passing it direct to `atoi()` you shouldn't need to even do the first stage, since it will stop parsing at the first non-numeric character.

There are more flexible ways of parsing the string too, using `strtok()`, but that is somewhat more advanced.

Note that this method is highly intolerant to invalid strings being passed, so you may want to first ensure that a) the string is the right length, and that b) there are the right separator tokens in the right placed, to validate that the string is properly formatted before proceeding.


body:
I have an **Arduino Mega** and the **CL5642BH**, a **4-digit 7-segment display.** I found very helpful code [here][1], but I don't understand how to wire it up on the breadboard.

The display has 12 pins: 6 on the top and 6 on the bottom. First I guess I need to find out which one is GND.

Then (see the link) there is this code:

    int digit1 = 11; //PWM Display pin 1
    int digit2 = 10; //PWM Display pin 2
    int digit3 = 9; //PWM Display pin 6
    int digit4 = 6; //PWM Display pin 8

    int segA = A1; //Display pin 14
    int segB = 3; //Display pin 16
    int segC = 4; //Display pin 13
    int segD = 5; //Display pin 3
    int segE = A0; //Display pin 5
    int segF = 7; //Display pin 11
    int segG = 8; //Display pin 15

It's 11 pins, that's the correct amount so far. But **how do I wire it up?** The pins on the display are in no way labeled.

*Note: I'm a software developer, but as far as electronics go, I'm still a beginner.*

  [1]: http://www.hobbytronics.co.uk/arduino-4digit-7segment

title: How to wire up 4-digit 7-segment display?

Answers: 4

body: As page 2 of the datasheet shows, there are 5 anode pins (4 digit and 1 aux) and 8 cathode pins (7 segments and 1 DP). Connect the digit lines to the digit anodes and the segment lines to resistors connected to the segment cathodes. The location of pin 1 is shown on the top right of page 2, and as always they go counter clockwise from there. Segments are lit by putting the anode high and the cathode low.

body:
The first thing you do is ask Google for a datasheet.  It tells you: http://www.robotshop.com/media/files/pdf/datasheet-com-09483.pdf

Then you can read the datasheet and find the pin diagram:

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

That tells you that it is a *Common Anode* LED display - which means that for each digit all the *Anodes* (positive pins) of the LEDs are wired together.

Further, all the *cathode* (negative) pins of the LEDs for the same segments across the digits are connected (that is the cathode for segment A on digit 1 is connected to the cathode for segment A on digit 2, digit 3 and digit 4, etc).

From that you can then infer that you need to provide current for each digit in turn through its common anode pin, and sink current from the segments you want to have lit for the digit that is currently having its current sourced.

The diagram also shows you which pin on the display is for what function - the common anodes are pins 9, 10, 12 and 13, with pin 11 the common anode for the extra dots.

The datasheet also tells you which pin is pin 1 - in this case the one in the bottom left when you have the display facing you and the numbers the right way up.  The pins count anti-clockwise from there, so 2 is to its right and 13 is above it.

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

By the sounds of it though you may not have the same display as in that datasheet.  If your display lacks the extra dots then it may not have the LEDs on pin 11, and pin 12-13 may be moved down one, so you have 4 commons on 9, 10, 11 and 12 with no pin 13.

So the four digit select pins in your program are wired to pins 9, 10, 12 and 13, and the segment select pins connect to pins 1, 2, 3, 4, 5, 6, and 7.  Don't forget the resistors on all the segment pins to limit the LED current or you will damage the Arduino.

You can do some manual testing of the display by using two wires and a resistor (say 1KΩ).  Connect the resistor to +5V, and one wire to the other end of the resistor.  The other wire you connect to ground.

You then take the loose ends of the wires and try probing pins.  Start with the 5V wire touching pin 9 and connect the other one in turn to pins 1-8 to see if the first digit's segments light up.  Repeat with the 5V wire on pins 10-12.

Edit:

If this (http://mklec.com/displays/7-segment-4-digit-12-pin-common-anode-display) is indeed the same display as yours you can ignore the numbers I mention above and work from the pin numbers on that page.  The same principle applies though, just the pin numberings are different.

  [1]: https://i.stack.imgur.com/TnON4.png
  [2]: https://i.stack.imgur.com/16F42.png

body:
From the datasheet found by Ignacio Vazquez-Abrams:

[![7-segment display][1]][1]

Now one segment will light up if there is a positive (eg. 5 V) on the anode, and a negative (eg. ground) on the cathode. You need a resistor (eg. 330 ohm) to protect the LED and the output pin.

---

Hopefully it is clear from the original question which Arduino pins go to which LED pins.

---

Then the code which I presume you found will have to multiplex the display. That is, it will ground (send LOW) to the appropriate cathode pins for the number of segments it needs to light up (all of them, for example, for the number 8, except the decimal point). And then it will raise to 5 V (send HIGH) to DIG 1. That will make some segments on digit 1 light up. Then it repeats that for digits 2 to 4, fast enough that they will all appear to be on at once.

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

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

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

Apply the pin 1, 2, 3 with 5v from Audrino passing through the resistors. Apply low voltage to pin-a to light up the led, so on so forth.
You can use the multi-meter to confirm the common pins and led pin.
For example touch the pin1 with (+) and pin-a with (-) of the multimeter.
If the pins are correct, led pin-a will light up.

Picture Reference:http://www.circuitstoday.com/voltmeter-using-arduino


body:
I have a pair of 433 MHz transmitter and receiver:

[![Transmitter / receiver][1]][1]

Transmitter is connected to Arduino pro mini, receiver to Arduino Uno R3.

Output of receiver on serial looks like that (it doesn't change much):

Basicly I am getting either 75x or zero regardless of transmitter is on or off.

    in > upper
    756
    in > upper
    758
    0
    0
     0
    in > upper
    758
    0
    in > upper
    757
    in > upper

Transmitter code:

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

    #define rfTransmitPin 4
    #define ledPin 6

    void setup()
    {
        pinMode(rfTransmitPin, OUTPUT);
        pinMode(ledPin, OUTPUT);
    }

    void loop()
    {
        for(;;)
        {
             digitalWrite(rfTransmitPin, HIGH);     //Transmit a HIGH signal
             analogWrite(ledPin, 255);              //Turn the LED on
             delay(500);                            //Wait for 1 second

             digitalWrite(rfTransmitPin,LOW);       //Transmit a LOW signal
             analogWrite(ledPin, 0);                //Turn the LED off
             delay(500);                            //Variable delay
        }
    }

Receiver code:

    const unsigned int upperThreshold = 70;  //upper threshold value
    const unsigned int lowerThreshold = 0;  //lower threshold value
    const int ledPin = 13;

    #define ReceiverPin  A0

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

        pinMode(ledPin, OUTPUT);

        DiodeTest();
    }

    void loop()
    {
       int data = analogRead(ReceiverPin);
       delay(50);

       if(data>upperThreshold)
       {
           digitalWrite(ledPin, LOW);   //If a LOW signal is received, turn LED OFF
           Serial.println("in > upper");
       }

       if(data<lowerThreshold)
       {
           digitalWrite(ledPin, HIGH);   //If a HIGH signal is received, turn LED ON
           Serial.println("in < lower" );
       }

       Serial.println(data);
    }

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

title: 433MHz transmitter and receiver pair doesnt work

Answers: 3

body:
You also need to attach a piece of insulated wire as a 1/4 wave length antenna to each of the receiver and transmitter boards. For the 433 MHz type antenna's this would be a piece of wire ~6.8" (17.3cm) long.

For reference if you were using the other popular type of low cost RF link pair at 315 MHz the antennas would be ~9.37" (23.8cm) long.

body:
These types of receivers are AC coupled so you will not be able to do what you are doing as you need to have regular transitions in the signal and not stay in one state for too long.

They are also limited in the speed at which they will work, I expect 19200 bps is too fast.

You need to use a modulation technique such as Manchester Encoding or other technique that guarantees a suitable density of transitions, can synchronize the data and perform error checking.

One popular software library that does this is [VirtualWire Arduino Library][1] that is designed for Arduino and the type of transmitters and receivers you are using.

  [1]: http://www.airspayce.com/mikem/arduino/VirtualWire.pdf

body:
See [this post about a radio-controlled car](http://www.gammon.com.au/forum/?id=11506).

I found when using what looks like a similar receiver to yours, that the received data looked like this:

[![Radio receiver][1]][1]

The cyan line was the receiver, the yellow line is what is being transmitted.

The trouble turned out to be the pull-up resistor on the Arduino Rx pin (from the USB chip).

Even with SoftwareSerial it wasn't too great:

[![Radio receiver software serial][2]][2]

I found that using an op-amp as a buffer helped a lot:

[![Op-amp buffer][3]][3]

---

I also agree with the comments about adding an aerial wire, just a short length of hookup wire should do it.

  [1]: https://i.stack.imgur.com/eJWAd.jpg
  [2]: https://i.stack.imgur.com/7aJQe.jpg
  [3]: https://i.stack.imgur.com/qBQiR.png


body:
I am working on a Project with
(a) Arduino Uno Clone (6 PWM Pins i.e, 3,5,6,9,10,11)
(b) 6 Servos
(c) MicroSD Reader Module
(d) Speaker

As We Know that MicroSD reader modules uses pins 10, 11, 12 of an Arduino board, but **my pin 11 is already being used by a servo motor**.
1. Then how can I connect the MicroSD reader in my project ?
2. Which pin can I use for the speaker in this case ?

Please help me plus Provide me some additional information if needed.

title: Connecting MicroSd Reader with arduino uno

Answers: 1

body:
The best answer is: *don't use pin 11 for your servo motor - move it to another pin*.

The SD card needs SPI.  SPI is pins 10/11/12/13.  You can't change that.  You can much more easily move the servo to a different pin, since there are multiple PWM pins that can support the servo in hardware. If they are all taken then software PWM is easy and there are libraries available to do it for you, so you can use any IO pin you like for that.  Much simpler than re-writing the SD card software to use bit-banged SPI on other pins (which would also be incredibly slow).


body:
I noticed something today. I am powering the Arduino Nano from a battery and a 5v step up converter. That works just fine and I'm getting a stable 5v output. I have a second cable coming out from the battery which plugs right into analog input A0 set as input so I can measure the battery voltage. However when I disconnect the battery from the usb plug and leave the voltage sensing cable connected to the analog input the power led stays on. I want it to shut down and be disconnected from the power source and have the voltage sensing cable still connected.
How can I fix this?

title: Arduino nano getting powered through analog input?

Answers: 2

body:
Power is flowing from the analog pin, through the internal clamping diodes, to the Vcc line. Those diodes are however not designed to handle that much current, so don't continue doing this.

Either also disconnect the ground wire from the battery, or simply add a resistor between the battery and the analog pin. Something like 10k. That way less than a mA of current will be clamped, and the arduino will stay off.

body:
This addresses a subset of your question which was covered in your added comment-question. I've addressed use of a 20V full scale input range to make the answer more general. The results would be "even better" for your 5V input case. Note that is Vin ~= 5V you would want a measurenet range somewhat above 5V max so that you can handle typical voltage variations.

> Do you know any transistors/FETs with a very low voltage drop which I need for switching off a sensor?

If you used a say 10k resistor in the upper leg of a voltage divider and added a MOSFET switch with an on resistance (Rdson) of 2 Ohms (a terrible spec) between Vin and the divider then the error introduced would be about 2/10k = 1:5000. If measuring a say 12V  battery and using a Vinmax voltage of 20V the error in voltage measurement would be in the order of 20V/5000 = 4 mV. If using an Arduino Nano with a 10 but ADC the resolution (not accuracy) is 1 in 2^10 = 1:1024 or 20V/1024  = about 19 mV for a 20V input range. ie the resistor introduces an error of about 1/5th of a bit of available measuring accuracy.
Worse (or better) - if you use 1% resistors they will swamp errors caused by ADC resolution. Even use of say 0.1% resistors or calibration is liable to produce a result where ADC resolution is not the main limiting factor.

Even with no resistive divider, getting accuracies that are doinated by the 1:1024 ADC resolution and not other factors takes care and effort. At 5V in ax ADC resolution of 1:1024 means that a variation of 1 part in 2048 could cause an erroneous reading. Input offset voltages, thermal effects, board and connector resistances and ground voltage dropsm and offsets can easily provide greater error magnitufes.

Test: Take a working design. Set meter to lowest voltage range such that 1 mV can easily be seen. (Ideally 200 mV range. 2V range marginally OK). Measure ground voltages between various "ground" points at various locations in the system. Differences ofm mV to 10's of mV can often be found. Differences are poptentially higher if power current are present - say 10's of mA or more.


body:
I've got an Arduino with an ATmega328 processor. It can be operated at 3.3V which nets a clock signal frequency of about 12 MHz respectively 16 Mhz at 5V.

I've got an IMU connected to the Arduino and a AHRS algorithm turning accelerometer, gyroscope and magnetometer data into orientation data.

What does the higher frequency of 16 MHz actually mean in this context?

Will the AHRS be calculated faster so I get a lower latency? Can I poll the sensors more often? I want a deeper understanding of what I'm doing here.

title: What does a higher clock signal frequency actually mean for my AHRS?

Answers: 1

body:
> What does the higher frequency of 16 MHz actually mean in this context?

The Arduino will run a bit faster (33% faster). Therefore it could calculate things faster. Whether you can poll the sensors more often might depend on the sensor. Limiting factors could be how fast you can communicate with the sensor, how often the sensor takes readings, what you are going to do with the readings, and whether it matters if calculations are a bit slower.

For a better response I suggest you post a link to the particular sensor, the AHRS algorithm you are using, and describe the application you are using it for.


body:
I'm currently working with a digital output gyroscope. Its sensitivity is given as 120 least-significant bit per degree per second.

While every single component of that unit is easy to understand I don't quite get what it means altogether.

**Can you explain it to me?**

title: What does “LSB per degree per second” mean?

Answers: 2

body: Let us say we have a number, "4025". The "most significant digit" of the number is the 4 in the thousands position, since it tells us the most about the magnitude of the number ("in the four thousands"). Consequently, the "least significant digit" is the 5 in the units position, since it tells us almost nothing about the magnitude of the number. "Most/least significant bit" is the same, except it applies to binary numbers (which the MCU cares about, of course; we can still use any radix we like to talk about them). So the device's output count can change by up to 120 per degree per second.

body:
With further elaboration on Ignacia's answer:

A gyroscope itself is generally an analog device in the sense that in reality, it will have a continous output. This output is digitized using some form of Analog to Digital A/D converter where the analog output is converted to a digital number. The output from the gyroscope is a measurement of angular speed, generally millidegrees/sec.

The number read by your Arduino from the gyroscope will be a digital version of your current angular speed at the time of measurement. For example, if you're getting an 8bit number back equal to 121, this in binary is equivalent to 01111001, where the '1' furthest to the right is the least significant bit.

The term "lsb per degree per second" means how many bits change with your angular speed. For example, with a gain of 1 (meaning 1 degree/second = 1 bit), an angular speed of 90 degrees/sec will produce a read value of 90 or 01011010. Therefore, 1 bit changes per degree/second. Increasing the essential "gain" (which will most likely be referred to as "dps" will change how many lsb's change per degree/second.