body:
I'm not sure if I should split this question in two.
I had to edit some libraries and I plan to make some myself but didn't try yet.

Editing a library seems very laborious comared to editing a sketch.

I have to use an external editor and then compile on the Arduino IDE with the help of a test sketch.

I wish to use the Arduino IDE to edit the libraries but it seems it is not easy, maybe in future reales it is supported.

The libraries used to be on %home%/Arduino/libraries/etc. but now I have to edit some located at %appdata%\Arduino15\packages\esp8266\hardware\esp8266\1.6.5-947-g39819f0\libraries and it seems these packages might get updated so maybe it is not a good idea to edit them there but I am not sure.

What about GitHub and conflicts? I clone the library and edit it but then I have two versions and you can't choose one of them. So I have to delete the original from the arduino instalation or wherever it is to avoid the conflict.

I also wish to post the progress to GitHub and maybe receive collaboration there. Do you have any hint about the clone process or something to avoid any trouble with it?

And what about the .h/.o? Arduino precompile the headers on startup so if I edit a .h I have to find and delete the .o or restart the IDE.

How do you do all of this? Is there any trick that helps?

Thank you.

title: How to develop or edit an Arduino library?

Answers: 4

body:
I am going to split my answer into 2 parts

**1. Editing an Arduino library:**

It **doesn't** matter how you edit your library, you can do it in notepad for all I care. It just doesn't matter.

**2. Version Control:**

Git is a version control software used to track software/code changes and ensure that people don't screw up the files by adding code that's not tested.

If you want to contribute to a certain library here is what you need to do

Step 1: create a github.com account since most people host it there

Step 2: **fork** the required library, this basically creates a clone of the library in your account.

Step 3: **clone** the forked repo from your account to your computer. So now you have the files on your computer to mess around

Step 4: create a **branch** a branch is your personal workspace to mess around as you wish. The advantage of have a branch is that if you screw up.  You could always go to the main branch (master) and start over :)

Step 5: once you are done editing and testing and are sure the file is perfect, you **commit** your changes and then you create **pull request ** with the original author so  that he can review your work and if he is happy will accept your change and merge it to master.

Note: read about adding remote to your git repo and fetching from remote repo, once you understand these basics you will understand the power of git :)

body:
This is the common process for all open source projects, not just arduino (example using github svn)

**1. Fork a project**

When you fork a project, you create a separate "project" of your own from the original project on the SVN.

**2. Clone your project**

Clone your fork down to your local directory so you can make changes and use it.

    git clone https://github.com/<your-repo>/<project>

**3. Push changes up**

Push your changes up to your repo regularly. At this point your changes are not affecting the original project in any way.

    git push -u origin <branch>

**4. Pull updates from the original project**

The original author(s) can make changes and improve his/her code. You can make sure your fork is up-to-date by pulling/merging those updates into your fork.

    git pull https://github.com/<original-author>/<repo> <branch>

Some time there will be conflicts, which are normal since your changes and the author's may collide. You'll be prompted to fix the conflicts before committing your changes.

    <<<<<<< HEAD
        # this portion is your code at the current HEAD
    =======
        # this portion is the one from the original branch master
    >>>>>>> master

You'll have to fix the conflict manually by either accepting your change and deleting the master's or deleting your change, and get rid of the marks before committing to your svn.

**4. Creat a pull request**

After using your supercharged version of the project for a while, you think it might be useful for others. To contribute, you create a pull request to the original author. It works similar to you pulling in his changes, just he will review your changes then merge in.

All the while, others can do all these with your project too!

To edit the project/make changes, you can use any editor to open your local project, code away, save it and commit. It is not ideal to use Arduino IDE since it is an environment to run the code (but otherwise possible).

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

> I'm not accepting any answer because they are only focused on versioning/git/github fork->edit->share and I am very interested on all the things that I have to do to make the development.

---

I will run through the basics of making a library. It's really quite simple, and they persist through upgrades to the IDE.

Let's imagine I have a useful function (or lots of functions) that I want to use in lots of sketches. For example, something that blinks an LED:

    void blinkLED (const byte which, const int times)
      {
      for (int i = 0; i < times; i++)
        {
        digitalWrite (which, HIGH);
        delay (500);
        digitalWrite (which, LOW);
        delay (500);
        }  // end of for loop
      } // end of blinkLED

And some test code:

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      pinMode (13, OUTPUT);
      blinkLED (13, 5);
      }  // end of setup

    void loop ()
      {
      }  // end of loop

---

## Make a library

To turn that into a library we need three steps:

1. Make a folder for the library. This should be placed inside the **libraries** folder **in your sketchbook folder**. This folder:

    [![Sketchbook folder][1]][1]

    In my case: `/home/nick/sketchbook/libraries`. It does **not** go into anywhere associated with the IDE download.

    > but now I have to edit some located at %appdata%\Arduino15\packages\esp8266\hardware\esp8266\1.6.5-947-g39819f0\libraries

    No, **not** there.

   I will call my library `blinkLED`. So I make that folder, which is now: `/home/nick/sketchbook/libraries/blinkLED`

---

2. Make a function prototype for any functions your library is going to "expose" to the end-user, and put that into a .h file, like this:

    **blinkLED.h**

        #include <Arduino.h>

        void blinkLED (const byte which, const int times);

    **Important**: You must include `<Arduino.h>` as in the example, or you will get compile errors.

---

3. Put the C++ code into a .cpp file, like this:

    **blinkLED.cpp**

        #include <blinkLED.h>

        void blinkLED (const byte which, const int times)
          {
          for (int i = 0; i < times; i++)
            {
            digitalWrite (which, HIGH);
            delay (500);
            digitalWrite (which, LOW);
            delay (500);
            }  // end of for loop
          } // end of blinkLED

    **Important**: You must include the .h file created in step 2, as in the example, or you will get compile errors.

---

That's it! Restart the IDE now so it notices the new folder with the library in it.

Now our test sketch can just use the new library.

    #include <blinkLED.h>

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      pinMode (13, OUTPUT);
      blinkLED (13, 5);
      }  // end of setup

    void loop ()
      {
      }  // end of loop

---

## Testing

For testing I just keep the library files open in a separate text editor (I am using Geany these days, but whatever your favourite editor is).

You can make changes to the library source and save them. You **do not** need to restart the IDE if you do this. It will always pick up the latest version.

In the IDE you alter your calling code, upload and test. It is really quite fast and simple.

---

## Git

Once you have put a bit of work into your library you probably want to put it under source control. Using a terminal/command window, navigate to the library folder and put it into a Git repository:

    git init
    git add *.cpp
    git add *.h
    git commit -m "Initial commit"

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

body:
There is one component of your question that remains unanswered:
>I wish to use the Arduino IDE to edit the libraries but it seems it is not easy, maybe in future reales it is supported.

>Any good editor if Arduino IDE is not an option? Why is not an option?

The rest of your questions already have good answers so I'll limit myself to explaining how the Arduino IDE 1.6.5-r4 and newer can be used to edit libraries:

Copy the library you want to modify to {sketchbook folder}/libraries or create a new folder at that location if you're writing a library from scratch. You can find the location of {sketchbook folder} at **File > Preferences > Sketchbook location**.

Create a file that matches the folder name that contains the source files with the .ino extension. For example:

    {sketchbook folder}
    |_libraries
      |_FooBar
        |_FooBar.ino
        |_FooBar.h
        |_FooBar.cpp
or:

    {sketchbook folder}
    |_libraries
      |_FooBar
        |_library.properties
        |_src
          |_src.ino
          |_FooBar.h
          |_FooBar.cpp
This dummy .ino file is necessary in order to open the library source files in the Arduino IDE but will not actually be used as part of the library. You can leave it blank. I like to use this file as a "to-do" list for my development work. I add this filename to .git/info/exclude so that it will not be tracked as part of the repository. It's also possible to use this file as a sketch to test the library with. Just remember to use the local file include style:
<!-- language: lang-cpp -->

    #include "FooBar.h"

Note that you will only be able to edit the files that are in the same folder as the .ino file via the Arduino IDE. Luckily most Arduino libraries place all their source files in a single folder so this is not much of a limitation. If you wanted to edit a library that has source files in multiple folders you could always put a dummy .ino file in each folder and open them in separate IDE windows.

Add a file named .development to the library root folder. This is necessary because normally the Arduino IDE does not allow saving to the library folders or the examples folder to prevent accidental modification of the example sketches. Using Windows Explorer (and possibly others), you will find that you are not allowed to create files that start with a dot. You can create the .development file using a text editor or the command line. The contents of the file don't matter, only the presence of the file. Note that you should not publish the .development file to repositories that will be included in the Arduino IDE Library Manager as the file will [cause the library to be skipped](https://github.com/arduino/Arduino/issues/3512#issuecomment-128029263) by the job that fetches releases. I also add this filename to .git/info/exclude.

If the library does not already contain one, add a library.properties file to the library root folder. You can find the correct format of this file in the Arduino Library Specification:

https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#libraryproperties-file-format

Now the structure of the example libraries above would look like this:

    {sketchbook folder}
    |_libraries
      |_FooBar
        |_.development
        |_FooBar.ino
        |_FooBar.h
        |_FooBar.cpp
        |_library.properties
or:

    {sketchbook folder}
    |_libraries
      |_FooBar
        |_.development
        |_library.properties
        |_src
          |_src.ino
          |_FooBar.h
          |_FooBar.cpp

Restart the Arduino IDE if it's running.

After doing this, when you open any of the source files of the library with the Arduino IDE, all source files in the folder will be opened and you can edit and save them as you would a sketch.


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

I use a single MCP23S17 connected to an Arduino Uno. I use its port B for output and port A for input. When I first started to use this device I noticed, I could read pins, but using them as output failed. After a lot of debugging and trial and error I found out, that the IODIRx Register was never programmed. I then copied the respective code from the setup() routine — where it belongs IMHO — to the loop() routine.

And miraculously the IODIRx Register was written correctly. The code below contains the IODIRx programming snippet in the setup() as well as in loop(). But only in loop() it yields an effect. This means: The output will work only after the first traversal of loop() in my example.

The rest of the setup() routine obviously works, which means it is called at least. SPI is initialised correctly there.

This drives me nuts. What the hell is a setup routine for, if you can't setup things there. And why on earth doesn't it work then? I don't do strange things there.

    #include <Arduino.h>
    #include <Wire.h>
    #include <inttypes.h>
    #include <SPI.h>
    #include "flanschcontrol.h"
    #define DEBUGOUTPUT
    #define PROTOV2
    typedef int elem_type;
    #define ADDRESS (0)
    #define    OPCODEW       (0b01000000)  // Opcode for MCP23S17 with LSB (bit0) set to write (0), address OR'd in later, bits 1-3
    #define    OPCODER       (0b01000001)  // Opcode for MCP23S17 with LSB (bit0) set to read (1), address OR'd in later, bits 1-3
    #define    ADDR_ENABLE   (0b00001000)  // Configuration register for MCP23S17, the only thing we change is enabling hardware addressing
    uint8_t PexSSPin=7;

    void setup() {
       Serial.begin(9600);
     pinMode(PexSSPin, OUTPUT);
     SPI.begin();
       SPI.setClockDivider(2);
       SPI.setBitOrder(MSBFIRST);
       SPI.setDataMode(SPI_MODE0);

        delay(1000);
     PORTD &= 0b01111111;  // Slaveselect low

      SPI.transfer(OPCODEW | (ADDRESS << 1));
     SPI.transfer(IODIRB);
     SPI.transfer(0b10101010);
     PORTD |= 0b10000000; // Slaveselect high
     delay(1000);
    }

    void loop()
    {
     PORTD &= 0b01111111;  // Slaveselect low
     SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
     SPI.transfer(GPIOB);
     SPI.transfer(0b00000000);
     PORTD |= 0b10000000; // Slaveselect high
     Serial.println("0");
     delay(1000);

     PORTD &= 0b01111111;  // Slaveselect low
     SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
     SPI.transfer(GPIOB);
     SPI.transfer(0b11111111);
     PORTD |= 0b10000000; // Slaveselect high
     Serial.println("ff");
     delay(1000);

     PORTD &= 0b01111111;  // Slaveselect low
     SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
     SPI.transfer(GPIOB);
     SPI.transfer(0b00001111);
     PORTD |= 0b10000000; // Slaveselect high
     Serial.println("0f");
     delay(1000);

     PORTD &= 0b01111111;  // Slaveselect low
     SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
     SPI.transfer(GPIOB);
     SPI.transfer(0b11110000);
     PORTD |= 0b10000000; // Slaveselect high
     Serial.println("f0");
     delay(1000);

     int value;

     PORTD &= 0b01111111;  // Slaveselect low
       SPI.transfer(OPCODER | (ADDRESS << 1));  // Send the MCP23S17 opcode, chip address, and read bit
       SPI.transfer(GPIOA);                      // Send the register we want to read
       value = SPI.transfer(0x00);               // Send any byte, the function will return the read value (register address pointer will auto-increment after write)
       value |= (SPI.transfer(0x00) << 8);       // Read in the "high byte" (portB) and shift it up to the high location and merge with the "low byte"
     PORTD |= 0b10000000; // Slaveselect high
     Serial.print("pindata: ");
     Serial.println(value);
     delay(1000);

     PORTD &= 0b01111111;  // Slaveselect low
      SPI.transfer(OPCODEW | (ADDRESS << 1));
     SPI.transfer(IODIRB);
     SPI.transfer(0b10101010);
     PORTD |= 0b10000000; // Slaveselect high
    }

Definitions of some preprocessor thingies:

    #define    IODIRA    (0x00)      // MCP23x17 I/O Direction Register
    #define    IODIRB    (0x01)      // 1 = Input (default), 0 = Output
    #define    GPIOA     (0x12)      // MCP23x17 GPIO Port Register
    #define    GPIOB     (0x13)      // Value on the Port - Writing Sets Bits in the Output Latch

title: MCP23S17: Programming IODIRx-Register works in loop(), but not in setup()

Answers: 1

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

You've fallen for the old "slave select pin is already low" trick!

Let me show you. First we add a line to bring pin 2 high before starting the sequence (for logic analyzer triggering):

    pinMode (2, OUTPUT);     // <--- pin 2 output
    delay(1000);
    PORTD |= bit (2);        // <--- pin 2 HIGH
    PORTD &= 0b01111111;     // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));
    SPI.transfer(IODIRB);
    SPI.transfer(0b10101010);
    PORTD |= 0b10000000;    // Slaveselect high
    delay(1000);

This is the logic analyzer output of running your sketch:

[![Slave select low][1]][1]

Notice how SS is low all the time, and thus the chip does not respond to the command?

---

Now we add a line **before** the `SPI.begin`

    PORTD |= 0b10000000;    // Slaveselect high
    SPI.begin();
    SPI.setClockDivider(2);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);

Now look at the results:

[![Slave select high][2]][2]

This time you get the transition of SS from high to low, the chip notices it, and we have a valid SPI transaction.

So without bringing SS high, the **first** thing you sent was always going to fail.

---

It was nothing to do with it being in `setup` - it couldn't be. After all the logic is basically this:

    init ();
    setup ();
    while (true)
      loop ();

---

Personally I wouldn't hard code all those bit patterns throughout the code. What if you change the slave select pin one day?

How about:

    digitalWrite (PexSSPin, LOW);
    /// write to chip
    digitalWrite (PexSSPin, HIGH);

Isn't that much more readable? And easier to change later?
  [1]: https://i.stack.imgur.com/c2IPr.png
  [2]: https://i.stack.imgur.com/Xu2HN.png


body:
I'm attempting to connect two Arduino boards to eachother using SotwareSerial as the title suggests!

The two boards are 1) Arduino UNO and 2)MultiWii Controller (MWC) FLIP 1.5 (Uses ATMega328 chip).

The idea, is to get Serial TX on the *"MWC"* FLIP 1.5 to Serial RX on the UNO.

These are my connections thus far:

MWC Pin ------->UNO Pin

Digital 3 (TX)--->Digital 6 (RX)

Digital 9 (RX)--->Digital 9 (TX)

This is the code on the MWC Chip -- the TX chip. (NOTE: These functions are called to run in a header file)

    #include "attout.h"
    #include "SoftwareSerial.h"

    SoftwareSerial altSerial(9,3); // RX=9 TX=3

    void startaltserial(){

      altSerial.begin(9600);

    }

    void attout(){

    pinMode(3,HIGH);
    pinMode(9,HIGH);

      altSerial.print('1');

    }

NOTE: I also tried `altSerial.write('1')`. Same result (or lack of one).

Then, the RX Code on the UNO Board:

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(6,9); // RX=6 TX=9

    void setup()
    {
      // Open serial communications:
      Serial.begin(9600);

      // Set the data rate for the SoftwareSerial port
      mySerial.begin(9600);

    }

    void loop()
    {
      while (mySerial.available()>0) {
        Serial.println(mySerial.read());
      }
    }

When I open Serial Monitor for the UNO board, I get nothing but zeroes streaming down. Curiously, if I disconnect the TX OUT wire from MWC, the Serial stream stops!

This means, as far as I can tell, that the UNO is doing its job of receiving, and the MWC is doing it's job of transmitting, but something is wrong with the formatting inbetween, so that I end up with zeroes.

Additionally, if I change the baud rate, the Serial Monitor output changes. When I go to 1200 baud, I get nothing but '4' followed quickly by '1' and then carriage return, so it looks like '41'.

Hope we can find a solution to these quandaries. My next course of action is trying I2C, but I'm not sure about it yet...

title: Sending Data between two boards using SoftwareSerial

Answers: 1

body:
Your problem here is that you are streaming out serial data non-stop.

See my answer in this thread: <https://arduino.stackexchange.com/questions/1569/what-is-serial-begin9600/14146#14146>

Without having a pause, the receiver just latches onto somewhere in the middle of the data stream and tries to make sense of it, often unsuccessfully.

If you add one "character time" delay to the **sender**, the receiver works fine:

      altSerial.print('1');
      delay (2);

It might get the first one wrong, but now the receiver has 2 ms to resynchronize on the data stream. At 9600 baud the delay should be 1/960 (second) at least, I used twice that to be sure.


body:
I'm looking to build a motion sensor which detects if an object is in the monitored area. Doing some researched I found out that I can use [PIR motion sensor][1] for this but it seems the area it monitors is pretty small.

I need something that can monitor about 3 feet x 1 feet area. Is there something else that I can use for this?

My goal is to light up some LED lights when an object is detected in that area.

Thanks in advance.

  [1]: http://www.adafruit.com/products/189?&main_page=product_info&cPath=35&products_id=189

title: Motion sensor large areas

Answers: 2

body:
A standard PIR motion sensor will work fine.  It can monitor motion in a very room.  You just need to make sure the PIR sensor is far enough away.

Here is one article that states it should work up to 10 meters away.

https://www.mobotix.com/eng_US/Support/FAQ/Configuration2/What-is-the-range-of-the-PIR-Passive-Infrared-motion-detector

Note that the device that the PIR sensor is mounted on must be stationary.  It will not work on a robot of anything that is moving.

body:
It sounds like what you want is an ultrasonic distance ("ping") sensor over the area where the car is.

When the car isn't there it will measure the height of the garage (say 3m).  With the car there it will measure the distance from the ceiling to the top of the car (say 1.5m).

Ultrasonic sensors have a limit to their range.  The cheap ones are usually around 2m, so may not work for you, or you may get away with it if it will return "infinite" for anything outside its range, in which case anything that is not "infinite" will be something present under the sensor.


body:
[![This is how it looks.][1]][1]

I'm working on a project that will log data to an SD card and display a user interface on an OLED. [The SparkFun OLED breakout][2] was super easy to set up. I was also able to get the [SD-Card library][3] working independently, though that was harder.

The trouble is when I combine these examples the SD card *only* writes during "setup" after that it isn't writing to the SD card as the loop continues. The OLED still works just fine.  I've read up on SPI a bit and tried various things to get "chip select" to work (I suspect this is the problem) I even tried setting the CS pins to LOW or HIGH using digitalWrite, but this had no impact.

My pins are connected as follows:

              SD CARD      OLED
    MOSI        A5            A5     same pin
    MISO        A4            --     just SD connected
    SCK         A3            A3     same pin
    CS          A1            A2     different pins

The SD card writes in the main loop if I comment out all of the code that runs the OLED. The OLED works either way.  What could I try next?

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

     #include "application.h"
     #include "sd-card-library/sd-card-library.h"
     #include "SparkFunMicroOLED/SparkFunMicroOLED.h"
     #include "math.h"

     //////////////////////////////////
     // MicroOLED Object Declaration //
     //////////////////////////////////
     // Declare a MicroOLED object. If no parameters are supplied,
     // default pins are used, which will work for the Photon Micro
     // OLED Shield (RST=D7, DC=D6, CS=A2)
     // Since I use A1 as the chip select pin for the SD card these
     // defaults seem fine.

        MicroOLED oled;

     // Declare a file object?

        File myFile;

     // These are the pins for the SD card. A5, A4, and A3 are all
     // shared by the OLED.

        const uint8_t chipSelectSD = A1;
        const uint8_t mosiPin = A5;
        const uint8_t misoPin = A4;
        const uint8_t clockPin = A3;

     ////////////
     // setup //
     ////////////
     void setup() {
      delay(500);

      SD.begin(mosiPin, misoPin, clockPin, chipSelectSD);
      File dataFile = SD.open("data.txt", FILE_WRITE);
      dataFile.println("this text was printed to the SD card during setup");
      dataFile.close();

      oled.begin();  // Initialize the OLED
      oled.clear(ALL); // Clear the display's internal memory
      delay(1000);  // Delay 1000 ms
      oled.clear(PAGE); // Clear the buffer.
      randomSeed(analogRead(A0) + analogRead(A7)); //seed to make test pattern random.

                   }//end setup

    //////////////////
    // main loop //
    //////////////////
    void loop()  {

      SD.begin(mosiPin, misoPin, clockPin, chipSelectSD);
      File dataFile = SD.open("data.txt", FILE_WRITE);
      dataFile.println("The text was added during the loop.");
      dataFile.close();

    //test the display with text and pixels.
      printTitle("Pixels", 1);
      for (int i=0; i<512; i++)
      { oled.pixel(random(oled.getLCDWidth()),  random(oled.getLCDHeight()));
      oled.display(); }
       delay(9000);

                   } //end loop

    //-------------------------//
    // function to print titles //
    //-------------------------//
      void printTitle(String title, int font) {
      int middleX = oled.getLCDWidth() / 2;
      int middleY = oled.getLCDHeight() / 2;
      oled.clear(PAGE);
      oled.setFontType(font);
      // Try to set the cursor in the middle of the screen
      oled.setCursor(middleX - (oled.getFontWidth() * (title.length()/2)),
      middleY - (oled.getFontWidth() / 2));
      // Print the title:
      oled.print(title);
      oled.display();
      delay(1500);
      oled.clear(PAGE);
                                               } //end title function

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

This is how the SD card is hooked up.

      oled.begin();  // Initialize the OLED

Any attempt to use the SD card after this line will not work. I've looked for something like "oled.end()" but have not found a way to reset to the state where the SD card works.

I have tried commenting out all of the OLED code and then the SD card writes fine in the main loop. So, I started adding the OLED code back in. This line of code breaks the SD card writing in the main loop:

  [1]: https://i.stack.imgur.com/qB9Jv.jpg
  [2]: https://learn.sparkfun.com/tutorials/photon-oled-shield-hookup-guide
  [3]: https://github.com/technobly/SparkCore-SD
  [4]: https://i.stack.imgur.com/qfxAr.jpg

title: Making CS (chip select) work in SPI (for and SD card and OLED)

Answers: 1

body:
I wanted to write to 2 SD cards simultaniously with one Arduino Mega. Used all the relevant pins including CS on 53 for the first SD card and 13 for the second SD card.  Can be any digital pin I think but this one makes the LED blink too).  Before the SD.begin(13) of the second SD card I do a digitalWrite(53,HIGH).  That de-selects the first SD card. and digitalWrite(13,HIGH) when switching back to SD.begin(53) I do a digitalWrite(13,HIGH).  This works real fine.

Now I tried to impelment this on a D1-Mini.  Cannot get it to work.
SD.begin(D8) starts the first SD fine.  By doing a digitalWrite(D8,HIGH) I tried to de-select SD1 and with SD.begin(D4) opened the second card. Strangely enough it still opens the first SD card again regardless of the pinnumber-parameter.
Maybe the SD library for ESP8266 remembers the first setting of the CS and later settings og the parameter with fifferent pinnembers are ignored???


body:
I am currently building a project involving a laser scanner (two galvanometers with mirrors that deflect a laser beam) that I want to control. The galvos need +-10V differential signals (and I'd like to have a least 12Bit) that I want create with some small board.

Most Arduinos I know use PWM to create an analog output which is not usable for this project. I found the Teensy3.1 which has at least one 12Bit DAC so that also doesn't work. An alternative would be a DAC breakout board like ["MCP4725"][1] but it would be nicer to just have a single board with no additional parts.

The best thing would be a small board with already two 12Bit DACs. (even If I had to upscale the voltage +-10v)

Is there a board I haven't found so far? Or have I missed a completely different approach?

  [1]: https://www.adafruit.com/products/935 "MCP4725"

title: Which board/shield to generate (non-PWM) analog outputs?

Answers: 1

body:
For 12-bit dual DAC you want the [MCP4822](http://ww1.microchip.com/downloads/en/DeviceDoc/22249A.pdf) which has two channels of 0-4.095V in 1mV steps.

The output of that you would then need to pass through a suitable amplifier arrangement with an op-amp giving a gain of 5 and adding an offset of -10V.  The gain would change the 0-4.095V to 0-20.475V, and the -10V offset would change that to -10V to +10.475V.  If you want to get more precise you could use an offset of -10.2375V (it's not easy to make an offset voltage that precise) then you would get -10.2375V to 10.2375V in 12-bit resolution.

It's doubtful you'll find a board already made up with that specific arrangement (it's fairly specialised) but it's not something that's hard to make - all the components are available as DIP or other through hole components, and the circuit for the amplification stage is pretty simple (check for non-inverting op-amp circuits online, there's millions), so building it up on strip board or matrix board would be easy enough.


body:
I got a copy of Arduino from a local retailer here (it's a local copy and I'm pretty confused with how the pins actually work).

I know basic electronics so far, there should be two pins for every node one acting as the negative terminal and other as the positive terminal. If I were to connect an LED with my Arduino board which pins would I be utilizing?

Here let me tell you how pins are arranged on mine:

    IOREF                                                                         GND

                                             13
    RESET                                                                         12
    3.3V     //this left group marked power                                        .
    5V                                  //right group marked PWM                   2
    GND            //right groupmarked communication                          TX0 -1
    GND                                                                       RX0- 0

    V1N                                                                       TX3-14
                                                                             RX2 -15
    A0                                                                         ..
    A1                                                                      SCL -21
    ..   //THIS left GROUP MARKED ANALOG IN
    A7

    A8
    A9 //I believe it is part of the above group
    ..
    A14
    A15

         //the pins below marked DIGITAL
         52-50-`48-46...........................................................22`

title: How do pins on an arduino mega 2560 work?

Answers: 2

body:
Any IO pin can be set to either be an input, where it reports to your program if the voltage present on that pin (relative to ground) is above or below a certain threshold (HIGH or LOW voltage), or it can be an output, where it can either be set to be a HIGH output (pin is connected internally to +5V) or a LOW output (pin is connected internally to GND).

To drive an LED you would connect one side of a small resistor (say 470Ω) to any IO pin you choose.  The other side of the resistor would connect to the anode of the LED.  The cathode of the LED would then connect to ground.  When you set the IO pin to HIGH it will provide 5V to the LED through the resistor (which is needed to limit the current as the LED is a non-linear, current driven, component) and the circuit is completed by the return path through ground.

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

Note that you *must not* exceed 40mA going into or out of any IO pin, and you *should not* exceed 25mA going into or out of any IO pin.  The total current going into or out of *all* IO pins *must not* exceed 200mA.

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

body:
> there should be two pins for every node one acting as the negative terminal and other as the positive terminal.

No, there is one pin per node, and a **common** "Ground" pin which is the negative terminal. On your Mega2560 are 5 ground pins (effectively equivalent because they are connected). They are circled on the photo below, and marked **GND** on the board.

[![Mega2560 board][1]][1]

---

As Majenko says in his answer you must use a resistor in series with any LED you connect, or you will damage both the LED and the processor.

You may find a "breadboard" handy for making connections, most prototyping boards have a long connected strip for sharing the Ground wire between different places, like this:

[![Prototyping board][2]][2]

The continuous blue lines indicate pins which are connected together (for Ground) and the continuous red lines are connected together for +5 V (usually).

---

> Btw can you tell me why there are two pins on the bottom horizontal row?

Just for convenience. You often want an extra ground pin, for example if you are trying to connect up two LEDs.

>  Secondly, yes each pin can be set as input or output but is there any specific difference in the type of pins?

Some of the pins can optionally be used for extra hardware-supported features.

* PWM: Pulse-width-modulated output
* COMMUNICATION: Serial input/output (4 serial ports)
* ANALOG IN: Analog-to-digital converter (ADC) input
* DIGITAL: Digital (not analog) input/output
* SDA/SCL: I2C communications
* Pins 50-53: SPI communications (not marked on the board)

However **all** pins, as you noted, can - if you wish - be used for digital input or output.

  [1]: https://i.stack.imgur.com/EWFnD.jpg
  [2]: https://i.stack.imgur.com/ArXKq.jpg


body:
I've created a very basic POV project.

It has a 12V DC motor with a piece of wood on it.
The wood has 6 LEDs on it as well as a copper ring.
The power is delivered to the LEDs from brushes connecting to the copper ring and from the shaft of the motor (the ground is attached to the base of the motor.) I'm using a TCRT5000L Sensor to count the RPM and have attached the LEDs to pin 13 and ground of the Arduino. (I've attached white tape to one side of the wood so that the sensor only counts one rev.)

I need help (please) with the program.

This is the code that I am using:

    int pin = 13;
    volatile  int tcnt = 0;
    volatile  int lastcount = 0;
    volatile int state = LOW;

    void setup() {
      Serial.begin(9600);
      pinMode(pin, OUTPUT);
      attachInterrupt(1, blink, RISING);
    }

    void loop() {
      Serial.println(tcnt);
      if (tcnt != lastcount)
      {
         digitalWrite(pin, HIGH);
         delay(10);
         digitalWrite(pin, LOW);
         delay(10);
         lastcount = tcnt;
      }

       delay(10);

    }

    void blink() {
      tcnt = tcnt + 1;
      state = !state;
    }

My first issue is that the when I use the code above, the lights don't seem to switch on / off on the exact same area. They are within 30 degrees but certainly not precise.

The second issue (and the biggest) is that I'm sure that this code is not the best way to do what I need. For example, if I wanted to use this as an analog clock, so that the lights would only show on the current hour / minute, how would I do this?

Any help is greatly appreciated.

[![Side View][1]][1]

[![Top View][2]][2]

  [1]: https://i.stack.imgur.com/mtp02.jpg
  [2]: https://i.stack.imgur.com/rmGd4.jpg

title: Need assistance with program for POV Project

Answers: 1

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

Your **third** delay is the issue. It means you have up to 10 ms before you notice the need to turn on the light. Try this:

    const byte pin = 13;
    volatile bool detected;

    void setup() {
      pinMode(pin, OUTPUT);
      attachInterrupt(1, blink, RISING);
    }

    void loop() {
      if (detected)
        {
        delay(10);
        digitalWrite(pin, LOW);
        detected = false;
        }

    }

    void blink() {
      digitalWrite(pin, HIGH);
      detected = true;
    }

Now that immediately turns on the LED, so it will always happen at the same time. Then in the main loop you notice it is on, wait 10 ms, and then turn it off.


body: I've been scouring the internet looking for a small Arduino that can power two sensors and a servo. Is there a way of getting a custom one? Does anyone know if theres software out there for creating custom Arduinos and having them made?

title: I'm looking for a real small but decent Arduino, that can fit in a watch but power a servo and a gyroscope

Answers: 3

body:
Look at the ATtiny85 MCU. It's a small 8pin device, and pretty easy to get up and running using Arduino code. You could also use the ATtiny84 which has more pins and still very small.

Start here: https://code.google.com/p/arduino-tiny/

Also, there are plenty of tutorials on setting up and programming them.

Regarding a custom board, your least expensive route would be to design your own. Otherwise you would need to outsource the design.

body:
No, there is no software specifically for designing custom Arduinos.  However, the Arduino is open source, so you can design your own if you have the skills.

You can download the schematics for your chosen base design from the Arduino website, then use any PCB design software you like to design your own PCB.

You can then send that PCB design off to China (for example) to have it fabricated, and when you get them back you can solder the components on and hope it works.

Of course, designing and building very small circuits well is a talent that few possess. Hand building circuits with the very tiny components you will need to make it fit into a watch is very difficult and normally requires specialist equipment.  That is unless you want your watch to be the size of a dinner plate, like most of the watch kits you can buy.

body: You might look into building a circuit, on a breadboard, from basic components. Think Atmel, AtMega instead of Arduino. Depending on your experience and willingness to read datasheets, this might be easier than you imagine. After you have a large-scale working prototype, find miniature surface-mount versions of all of the components. Designing an actual circuit board to connect these things might be the real trick, but if you can get it done then you can have the board made. I believe, am uncertain about this, that there are software tools available that help turn schematics into circuit board designs. This part might be expensive. Getting to the point of having a large-scale working prototype, on the other hand, would be inexpensive and fun. Once you have a board designed you'll have to get it made. Testing this prototype might be difficult and perhaps expensive as well. (Engineers are paid well because they tend to know before construction if a design will work.) If you come up with something that works then selling the extras might pay for having it made.


body:
I've been getting involved with arduino recently as a means of improving a heating device which is quite small, a box about 15x10x5cm which I would like to rig with an [MLX90614][1] infrared sensor.

The box is already "wired" with many small flexible tubes, so I would like to set up the sensor so that I can read from it wirelessly, to keep it from getting anymore complicated than it needs to be.

What would be the most compact way to set up a transceiver capable of I2C (ideally with arduino uno coding compatibility) and to then communicate with another arduino? (I already have an Uno to act as the base station)

The reason I mention that the device should be codable with Arduino is that the MLX90614 uses a communication protocol that is beyond my skill level and which I can only operate with open source code libraries for arduino.

I've been doing some research and the best thing I've found so far is the [PanStamp][2], but I have never soldered before, and they are not in business at the moment.

Another limitation is size. I would prefer not to use another entire arduino Uno, with shield.

And of course low cost is a plus :)

So if any of you have worked on something like this before and you have a recommendation, it would be greatly appreciated.

-Ryan

  [1]: http://www.melexis.com/Infrared-Thermometer-Sensors/Infrared-Thermometer-Sensors/MLX90614-615.aspx
  [2]: http://www.panstamp.com/products/

title: How to wirelessly communicate with I2C infrared thermometer

Answers: 1

body:
>So if any of you have worked on something like this before and you have a recommendation, it would be greatly appreciated.

See [Solar powered Arduino](http://www.gammon.com.au/forum/?id=12821) - I used a standalone Atmega328P on a prototyping board for that. That used the NRF24L01 to send information (the current voltage in this case) to another Arduino.

For small and simple you could get an [Arduino Nano](https://www.arduino.cc/en/Main/ArduinoBoardNano) or [Arduino Pro Mini](http://www.adafruit.com/products/2378). The Pro Mini is around $US10, and is quite small.

They have the same processor (Atmega328P) so you can connect your I2C sensor to it, and the NRF24L01 as well.

> I have never soldered before ...

I think you will have to do a little soldering, to connect up the sensor, and the transmitter, but soldering on connecting wires isn't too onerous.


body:
I am doing simple proof of concept trying to send C++ program output to Adafruit CC3000 WiFi Shield (using Visual Studio 2013 Desktop Edition on Windows 8.1).

In my design laptop is connected to UNO via USB, UNO is connected to WiFi Shield, and WiFi Shield is connected to D-Link router running Adafruit example sketch ("EchoServer"). These connections are working fine.

Next, I am using TCP client sample code from Microsoft for WiFi connectivity with client code running on the laptop to connect to WiFi Shield. Tested this code with sample TCP server code from Microsoft, and client was able to communicate with server code but for some reason this client is not able to find WiFi Shield TCP Server. I get "Unable to connect to server" error with CC3000 continue to show it is listening for connections but never finds one

I am sure it is due to my lack of understanding TCP/networking world. Below is the client code I am running on laptop using Visual Studio:

    #define WIN32_LEAN_AND_MEAN

    #include <windows.h>
    #include <WinSock2.h>
    #include <ws2tcpip.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include<iostream>

    // Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
    #pragma comment (lib, "Ws2_32.lib")
    #pragma comment (lib, "Mswsock.lib")
    #pragma comment (lib, "AdvApi32.lib")

    #define DEFAULT_BUFLEN 512   //Default buffer length of port
    #define DEFAULT_PORT "7"  //Change this to change port

    int main()//int argc, char **argv
    {
     WSADATA wsaData;
     SOCKET ConnectSocket = INVALID_SOCKET;
     struct addrinfo *result = NULL,
      *ptr = NULL,
      hints;
     char *sendbuf = "100";
     char recvbuf[DEFAULT_BUFLEN];
     int iResult;
     int recvbuflen = DEFAULT_BUFLEN;
     /*
     // Validate the parameters - not necessary for use
     if (argc != 2) {
      printf("usage: %s server-name\n", argv[0]);
      system("pause"); return 1;
     }
     */

     // Initialize Winsock
     iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
     if (iResult != 0) {
      printf("WSAStartup failed with error: %d\n", iResult);
      system("pause"); return 1;
     }

     ZeroMemory(&hints, sizeof(hints));
     hints.ai_family = AF_UNSPEC;
     hints.ai_socktype = SOCK_STREAM;
     hints.ai_protocol = IPPROTO_TCP;

     // Resolve the server address and port
     iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
     if (iResult != 0) {
      printf("getaddrinfo failed with error: %d\n", iResult);
      WSACleanup();
      system("pause"); return 1;
     }

     // Attempt to connect to an address until one succeeds
     for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {

      // Create a SOCKET for connecting to server
      ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
       ptr->ai_protocol);
      if (ConnectSocket == INVALID_SOCKET) {
       printf("socket failed with error: %ld\n", WSAGetLastError());
       WSACleanup();
       system("pause"); return 1;
      }

      // Connect to server.
      iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
      if (iResult == SOCKET_ERROR)
      {
       closesocket(ConnectSocket);
       ConnectSocket = INVALID_SOCKET;
       continue;
      }
      break;
     }

     freeaddrinfo(result);

     if (ConnectSocket == INVALID_SOCKET) //If failed to get a socket, end program
     {
      printf("Unable to connect to server!\n");
      WSACleanup();
      system("pause"); return 1;
     }

     // Send an initial buffer
     iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
     if (iResult == SOCKET_ERROR) {
      printf("send failed with error: %d\n", WSAGetLastError());
      closesocket(ConnectSocket);
      WSACleanup();
      system("pause"); return 1;
     }

     printf("Bytes Sent: %ld\n", iResult);

     // Receive until the peer closes the connection
     do {

      iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
      if (iResult > 0)
      {
       printf("Bytes received: %d\n", iResult);
       std::cout << recvbuf << std::endl;
      }
      else if (iResult == 0)
       printf("Connection closed\n");
      else
       printf("recv failed with error: %d\n", WSAGetLastError());

     } while (iResult > 0);
     // shutdown the connection since no more data will be sent
     iResult = shutdown(ConnectSocket, SD_SEND);
     if (iResult == SOCKET_ERROR) {
      printf("shutdown failed with error: %d\n", WSAGetLastError());
      closesocket(ConnectSocket);
      WSACleanup();
      system("pause"); return 1;
     }
     // cleanup
     closesocket(ConnectSocket);
     WSACleanup();
     return 0;
    }

title: Having issues with sending output to WiFi Shield

Answers: 1

body:
At no point in your program are you telling it where to connect to.  You are requesting service "7", which of course is resolved to port number 7, but you aren't giving it an IP address or host name to connect to.  Ergo, it is trying to connect to port 7 of the same computer that the program is running on - which will fail.

You need to specify the IP address of the WiFi shield as the first parameter to `getaddrinfo()` (currently `NULL`):

> `int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res);`
>
> `node` specifies either a numerical network address (for IPv4, numbers-and-dots notation as supported by `inet_aton(3)`; for IPv6, hexadecimal  string format  as  supported  by  `inet_pton(3)`),  or  a network hostname, whose network addresses are looked up and resolved.  If `hints.ai_flags` contains the `AI_NUMERICHOST` flag, then node must be a numerical network address.  The  `AI_NUMERICHOST`  flag suppresses any potentially lengthy network host address lookups.
>
> If the `AI_PASSIVE` flag is not set in `hints.ai_flags`, then the returned socket addresses will be suitable for use with `connect(2)`, `sendto(2)`, or `sendmsg(2)`.  **If node is `NULL`, then the network address  will  be  set  to  the  loopback  interface address**  (`INADDR_LOOPBACK`  for  IPv4 addresses, `IN6ADDR_LOOPBACK_INIT` for IPv6 address); this is used by applications that intend to communicate with peers running on the same host.
>
> -- Extract from the `getaddrinfo(3)` manual page


body:
Disabling a push button after being under pressure for some time?

I need to disable a button where the user is pressing for a time it is disabled.

Code:

    int ledPin = 13;

    int inPin = 7;

    int val = 0;

    void setup() {

    pinMode(ledPin, OUTPUT);

    pinMode(inPin, INPUT);

    }

    void loop(){

    val = digitalRead(inPin);

    if (val == HIGH) {

    digitalWrite(ledPin, LOW);

    } else {

    digitalWrite(ledPin, HIGH);

    }

    }

Answers: 2

body:
    int ledPin = 13;
    int inPin = 7;
    int val = 0;
    int oldVal = 0;

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(inPin, INPUT);
    }

    void loop(){
      val = digitalRead(inPin);
      if (val == HIGH && oldVal == LOW) {
        digitalWrite(ledPin, LOW);
        oldVal = HIGH;
      } else if (val == LOW && oldVal == HIGH) {
        digitalWrite(ledPin, HIGH);
        oldVal = LOW;
      }
    }

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

I think the question is about activating something on a switch push, but only for x seconds. For example, you press a button to sound an alarm, but it stops after 5 seconds.

---

This should do it:

    const byte ledPin = 13;
    const byte inPin = 7;

    const unsigned long MAX_PUSH_TIME = 2000;  // ms
    const unsigned long DEBOUNCE_TIME = 20;    // ms
    unsigned long whenPushed;

    bool switchState;
    bool awaitingRelease;

    void setup()
      {
      pinMode(ledPin, OUTPUT);
      pinMode(inPin, INPUT_PULLUP);
      }  // end of setup

    void switchPushed ()
      {
      // we want them to let go now, ignore it
      if (awaitingRelease)
        return;

      // is LED already on?
      if (digitalRead (ledPin) == HIGH)
        {
        // held for too long? turn off LED, remember it
        if (millis () - whenPushed >= MAX_PUSH_TIME)
          {
          awaitingRelease = true;
          digitalWrite(ledPin, LOW);
          }
        return;  // all done
        }

      // turn LED on, remember when
      digitalWrite(ledPin, HIGH);
      whenPushed = millis ();
      delay (DEBOUNCE_TIME);
      }  // end of switchPushed

    void switchReleased ()
      {
      digitalWrite(ledPin, LOW);
      awaitingRelease = false;  // they released it!
      delay (DEBOUNCE_TIME);
      }  // end of switchReleased

    void loop()
      {
      switchState = digitalRead(inPin);
      if (switchState == LOW)
        switchPushed ();
      else
        switchReleased ();
      }  // end of loop

---

**Note:** I used an input pull-up resistor on the switch to avoid having to use extra components. Thus the switch is wired between pin 7 and **ground**. That is why the test for the switch being pressed is for it to be LOW.

---

## Reference

* [Switches tutorial](http://www.gammon.com.au/switches)


body:
I installed the Arduino IDE 1.6.4, and used the "boards manager" to install the package for Arduino Due.

I am using c++11 in my project so i need to add the `compiler.cpp.extra_flags=-std=gnu++11` like i did in the `/Applications/Arduino.app/Contents/Java/hardware/arduino/platform.txt` file (i am on MacOSX).
It seems that arduino is ignoring that file and using a configuration coming from somewhere else.

Where is the downloaded package installed? Can it be configured?

title: arduino boards manager configuration

Answers: 1

body: Ok, as @IgnacioVazquez-Abrams suggested: the configuration files for the plugins can be found in the Arduino ide preferences directory. Click the menu Arduino->Preferences (under macosx) at the bottom of the window there is the clickable path of the `preferences.txt` file. In the same folder as that file you will find a `packages` folder, where the plugins are downloaded.


body:
I tried to flash my ATmega328P-PU not over the Arduino but over a self-made programming board and an USBasp. The problem is, I made the board a while ago and didn't mark which direction the 10-pin connector has to go.

My question is, can I fry the ATmega if I connect the 10-pin connector the wrong way around? Also, can this harm the USBasp in any way?

Connecting it the wrong way around would give me the following connections:

    USBasp  ---  ATmega

    MOSI    -|
    NC      -|-  GND
    RST     -|
    SCK     -|

    MISO    ---  Vcc
    Vcc     ---  MISO

             |-  MOSI
    GND     -|-  NC
             |-  RST
             |-  SCK

title: ISP - Wrong direction frying ATmega

Answers: 1

body:
No, connecting it backwards shouldn't do any damage, it just won't work.  The clue is in these two connections:

    NC      -|-  GND
    GND     -|-  NC

With it backwards the ground connection doesn't go anywhere.  Without that ground connection there's no circuit.  With no circuit, no current flows.

The only possible danger is to the protection diodes in the IO pins when you try and operate the programmer.  The lack of a ground connection could cause some current to flow the wrong way through the circuit (in through the ATMega's MISO pin and out through the MCU's Vcc pin) through the ESD protection diode.  That could cause damage to that diode and maybe the rest of the MISO pin's logic, but it's not that likely since the currents involved would be somewhat limited by the route the power then takes through the MISO pin of the programmer.


body:
Recently I've bought an Arduino Mega 2560 R3 and a Shield Model Wireless SD R3 from http://www.amazon.de/Arduino-A000065-Netzwerkkarte-Wireless-SD-Shield/dp/B00L1FO860. I try to run the example from https://www.arduino.cc/en/Tutorial/ConnectWithWPA

Before running the sketch I turn the DIP switch to the position USB.
It seems like the WIfi Shield is correct connected to the Arduino since the LEDs TX and RX are blinking during upload the Sketch.

Sadly as output I got only:
    WiFi shield not present

Currently I'm not sure if the hardware itself provide Wifi functionality. Does somebody know if it should work with this hardware?

title: Arduino Mega 2560 R3 with Shield Model Wireless SD R3 not working

Answers: 1

body:
You see that double row of 10 pin headers?  That's an XBee connector.

https://www.sparkfun.com/pages/xbee_guide

You use it to connect your XBee module of choice (there's a few to choose from) to communicate wirelessly between Arduinos using the special XBee system.

Note that XBee is not WiFi, it's Wireless.  The two are very different things (Wireless refers to any wire-free communication system, WiFi is one specific protocol on one specific set of frequencies using a specific set of encodings, etc).  XBee *cannot* talk WiFi in the same way that I can't talk Chinese.

For WiFi you need a WiFi shield.

https://www.arduino.cc/en/Main/ArduinoWiFiShield


body:
I would like to detect signals in nanosecond scale. For that, an ADC with at least 500 MSPS is required.

My question is if its possible to use an external ADC with 500 MSPS with a 16MHz Arduino Mega? If not, is there any additional hardware like FIFO buffer to overcome this problem?

Please help, thanks!

title: Hi-speed external ADC

Answers: 2

body:
No, it's certainly not possible to directly sample at 500Msps on an Arduino using an external ADC.  Simple maths:

* The Arduino can perform 16 million instructions (best case) per second
* The ADC performs 500 million samples per second.
* 500 / 16 = 31.25

Therefore the ADC would be generating 31.25 samples for every clock of the Arduino, so unless you can build in a time compressor (maybe with a flux capacitor too), it just ain't gonna do it.

So you will have to think creatively instead.  A possible solution would involve:

* A high speed *flash* or *pipelined* ADC, ideally with parallel output.
* A large chunk of memory to act as a buffer.
* A high speed clock source to set the timing (500MHz?).
* Glue logic and counters to take one sample, store it in the buffer, and increment the buffer address.
* More glue logic and interfacing to allow the Arduino access to the buffer memory and to control the operation of the sampling system.

This, to me, sounds like a job for an FPGA, and at 500MHz, quite a fast FPGA.  You should investigate some of the FPGA development boards from Xilinx and Altera.

body:
From the Arduino reference on AnalogRead:
"It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate is about 10,000 times a second."

500msps is an awfully high rate - my first instinct is, perhaps you need to revisit what you are after, and why.

There are indeed chips that will do this for you. It is still not possible with an Arduino, since the Arduino can't even receive the data this fast, let alone process it. Assuming 8-bit sampling, this would generate a stream of data at 4gigabits/second - I doubt any disk drive could write that fast (SATA3 is 4.8gbit/sec, which is 20% more, I suspect that the 20% would be eaten up by overhead - you can't just send raw data to a drive, you also have to tell it where to put it. That just accounts for getting the data to the drive circuitry, not actually storing it).

Perhaps what you're looking for is an oscilloscope. An oscilloscope takes high speed readings and displays them. Oscilloscopes are often used for testing circuits (e.g. looking at what an Arduino puts out/reads in when it's being programmed). Looking on National Instruments' websites, their cheapest one I could find that does > 500msps is worth about US$8,000 (ballpark). You will still not be able to store this to disk, or process it in any meaningful way, in realtime - a board like this will typically capture data (based on a trigger, sample until the memory is full, then slowly move the data to the PC to process.


body:
I've got a MAX7456 chip and I am using [this (this is the unmodified one)][1] library with it.
There's a sketch inside the examples folder (Max7456WriteTable) that I need to get to work to update the character table.

I modified three lines and then I got really stuck as I do not know how to continue. [This][2] is the modified one.

    In file included from Max7456Write.ino:2:0:
    /tmp/build4608284042510222737.tmp/sketch/Max7456WriteTable.h:29:69153: warning: narrowing conversion of '243' from 'int' to 'const char' inside { } is ill-formed in C++11 [-Wnarrowing]

This happens for every item in the array. But that is not the only problem. (I'll skip a few hundred lines)

    /tmp/build8855411239666100148.tmp/sketch/Max7456Write.cpp.o: In function `setup':
    /home/t/Max7456Write.ino:13: undefined reference to `Max7456::Max7456(unsigned char)'
    /home/t/Max7456Write.ino:19: undefined reference to `Max7456::activateOSD(bool)'
    /home/t/Max7456Write.ino:44: undefined reference to `Max7456::getCARACFromProgMem(char const*, unsigned char, unsigned char*)'
    /home/t/Max7456Write.ino:46: undefined reference to `Max7456::sendCharacter(unsigned char const*, unsigned char, unsigned char)'
    collect2: error: ld returned 1 exit status
    Error compiling.

It takes a huge amount of time for it to abort the compilation.

  [1]: https://www.dropbox.com/s/3cp4am1f271odcm/max7456.tar?dl=1
  [2]: https://www.dropbox.com/s/sljvyngc27zver4/max7456_new.tar?dl=1

title: Updating a sketch to work with IDE 1.6.6

Answers: 1

body:
If I change `prog_uchar` to `unsigned char` in both max7456.h and max7456.cpp the hello world example sketch compiles.

In Max7456WriteTable change

 Max7456::getCARACFromProgMem(i,currentChar); //Because the table is too big for ram memory

 osd->sendCharacter(currentChar,i); //We send currentChar at address i.

to

 Max7456::getCARACFromProgMem(tableOfAllCharacters, i,currentChar); //Because the table is too big for ram memory

 osd->sendCharacter(currentChar,i, 0); //We send currentChar at address i.

`0` is probably the wrong value, but at least it compiles.


body:
I asked a previous question about esp8266 that made a lot of things clear for me that esp8266 is very powerful and can be independently used as the webserver now, I have used the following library(https://github.com/sandeepmistry/esp8266-Arduino) to achieve this thing as I found a tutorial(https://learn.adafruit.com/esp8266-temperature-slash-humidity-webserver/code) to help me out.
Now this is the code that was in the tutorial and is working fine

    /* DHTServer - ESP8266 Webserver with a DHT sensor as an input

       Based on ESP8266Webserver, DHTexample, and BlinkWithoutDelay (thank you)

       Version 1.0  5/3/2014  Version 1.0   Mike Barela for Adafruit Industries
    */
    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <DHT.h>
    #define DHTTYPE DHT22
    #define DHTPIN  2

    const char* ssid     = "--MYRouterID";
    const char* password = "--MYRouterPassword";

    ESP8266WebServer server(80);

    // Initialize DHT sensor
    // NOTE: For working with a faster than ATmega328p 16 MHz Arduino chip, like an ESP8266,
    // you need to increase the threshold for cycle counts considered a 1 or 0.
    // You can do this by passing a 3rd parameter for this threshold.  It's a bit
    // of fiddling to find the right value, but in general the faster the CPU the
    // higher the value.  The default for a 16mhz AVR is a value of 6.  For an
    // Arduino Due that runs at 84mhz a value of 30 works.
    // This is for the ESP8266 processor on ESP-01
    DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266

    float humidity, temp_f;  // Values read from sensor
    String webString="";     // String to display
    // Generally, you should use "unsigned long" for variables that hold time
    unsigned long previousMillis = 0;        // will store last temp was read
    const long interval = 2000;              // interval at which to read sensor

    void handle_root() {
      server.send(200, "text/plain", "Hello from the weather esp8266, read from /temp or /humidity");
      delay(100);
    }

    void setup(void)
    {
      // You can open the Arduino IDE Serial Monitor window to see what the code is doing
      Serial.begin(115200);  // Serial connection from ESP-01 via 3.3v console cable
      dht.begin();           // initialize temperature sensor

      // Connect to WiFi network
      WiFi.begin(ssid, password);
      Serial.print("\n\r \n\rWorking to connect");

      // Wait for connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("DHT Weather Reading Server");
      Serial.print("Connected to ");
      Serial.println(ssid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());

      server.on("/", handle_root);

      server.on("/temp", [](){  // if you add this subdirectory to your webserver call, you get text below :)
        gettemperature();       // read sensor
        webString="Temperature: "+String((int)temp_f)+" F";   // Arduino has a hard time with float to string
        server.send(200, "text/plain", webString);            // send to someones browser when asked
      });

      server.on("/humidity", [](){  // if you add this subdirectory to your webserver call, you get text below :)
        gettemperature();           // read sensor
        webString="Humidity: "+String((int)humidity)+"%";
        server.send(200, "text/plain", webString);               // send to someones browser when asked
      });

      server.begin();
      Serial.println("HTTP server started");
    }

    void loop(void)
    {
      server.handleClient();
    }

    void gettemperature() {
      // Wait at least 2 seconds seconds between measurements.
      // if the difference between the current time and last time you read
      // the sensor is bigger than the interval you set, read the sensor
      // Works better than delay for things happening elsewhere also
      unsigned long currentMillis = millis();

      if(currentMillis - previousMillis >= interval) {
        // save the last time you read the sensor
        previousMillis = currentMillis;

        // Reading temperature for humidity takes about 250 milliseconds!
        // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
        humidity = dht.readHumidity();          // Read humidity (percent)
        temp_f = dht.readTemperature(true);     // Read temperature as Fahrenheit
        // Check if any reads failed and exit early (to try again).
        if (isnan(humidity) || isnan(temp_f)) {
          Serial.println("Failed to read from DHT sensor!");
          return;
        }
      }
    }
Now this is my modification of code(of esp8266) as I am willing to communicate it over serial with my arduino which will further send data to the esp8266 when it requests using the attached sensor to the batteries(I am making a solar related project).

Its only a basic code but the problem is that it compiles and runs ok but I am only able to access the web page once and that is also only the root. The other links do not open up or when I try to even reload the web page root it stuck and browser says error timed out

Here is code

    void handle_root() {
      //server.send(208, "text/plain", "
Hello from the weather esp8266, read from /temp or /humidity
");
      String sendx = "
This Page Shows the Basic Info
";
    //  Serial.write("MP");
    //  delay(20);

    //  while(Serial.available()>0)
     // {
      //  rec = Serial.readString();
      //}
      rec = "TESt";
      if(rec[0] == AllMain)
      {
         sendx += "
Running on Main Power Now
";
         sendx += "
" + rec + "
";
      }
      else if(rec[0] == HouseMain)
      {
        sendx += "
Home on Main Power
";
        sendx += "
" + rec + "
";
        sendx += "Turn on Hospital Main";
      }
      else if(rec[0]==HospitalMain)
      {
        sendx += "
Hospital on Main Power
";
        sendx += "
" + rec + "
";
        sendx += "Turn on House Main";
      }
      else
      {
        sendx += "
" + rec + "
";
        sendx += "
Turn on House Main
";
        sendx += "
Turn on Hospital Main
";
      }
    // sendx +=  "Temp";

        server.send(200,"text/html",sendx);
      delay(100);
    }
    void thm()
    {
     // if(Serial.available())
      {
    //    Serial.println("thm");
        String sendx = "signal sent... go back to previous page to verify";
      //  sendx += "Go Back";
        server.send(200,"text/html",sendx);
        delay(100);
      }
    }
    void thos()
    {
     // if(Serial.available())
      {
    //    Serial.println("thos");
        String sendx = "signal sent... go back to previous page to verify";
     //   sendx += "Go Back";
        server.send(200,"text/html",sendx);
        delay(100);
      }
    }
    void setup(void)
    {
      // You can open the Arduino IDE Serial Monitor window to see what the code is doing
      Serial.begin(115200);  // Serial connection from ESP-01 via 3.3v console cable

      // Connect to WiFi network
      WiFi.begin(ssid, password);
      if(debug)
        Serial.print("\n\r \n\rWorking to connect");

      // Wait for connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        if(debug)
          Serial.print(".");
      }
      if(debug)
      {
        Serial.println("");
        Serial.println("DHT Weather Reading Server");
        Serial.print("Connected to ");
        Serial.println(ssid);
        Serial.print("IP address: ");
        Serial.println(WiFi.localIP());
      }
      if (mdns.begin("esp8266", WiFi.localIP())) {
        Serial.println("MDNS responder started");
      }

      server.on("/", handle_root);

     server.on("/thm", thm);
     /*server.on("/thm", [](){  ===== I have tried this inline as well no luck ====
       Serial.println("thos");
        String sendx = "signal sent... go back to previous page to verify";
        server.sendContent(sendx);
     });*/
      server.on("/thos",thos);

      server.begin();
      if(debug)
        Serial.println("HTTP server started");
    }

    void loop(void)
    {

      server.handleClient();
    }

Now please I would also appreciate your help for the commented portion of my code dealing with serial communication in function `handle_root` but it would be more than enough if you can point out my misconception or error or point me in right direction

title: ESP8266 problem as Web server

Answers: 0


body:
-edit-
This is a simplified recreation of personal learning project I have ongoing.  My issue is in accessing data in flash, the path to which includes multiple layers of indirection.  When the data was in RAM I found accessing it easy and all worked as expected.

In flash I have created a struct mylist, aa in the example, containing a pointer to an char* array (item_list[ ])(in flash) pointing to char[ ] (in flash).

Problem: (refer to example) Given a pointer to struct aa (pml) and an index into item_list[] (ndx), how to correctly retrieve the string from flash.  My example illustrates the only method I can find that works. It seems kludgy at best, in particular needing to twice read pointers from flash as well as calculating the array item offset.  Have I missed a proper cast or perhaps become confused about 32 vs 16 bit pointers? Or, as strange as it seems, is this the correct and/or best approach?

All help and constructive criticism will be appreciated.

Code:

<!-- language: c -->

    #include "Arduino.h"
    #include <avr/pgmspace.h>

    const char x[] PROGMEM = {"Item x"};
    const char y[] PROGMEM = {"Item y"};
    const char* const item_list[] PROGMEM = {x, y};

    struct mylist {
      uint8_t nitems;
      const char** const list;
    };
    const mylist aa PROGMEM = {2,(const char** const)item_list};

    const mylist* pml = &aa;

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

      char cbuf[11] = {"__________"};

      // two line with declared intermediate pointer
      uint8_t ndx = 0;
      const char* pitem = (const char*)pgm_read_ptr_near(&pml->list) + (ndx * sizeof(const char*));
      strcpy_P(cbuf, (const char*)pgm_read_ptr_near(pitem));
      Serial.print("item[0]: /");
      Serial.print(cbuf);
      Serial.println("/");

      // one line without declared intermediate pointer
      ndx++;
      strcpy_P(cbuf, (const char*)pgm_read_ptr_near(pgm_read_ptr_near(&pml->list)
                                                    + (ndx * sizeof(const char*))));
      Serial.print("item[1]: /");
      Serial.print(cbuf);
      Serial.println("/");
    }

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

    }

Output:

    item[0]: /Item x/
    item[1]: /Item y/

-edit-

After many more hours trying many more variations, I feel the approach shown in the following example is workable for me. I have chosen to keep the extra level of indirection to maintain all the flash data for a particular Field in one struct ‘package’. @NickGammon and his excellent examples greatly helped my understanding and comfort level with pointers in and to flash.

The listing is meant to give context to my point in question and is summarized in the method _copyitem( ) (hope the underscore is ok):

    void Field::_copyitem(uint8_t ndx){
      PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
      PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
      strlcpy_P(_value, pitem, getLength());
    }

This listing recreates a very small subset of the overall codebase, but the one part that has stopped my progress.

    #include "Arduino.h"
    #include <avr/pgmspace.h>

    struct FieldDefinition {
      uint8_t nitems;
      const char** list;
      uint8_t row;
      uint8_t column;
      uint8_t length;
      // etc, etc
    };

    class Field {
    public:
      Field(const FieldDefinition*  /* other parameters */);
      ~Field();  // -edit-
      char * selectItem(uint8_t);
      uint8_t getLength();
      char * selectItem(uint8_t);
      uint8_t getLength();
    private:
      const FieldDefinition * _fp;
      char * _value;
      uint8_t _ndx;
      void _copyitem(uint8_t);
    };

    Field::Field(const FieldDefinition* fp ) : _fp(fp) {
      _ndx = 0;
      char * _value = new char[getLength()];
     _copyitem(_ndx);
    };
    Field::~Field(){  // -edit-
      delete _value;
    };
    char * Field::selectItem(uint8_t ndx){
      _ndx = ndx;
      _copyitem(_ndx);
      // display item
      // do more here . . .
     return _value;
    }
    uint8_t Field::getLength(){
      return pgm_read_byte(&_fp->length);
    }
    void Field::_copyitem(uint8_t ndx){
      PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
      PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
      strlcpy_P(_value, pitem, getLength());
    }

    // Setup flash data
    // selection list
    const char f1_0[] PROGMEM = {"Item 0"};
    const char f1_1[] PROGMEM = {"Item 1"};
    const char f1_2[] PROGMEM = {"Item 2"};
    const char* const f1_list[] PROGMEM = {f1_0, f1_1, f1_2};
    // create in-flash struct
    const FieldDefinition f1 PROGMEM = {4,(const char**)f1_list,1,1,10};
    // global instance and pointer to Field
    Field * s1f1 = new Field(&f1);

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

      Serial.println();
      Serial.print("Field Length: ");
      Serial.println(s1f1->getLength());
      Serial.println();
      for (uint8_t i = 0 ; i < 3; i++) {
        Serial.print("Selection at index ");
        Serial.print(i); Serial.print(" : ");
        Serial.println(s1f1->selectItem(i));
      }
    }

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

    }

Output

    Field Length: 10

    Selection at index 0 : Item 0
    Selection at index 1 : Item 1
    Selection at index 2 : Item 2

I could very wrong (as previously demonstrated) so comments please.

-edit-

Point taken and completely understood.  Destructor added for completeness.  In my actual application, multiple fields are constructed by a screen class when a screen is displayed, user interaction accepted, configuration data stored in EEPROM (my next endeavor), then destroyed on screen exit. Selecting from a list is one method available to populate the field value. The whole interface consists of multiple fields, for multiple screens, driven by an underlying state engine, stepped during each ‘loop’ to minimize impact. It functions as expected in an Xcode simulation, and has been a wonderful learning experience moving it to Arduino.  I thought all this was non sequitur to my question and regret any confusion I may have caused.

To restate my issue: how to get from

    // ram based
    strcpy(value, _fp->list[ndx]);

to

    // flash based
    PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
    PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
    strcpy_P(value, pitem);

using best/correct form with multiple layers of indirection as posted. Is it possible I have missed a proper cast or other mechanism that would allow the compiler to handle the ‘pointer magic’? It appears I have not. @NickGammon I greatly appreciate your input.

title: Better method for PROGMEM data access with multiple indirection?

Answers: 1

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

    const char x[] PROGMEM = {"Item x"};
    const char y[] PROGMEM = {"Item y"};
    const char* const item_list[] PROGMEM = {x, y};

    struct mylist {
      uint8_t nitems;
      const char** const list;
    };
    const mylist aa PROGMEM = {2,(const char** const)item_list};

It seems to me this is way too wordy for what appears to be trying to store a list of a couple of strings.

---

First:

    const char* const item_list[] PROGMEM = {x, y};

You have a array of pointers to strings. OK.

---

Now:

    struct mylist {
      uint8_t nitems;
      const char** const list;
    };
    const mylist aa PROGMEM = {2,(const char** const)item_list};

Now you have a *list* of an *array*? This is where I am confused.

---

Compare to an adaptation of the code on [Putting constant data into program memory (PROGMEM)](http://www.gammon.com.au/progmem):

    const int NUMBER_OF_ELEMENTS = 2;

    const char Message0000 [] PROGMEM = "Item X";
    const char Message0001 [] PROGMEM = "Item Y";

    const char * const messages[NUMBER_OF_ELEMENTS] PROGMEM =
       {
       Message0000,
       Message0001,
       };

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

      for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
        {
        char * ptr = (char *) pgm_read_word (&messages [i]);
        char buffer [80]; // must be large enough!
        strcpy_P (buffer, ptr);
        Serial.println (buffer);
        }   // end of for loop

      }  // end of setup

    void loop () { }

---

## Edited to comment on new code

You have a major problem here:

    Field::Field(const FieldDefinition* fp ) : _fp(fp) {
      _ndx = 0;
      char * _value = new char[getLength()];
     _copyitem(_ndx);
    };
    char * Field::selectItem(uint8_t ndx){
      _ndx = ndx;
      _copyitem(_ndx);
      // display item
      // do more here . . .
     return _value;
    }
    uint8_t Field::getLength(){
      return pgm_read_byte(&_fp->length);
    }
    void Field::_copyitem(uint8_t ndx){
      PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
      PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
      strlcpy_P(_value, pitem, getLength());
    }

What I gather you are doing here is, to get the string for an item (for printing) doing a `new` (which allocates memory), copying from PROGMEM into that memory, displaying that item, and then ignoring the allocated memory. Well, you can't do that. You will run out of RAM very quickly.

The code doesn't even have the word `delete` in it. Every `new` should have a corresponding `delete`. It's a fundamental principle.

It looks too complex still. Make a function that just displays the item (menu or whatever it is) without actually making a copy of it. Certainly don't allocate memory and not free it.


body:
I installed LininoIO (OS dated 02 06 2015).

Everything seems to work fine - but nothing works as expected.

I have a running Linux - but when I try to use GPIO, as described on Lilino.org -[GPIO on lininoIO][1], I run into the first problems.

D13 doesn't exist (this should be the little red LED on board of the Yún).

Next I tested reading the analog inputs.

I can for example use `cat /sys/bus/iio/devices/iio:device0/in_voltage_A0_raw`. There are no errors, but I always get the value `0`.

Checking with `/etc/linino/test_avrdude.sh` shows:

    Testing AVRDUDE on ATMEL 32U4 ...

    avrdude: Version 6.1-20140519, compiled on Jun  2 2015 at 12:34:59
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "/etc/avrdude.conf"
             User configuration file is "/root/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : unknown
             Using Programmer              : linuxgpio
    Can't export GPIO 11, already exported/busy?: Device or resource busy
    avrdude done.  Thank you.

Maybe this is "by design" or another sign of an error.

By the way - when I start a serial console I get the message:

    avr-uart: switched to uart mode: mcuio

Further in kernel log I found:

    [   42.480000] fuse init (API version 7.18)
    [   42.620000] spi_tty_plain spi1.0: spi_tty_probe
    [   45.380000] No need to change console settings
    [   49.550000] mcuio-hc 0:0.0: unexpected reply
    [   49.600000] gpiochip_add: registered GPIOs 100 to 139 on device: generic
    [   49.630000] mcuio adc is 0:1:1
    [   49.750000] mcuio-adc 0:1.1: 6 input channels detected
    [   49.910000] mcuio-hc 0:0.0: unexpected reply
    [   49.970000] mcuio pwm is 0:1:2
    [   49.970000] mcuio-pwm 0:1.2: 6 pwm outputs detected
    [   55.790000] busybox: sending ioctl 5310 to a partition!
    [   55.800000] busybox: sending ioctl 5310 to a partition!
    [   55.820000] busybox: sending ioctl 5310 to a partition!
    [   55.830000] busybox: sending ioctl 5310 to a partition!
    [   56.290000] EXT4-fs (sda2): couldn't mount as ext3 due to feature incompatibilities
    [   56.310000] EXT4-fs (sda2): couldn't mount as ext2 due to feature incompatibilities
    [   56.360000] EXT4-fs (sda2): mounted filesystem with ordered data mode. Opts: (null)
    [   58.520000] cfg80211: Calling CRDA for country: AT

It seems as if there are problems with `mcuio-hc`.

Last thing - when I ran `run-avrdude /etc/linino/bathos-one.hex`
I get an error when comparing the written data (I found information that this can be ignored).

How can I fix this / find out what to fix / what's going wrong?

  [1]: http://wiki.linino.org/doku.php?id=wiki:lininoio_sysfs

title: LininoIO running "partially"

Answers: 3

body:
finally I got it (somehow) working.
After a reset and another run of run-avrdude /etc/linino/bathos-yun.hex (the first was a mistake by copy and past - not bathos-one I already ran bathos-yun before) and a reboot again I was able to read analog IO.

But still the digitals were missing.
Than I found the command gpioexport an ran it.
After that the correct entries (D13, D14...) were present in sys/class...

But an echo out > D13/direction resulted in a timeout error message.
Again reboot - again the Dxxx entries were gone.
Another gpioexport made them appear again.

And this time not timeouts - instead I could turn on / of D13 (for test).

I guess all I have to do to make the things better is include gpioexport in "startup code" so that it runs after a reboot.

body:
Have a look at the schematics of the YUN https://www.arduino.cc/en/uploads/Main/arduino-Yun-schematic.pdf

You will notice that most of the GPIO pins on the Atheros is not available to you. You only have access to the GPIO pins of the atmega.

body:
LininoIO has a part which runs on the microcontroller and make the Atheros enable to use the mcu pinout as linux gpios. So you are right, you need to flash the bathos to the mcu.

In general to enable/disable lininoIO run:

    > lininoio start
    > lininoio stop

those commands do everything for you.
have also a look [here][2]

Anyway your Linino version seems old, try to upgrade it: http://www.arduino.org/learning/tutorials/advanced-guides/how-to-upgrade-the-linino-distribution-for-arduino-yun-and-yun-mini

  [1]: http://www.arduino.org/learning/tutorials/advanced-guides/linino-gpio-configuration
  [2]: http://www.arduino.org/learning/tutorials/advanced-guides/how-to-pilot-gpio-on-lininoio-2


body:
I have a Gboard module (from [Itead][1]) configured to recieve data from Xbee sensors, and log data to a server DB on inet (via GPRS). This module is programmed with Arduino IDE.
I turn on the module (without any xbee sending, to check that the GPRS is working). The module works fine; The GPRS part sends some "control" packages to the DB to inet as expected. The problem appears after 1'5 hours because module is still on but the GPRS doesn't seem to be working (doesn't send any more packages to inet).
Excuse me for my messy code, I´m newbie! (a lot of copy/pastes from others!). Thank you in advance for your tipps and recomendations!.
Note: I use a power supply 12v and 2Amp.

Code:

    #include <elapsedMillis.h>///para controles
    #include <SoftwareSerial.h>
    #include <Streaming.h> ///para xbee
    #include <XBee.h>      ///para xbee
    int xbeeRecibido;
    char urlArreglo[100];
    uint8_t slCmd[] = {'S', 'L'};
    uint8_t dbCmd[] = {'D', 'B'};
    char adr_part[8];
    char rssiValor_part[8];
    String adr = "";
    String rssiValor = "";
    AtCommandRequest atRequest = AtCommandRequest();
    AtCommandResponse atResponse = AtCommandResponse();
    elapsedMillis timeElapsed = 0;
    unsigned long interval = 180000 ;////en milisegundos  cada 3 min.
    String direccionRed;
    int bateria;
    String valorRssi;
    int actividadPir;
    String datosHttp; ///concatenacion de datos para enviar por HTTP
    int8_t answer;
    char data[512];
    int data_size;
    char aux_str[100];
    char aux;
    int x = 0;
    XBee xbee = XBee();                //XBee object
    Rx16Response rx = Rx16Response();
    SoftwareSerial mySerial(2, 3); // RX, TX (ahora puesto en TX, RX)
    int b01;
    int b02;
    int b03;
    int b04; //source network adress 64Bit
    int b05; //source network adress 64Bit
    int b06; //source network adress 64Bit
    int b07; //source network adress 64Bit
    int b08; //source network adress 64Bit
    int b09; //source network adress 64Bit
    int b10; //source network adress 64Bit
    int b11; //source network adress 64Bit
    int b12; //source network adress 16Bit
    int b13; //source network adress 16Bit
    int b14;
    int b15; //pir digital
    int b16; //bateria
    int b17; //checksum
    char response[100];
    unsigned long previous;

    void setup() {
      pinMode(6, OUTPUT);///para encender SIM900 ...en pin6 HIGH de arduino GBOARD
      digitalWrite(6, HIGH);///para encender SIM900 ...en pin6 HIGH de arduino GBOARD
      mySerial.begin(9600);
      Serial.begin(9600);
      ///////GPRS////////
      power_on();
      delay(3000);
      sendATcommand("AT+ipr=9600", "OK", 2000);///////MIO PARA BAUDERATE A 9600 (por defecto 0=auto..¿se apaga?)
      // sets the PIN code
      sendATcommand("AT+CPIN=****", "OK", 2000);
      delay(3000);
      while (sendATcommand2("AT+CREG?", "+CREG: 0,1", "+CREG: 0,5", 2000) == 0);
      sendATcommand("AT+SAPBR=3,1,\"Contype\",\"GPRS\"", "OK", 2000);
      sendATcommand("AT+SAPBR=3,1,\"APN\",\"gprs.lebaramobile.es\"", "OK", 2000);
      sendATcommand("AT+SAPBR=3,1,\"USER\",\"\"", "OK", 2000);
      sendATcommand("AT+SAPBR=3,1,\"PWD\",\"\"", "OK", 2000);
      while (sendATcommand("AT+SAPBR=1,1", "OK", 20000) == 0)
      {
        delay(5000);
      }
      ////FIN GPRS////
      ////PRIMER AUTOCONTROL!
      lanzarHttpAutoControl();
      delay(15000);
    }

    void loop() {
      // PARA AUTOCONTROL!
      if (timeElapsed > interval)
      {
        lanzarHttpAutoControl();
        timeElapsed = 0;    // reset the counter to 0 so the counting starts over...
      }
      if (Serial.available() == 18) { //make sure the frame is all there
        if (Serial.read() == 0x7E) {
          b01 = Serial.read();
          b02 = Serial.read();
          b03 = Serial.read();
          b04 = Serial.read(); //source network adress 64Bit
          b05 = Serial.read(); //source network adress 64Bit
          b06 = Serial.read(); //source network adress 64Bit
          b07 = Serial.read(); //source network adress 64Bit
          b08 = Serial.read(); //source network adress 64Bit
          b09 = Serial.read(); //source network adress 64Bit
          b10 = Serial.read(); //source network adress 64Bit
          b11 = Serial.read(); //source network adress 64Bit
          b12 = Serial.read(); //source network adress 16Bit
          b13 = Serial.read(); //source network adress 16Bit
          b14 = Serial.read();
          b15 = Serial.read(); //pir digital
          b16 = Serial.read(); //bateria
          b17 = Serial.read();  //checksum
          direccionRed =  String(b04, HEX);
          direccionRed +=  String(b05, HEX);
          direccionRed +=  String(b06, HEX);
          direccionRed +=  String(b07, HEX);
          direccionRed +=  String(b08, HEX);
          direccionRed +=  String(b09, HEX);
          direccionRed +=  String(b10, HEX);
          direccionRed +=  String(b11, HEX);
          actividadPir = b15;
          bateria = int(b16);
          xbeeRecibido = 1;
        } //fin if 0x7E
      }///fin recorrer bytes
      Serial.flush();
      Serial.end();
      Serial.begin(9600);///paro el serial para evitar solapaciones, y hacer esperar a los sensores (al no recibir resp. del gateway)
      if (xbeeRecibido == 1) {///si se ha recibido info de xbee sensor
        colectorDatos();
        xbeeRecibido = 0;
      }
    }//fin loop

    ///FUNCION PARA RSSI XBEE///
    void rss() {  ///PARA RSSI
      /* returns received signal strength value for the last RF data packet */
      union {
        byte B;
        char C;
      } atCmd[3];
      AtCommandRequest atCmdReq;
      AtCommandResponse atResp;
      byte respLen, *resp, dBm;
      strcpy(&atCmd[0].C, "DB");
      atCmdReq = AtCommandRequest(&atCmd[0].B);
      atResp = AtCommandResponse();
      xbee.send(atCmdReq);
      if (xbee.readPacket(5000)) {
        if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {
          xbee.getResponse().getAtCommandResponse(atResp);
          if (atResp.isOk()) {
            respLen = atResp.getValueLength();
            if (respLen == 1) {
              resp = atResp.getValue();
              dBm = resp[0];
              valorRssi = (String)dBm;

            }
            else {
            }
          }
          else {

          }
        }
        else {
        }
      }
      else {
      }
    }///fin rss()

    void power_on() {
      uint8_t answer = 0;
      // checks if the module is started
      answer = sendATcommand("AT", "OK", 2000);
      if (answer == 0)
      {
        // waits for an answer from the module
        while (answer == 0) {
          // Send AT every two seconds and wait for the answer
          answer = sendATcommand("AT", "OK", 2000);
        }
      }
    }

    int8_t sendATcommand(char* ATcommand, char* expected_answer1, unsigned int timeout) {
      uint8_t x = 0,  answer = 0;
      memset(response, 0, sizeof(response));///a cero el array ///15-08-2015
      memset(response, '\0', 100);    // Initialize the string
      delay(100);
      while ( mySerial.available() > 0) mySerial.read();   // Clean the input buffer
      mySerial.println(ATcommand);    // Send the AT command
      x = 0;
      previous = millis();
      do {
        if (mySerial.available() != 0) {
          response[x] = mySerial.read();
          x++;
          if (strstr(response, expected_answer1) != NULL)
          {
            answer = 1;
          }
        }
      }
      while ((answer == 0) && ((millis() - previous) < timeout));
      return answer;
    }

    int8_t sendATcommand2(char* ATcommand, char* expected_answer1,
                          char* expected_answer2, unsigned int timeout) {
      uint8_t x = 0,  answer = 0;
      memset(response, 0, sizeof(response));///a cero el array ///15-08-2015
      memset(response, '\0', 100);    // Initialize the string
      delay(100);
      while ( mySerial.available() > 0) mySerial.read();   // Clean the input buffer
      mySerial.println(ATcommand);    // Send the AT command
      x = 0;
      previous = millis();
      do {
        if (mySerial.available() != 0) {
          response[x] = mySerial.read();
          x++;
          // check if the desired answer 1 is in the response of the module
          if (strstr(response, expected_answer1) != NULL)
          {
            answer = 1;
          }
          // check if the desired answer 2 is in the response of the module
          if (strstr(response, expected_answer2) != NULL)
          {
            answer = 2;
          }
        }
        // Waits for the asnwer with time out
      } while ((answer == 0) && ((millis() - previous) < timeout));
      return answer;
    }

    void colectorDatos() {
      rss(); ////recupero rssi que se pone en variable valorRssi
      datosHttp = direccionRed + ";"; ///cualquier valor del array, todos deverian tener mismo valor (direccion64bits)
      datosHttp += bateria;
      datosHttp += ";";
      datosHttp += valorRssi;
      datosHttp += ";";
      datosHttp += actividadPir; //pir
      envio(datosHttp); ///envio por gprs
    }///fin colectorDatos

    void lanzarHttpAutoControl() {
      adr = "";
      // set command to SL to get low part of MAC address
      atRequest.setCommand(slCmd);
      while (!sendAtCommand()) {};
      for (int i = 0; i < atResponse.getValueLength(); i++) {
        mySerial.print(atResponse.getValue()[i], HEX);
        sprintf(adr_part, "%lX", (unsigned long)(atResponse.getValue()[i]));
        if (atResponse.getValue()[i] <= 0xF)
          adr += 0;
        adr += adr_part;
      }
      envio(adr); ///envio por gprs
    }

    ///envio GPRS...recibe String con datos (o control o sensor)
    void envio(String entrada) {
      Serial.end();///paro el serial para evitar solapaciones, y hacer esperar a los sensores (al no recibir resp. del gateway)
      memset(urlArreglo, 0, sizeof(urlArreglo));///a cero el array
      answer = sendATcommand("AT+HTTPINIT", "OK", 10000);
      if (answer == 1)
      {
        // Sets CID parameter
        answer = sendATcommand("AT+HTTPPARA=\"CID\",1", "OK", 5000);
        if (answer == 1)
        {
          //char urlArreglo[100];
          sprintf(urlArreglo,  "AT+HTTPPARA=\"URL\",\"www.pestmonitors.com/dream/prueba_gsm_get.php?datos=%s\"", entrada.c_str());
          answer = sendATcommand(urlArreglo, "OK", 5000);
          delay(5000);
          if (answer == 1)
          {
            answer = sendATcommand("AT+HTTPACTION=0", "+HTTPACTION:0,200", 10000);
          }
          else
          {
          }
          sendATcommand("AT+HTTPTERM", "OK", 5000);
          delay(5000);
        }
      }
      Serial.begin(9600);///paro el serial para evitar solapaciones, y hacer esperar a los sensores (al no recibir resp. del gateway)
    }

    // used here to sens AT command to the Xbee to get information such as the MAC address
    int sendAtCommand() {
      xbee.send(atRequest);
      if (xbee.readPacket(5000)) {
        if (xbee.getResponse().getApiId() == AT_COMMAND_RESPONSE) {
          xbee.getResponse().getAtCommandResponse(atResponse);
          if (atResponse.isOk()) {
            if (atResponse.getValueLength() > 0) {
              mySerial.println(atResponse.getValueLength(), DEC);
              for (int i = 0; i < atResponse.getValueLength(); i++) {
                mySerial.print(atResponse.getValue()[i], HEX);
              }
            }
            return 1;
          }
          else {
          }
        } else {
          mySerial.print(xbee.getResponse().getApiId(), HEX);
        }
      } else {
        if (xbee.getResponse().isError()) {
        }
        else {
        }
      }
      return 0;
    }

  [1]: http://imall.itead.cc/gboard.html

title: SIM 900 stop after 1'5 hours; what's wrong?

Answers: 0