body:
I tried connect my Arduino Uno R3 with module camera VC0706 following this instruction of Adafruit: https://learn.adafruit.com/ttl-serial-camera/using-the-camera.

    [VC0706] --- [Arduino]
      Vcc    ---   +5V
      GND    ---   GND
      Tx     ---   PIN 2
      Rx     ---   PIN 3

And upload this example source code: **Snapshot.ino** of **Adafruit_VC0706** library to my Arduino:

    // This is a basic snapshot sketch using the VC0706 library.
    // On start, the Arduino will find the camera and SD card and
    // then snap a photo, saving it to the SD card.
    // Public domain.

    // If using an Arduino Mega (1280, 2560 or ADK) in conjunction
    // with an SD card shield designed for conventional Arduinos
    // (Uno, etc.), it's necessary to edit the library file:
    //   libraries/SD/utility/Sd2Card.h
    // Look for this line:
    //   #define MEGA_SOFT_SPI 0
    // change to:
    //   #define MEGA_SOFT_SPI 1
    // This is NOT required if using an SD card breakout interfaced
    // directly to the SPI bus of the Mega (pins 50-53), or if using
    // a non-Mega, Uno-style board.

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

    // comment out this line if using Arduino V23 or earlier
    #include <SoftwareSerial.h>

    // uncomment this line if using Arduino V23 or earlier
    // #include <NewSoftSerial.h>

    // SD card chip select line varies among boards/shields:
    // Adafruit SD shields and modules: pin 10
    // Arduino Ethernet shield: pin 4
    // Sparkfun SD shield: pin 8
    // Arduino Mega w/hardware SPI: pin 53
    // Teensy 2.0: pin 0
    // Teensy++ 2.0: pin 20
    #define chipSelect 10

    // Pins for camera connection are configurable.
    // With the Arduino Uno, etc., most pins can be used, except for
    // those already in use for the SD card (10 through 13 plus
    // chipSelect, if other than pin 10).
    // With the Arduino Mega, the choices are a bit more involved:
    // 1) You can still use SoftwareSerial and connect the camera to
    //    a variety of pins...BUT the selection is limited.  The TX
    //    pin from the camera (RX on the Arduino, and the first
    //    argument to SoftwareSerial()) MUST be one of: 62, 63, 64,
    //    65, 66, 67, 68, or 69.  If MEGA_SOFT_SPI is set (and using
    //    a conventional Arduino SD shield), pins 50, 51, 52 and 53
    //    are also available.  The RX pin from the camera (TX on
    //    Arduino, second argument to SoftwareSerial()) can be any
    //    pin, again excepting those used by the SD card.
    // 2) You can use any of the additional three hardware UARTs on
    //    the Mega board (labeled as RX1/TX1, RX2/TX2, RX3,TX3),
    //    but must specifically use the two pins defined by that
    //    UART; they are not configurable.  In this case, pass the
    //    desired Serial object (rather than a SoftwareSerial
    //    object) to the VC0706 constructor.

    // Using SoftwareSerial (Arduino 1.0+) or NewSoftSerial (Arduino 0023 & prior):
    #if ARDUINO >= 100
    // On Uno: camera TX connected to pin 2, camera RX to pin 3:
    SoftwareSerial cameraconnection = SoftwareSerial(2, 3);
    // On Mega: camera TX connected to pin 69 (A15), camera RX to pin 3:
    //SoftwareSerial cameraconnection = SoftwareSerial(69, 3);
    #else
    NewSoftSerial cameraconnection = NewSoftSerial(2, 3);
    #endif

    Adafruit_VC0706 cam = Adafruit_VC0706(&cameraconnection);

    // Using hardware serial on Mega: camera TX conn. to RX1,
    // camera RX to TX1, no SoftwareSerial object is required:
    //Adafruit_VC0706 cam = Adafruit_VC0706(&Serial1);

    void setup() {

      // When using hardware SPI, the SS pin MUST be set to an
      // output (even if not connected or used).  If left as a
      // floating input w/SPI on, this can cause lockuppage.
    #if !defined(SOFTWARE_SPI)
    #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      if(chipSelect != 53) pinMode(53, OUTPUT); // SS on Mega
    #else
      if(chipSelect != 10) pinMode(10, OUTPUT); // SS on Uno, etc.
    #endif
    #endif

      Serial.begin(9600);
      Serial.println("VC0706 Camera snapshot test");

      // see if the card is present and can be initialized:
      if (!SD.begin(chipSelect)) {
        Serial.println("Card failed, or not present");
        // don't do anything more:
        return;
      }

      // Try to locate the camera
      if (cam.begin()) {
        Serial.println("Camera Found:");
      } else {
        Serial.println("No camera found?");
        return;
      }
      // Print out the camera version information (optional)
      char *reply = cam.getVersion();
      if (reply == 0) {
        Serial.print("Failed to get version");
      } else {
        Serial.println("-----------------");
        Serial.print(reply);
        Serial.println("-----------------");
      }

      // Set the picture size - you can choose one of 640x480, 320x240 or 160x120
      // Remember that bigger pictures take longer to transmit!

      cam.setImageSize(VC0706_640x480);        // biggest
      //cam.setImageSize(VC0706_320x240);        // medium
      //cam.setImageSize(VC0706_160x120);          // small

      // You can read the size back from the camera (optional, but maybe useful?)
      uint8_t imgsize = cam.getImageSize();
      Serial.print("Image size: ");
      if (imgsize == VC0706_640x480) Serial.println("640x480");
      if (imgsize == VC0706_320x240) Serial.println("320x240");
      if (imgsize == VC0706_160x120) Serial.println("160x120");

      Serial.println("Snap in 3 secs...");
      delay(3000);

      if (! cam.takePicture())
        Serial.println("Failed to snap!");
      else
        Serial.println("Picture taken!");

      // Create an image with the name IMAGExx.JPG
      char filename[13];
      strcpy(filename, "IMAGE00.JPG");
      for (int i = 0; i < 100; i++) {
        filename[5] = '0' + i/10;
        filename[6] = '0' + i;
        // create if does not exist, do not open existing, write, sync after write
        if (! SD.exists(filename)) {
          break;
        }
      }

      // Open the file for writing
      File imgFile = SD.open(filename, FILE_WRITE);

      // Get the size of the image (frame) taken
      uint16_t jpglen = cam.frameLength();
      Serial.print("Storing ");
      Serial.print(jpglen, DEC);
      Serial.print(" byte image.");

      int32_t time = millis();
      pinMode(8, OUTPUT);
      // Read all the data up to # bytes!
      byte wCount = 0; // For counting # of writes
      while (jpglen > 0) {
        // read 32 bytes at a time;
        uint8_t *buffer;
        uint8_t bytesToRead = min(32, jpglen); // change 32 to 64 for a speedup but may not work with all setups!
        buffer = cam.readPicture(bytesToRead);
        imgFile.write(buffer, bytesToRead);
        if(++wCount >= 64) { // Every 2K, give a little feedback so it doesn't appear locked up
          Serial.print('.');
          wCount = 0;
        }
        //Serial.print("Read ");  Serial.print(bytesToRead, DEC); Serial.println(" bytes");
        jpglen -= bytesToRead;
      }
      imgFile.close();

      time = millis() - time;
      Serial.println("done!");
      Serial.print(time); Serial.println(" ms elapsed");
    }

    void loop() {
    }

But when I open my Serial Monitor, it says:

> No camera found?

Where did I go wrong ?

title: Camera VC0706 not found

Answers: 0


body:
Folks,
I want to use my arduino with ethernet shield to access the following webpage "http://www.met.ie/forecasts/sea-area.asp" and take some information.

On the website it has a line "Small Craft Warning"- This is always either "In Operation" or "Nil".

Basically i want to hook up a RGB LED to the duino and if "Small Craft Warning" is "in Operation" i want LED to be Red, and if "Nil" LED can be green.

My issue is i cant figure out hot to go about getting the information from the webpage.- Can the arduino read this directly?

I am confident with arduino but this is my first web based project!

Any Tips or advice would be savage helpful
Thanks

title: Arduino Accessing a web page

Answers: 4

body:
Unfortunately that text is delivered as part of the complete web page and not, for example, an AJAX request.

>Do you supply an RSS feed of your forecasts?
>
>_This is not something we provide at present, although we hope to do so in the future._ [Source](http://www.met.ie/faqs/#rss).

Your only option is to scan through the whole page looking for the text strings.

This is a little dangerous as the page could, for example, contain the phrase as part of a help file and give you an incorrect status reading. I wouldn't set to sea on the basis of your LED.

Bí cúramach!

body: To add to Transitor's answer, while not guaranteed to work perfectly, you can always try to narrow down the page's source by only searching the component the text is in which should hopefully work. (unless they redo their website)

body:
I think this can be accomplished with the use of a few libraries.  Also, I'd recommend the use of a third color to let you know when your program has encountered an unexpected condition, such as couldn't retrieve the webpage or couldn't find "Small Craft Warning" in the page or if the value for that attribute is something unexpected.

So first you'd want to use the Ethernet library that comes with the Arduino IDE. There is even an example sketch that shows you how to use it to download a webpage. Make sure you parse the status returned from the webserver to ensure its giving you a 200 HTTP status code and produce an error if it does not or if the connection fails.

As for parsing the webpage itself, you might try [this regular expression library][1] that Nick Gammon wrote.
Just have it search for the line with Small Craft Warning and then parse that line as a string as test for matches against the strings you are expecting to find or erroring out. Or you can use additional regular expressions to match your expected values once you find the right line. Remember to make the LED show an error color if it doesn't find the line or an expected value.

Just talking about this makes me want to try it. ;-)

  [1]: https://github.com/nickgammon/Regexp

body:
As I commented on deltaray's answer, a regular expression library is
overkill for finding a fixed string. There is a standard avr-libc
function for that called [strstr()][]:

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

    char * strstr(const char *haystack, const char *needle);

where `haystack` is the Web page and `needle` is the fixed string you
are searching for.

There is an issue with this function though: in order to use it, you
need to have the whole haystack in RAM. For a non-trivial Web page, this
may not be doable on a small Arduino.

Below is a custom solution based on a [finite state machine][fsm]: the
parser can be in a number of different states:

* state 0 = waiting for the 'S' of "Small Craft"
* state 1 = waiting for the 'm' of "Small Craft"
* etc...

The state is actually an index in a character array representing the
string we are looking for. Each time the parser finds the expected
character, it moves to the next state. Otherwise it moves back to state
0. There is a small kludge though: when in the state _waiting for the
'N' of "Nil"_, if it doesn't get an 'N', it moves to the state _waiting
for the 'I' of "In Operation"_ and tries the match again. This way it
can look for both the possible strings at once. Also, once it got the
full preamble "Small Craft Warning: </b>", if it gets something
invalid, it moves to an extra state called _INVALID_ instead of state 0.

Here is the code:

    // Possible return values of parse_forecast().
    // The last three are sticky.
    enum parse_state {
        NO_PREAMBLE,        // no complete preamble seen yet
        PREAMBLE_COMPLETE,  // preamble just completed
        PARTIAL_NIL,        // received preamble and start of "Nil"
        PARTIAL_IN_OP,      // received preamble and start of "In Operation"
        COMPLETE_NIL,       // result = Nil
        COMPLETE_IN_OP,     // result = In Operation
        INVALID             // valid preamble followed by invalid data
    };

    parse_state parse_forecast(char c)
    {
        // position:      0                        25   29            42
        const char T[] = "Small Craft Warning: </b>Nil\0In Operation\0";
        static size_t i;  // T[i] is the character we expect next

        if (T[i]) {  // non-sticky state
            if (i == 25 && c != T[i])
                i = 29;      // switch to "In Op" branch
            if (c == T[i])   // found expected char
                i++;         // wait for the next one
            else {
                if (i < 25)
                    i = 0;   // reset to start of the string
                else
                    i = 42;  // invalid state
            }
        }
        return i <  25 ? NO_PREAMBLE :
               i == 25 ? PREAMBLE_COMPLETE :
               i <  28 ? PARTIAL_NIL :
               i == 28 ? COMPLETE_NIL :
               i <  41 ? PARTIAL_IN_OP :
               i == 41 ? COMPLETE_IN_OP :
               INVALID;
    }

With this you do not need to store the Web page in RAM. Instead, you
feed the parser one character at a time and, at the end, check the
return value. You expect it to be either `COMPLETE_NIL` or
`COMPLETE_IN_OP`.

Implementation detail: there are three NUL characters in the template
string, at positions 28, 41 and 42 (the last one is implicit). They
correspond to the three possible "sticky" states.

[strstr()]: http://www.nongnu.org/avr-libc/user-manual/group__avr__string.html#ga6a441da9211eb85881d99c60b1003552

[fsm]: https://en.wikipedia.org/wiki/Finite-state_machine


body:
I have tried several different ways to do this, but in the line:

  `myTFT.println("DS32(32,g,'Hello!',4);");`

where `g` is an int, it simply doesn't print. If I just replace the `g` with a value of any kind, all is well.

I'm using an Uno (well, an Orion board from Makeblock) and the Makeblock TFT.

All my other print lines work fine but of course, none contain variables.

title: Using softwareserial with a TFT, how can I use a variable to position cursor?

Answers: 1

body:
Just split the print into three parts:

    myTFT.print("DS32(32,");
    myTFT.print(g);
    myTFT.println(",'Hello!',4);");


body:
I am trying to read an MCP23S17 I/O expander port B with the Arduino SPI library.
The following example is simple as possible, and I still can not get it to work.
[![enter image description here][1]][1]
The setup is an MCP23S17 I/O expander on a Teensy LC controller.
MCP23S17 port B pins are alternately grounded and energized.
I confirmed the pin voltages with a multi-meter.
Variable portBState is a bitwise reading of port B, and printed.

Expected output is:

    10101010

Actual output is:

    11111111

Sketch:

    #include <SPI.h>

    const uint8_t ADDR = 0x20;      //MCP23S17 address, all 3 ADDR pins are grounded
    const uint8_t OPCODE_READ  = (ADDR << 1 | 0x01); //MCP23S17 read command

    const uint8_t IODIRB = 0x01;
    const uint8_t GPIOB  = 0x13;

    uint8_t portBState = 0;                 //bit wise

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

        pinMode(SS, OUTPUT);                //configure controller's Slave Select pin to output
        digitalWrite(SS, HIGH);             //disable Slave Select
        SPI.begin();

        //IODIRB register is already configured to input by default

        SPI.beginTransaction(SPISettings (SPI_CLOCK_DIV8, MSBFIRST, SPI_MODE0));
        digitalWrite(SS, LOW);              //enable Slave Select
          SPI.transfer(OPCODE_READ);        //read command
          SPI.transfer(GPIOB);              //register address to read data from
          portBState = SPI.transfer(0);     //save the data (0 is dummy data to send)
        digitalWrite(SS, HIGH);             //disable Slave Select
        SPI.endTransaction();               //release the SPI bus

        Serial.println(portBState, BIN);    //should print 10101010
    }

    void loop() { }

Why is the output not "10101010"?

The controller is Teensy LC (3.3 volts) on Arduino 1.6.7.

SPI library: https://www.arduino.cc/en/Reference/SPI

More links in the comments below (I don't have enough reputation points to post more links in the question).

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

title: Reading an MCP23S17 I/O expander port with the Arduino SPI library

Answers: 1

body:
It's working now.  Here is what was missing:
A yellow jumper from the micro-controller MOSI pin to the MCP23S17 SO pin.
So the read command can travel from micro-controller to MCP23S17.

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

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


body: Sometimes I run out of space of the program size for the embedded C program that I want to put on an arduino. So what chip do I need to expand the program memory of the arduino so that I can use bigger C programs with my arduino?

title: How to expand program memory on an arduino?

Answers: 5

body:
An ATmega2560 is the chip to add for more memory when you run out of program memory on an Uno.  Referring to the [Memory](https://www.arduino.cc/en/Tutorial/Memory) webpage at arduino.cc, you'll see that it has Flash=256KB, SRAM=8KB, EEPROM=4KB, where the ATmega328 chip on the Uno has Flash=32KB, SRAM=2KB, EEPROM=1KB.

When you run out of program memory on an Uno, you have about three choices that are practical:  make the program smaller; remove the bootloader (to free up one or two KB); use a different board with a more-capable processor.  The CPU on an Uno board doesn't have a way to access program bytes from places other than the on-chip 32KB flash.  The CPU on a Mega2560 board starts out with 8 times as much flash, so it can hold bigger programs than an Uno can.

If you remove the bootloader, you could instead program using a USBASP board, as described in a
[“Program AVR chip using a USBASP with 10 pin cable”](http://www.learningaboutelectronics.com/Articles/Program-AVR-chip-using-a-USBASP-with-10-pin-cable.php) article at learningaboutelectronics.com.

body:
Another way (other than MCU with more memory) is not using Arduino framework and its libraries. Such level of abstraction is expensive in both ways - memory usage and speed. But that's much harder way. If you need some library, you have to port it (if you haven't found native one) or at least provide required functions from Arduino.

For example in Arduino IDE 1.6.11 empty sketch is using up 444 Bytes of flash. Using one `pinMode` and `digitalWrite(13, ! digitalRead(13));` + `delay(500);` means 964 Bytes. Of course, these are most likely one-timers. If you use six more pins and toggle it, it uses much less program memory than using first one (1192B). But it still grows really fast.

In pure C empty program is about 134 Bytes long. Same functionality (toggling one pin every 500ms) takes 158 Bytes (and it's way faster).

But for hobby project i would go for ATMega2560 or ATMega644/1284 instead.

And you can use direct access to hardware too. Toggle pin sketch with using registers directly and _delay_ms from avr libraries uses 468 Bytes instead of 964B. With delay from Arduino core libraries it's 602B.

body:
What about a [raspberry pi zero][1]?  I have a couple and use them quite often as arduinos.

  [1]: https://www.raspberrypi.org/blog/zero-grows-camera-connector/

body: You could also look into other platforms. For instance, a Teensy 3.2 is Arduino compatible and has a 2KB eeprom and 64KB of RAM.

body:
When asking a broad question, it is helpful to include some details.  Like how much memory you need and why you think you need it.

I once specified a processor at 2 KB program space, 64 bytes RAM and 1 KIPS.
The engineer asked, "MIPS?", and I explained thousands per second.  He replied, "They don't come that slow".  At the end of the project, a huge UI was added and memory got tight... but it still fit with no problem.

So, consider being more thoughtful about the resources being used.

To answer the question:

1) The Arduino does not provide a convenient bus to fetch memory over.
So, there is no way to plug in a chip to get more memory.

2) The Arduino has SPI, so an SD card can be accessed.
Any code on the SD card would need to be loaded into executable memory.
This is complicated and not for beginners...

3) As suggested, tighten up you code.  This is probably a good way to learn.

3) Move to a larger Arduino.

There are different Arduino processors.  Some in the ACR line, others in the ARM line.  Going to a different device in the same family is a relatively modest change and can provide up to 368 Bytes of program FLASH.  But these are not Arduino boards exactly.

The Arduino ARM based devices are very different and use different libraries.

Check out the Arduino Mega 2560 it is very similar to the Uno, has a similar footprint, code should port relatively easily and is inexpensive.

There are also larger devices in the AVR family.

Note, the AVR32 is a different processor and the peripherals are enough different that it is a different device.

If you want to get into very large programs (gigabytes of memory) check out the Beagleboard.  It has a full linux, with virtual memory (see #2 above) and has more powerful I/O mechanisms.


body:
I am doing some experiments with nodemcu 12 (which has built in esp8266). There most of the tutorials I found by internet describe how to connect to home wifi connection using it.

But when I power on nodemcu, I can see wifi network called "ESPXXX" in my laptop's wifi connection list.

So is there a way to directly connect to the wifi nw of esp8266 by my laptop or via another esp8266 (so I don't have to switch on my home wifi router)?

If it is possible, is there is way to change ssid of esp8266's wifi connection and add password (again this is not about connecting to home wifi and this is about the wifi connection on esp8266 it self)?
So we can make one esp8266 as a wifi host and connect other esp8266s as slave to it.

I am using arduino IDE to upload program into esp8266 and not Lua.

Thanks.

title: Wifi networking with ESP8266 (NODEMCU version)

Answers: 1

body:
Here you are the working code allowing you to choose `SSID`, `password`, `network name` and `IP address` of your ESP8266 acting as an access point. In addition, you can specify `wifi channel` to avoid interference with other devices. A password must be at least 8 characters long or it wouldn't work.

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>

    IPAddress ip(192,168,1,81);         // choose IP address
    IPAddress subnet(255,255,255,0);

    ESP8266WebServer server(80);

    void handleRoot() {
      String page = "<!DOCTYPE html>\n";

      page += "\n\n
Some heading

Generated by ESP8266\n\n";
      server.send(200, "text/html", page);
    }

    // what to do when accessed through http://ip_address/something_undefined
    void handleNotFound(){
      String message = "File not found\n\n";
      message += "URI: ";
      message += server.uri();
      message += "\nMethod: ";
      message += (server.method() == HTTP_GET)?"GET":"POST";
      message += "\nArguments: ";
      message += server.args();
      message += "\n";
      for (uint8_t i=0; i<server.args(); i++){
        message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
      }
      server.send(404, "text/plain", message);
    }

    void setup(void){
      Serial.begin(74880);                      // so you can see debug messages automatically sent by ESP8266
      WiFi.mode(WIFI_AP);
      WiFi.softAPConfig(ip, ip, subnet);        // declared as: bool softAPConfig (IPAddress local_ip, IPAddress gateway, IPAddress subnet)
      WiFi.softAP("SOME_NAME", "password", 7);  // network name, network password, wifi channel

      IPAddress myIP = WiFi.softAPIP();
      Serial.println();
      Serial.print("AP IP address: ");
      Serial.println(myIP);

      server.on("/", handleRoot);               // what to do when accessed through browser using http://IP_address

      // what to do when accessed through http://ip_address/test
      server.on("/test", [](){
        server.send(200, "text/plain", "This is another page");
      });

      server.onNotFound(handleNotFound);

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

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

You can write something like:

    server.on("/open_door", [](){
            // the code to switch on the relay to open the door
            // ... <-- put here the code
            server.send(200, "text/html", "Door: opened");
    });

so you can open the door with `http://ip_address/open_door`.

You can try `http://ip_address/something_undefined?a=24&b=25` to get an idea how to process the parameters.


body:
This is my first program on Arduino Uno (the starter kit), although I do have prior experience with programming (JavaScript, coding class last year 7th grade). It blinks the internal led (pin 13) in a Morse Code message:

> **.... . .-.. .-.. ---   .-- --- .-. .-.. -..**
>
>     . = dit();
>
>     - = dah();
>
>     (interval between parts of letter) = wip();
>
>     (interval between letters/words) = wah();

Here's my code:

    /*
     * Roman's first program
     * Decipher the message!
    */

    int ledPin = 13;
    int index = 0;

    void setup() {
      //initialize pins as outputs
      pinMode(ledPin, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      int sequence[] = {1,0,1,0,1,0,1,3,1,3,1,0,2,0,1,0,1,3,1,0,2,0,1,0,1,3,2,0,2,0,2,3,3,3,1,0,2,0,2,3,2,0,2,0,2,3,1,0,2,0,1,3,1,0,2,0,1,0,1,3,2,0,1,0,1};
      int arrLength = sizeof(sequence)/sizeof(int); //however THIS works?!
      if (index < arrLength-1) { //0-based array
        index++;
      } else {
         index = 0; //restart the sequence once finished
      }
      if (sequence[index] == 0) {
        wip();
      } else if (sequence[index] == 1) {
        dit();
      } else if (sequence[index] == 2) {
        dah();
      } else if (sequence[index] == 3) { //because sometimes I the values are screwed past arrLength...
        wah();
      }
      //Serial.println(String(sequence[index])+" , "+String(index));
    }

    void dit () {
      digitalWrite(pinMode, HIGH);
      delay(300);
      digitalWrite(pinMode, LOW);
    }

    void dah () {
      digitalWrite(pinMode, HIGH);
      delay(900);
      digitalWrite(pinMode, LOW);
    }

    void wip () {
      delay(900);
    }

    void wah () {
      delay(2100);
    }

Yet nothing is happening, except for the four/five startup flashes on the led when I restart it (red button). And yes, I saved and compiled.

title: LED pin 13 not flashing properly

Answers: 1

body:
Well, mainly `digitalWrite(pinMode, HIGH);` looks suspicious. I though you called LED pin as `ledPin`

If you fix this, it should be working. As this one is working too, it's just simplified a little:

    int ledPin = 13;
    int index = 0;
    const int8_t sequence[] = {1,0,1,0,1,0,1,3,1,3,1,0,2,0,1,0,1,3,1,0,2,0,1,0,1,3,2,0,2,0,2,3,3,3,1,0,2,0,2,3,2,0,2,0,2,3,1,0,2,0,1,3,1,0,2,0,1,0,1,3,2,0,1,0,1};
    int arrLength     = sizeof(sequence);

    void setup() {
      pinMode(ledPin, OUTPUT);
      Serial.begin(57600);
    }

    void loop() {
      Serial.println(String(sequence[index])+" , "+String(index));
      switch (sequence[index++]) {
        case 0: wip(); break;
        case 1: dit(); break;
        case 2: dah(); break;
        case 3: wah(); break;
      }
      if (index == arrLength) {
        index = 0;
      }
    }

    void dit () {
      digitalWrite(ledPin, HIGH);
      delay(300);
      digitalWrite(ledPin, LOW);
    }

    void dah () {
      digitalWrite(ledPin, HIGH);
      delay(900);
      digitalWrite(ledPin, LOW);
    }

    void wip () {
      delay(900);
    }

    void wah () {
      delay(2100);
    }


body: motor driver is for current amplification.for that we could connect more batteries to servos to get more current.but why are we using motor shields?

title: use more no of batteries for more current for servos,why using motor shield?

Answers: 1

body:
The motor shield is useful because you cannot pass the required amount of current through Arduino's microcontroller without blowing it up.

Of course you don't need to use the motor shield if you create a similar circuit of your own that performs the same task.


body: I'm working on trying to control a hard drive with an Arduino Uno, but I'm having trouble with the power supply. From what I know, both the Molex Mate-n-Lok and the new SATA connectors both have 2 grounds, a 5V and a 12V power in. I'm wondering what the purpose of the 12V power supply is. I suspect it's used to drive the motor but I'm not sure.

title: Do I need to supply the 12V connection to an HDD

Answers: 2

body:
Judging by my old copy of "Upgrading and repairing PCs" - which I found a quote for on [Google Books](https://books.google.com.au/books?id=jw7yCQAAQBAJ&pg=PT901&lpg=PT901&dq=ATA++HDD+spindle+motor&source=bl&ots=Jvb80oa6A1&sig=9H1agBSU7sXF_vYtrLlz1f16M14&hl=en&sa=X&ved=0ahUKEwisv5aG6eXOAhVGoJQKHQU-CoEQ6AEIQDAI#v=onepage&q=ATA  HDD spindle motor&f=false) - the 12V supply is for the spindle motor, and it says:

> Spindle motors, particularly on the larger form-factor drivers, can consume a great deal of 12V power.

body:
3.5" hard drives require 12V and 5V for the motor and logic respectively. SATA ones may also require 3.3V for the logic.  Most smaller laptop drives (2.5") only require 5V and 3.3V.  [Some][1] 2.5" drives also require 12V.

You will not be able to interface a SATA hard drive to an Arduino without some kind of SATA hard drive controller, which you could possibly build using a fast FPGA (in which case why would you bother with an Arduino?). For SATA-I (way out of date now) you need to generate a 1.5Gbps LVDS (Low-Voltage Differential Signal) data stream. For SATA-3.2 that is now 16Gbps. Impossible on an Arduino.

PATA (Parallel ATA) is more realistic, although you need a lot of pins since it is a 16-bit parallel interface. Timing is less critical since it is synchronous with the read / write strobes.

  [1]: https://www.seagate.com/files/www-content/product-content/enterprise-hdd-fam/enterprise-capacity-2-5-hdd/en-us/docs/100827452b.pdf


body:
I have an HC-SR04 sensor and I need to get the distance from it. I use this code:

    digitalWrite(trig, LOW);
    delayMicroseconds(2);
    digitalWrite(trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig, LOW);
    duration=pulseIn(echo, HIGH, 24000L);
    cm=duration/2/29.1;

Pulsein takes too much time and I would like to use interrupts to prevent code from being blocked. From the beginning, I had no idea how to do it. I did not want to ask this question without trying on my own so here is my miserable attempt:

     while(digitalRead(echo)==LOW){
     }
    if(digitalRead(echo)==HIGH){
          lowTimer=millis();
    }
    while(digitalRead(echo)==HIGH){

    }

    if(digitalRead(echo)==LOW){
       duration=millis()-lowTimer;
    }

Obviously, this does not work. I don't know if I am on the right track, but I do know that even if this worked, it would still block my code for a long time. Can someone help me, point me in the right direction? Please don't just write it for me - I want to learn. I would like someone to point me to the right direction till I get it. Thank you!

EDIT:

I tried on of the suggestions:

    unsigned long duration;
    int cm;
    const int echo = 24;
    const int trig = 22;
    bool doPing=true;

    void setup()
    {
      pinMode(echo, INPUT);
      pinMode(trig, OUTPUT);
      Serial.begin(9600);
    }

    void loop()
    {
     if(doPing){
      ping();
      doPing=false;
     }
     read_pulse();
     if(duration!=0){
      cm=duration/29.1/2;
      Serial.println("cm: "+cm);
      doPing=true;
     }
     delay(2);
    }
    void ping(){
      digitalWrite(trig, LOW);
      delayMicroseconds(2);
      digitalWrite(trig, HIGH);
      delayMicroseconds(10);
      digitalWrite(trig, LOW);
    }

    void read_pulse()
    {
        static unsigned long rising_time;  // time of the rising edge
        static int last_state;             // previous pin state
        int state = digitalRead(echo);      // current pin state
        duration = 0; // default return value

        // On rising edge: record current time.
        if (last_state == LOW && state == HIGH) {
            rising_time = micros();
        }

        // On falling edge: report pulse length.
        if (last_state == HIGH && state == LOW) {
            unsigned long falling_time = micros();
            duration = falling_time - rising_time;
        }

        last_state = state;
    }

This does not print anything to my serial monitor. Is there something I am missing?

title: How can I replace pulseIn with interrupts?

Answers: 1

body:
You do not want the reading of the incoming pulse to **block** your
program execution. This is the very key requirement: you want a
_non-blocking_ pulse reading. You can write a non-blocking replacement
for `pulseIn()`, but you will have to use it differently. You cannot
expect a non-blocking `pulseIn()` to return the pulse length whenever
you call it: instead, it would return that value _only_ when you call it
right after the pulse falling edge. On all other circumstances it will
return a dummy value meaning “the pulse is not finished yet, thus I
cannot give you its length right now, please call me later”.

Below is an example of a function implementing this approach. You have
to call it on every loop iteration: the more often you call it, the
better resolution you will have. This function uses 0 as the dummy value
meaning “no answer available right now”:

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

    /*
     * Non-blocking pulseIn(): returns the pulse length in microseconds
     * when the falling edge is detected. Otherwise returns 0.
     */
    unsigned long read_pulse(int pin)
    {
        static unsigned long rising_time;  // time of the rising edge
        static int last_state;             // previous pin state
        int state = digitalRead(pin);      // current pin state
        unsigned long pulse_length = 0;    // default return value

        // On rising edge: record current time.
        if (last_state == LOW && state == HIGH) {
            rising_time = micros();
        }

        // On falling edge: report pulse length.
        if (last_state == HIGH && state == LOW) {
            unsigned long falling_time = micros();
            pulse_length = falling_time - rising_time;
        }

        last_state = state;
        return pulse_length;
    }

A better approach, but harder to implement for a novice, is to use
interrupts. Chris gave you a pointer to Nick Gammon’s tutorial on
interrupts. This is definitely a good reading. But you will also have to
dig into the [data sheet of the ATmega328P microcontroller][ATmega328P].
It's a little bit daunting, but a must read if you go into low-level
programming. If you follow this path, I suggest you look at the “input
capture” capability of Timer 1 (chapter 20, section 20.9). This is a
feature of the timer that can have it automatically save a timestamp
whenever some external pin changes state. You then use the input capture
interrupt to alert the program when an edge has been detected, and your
interrupt service routine can read the automatically saved timestamp.
Using this approach, you can have extremely accurate pulse length
measurements, independent on how fast your program goes through its
`loop()`.

[ATmega328P]: http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_datasheet.pdf


body:
as a project I have to build a sensor hub based on Arduino. I need a couple of sensors like gyroscope, barometer, etc. This is no problem so far. The problem arises when it comes to power measurement. We have to measure the power consumption of the Arduino AND all the sensors. Sure, I could use a sensor like the [Adafruit INA219 sensor](https://learn.adafruit.com/adafruit-ina219-current-sensor-breakout). But this only gives the total consumed power of the Arduino and the sensors.

Is it possible to measure the energy, say, for every pin on the Arduino?

title: Power measurement on Pins

Answers: 1

body:
"Sorry, my description was not clear enough. We want to measure everything in total AND every sensor separately. So, we do not really have to measure every sensor, it would be enough to have some reliable numbers to work with."

"it possible to measure the energy, say, for every pin on the Arduino?"

You ask if it possible to measure the energy- yes it is-or at least an approximation. The basic solution is as follows. Suppose you want to find the energy consumed by some component at one pin.  Energy is measure in joules. For an electrical circuit we the amount of energy (consumed in 1 second) is given by the formula

 joules=current X voltage.
Lets consider the case with one sensor first , lets refer to this as sensor A.
The amount of energy that electrical component consumes in some time duration is by sensor A is:

joules (use by sensor A)=current X voltage X time duration sensor A is on

Now to make this formula applicable to your answer- we can replace voltage by the average voltage, and current by average current, since this is mathemtically equivalent, that the component is on for, and the time duration would be the time the component is on for. So the equivalent formula that can be used is

joules= average current X average voltage of sensor A during time duration X time duration sensor A is on

So for example if the sensor is only ever used for 50 minutes for all time throughout your project- and the sensor is turned on at the arduino pin for 1 second for every minute of that 50 minutes then the energy used by that sensor on that specific pin is equivalent to leaving the pin on for 50 seconds at the average voltage and average current of that sensor. Say the average voltage is 3v then the energy and average current is 20ma. Then the energy used by that sensor is thus
3v*0.02amps*55 seconds=3.3 joules.

Thus to get the total energy (if there were two sensors A and B) you would just need to sum

(joules (use by sensor A)= current of A X voltage of A Xtime duration sensor A is on)+(joules (use by sensor B)=current of B Xvoltage of B Xtime duration sensor B is on.)

Similar formula for more sensors.

To sum up- basically you would need your arduino program to keep track of how long each sensor pin is on (assuming high voltage turn on the sensor and makes it use power, low voltage turns off the sensor or make it use no power)  for each of the time duration in the formula for the duration of the project, you would need an estimate of the average voltage and current (e.g. from data sheet) or another way. Then you would need to use the formula in your code to compute the energy used by each sensor and the total energy.
If you have a way to measure the voltage and current fast enough then you could use them measurement instead of using average value as explained above-but I guess using averages is the easiest way to do it.

.


body:
It looks like I cannot combine the Grove sunlight sensor and the Grove DHT22 temperature and humidity sensor. I can't figure out why.

I have the following setup:

 - Seeeduino Cloud (Arduino Yún clone)
 - Grove Shield Grove sunlight sensor connected to an I2C port
 - Grove DHT22 temperature and humidity sensor connected to port A0

I'm sending the data to Initialstate.com. This is my code:
<!-- language-all: lang-cpp -->

    // Process.h gives us access to the Process class, which lets
    // us communicate with the shell
    #include "DHT.h" //Temp Hum sensor
    #include <Bridge.h>
    #include <Process.h>
    #include <Wire.h>
    #include "SI114X.h" //Sunlight sensor

    SI114X SI1145 = SI114X();

    ////////////////////////////////////////////

    //Temperature and Humidity sensor data start
    #define DHTPIN A0
    // what sensor is connected to, in this case A0
    #define DHTTYPE DHT22   // DHT 22  (AM2302)

    DHT dht(DHTPIN, DHTTYPE);
    //Temperature and Humidity sensor data end

    ////////////////////////////
    // Initial State Streamer //
    ////////////////////////////
    // URL to IS Bucket API
    String ISBucketURL = "https://groker.initialstate.com/api/buckets";
    // URL to IS Event API
    String ISEventURL = "https://groker.initialstate.com/api/events";
    // Access key (the one you find in your account settings):
    String accessKey = "KRYLC3tvJUiyTVqTJr5nRqgkKQI2FiDh";
    String bucketKey = "Test_Klimaat2";
    // Bucket name (name your data will be associated with in Initial State):
    String bucketName = "Test klimaat 2";
    // Bucket key (hidden reference to your bucket that allows appending):
    //String bucketKey = "arduino_stream";
    // Bucket name (name your data will be associated with in Initial State):
    //String bucketName = "Arduino Stream";
    // How many signals are in your stream? You can have as few or as many as you want
    const int NUM_SIGNALS = 5;
    // What are the names of your signals (i.e. "Temperature", "Humidity", etc.)
    String signalName[NUM_SIGNALS] = {"Humidity", "Temperatur", "Visable", "Infrared", "UV"};
    // This array is to store our signal data later
    String signalData[NUM_SIGNALS];

    // This only runs once at the very beginning
    void setup() {
      Serial.begin(9600);
      Bridge.begin();
      Wire.begin();
      SI1145.Begin();
      dht.begin(); //Initialize temparature and humidity sensor

      while (!Serial);
        // Post Bucket
        Serial.println("Posting Bucket!");
        // The postBucket() function creates a bucket
        // (unnecessary if the bucket already exists)
        postBucket();
    }

    // This repeats
    void loop() {
      // Gather Data
      // Read from a port for input or output or generate your own values/messages
      // These signals are random numbers for the sake of example

      String VIS;
      String IR;
      String UV;
      String TEMP;
      String HUM;

      //Code reading DHT22
      HUM = String((float)dht.readHumidity());
      TEMP = String((float)dht.readTemperature());

      //code reading Sunlight data
      VIS = String(SI1145.ReadVisible());
      IR = String(SI1145.ReadIR());
      UV = String((float)SI1145.ReadUV()/100);

      signalData[0] = HUM;
      signalData[1] = TEMP;
      signalData[2] = VIS;
      signalData[3] = IR;
      signalData[4] = UV;

      // Post Data
      Serial.println("Posting Data!");
      // The postData() function streams our events
      postData();
      // Wait for 5 seconds before collecting and sending the next batch
      delay(5000);
    }

    // Here are the data bucket creation and posting functions
    // They do not need to be edited - everything you would need to change for
    // your situation can be found above

    void postBucket() {
      // Initialize the process
      Process isbucket;

      isbucket.begin("curl");
      isbucket.addParameter("-k");
      isbucket.addParameter("-v");
      isbucket.addParameter("-X");
      isbucket.addParameter("POST");
      isbucket.addParameter("-H");
      isbucket.addParameter("Content-Type:application/json");
      isbucket.addParameter("-H");
      isbucket.addParameter("Accept-Version:0.0.1");

      // IS Access Key Header
      isbucket.addParameter("-H");
      isbucket.addParameter("X-IS-AccessKey:" + accessKey);

      // IS Bucket Key Header
      isbucket.addParameter("-d");
      isbucket.addParameter("{\"bucketKey\": \"" + bucketKey + "\", \"bucketName\": \"" + bucketName + "\"}");
      isbucket.addParameter("https://groker.initialstate.com/api/buckets");
      // Run the process
      isbucket.run();
      Serial.flush();
    }

    void postData() {
      // Initialize the process
      Process isstreamer;
      isstreamer.begin("curl");
      isstreamer.addParameter("-k");
      isstreamer.addParameter("-v");
      isstreamer.addParameter("-X");
      isstreamer.addParameter("POST");
      isstreamer.addParameter("-H");
      isstreamer.addParameter("Content-Type:application/json");
      isstreamer.addParameter("-H");
      isstreamer.addParameter("Accept-Version:0.0.1");

      // IS Access Key Header
      isstreamer.addParameter("-H");
      isstreamer.addParameter("X-IS-AccessKey:" + accessKey);

      // IS Bucket Key Header
      // Note that bucketName is not needed here
      isstreamer.addParameter("-H");
      isstreamer.addParameter("X-IS-BucketKey:" + bucketKey);

      isstreamer.addParameter("-d");

      // Initialize a string to hold our signal data
      String jsonData;
      jsonData = "[";
      for (int i=0; i<NUM_SIGNALS; i++) {
        jsonData += "{\"key\": \"" + signalName[i] + "\", \"value\": \"" + signalData[i] + "\"}";
        if (i != NUM_SIGNALS - 1) {
          jsonData += ",";
        }
      }
      jsonData += "]";
      isstreamer.addParameter(jsonData);
      isstreamer.addParameter("https://groker.initialstate.com/api/events");
      // Print posted data for debug
      Serial.print("Sending data: ");
      Serial.println(jsonData);
      // Run the process
      isstreamer.run();
      Serial.flush();
    }

When I run this code, the Serial monitor will correctly display the data string I want to send with all values. However the data is NOT sent. Only when I comment out one of these lines in the `loop()` declaration the data is sent to Initialstate successfully. Obviously without the data commented out:

      //Code reading DHT22
      HUM = String((float)dht.readHumidity());
      TEMP = String((float)dht.readTemperature());

      //code reading Sunlight data
      VIS = String(SI1145.ReadVisible());
      IR = String(SI1145.ReadIR());
      UV = String((float)SI1145.ReadUV()/100);

Any ideas are appreciated.

title: Combine DHT22 and SI114X.h

Answers: 1

body: I found the solution. Based on this post: http://forum.arduino.cc/index.php?topic=198433.0 I concluded that my strings are too long or my board runs out of memory. I removed the posting of the bucket and created abbreviations in my signal names. This solved the problem.


body:
I am using DHT22 temperature/humidity sensor and I noticed that there exist so many libraries. I wonder which one is the most accurate?

It is giving me readings that does not seem to be logic. High temperature and very low RH%. Is it because of the library or because I am not connecting 10k or 4.7k resistor?

Thank you so much in advance.

Regards,
Badr Eddine

title: DHT22: Library and Data accuracy

Answers: 0


body:
I've got an Adafruit Trinket microcontroller set up using [this USB keyboard tutorial][1], and it works great.

I'd like to set up my project to type a shruggie ( `¯\_(ツ)_/¯` ) when I press a hardware button.

My naive solution was:

    TrinketKeyboard.print("¯\_(ツ)_/¯");

But that only printed the underscores, parentheses and slashes, not the "hands" or the "face."

Is there a standard keyboard input method I could use so this device, when plugged into any Mac, will type out a string that includes Unicode (specifically Katakana) characters?

An *ideal* solution does not require configuring the machine before plugging this widget in, and doesn't require changing state on the machine -- although I'll take what I can get! :) (e.g., configuring Japanese keyboard support and toggling input source -- all of which is done blind since the computer can't give feedback to a lowly keyboard -- is un-ideal.)

  [1]: https://learn.adafruit.com/trinket-usb-keyboard/code

title: How can a USB keyboard emulator (TrinketKeyboard) type Unicode characters?

Answers: 2

body:
It depends entirely on the operating system you are working with. The Arduino is merely a keyboard. It sends keystrokes. Whatever keystrokes your operating system will accept to generate unicode character are the keystrokes you have to program the Arduino to send. Most likely there is some combination of ALT-GR + keypad numbers that will do the trick.

For OS X it looks like the only possible way is to change the input settings on the computer to allow "Unicode HEX" entry.

* https://discussions.apple.com/thread/1899290?tstart=0

There is no other way of doing it. As I say, the Arduino is just a keyboard. It is subject to the same rules as any other keyboard. You can only type things that can be typed. If you need to type other things the OS has to be made aware that you want to type those things through settings.

body:
You could hack it.

 1. Make it press CMD+SPACE
 2. type `terminal.app`
 3. press ENTER
 4. type  `echo -e
    "\xC2\xAF\\_(\xE3\x83\x84)_/\xC2\xAF" | pbcopy`
 5. press ENTER
 6. press CMD+Q
 7. press CMD+V

though the user would see a terminal window for a second.


body:
I want to replace my door lock with an one made with an Arduino and a servo, but I'm not sure if the platform is stable enough to use it for something like this.

If I do everything right (code, connections, constant power), could I trust in this?

title: Is Arduino stable enough to use it for a door lock?

Answers: 5

body:
If you can *guarantee* that your hardware and software skills are *impeccable* then you can certainly trust the MCU on the board. After all, the ATMega chips aren't toys, even though many people around here seem to treat them as such. They are a professional industrial product.

Of course, this is assuming that the Arduino you have is genuine and not some cheap Chinese knock-off with gawd knows what on the board.

body:
Replying to Majenko's answer with more depth. The limits of the Arduino hardware depend on the ATmega CPU it's built around (I suspect you'll be directly migrating from Arduino to the final PCB).

>but I'm not sure if the platform is stable enough to use it for something >like this.

Thus it may be worth considering for you to read through the data sheet. I'd read through it and look at the parameters which could affect your project. For example, the ATmega is only designed to work properly within certain temperature ranges (so this may affect your lock if it's outdoors in the cold). If you're relying on the built-in timer for something in your project, then that can get affected by temperatures, for example — as opposed to using a quartz crystal for reliable timing.

So you'd need to think how your project can fail with the parameter limits of the hardware components. For example, if you're activating the door lock with a secret code stored on external memory, then the memory used may get corrupted when it gets near a magnetic field.

body:
>  I'm not sure if the platform is stable enough to use it for something like this.

Absolutely it is. As I describe in [my post about an RFID door lock](http://www.gammon.com.au/forum/?id=11283) I use a Uno (and some additional parts) to unlock my door.

Since writing that I improved the software [as described here](http://www.gammon.com.au/forum/?id=12869) so you can reprogram the valid list of cards "on the fly" (without uploading new code) as the valid cards are stored in EEPROM.

[![RFID door lock][1]][1]

My system has been operating for over 5 years without any problems, except once when there was a brownout in the area and I had to power cycle the system (possibly the RFID reader failed and not the Arduino).

My system "fails shut" so it keeps the door locked in the event of a power failure. However I have alternate ways of leaving the building in the event of a power failure combined with a fire.

You are talking about a servo rather than an electric strike. That is likely to be the weak point, and not the Arduino as such. You would need to ensure it was powerful enough to do whatever-it-is you are planning to do, and that it had suitable drivers (eg. MOSFET or driver board).

My system gets used dozens of times each day. We never have a problem with it.

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

body:
If you want to use an Arduino in this sort of environment, there are a few things to watch out for:

 - Heat (usually from sunlight striking the enclosure). This could be
   relevant for your project, depending on the installation and location
   of the door. Choice of enclosure material, colour and finish can all affect this.

 - Rollover of millis() (see http://playground.arduino.cc/Code/TimingRollover). After 55 days, the millis() function on the Arduino rolls over and resets back to 0. Depending on if/how you use this, it may affect you.

 - Power supply stability. If you choose to power your Arduino directly from 5v, ensure that it is a smooth stable supply. I've had noisy power supplies cause some weird resets and glitches.

 - Water ingress. Again, this depends on location. Don't forget to account for condensation and frost (if applicable).

 - Flyback from relay switching and locking solenoids. Add flyback diodes to relay coils and solenoids to stop any flyback voltages killing your control circuitry. See https://en.wikipedia.org/wiki/Flyback_diode

I've run in to all of these issues across various Arduino projects. They may not cause the system to fail completely, instead causing strange behaviour.

If you design your system to account for all of these factors, then it is absolutely reliable enough to run something 24x7x365.

body:
To add to the already good advice so far.

Safety and security wise you need to plan and anticpate for failure. An electromechanical lock or your power supply are hardware wise probably more likely to cause issue than the Arduino board, just watch for back emf and use a flyback diode or snubber as mentioned if required. There may be issues though in your code being stuck in a loop or say card reader or contact faults and so on, this may require a simple on-off at best.

Consider using a battery backed power supply for short blackouts or brownouts.

Then consider your lock type and what will happen in an emergency or with a fault.

Locks such as a strike or mortice lock allow you to use standard door hardware so you have the capability to use a free handle egress out so you won't be trapped in an emergency. You can then also fit a key barrel so if the lock has failed you have a backup way of entry.

With either type you can then have a fairly good balance of safety and security, if you set it up as fail secure your house will not be vulnerable in a power outage or PSU fault whilst also not trapping you inside.

In a commercial setting fail safe is commonly used on non secure common areas and rooms but preference for a residential front door is fail secure.

Other lock types such as maglock, drop bolt, V-Lock, hook and loop and automatic doors among others do not have purely mechanical methods of using the door in a fault so are harder to use in a residential setting and may need emergency breakglass or stop buttons to cut power on the inside and keyswitch or pincode unit on the outside in case of fault if no other entry point available.

Maglocks for example are fail safe only and will open once power is off,potentially leaving your home vulnerable, so need fairly significant battery backup. However I have also experienced issues where a door controller has failed and will not release, as it is a maglock the power has to be broken and there was no method of release externally and no other point of entry.

I would suggest a strike or electronic mortice lock for your purpose and suggest an off the shelf unit, it will be far more reliable long term.


body:
I am recently seeing strange behavior in my Arduino Yun.

Just using the microcontroller, I enter the following:

    #include <stdlib.h>
    #include <string.h> // For string operations.
    #include "Keyboard.h"
    #include "Mouse.h"

    void setup() {
      Keyboard.begin();
      Keyboard.println("Hello world.");
      Keyboard.print("Hello world.");
    }

Rather than getting two lines as expected, I get `Hello world.Hello world.`.

It is a very strange error because [println (docs)][1] is so 'core' to Keyboard function. I've never had this issue before and I've been playing with it for months. I am running IDE 1.6.11.

### A possibly relevant detail

I had this working on my Yun months ago **without** the `#include "Keyboard.h"` and `#include "Mouse.h"`. I opened the IDE again just recently and, upon compiling, it failed saying I needed to add those lines. So I did, and it now `println` doesn't work.

  [1]: http://www.arduino.org/learning/reference/keyboard-println

title: Arduino Keyboard - print() works but println() does not

Answers: 1

body:
> Please test: Keyboard.print("Hello world.\n");

...

>  That works. println still doesn't.

I'm going to guess here that println is doing something odd in the Yun libraries. I note that the Keyboard.cpp file in my release has this in it:

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

    #define SHIFT 0x80
    const uint8_t _asciimap[128] =
    {
     0x00,             // NUL
     0x00,             // SOH
     0x00,             // STX
     0x00,             // ETX
     0x00,             // EOT
     0x00,             // ENQ
     0x00,             // ACK
     0x00,             // BEL
     0x2a,   // BS Backspace
     0x2b,   // TAB Tab
     0x28,   // LF Enter
     0x00,             // VT
     0x00,             // FF
     0x00,             // CR    <---------- note!

Notice that linefeed has a code mapped (0x28) but carriage return (CR) does not (unless you call 0x00 a mapping).

I *think* you'll find that when you hit Enter on a keyboard it is sending a CR (after all, it used to be labelled the "return" key) and not a LF.

However I thought that the Print class outputted both:

    size_t Print::println(void)
    {
      return write("\r\n");
    }

Maybe yours doesn't. I'm not certain which exact `println` will be pulled in for a Yun. The fact that it used to work, and now doesn't, suggests a change there somewhere.


body:
I have an Atmega328 programmed using the Arduino software and libraries (but is standalone on on a board in the TSOP package) without bootloader and with ISP programming). I am using the Wire library to act as an I2C peripheral, where I implement (and register) the `requestEvent` and `receiveEvent` callbacks.

Is it possible to determine, either during the `requestEvent` callback or after it at some point, how many bytes were read by the master before it sent a NACK?

title: How can I determine how many bytes an I2C master read from my Arduino acting as I2C slave?

Answers: 1

body:
You can't.

The master will have to inform the slave how many bytes to transfer, or the master will have to query the slave how many bytes there are to receive.


body: I will be teaching Arduino during a fair in my university, and the school gave me 3 afternoons to teach Arduino to Engineering students. Now I am looking for ideas on how to organize this course, and any help would be very nice.

title: How should I organize a 3-day Arduino beginners course?

Answers: 0


body:
Below is some code that I'm writing to concurrently run "animations" on the same strip of NeoPixels. When I try to make use of the Serial monitor to control the program functions, I just get a bunch of garbled garbage and often, a reboot. I have similar code to this that is actually smaller that runs from a Bluetooth module attached to the same Arduino and has worked for years. Is there some obvious memory issue I'm missing, could my Arduino's SRAM finally be starting to eat it?

    #include "TripCycling.h"
    #include "CycleLight.h"
    #include "Alternate.h"
    #include "Collision.h"
    #include "FluidColor.h"
    #include "ColorRandomizer.h"
    #include "StreamAnimation.h"
    #include "StreamControl.h"
    #include <MemoryFree.h>

    #define MAX_STRIPS 1
    #define MAX_ANIMATIONS 6

    #define control Serial

    static Adafruit_NeoPixel** strips = new Adafruit_NeoPixel*[MAX_STRIPS];

    static uint32_t colors[] = {LEDUtils::red, LEDUtils::orange, LEDUtils::yellow, LEDUtils::green, LEDUtils::blue, LEDUtils::purple};

    static Animation** animations = new Animation*[MAX_ANIMATIONS];

    static int8_t stripIDs[MAX_STRIPS];

    static String temp = "";
    static char val;
    static String strings[12];

    void setup() {

      Serial.begin(9600);
      Serial.println("Free Memory: " + String(freeMemory()));

      strips[0] = new Adafruit_NeoPixel(42, 9);
      stripIDs[0] = 1;

      strips[0]->begin();
      strips[0]->clear();
      strips[0]->show();

      control.println("Setup finished!");
    }

    void loop() {
      Serial.println("Free Memory: " + String(freeMemory()));

      if(control.available())
      {
        if(control.find('~'))
        {
          temp = control.readStringUntil('~');

          val = LEDUtils::split(strings, temp, ':');

          if(strings[0].equals("CLR"))
          {
            int8_t arrayPos = getArrayPosByID(strings[1].toInt());

            if(arrayPos == -1)
            {
              control.print("ERR:Strip ID not found~");
            }
            else
            {
              LEDUtils::clearSection(*strips[arrayPos], strings[2].toInt(), strings[3].toInt());

              if(strings[4].equals("True"))
              {
                strips[arrayPos]->show();
              }
            }
          }
          else if(strings[0].equals("ALL"))
          {
            int8_t arrayPos = getArrayPosByID(strings[1].toInt());

            if(arrayPos == -1)
            {
              control.print("ERR:Strip ID not found~");
            }
            else
            {
              LEDUtils::setAll(*strips[arrayPos], strings[2].toInt(), strings[3].toInt(), strings[4].toInt());
            }
          }
          else if(strings[0].equals("MAT"))
          {
            int8_t arrayPos = getArrayPosByID(strings[1].toInt());

            if(arrayPos == -1)
            {
              control.print("ERR:Strip ID not found~");
            }
            else
            {
              int8_t findValue = getNextAniPos();

              if(findValue == -1)
              {
                control.print("ERR:Max animations reached~");
              }
              else
              {
                uint16_t startPixel = strings[2].toInt();
                uint16_t stopPixel = strings[3].toInt();
                long updateTime = strings[4].toInt();
                uint16_t refNum = strings[5].toInt();

                uint32_t colors[val - 6];

                for(uint8_t i = 6; i < val; i++)
                {
                  colors[i - 6] = strings[i].toInt();
                }

                animations[findValue] = new Alternate(*strips[arrayPos], refNum, startPixel, stopPixel, colors, val - 6, updateTime);
                animations[findValue]->start();
              }
            }
          }
          else if(strings[0].equals("CRZ"))
          {
            int8_t arrayPos = getArrayPosByID(strings[1].toInt());

            if(arrayPos == -1)
            {
              control.print("ERR:Strip ID not found~");
            }
            else
            {
              int8_t findValue = getNextAniPos();

              if(findValue == -1)
              {
                control.print("ERR:Max animations reached~");
              }
              else
              {
                uint16_t startPixel = strings[2].toInt();
                uint16_t stopPixel = strings[3].toInt();
                long updateTime = strings[4].toInt();
                boolean fade = strings[5].toInt() ? true : false;
                uint16_t refNum = strings[6].toInt();

                uint32_t colors[val - 7];

                for(uint8_t i = 7; i < val; i++)
                {
                  colors[i - 7] = strings[i].toInt();
                }

                animations[findValue] = new ColorRandomizer(*strips[arrayPos], refNum, startPixel, stopPixel, colors, val - 7, fade, updateTime);
                animations[findValue]->start();
              }
            }
          }
          else if(strings[0].equals("TCL"))
          {
            int8_t arrayPos = getArrayPosByID(strings[1].toInt());

            if(arrayPos == -1)
            {
              control.print("ERR:Strip ID not found~");
            }
            else
            {
              int8_t findValue = getNextAniPos();

              if(findValue == -1)
              {
                control.print("ERR:Max animations reached~");
              }
              else
              {
                uint16_t startPixel = strings[2].toInt();
                uint16_t stopPixel = strings[3].toInt();
                long updateTime = strings[4].toInt();
                uint32_t color1 = strings[5].toInt();
                uint32_t color2 = strings[6].toInt();
                uint16_t tripSize = strings[7].toInt();
                uint16_t refNum = strings[8].toInt();

                animations[findValue] = new TripCycling(*strips[arrayPos], refNum, startPixel, stopPixel, tripSize, color1, color2, updateTime);
                animations[findValue]->start();
              }
            }
          }
          else if(strings[0].equals("CLI"))
          {
            int8_t arrayPos = getArrayPosByID(strings[1].toInt());

            if(arrayPos == -1)
            {
              control.print("ERR:Strip ID not found~");
            }
            else
            {
              int8_t findValue = getNextAniPos();

              if(findValue == -1)
              {
                control.print("ERR:Max animations reached~");
              }
              else
              {
                uint16_t startPixel = strings[2].toInt();
                uint16_t stopPixel = strings[3].toInt();
                long updateTime = strings[4].toInt();
                uint32_t color1 = strings[5].toInt();
                uint32_t color2 = strings[6].toInt();
                uint16_t refNum = strings[7].toInt();

                animations[findValue] = new CycleLight(*strips[arrayPos], refNum, startPixel, stopPixel, color1, color2, updateTime);
                animations[findValue]->start();
              }
            }
          }
          else if(strings[0].equals("COL"))
          {
            int8_t arrayPos = getArrayPosByID(strings[1].toInt());

            if(arrayPos == -1)
            {
              control.print("ERR:Strip ID not found~");
            }
            else
            {
              int8_t findValue = getNextAniPos();

              if(findValue == -1)
              {
                control.print("ERR:Max animations reached~");
              }
              else
              {
                uint16_t startPixel = strings[2].toInt();
                uint16_t stopPixel = strings[3].toInt();
                long updateTime = strings[4].toInt();
                uint32_t color1 = strings[5].toInt();
                uint32_t color2 = strings[6].toInt();
                uint16_t refNum = strings[7].toInt();

                animations[findValue] = new Collision(*strips[arrayPos], refNum, startPixel, stopPixel, color1, color2, updateTime);
                animations[findValue]->start();
              }
            }
          }
        }
      }

      for(uint16_t i = 0; i < MAX_ANIMATIONS; i++)
      {
        if(animations[i]->getRefNum() != 65535 && animations[i]->isStarted())
        {
          animations[i]->update();
        }
      }

      delay(1);
    }

    int8_t getArrayPosByID(int8_t id)
    {
      for(int8_t i = 0; i < MAX_STRIPS; i++)
      {
        if(stripIDs[i] == id)
        {
          return i;
        }
      }

      return -1;
    }

    int8_t getNextAniPos()
    {
      for(int8_t i = 0; i < MAX_ANIMATIONS; i++)
      {
        if(animations[i]->getRefNum() == 65535)
        {
          return i;
        }
      }

      return -1;
    }

Note that the includes above are all based on classes I designed to represent the animations, each one has some information in them like the strip to use (passed by reference), the starting pixel, stopping pixel, colors, how long there timers should wait before executing the next animation step, etc. And they are all subclasses of the parent class Animation. I cannot seem to find what is causing the garbling to happen, if I remove references to Serial and just hard-code animations in, everything works fine, and I have around 1KB of SRAM (out of 2K) for other stuff running 6 different animations on one strip of 42 LEDs. At this point I don't make it through the Free Memory println before stuff starts coming up weird and normally the Arduino will just hang and do nothing or keep transmitting the last garbled character over and over as fast as it can. Am I missing something?

title: Help with a Memory Issue

Answers: 2

body:
In short:

* Lots of `new`, no `delete`.
* Constant strings like `Serial.print("something")` can be stored in flash memory by Flash Helper `Serial.print(F("something"))`.
* Maybe too wide color spectre. You can save 1Byte per pixel if you use struct with 8b R/G/B. (or you can use even 16b depth colors - but it is little bit harder).
* And maybe, if you were storing some instructions only and prepare pixels into ledstrip directly, you can save a lot. However it takes some time to prepare it, so you have to count with it. Something like fill(color, from, to), gradient(...), move left/right...
* Using Arduino framework is memory and cpu extensive too.

Anyway crashing as you described sounds like stack overflow or memory corruption.

body: There was a very major issue with the amount of Strings I was storing in RAM. Moving Strings out of RAM and into PROGMEM using the F() macro has helped significantly. Going at things step by step helped me see where the issue was.


body:
As a project I have to build a SensorHub with multiple sensors. I am relatively new to the Arduino and circuit world, so I need a little help.

The Goal is to build hub with multiple sensors and to be able to measure power consumption of the entire thing and log the data from all sensors.

So I came up with the following part list:

* Arduino Uno (Rev3)
* Adafruit 10-DOF IMU L3GD20H + LSM303 + BMP180
* Adafruit Ultimate GPS v3
* Adafruit VCNL4010 Proximity and Light sensor
* Adafruit INA219 High Side DC Current Sensor Breakout
* Adafruit MicroSD card breakout board
* of course breadboard, powersupply, calbes, etc.

Everything is connected like this:

[![SensorHub diagram][1]][1]

My question is now if this thing will work as I expect. With the 10-DOF, GPS and VCNL4010 I'm pretty sure. They work all with I2C on different addresses and all of them need 5V.

The question is now if I can measure the needed power with this setup. Or does the INA219 need power to be able to get the power to the Arduino? Do you see any problems?

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

title: Will this SensorHub work?

Answers: 1

body: The INA219 breakout will pass current, even if it doesn't receive any power itself.


body:
I have a [Sparkfun GPS Logger Shield][1] and I want to save power by shutting it off when I do not need GPS readings. Now reading the hookup guide it says that the "EN" pin can do this: "Active-high chip-enable – pull low to reset or turn off".

I wanted to ask some advice as to what this actually means and how I safely go about it. Is it as simple as:

    pinMode(pin, OUTPUT);

    //turn off
    digitalWrite(pin, LOW);

    //turn on
    digitalWrite(pin, HIGH);

Where the pin is a digital pin on the Arduino and it is connected to the "EN" pin of the GPS shield.

  [1]: https://learn.sparkfun.com/tutorials/gps-logger-shield-hookup-guide

title: Turning my GPS logger shield off and on

Answers: 1

body:
Yes, it is as simple as that.

However, since the pin is pulled up already you could also do this:

    pinMode(pin, INPUT);
    digitalWrite(pin, LOW);

    // Turn off
    pinMode(pin, OUTPUT);

    // Turn on
    pinMode(PIN, INPUT);

That then emulates an Open Drain pin which means you're not actively driving the pin when turned on, only when turned off.

Personally I prefer system that are active low not active high, and are pulled down by default (normally off) so that you don't waste power driving the pin in order to save power (it's kind of silly really) - you drive the pin to turn on and let the pin float to turn off (especially good with deep deep comatose sleep on some MCUs where the IO pins all switch off).

However the designers of this module decided otherwise, so you're stuck with driving the pin LOW to make it sleep.


body: I am building a robotic arm using 8 servo motors. I am wondering about what voltage my external power will need to be to control all of them at 6v. I am wanting to use a rechargeable battery.

title: What power supply should I use?

Answers: 2

body:
> I am wondering about what voltage my external power will need to be to control all of them at 6v

Well that would be 6V then wouldn't it?

You're asking the wrong question. The question you should be asking is:

> How much current will I need from my 6V power supply?

And the answer is:

**Add up the total current required by all of the devices and that is the *minimum* current the PSU has to provide**

On top of that you need to consider *how long the supply should last*. The average current need to draw from the batteries, multiplied by the number of hours you need it to run for, is the minimum capacity of battery you need.

For instance, if you need to draw an average of 500mA for 6 hours then you need (0.5*6 =) 3Ah (or 3000mAh) batteries (or better).

body:
You should use a **Voltage Regulator** for a stable Voltage Output.

First you should know your **maximum Current consumption**. Lets say for example maximum 2A.

You want the Voltage of the Servos stable, so they dont jerk around when there is a voltage drop or change. Because of this reason you should use a Voltage Regulator. For this example, choose one which has a Output of 6V 2A.

For the most of the Voltage Regulators you will be safe if you calculate **an extra of 2V for the Voltage Drop**. The Voltage Drop Value is specific for every Voltage Regulator Model. You can find this Value in its Datasheet.

So you would need a Power Source, for example a rechargeable NiMh battery with 8V(6V+2V), which can supply 2A. Not all batteries in the world will be able to give you 2A, but like all of the NiMh batteries should.

You can find the exact circuit for your Voltage Regulator in its Datasheet, which most likely also will have some (optional) capacitors in it.

----------

**In Summary:**

 1. Your needed Voltage (6V)
 2. Your maximum needed Current (for example 2A)
 3. Find one Voltage Regulator with 6V and 2A Output
 4. Find out its Voltage Drop Value
 5. 6V + Voltage Drop Value = minimum battery voltage
 6. Be sure the battery can support the maximum current (2A)
 7. Design your circuit with the help of the Voltage Regulators Datasheet
 8. Calculate if you need a heat sink for your Voltage Regulator


body:
I've successfully implemented Door Unlock system described in [this tutorial][1].
At first I used Arduino Uno and RFID RC522 Reader and [MG90S Micro servo][3].

When I used Arduino Uno with Arduino Pro Micro for arduino ATmega32U4 5V/16MHz, the RFID reader stops working after plugging the servo.
Since Arduino Pro Micro have only 5V output, I used resistors to downgrade 5V to 3V in order to poser the RFID reader. I used same output 'vcc' to select 5V for the servo and 3V converted to the reader.

The problem is that each component works perfectly independent of each other, however, when I place them together they stop working.

  [1]: http://www.instructables.com/id/Arduino-RC522-RFID-Door-Unlock/
  [2]: https://www.aliexpress.com/item/86061-MFRC-522-RC522-mfrc-522-RFID-RF-IC-card-inductive-module-with-free-S50-Fudan/32433898442.html?spm=2114.13010608.0.77.NhxLQJ
  [3]: https://www.aliexpress.com/item/1pcs-MG90S-Metal-Geared-Micro-Servo-F4-for-RC-Helicopter-Airplane-Car-Boat-HB88-Free-Shipping/32652367219.html?spm=2114.13010608.0.56.NhxLQJ
  [4]: https://www.aliexpress.com/item/Free-Shipping-New-Pro-Micro-for-arduino-ATmega32U4-5V-16MHz-Module-with-2-row-pin-header/1871481789.html?spm=2114.13010608.0.143.5Ad1oD

title: RFID stops working when I place the servo

Answers: 3

body: Use a 3.3VDC regulator for your RFID board a small boxed DC-DC buck converter will be easiest, if linear use an LDO type. Ideally also use a level shifter on your data lines. This could be a resistor voltage divider or zener diode clamp at the most basic, FETs or a dedicated IC is a bit more involved but gets better results.

body:
The code you are using is not complete. You should check the second code given at [Interfacing of RFID RC522 with Arduino UNO][1]. In this second code they have a function:

> void dump_byte_array(byte *buffer, byte bufferSize)

In this funtin place your servo Motor Routines. Like when First card is detected then move serbo in one direction and when second card is detected then move your servo in opposite direction. I have tried it and it works perfectly fine.

  [1]: http://www.theengineeringprojects.com/2015/08/interfacing-rfid-rc522-arduino.html

body:
The current may be not enough. Try using [extra power supply for Servo Motor][1]

  [1]: https://arduinogetstarted.com/tutorials/arduino-servo-motor#content_additional_knowledge


body: Can I generate a PWM signal for a Mosfet driver using a saw tooth wave and sine wave through Arduino ?

title: PWM generation for inverter by Arduino

Answers: 2

body:
Currently, none of the boards have a DAC on them, with the exception of the arduino Due. Thus, Unless you have the Due board, it is not possible.
If you have a due board, and are interested in generating wave functions, then check out here: https://www.arduino.cc/en/Tutorial/DueSimpleWaveformGenerator

body:
Yes you can very easy generate an PWM Output with an Arduino:

    void setup()

    {

      pinMode(pwmPin, OUTPUT);   // sets the pin as output

    }

    void loop()

    {

      analogWrite(pwmPin, yourWantedValue);  // analogWrite values from 0 to 255

    }

> On most Arduino boards (those with the ATmega168 or ATmega328), this
> function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it
> works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8
> only support analogWrite() on pins 9, 10, and 11.
>
> The Arduino Due supports analogWrite() on pins 2 through 13, plus pins
> DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to
> Analog converters, and act as true analog outputs.

Visit [quote origin][1] for more Information.

  [1]: http://www.arduino.cc/en/Reference/AnalogWrite


body:
I am building a shield that contains an AC power supply and relay for an Arduino-like board. The problem I am having is that the relay is quite noisy with respect to EMI, and I can see a few jitters or jumps in my system during normal operation even with a zero cross detector.

I have added in another shield between the 'relay' shield and the main board, which has helped the problem by creating a larger gap, but I would like a more permanent and robust solution.

I was thinking of building a simple shield that has nothing much on it and is simply a large ground plane that sits in between the relay shield and the main board. This would be a simple solution that does not involve making any shielding cages.

This ground plane would be connect to the chassis of my device, which is then earthed.

Since the device has both a DC ground voltage (0V DC) and a AC earth (0V AC) I was thinking maybe I should use both as part of my shielding. Since the board has layers on both sides perhaps I could design it to have the side facing the relays to be earthed, while on the other side, facing the CPU, would be DC ground. I could even couple the two planes with a capacitor, if it helps.

On the one hand I think the earthed option should be fine, but on the other hand I would like to know more about using the DC ground as an EMI shield. Would the simple earth only option work? Would even a DC ground only option work? Does it help to use the DC ground as an EMI shield for the DC components or am I over complicating it?

title: Design considerations for creating an Arduino 'shield' shield to limit EMI

Answers: 1

body:
What would be helpful would be explanation of the type of AC you are using and then possibly a schematic or board layout.

That aside, there does seem to be noise between the two boards. The Idea of placing a PCB with just a large copper pour would work.

DC Ground

If you connect the DC ground from the main board you should use a `ferrite bead`(FB) between the two grounds, this will ensure that you don't get noise getting back into the ground of the main board after you have tried to shield it. You should try to match the ferrite bead to the noise frequency you experiencing (use a scope if you have one).

Using the DC ground as a shield is often done, if you look at the EMI cages on cellular phones, WiFi modules, and other noise generating devices/susceptible-to-noise devices, they are connected to ground. It gives the noise somewhere to go, instead of your signal lines. Thus using the DC ground is defiantly an option

i.e.:

    Main ground>--------[__FB__]-------<SHIELD

AC Ground

You could use the AC earth line on the top part of the shielding board. The coupling part might be a bit over kill, leave space for it to test to see if it helps when you make the board. Also AC earth can be used for shielding but is used for the safety aspect of earth leakage.

Don't do a direct *DC ground* to *AC ground* unless you know what you are doing as this will create a ground loop, this will change the way stuff behaves and will make your circuit no longer a floating device.

Other stuff

I would also make sure how you drive the relay is isolated from the control circuitry, although from what you describe:

> if I move the shield further away I also don't see the issues.

If you share power rails between the relay board and the main board, try filtering the power going to the CPU section. Also the control lines can be isolated between the controller and the relay with opto-couplers, this might stop noise coming back into the circuit from the relay part.


body:
How to produce a sine wave with variable frequency and variable amplitude?
I found a library to produce variable frequency called `sinwave` but not produce variable amplitude (I want -2V to 2V amplitude)

title: producing sine wave variable in amplitude and frequency

Answers: 2

body:
You can use a digital potentiometer as a programmable attenuator or as a feedback element in a programmable gain amplifier circuit.

See references  at arduino.cc regarding interfacing an [AD5171](https://www.arduino.cc/en/Tutorial/DigitalPotentiometer) or [AD5206](https://www.arduino.cc/en/Tutorial/DigitalPotControl) to Arduinos.

body:
Here's one solution to do it using your own code implementing the following.The basic solution is as follows.
Start with the basic sine wave output (this has amplitude between -1 and 1, and repeats ever 360 degrees) implemented as a function in your Arduino sketch with a variable parameter for the frequency and amplitude.

Now input the frequency you want (which you don't specify) and the amplitude (that is multiply your sine function by 2). The frequency can be implemented by using the delay function to output a value corresponding to the y-axis of the sine wave  at the specified time on the x-axis. You would need the y output to depend on the delay and the frequency. This is all in code so far.

The next step is to output the corresponding voltages for each point on the sine wave. To make a varying voltage you can use a digital potentiometer with a voltage divider type circuit (it's not quite an voltage divider because it needs to produce negative voltages too). Thus you just need to make your code activate the digital potentiometer at the required resistance to create the required voltage that represents the y value of that sine value at that point in time (x axis has time). This voltage divider requires some more circuity to make the voltage between 0 and -2 volts (the negative voltage depends on the time the circuit has been on or the x-axis of the sine wave). There are lots of ways to make a corresponding negative voltage (the bottom half of the sine wave).  The triggering on or off of the potentiometer is done from the Arduino thus this also controls the frequency of the sine wave.

To sum up code the sine wave in a sketch with your desired frequency and amplitude use these values and implement the discrete point on the sine wave using a (digital) potentiometer which is part of a circuit which is a variation of  the simple voltage divider (the voltage divider type circuit will implement the amplitude of the sine wave which you want between 2v and -2v). The frequency is, basically, implemented with the delay function.


body:
The XBee part of the entire thing works flawlessly no matter how things are being run.

Equipment:

 - Laptop
 - Arduino Uno
 - Sainsmart XBee Shield
 - USB XBee Explorer
 - 2 x XBee Series1 modules
 - Terminal software

What we are doing:

Send data through terminal software using "XBee 1" on a USB explorer, to remote "XBee 2" which is connected to Arduino Uno using the Sainsmart Shield. Arduino sends a reply which we see in the terminal software. (This is basically just using the two XBee modules to eliminate physical RX-TX connections in a simple point to point communication.)

This configuration works perfectly fine when the remote Arduino + XBee are powered by a USB port of a PC (doesn't have to be the same PC - tried with separate PCs, one powering the transmitter and other the receiver.)

The problem:

This configuration does not work if the remote Arduino + XBee are being powered by:

 - 9V Battery (brand new)
 - 12V, 2A adaptor
 - 5V, 2A mobile charger directly supplying through USB

BUT it starts working after pressing RESET (sometimes, very rarely, we have to press RESET 2 or 3 times but it does start working) and keeps working while the supply is not disconnected/turned off.

**Important Note 1:** As mentioned earlier, the remote XBee always works perfectly fine in all of the above cases as shorting RX/TX shows that the data perfectly and flawlessly echoes back.

**Important Note 2:** I don't think that the Arduino isn't starting up, as to check that I am blinking pin13 LED which always starts working fine in any of the scenarios listed above.

Please help. Having to RESET every time after power up makes the whole thing pretty useless for any real world application.

When I say that does not work, I mean I don't get a reply from arduino when I send a query over terminal.

After pressing Reset, it begins working, i.e. I start getting a reply.

But I don't think that Arduino isn't startup because Pin 13 LED blinks as expected which is something I put just to check whether Arduino code starts running.

As far as circuit, it is nothing but XBee Explorer USB plugged into my laptop and arduino with ready made XBee shield plugged into another USB port (which is when it works). Powering Arduino from a USB port of a different PC also gives no issues.

Only when Arduino is powered by external power source like an adapter or phone charger or 9V battery (literally tried all 3) does it not work automatically and I have to Reset the Arduino after which it starts replying.

title: XBee Shield Arduino External Power Issue

Answers: 0


body:
I am trying to write a program to control a stepper, and incorporate a selector switch and a rheostat.

The object is to make the stepper oscillate, and to be able to control the speed with the rheostat, and the amount of oscillation with the selector switch.

What would the best way to go about this?

title: Arduino IDE programming help

Answers: 2

body:
Majenko provided the correct answer in his comment: you just have to
write a program to do it! This site is not meant to provide you with a
ready made solution, but to give help if you run into an issue while
trying to _solve the problem yourself_.

That being said, before you attempt to write the program, you should
learn how to interface with the hardware you are using. Here are the
relevant Arduino tutorials:

* The [Button][] tutorial is about reading a push button, but you would
  do exactly the same to read a switch
* [Reading a Potentiometer (analog input)][potentiometer]
* [Stepper Speed Control][stepper] will teach you how to control your
  stepper motor

And then there is plenty of material available on the Web for each of
these topics.

Go through the tutorials, understand the programs given as examples,
make them work with your hardware, then put the pieces together to solve
your problem. If you run into an issue you cannot solve buy yourself,
then come back here with a _specific_ question and show us what you have
attempted so far, including code and schematic. See also [How do I ask
a good question?][how-to-ask].

[potentiometer]: https://www.arduino.cc/en/tutorial/potentiometer
[Button]: https://www.arduino.cc/en/Tutorial/Button
[stepper]: https://www.arduino.cc/en/Tutorial/StepperSpeedControl
[how-to-ask]: https://arduino.stackexchange.com/help/how-to-ask

body:
Here are the code fragments that would help you.

Connect the three wires from the potentiometer to your board. The first goes from one of the outer pins of the potentiometerto ground. The second goes from the other outer pin of the potentiometer to 5 volts. The third goes from the middle pin of the potentiometer to the analog pin `A0`.

**Here is the connection schematic:**

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

Here is the code to read the analog value from port A0:

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

    int sensorValue = analogRead(A0);

this would assign a value ranging fro 0-1023 to `sensorValue` according to the position of the Pot.

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

    int stepsPerRevolution = 200;
    //this variable holds the no of steps the motor rotates to complete a full circle rotation.

    int stepCount = 0;  // number of steps the motor has taken

    stepsPerRevolution = map(sensorReading, 0, 1023, 0, 200);

    // step 1/100 of a revolution:
    myStepper.step(stepsPerRevolution / 100);

**Here is an example program for controlling the direction of stepper using microswitches:**

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

    #define stepPin 2
    #define dirPin 3
    #define pinLimitswitchLeft 4  // these can be either left or right depending on motor wiring and dir pin.
    #define pinLimitswitchRight 5 // these switches must be N.O. types
    int stepDelay = 100; // this is the step delay in microseconds. Reduce this to speed up motor rotation and vice versa.

    void setup()
    {
        pinMode (stepPin, OUTPUT);
        pinMode (dirPin, OUTPUT);
        pinMode (pinLimitswitchLeft, INPUT_PULLUP);
        pinMode (pinLimitswitchRight, INPUT_PULLUP);
    }

    void loop()
    {
        digitalWrite(dirPin, HIGH);  // set direction pin, the direction that the motor will rotate is dictated by it's wiring
        while (digitalRead(pinLimitswitchLeft) == HIGH) // move motor until left limit switch is pressed.
        {
            stepMotor();
        }

        digitalWrite(dirPin, LOW);  // set direction pin, the direction that the motor will rotate is dictated by it's wiring
        while (digitalRead(pinLimitswitchRight) == HIGH) // move motor until right limit switch is pressed.
        {
            stepMotor();
        }

    }

    void stepMotor()
    {
        digitalWrite(stepPin, HIGH);
        delayMicroseconds(stepDelay);
        digitalWrite(stepPin, LOW);
        delayMicroseconds(stepDelay);
    }

Change the control from the control switch to the number of steps taken by your motor when the switch is pressed and it will work as you require.

**I have not included the header files.**

Please edit the program as you require

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


body:
I'm doing a little project that requires a lot of sensors. Right now I'm using 4, but i want to reach up to 60 sensors, and a minimum of 16 (for me that's a lot).
So, I have an Arduino MEGA 2560, and I'm new to Arduino (Had a little experience with PIC before).

I've started my project with buttons and leds to simulate the sensor, but my sensors work normally HIGH, and when something pass in front of it, it goes quickly to LOW and back. English is not my first language so I don't recall the name of this sensor, kind of like movement sensor(?).

A lot of stuff pass normally, up to 50/s, in front of it, so it should keep "bouncing" between HIGH and LOW. But when I changed the buttons for the sensors, sometimes my processor won't react, and I think it's because the signal goes back to HIGH before the code reads it. Maybe it's not a problem when it's sensing lot of things, but I can't test it right now with a lot of sensors, and it's not something that can keep getting errors.

So I got to interrupts, reading the awesome gammon review. I understood a lot of new things that i didn't know and I searched for a interrupt Library, but the one I found can't use too many sensors.

I forgot to tell, but I'm using a touch 2,4" shield too, so a lot of interrupts pins can't be used.

Will I be able to use all the sensors I want? If not, could I do it with 2 Arduinos and 1 screen? Am i missing something about the interrupts? Where can I find something to help me?

Edit 1: All the sensor are the same

title: Using a lot of interrupts on a single Arduino

Answers: 3

body:
For that many sensors (way more than the number of interrupts available on the chip), your interrupt service routine (ISR) will need to be able to poll the sensors to discover which one(s) caused the interrupt.

That might mean connecting each motion-sensor's output to both a latch and a many-input OR-gate to one of the interrupt pins. Your ISR would have to read the latches; set a flag for each LOW latch; clear the latches (to HIGH) and exit. The main routine would then take whatever action was needed for each sensor that had been LOW.

body:
On a *Uno*, all of the digital and analog pins can trigger a pin-change interrupt. That gives you 20 inputs straight away. The Mega also has pin change interrupts but not on all its pins. The pins that the Mega supports for pin-change interrupts are documented on the [Software Serial page](https://www.arduino.cc/en/Reference/SoftwareSerial).

> Not all pins on the Arduino Mega and Arduino Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

(Note that the Atmega2560 chip itself supports more pin change interrupts, however those extra ones are not brought out to header pins on the Arduino board).

That's still quite a few (18 if I counted correctly). Plus the *hardware* interrupt pins: 2, 3, 18, 19, 20, 21.

> Right now I'm using 4, but i want to reach up to 60 sensors, and a minimum of 16

To reach 60 you probably want an input shift register such as the [74HC165](http://www.gammon.com.au/forum/?id=11979) - you can daisy-chain them together to get lots of inputs. However you would have to *poll* to see if pins changed.

Otherwise you could use something like the MCP23017 chip, which has 16 input/output pins, and supports interrupts. You can use 4 of them (interfacing with I2C) and thus get 64 inputs. There is [a shield](http://docs.macetech.com/doku.php/centipede_shield) that has 4 of those chips on it:

[![Centipede board][1]][1]

With suitable software (see [my page about I2C](http://www.gammon.com.au/i2c)) you could configure for interrupts and read any of those 64 inputs when they change.

---

>  Do I have to keep checking all the time for every sensor one by one?

No, because you can configure the interrupts as open-drain, which means you can connect them all together (if you want to). Or, you could bring out the interrupts for the 4 x MCP23017 chips to four interrupt inputs on the Mega (that narrows down for you which chip caused the interrupt). Then you can read the chip's register(s) to find the state of the pins - either at the time of the interrupt, or right now.

However you might find that it is actually faster to just poll the chips (say) 100 times a second. There is *some* overhead to using I2C, you can also get SPI versions of that chip (MCP23S17) which would operate a bit faster.

Alternatively, the 74HC165, whilst simpler, could also turn out to be overall faster if you just poll rapidly.

---

>  And the sensor sense a lot of movement per second, won't that cause trouble for the Arduino?

You need to define "a lot" and "trouble". You won't do billions of read a second. You can probably do thousands. What would you do with thousands of readings anyway? The time taken to process them would probably be the limiting factor.

---

> At the same time I'm using a GPS, no problem for the usage of Serial and I2C together right?

No problem, because serial input is interrupt-driven. Within reason, you can do both at once.

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

body:
When you have implemented the solution given above, by Nick Gammon, it is recommendable that you try both of the solutions he provides, and use the timer circuit to time each version of the algorithm.

That is: You need to try out if the polled reading he mentions of lets say 100 times per second, or the interrupted method is the best, given your circumstances.

Reason being that if your system pulls the interrupts from time to time, lets say, each of the 64 inputs pulls its interrupt pin maybe once in 30 seconds, then you have just above 2 pulls per second to the board. That is not a lot, and checking the registers like 100 times per second (if you need time wise accuracy for instance), may prove very time consuming, as you would otherwise only run 2 interrupted algorithms per second.

Use the diode on the Arduino Mega circuit board if you have no display or output unit on the Arduino, to display the results. (If you need help communicating from the Arduino to yourself (human) via 1 diode, such that you can be told how much different a particular setup is, then let me know - that would be outside of the scope of this answer, I guess). I short, you can communicate to yourself by creating a little algorithm which starts with ie. 3 rapid blinks, then a pause, then it can create countable blinks for each figure, counting 0 with 10 blinks, and then you can count the blinks by putting breaks in between the figures. Thereby you can communicate the figure 1874 by 1 blink, pause, 8 blinks, pause, 7 blinks, pause, 4 blinks - then long pause, then 3 short blinks, pause, then it repeats.