text:
Camera VC0706 not found
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%10;
    // 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 ?


text:
Arduino Accessing a web page
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

I suspect that you may get a better answer on Stack Overflow.

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():
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: 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.

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.

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!

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)

Thanks...I have no clue how to code that. And cant find examples. Any hints?

Simply use if (String.substring(length of element data here) == "element name here") {} to find it on the webpage and then execute whatever code you need inside

what is lenght of element data representing?

Go into the source code of the website you wish to get (you know how to in chrome right?) and copy the html element which contains said text into the "element name here" part of the code and put the length (in chars) in place of the "length of element data here".

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 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. ;-)

Using a regular expression parser to find a fixed string is kind of overkill.

Just trying to make it easier for them.

Thanks. This is awsome help. Just read the readme and its brilliant but im just not getting it.  I dont know where to start

If you're trying to go from 0 to parsing a webpage with an arduino, you're pressing too hard on the gas. You need to work your way through some other examples and tutorials first, then it will all make more sense. And you'll have a lot of fun along the way.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Using softwareserial with a TFT, how can I use a variable to position cursor?
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.

Just split the print into three parts:
myTFT.print("DS32(32,");
myTFT.print(g);
myTFT.println(",'Hello!',4);");

My problem was that I didn't stop to think that the entire line being passed was a string. As soon as that dawned on me, I changed the int to a string and split it just as you showed. Worked perfect. THANK YOU!

authors: Александр Вохминцев

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Reading an MCP23S17 I/O expander port with the Arduino SPI library
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.

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).

Teensy LC pin out: https://www.pjrc.com/teensy/card6a_rev2.png

MCP23S17 datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/20001952C.pdf

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.


text:
How to expand program memory on an arduino?
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?

Considering that a fellow by the name of Petri Häkkinen put an arcade-style game on an Atmega328P, maybe you should look at saving space in your code? If that isn't practical, as some of the answers say, you can get a bigger chip with more program memory. The Atmega644, for example, comes in a DIP-chip package, amongst others.

See also https://forum.arduino.cc/index.php?topic=226465.0

can you please explain a bit more your answer ? 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... You mean that you can change or re-program de instruction memory while the program is running ?
Can the running program call the bootloader and load new instructions on a different addresses ? Won´t this age the program memory ? A different solution may be identify rutines in your program and all the "call´s" stored whith the data on a spi external memory... Thanks !

An ATmega2560 is the chip to add for more memory when you run out of program memory on an Uno.  Referring to the 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” article at learningaboutelectronics.com.

but if you free up the bootloader then how would i use the arduino IDE to program?

@qwerty10, see last paragraph of edit.   Arduino IDE supports USBASP ok.

Wouldnt it work with any programmer that can upload code to ATMEGA? Instead of only a USBASP. As I understand it itns not actually using 10 pins but a subset of those pins.

@qwerty10,  USPASP is an ISP (in system programming) programmer.  Generally, any ISP programmer  can be used to program a chip (with or without a bootloader on it) as long as MOSI, MISO, SCK, RST, VCC, and GND pins are available on the target chip.

Current Unos use the very compact optiboot bootloader. Removing it will only free 512 bytes.

@qwerty10: There are versions of the USBASP with a 6 pin connector. The 10 pin connector has 4 redundant pins.

@Edgar Bonet . I have another question Edgar. If I take out the atmega 328 chip from its socket on the Uno and replace it with using atmega8-16PU instead and I burn this 512 bytes bootloader-does that mean I can use the arduino Uno with the atmega8 like the atmaga328 (but with a subset of the features of the 328). The atmega8 is of course an older chip than the 328 but it still has same pinouts.

@qwerty10: I am quite confident it should work on the physical level. On the software level however, you will have to convince the Arduino IDE to play well with it. You may try to tell the IDE your board is actually an “Arduino NG or older w/ ATmega8”.

@Edgar Bonet. So using it as an Arduino NG with atmeg8 chip does this mean that the bootloader will set the fuses on the arduino's atmega8 to use the crystal on the arduino pcb? Or does the bootloader set the fuses on the arduino's atmega8 to use its internal oscillator? This clock info needs to be known to move  from arduino prototype to a permanent PCB version of circuit. How  much memory is left after writing bootlader to atmega8 -is it 7.5 KB instead of 8KB?

@qwerty10: Your are drifting very far from your original question. That should really be a new question.

@Edgar Bonet. I would guess, the answer as, because it pin for pin subset of the  atmega328 (i.e. the pins of the 328 can be the same as the mega8) of the uno board hence it  would require a crystal and capacitors.

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.

You mean _delay_ms().

This has the added benefit of actually learning about the mcu that you're using. The AVRs on these Arduinos are much more capable than the "standard library" would have you believe. ++

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:

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.

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...

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

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.

Perhaps fix some typos, like Wen, 3, and differnt

I mean, if you fix those typos, someone might vote up your answer...

What about a raspberry pi zero?  I have a couple and use them quite often as arduinos.

Other architectures should indeed be considered, but an embedded linux system with mandatory SD card booting like the pi adds a lot of complexity and is fragile in unique ways, even if not more expensive.  There are a lot of boards based on smaller, more highly intergrated ARM MCUs which are much more similar to an Arduino in terms of applications, while being drastically more capable.  But if you need a lot of processing, or megabytes of memory, then yes, these complexities start to be worthwhile.

I also prefer the zero because it is so flexible.  You can add more storage or embed it in projects while also having a large enough processor to do pretty much anything.

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.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Wifi networking with ESP8266 (NODEMCU version)
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.

If you are programming in Lua then we do not know. I do know that it is possible to program (using the Arduino IDE plugins) the NodeMCU as a WiFi access point, and the SSID etc are up to you to select when you write the sketch.

Why did you tag your question "arduino-uno"? I see no Arduino UNO involved here, not even any Arduino at all. Could you describe your circuit? If there is no Arduino, then this is not a question for this site.

Sorry it seems my question is not clear. I will modify it.

That's a little better.  But you should provide the details of the sketch you loaded, and what you expect it to do, especially network wise.  If you have not loaded one yet, then that should be the obvious first step.

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.


text:
LED pin 13 not flashing properly
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.

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);
}

Thank you! But, I'm pretty new to C code. Could you explain const int8_t or should I learn later? Also, you changed the baud...?

@Roman int is likely to be 16 or 32 bits (can't recall off the top of my head). IIRC the size of int may vary depending on the compiler you're using. Using int8_t guarantees an array of 8 bit ints, saving quite a bit of space. You're likely to have plenty of space at first, but eventually you'll write a large program and need to squeeze out every wasted byte you can just to fit it on the mcu.

Specifying 'const' informs the compiler that these variables are not meant to be changed (once initialized) and enables the compiler to check for and enforce that.


text:
use more no of batteries for more current for servos,why using motor shield?
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?

Questions on this site must be clearly stated and specific.  Perhaps you should read a bit about the difference between radio control type servos which have their own drive electronics, vs. DC motors that do not and so need external drivers.  Also you cannot simply connect more batteries to most servos - they have voltage limits!

Because science.

Possible duplicate of What is the advantage of using a motor shield if I want to use a stepper motor?

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.


text:
Do I need to supply the 12V connection to an HDD
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.

Which hard drive? Are you planning to use it as a mechanical device, or to actually read/write to the disk?

@NickGammon Any ATA Compliant HDD, I plan to use the hdd as an hdd, but currently am having issues with power supply. At the moment, I'm working with an IDE, but may move to a SATA if I don't have enough pins

The hard drive lists what voltages and currents it needs on the casing.

@IgnacioVazquez-Abrams Yes, the standards indicate that there will be a 5V supply needed and a 12v. What I want to know is whether the 12v supply is crucial

Have you looked at the hard drive? On its casing?

Yes, it says 12v and 5V. The ATA standard has two inputs for power, one at 5V one at 12V. I'm not asking what the voltages are, I'm asking what the 12v supply is for, and whether I need to power it

This would depend on the drive.  Since you won't state a specific one, it is off topic as too broad.  But regardless, it is off topic because this is the Arduino site, not the hard disk drive site.  Also, you aren't going to talk SATA with an Arduino.  But you can get away with using only 8 of the 16 bits on the IDE bus, if you are willing to waste half the capacity, as the commands are only 8-bit.  For anything practical, SD cards will probably serve you better, if not you should probably look at something better than an Arduino.

but may move to a SATA if I don't have enough pins That's a laugh for a start...  Do you even have the slightest clue about hard-drive interfacing and protocols?

I would love to see you try and generate a 1.5Gbps LVDS signal from an Arduino... and that's just for the old-fashioned SATA-1.  It's 6Gbps these days...

The "sensible" option would be to get a USB Host Shield and a USB to SATA adapter cable.

An SD card is much more practical if you just want to store lots of data. With a $15 (or so) interface board you can connect the card to your Arduino using SPI and have gigabytes of storage space.

@Majenko Not much, but I'm reading the ATA standards at the mo

Also, the point of this is not using the HDD as such, it's the challenge of interfacing with it. If it's difficult, all the better

Judging by my old copy of "Upgrading and repairing PCs" - which I found a quote for on Google Books - 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.

Thanks, answered the question clearly and succinctly. Without casting aspersions on the idea itself

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 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.

Yes, I'm currently working with an IDE HDD, which is PATA.


text:
How can I replace pulseIn with interrupts?
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?

This page explains Arduino interrupts really well:
Interrupts by Nick Gammon also see this: answer on StackOverflow

Start by studying NewPing; https://bitbucket.org/teckel12/arduino-new-ping/downloads.

Note that you can remove both if-statements. Since the while loop before it will only exit, if the condition inside the if-statement is true. Also work on proper indentation. It makes your code a lot easier to read.

First, remove the delay() from your code. The whole purpose of all this is to make the thing non-blocking, and you are completely defeating this with delay(): Not only will you have a terrible resolution of only 2 ms, you may miss the pulse altogether. Second, your pin assignments look dubious: you tagged the question “arduino-uno”, but there are no pins 22 nor 24 on the Uno.

@EdgarBonet I removed the delay and it works! I don't think it makes a difference on which board I tried it. I changed the tag know to arduino mega. Since the speed of sound is 340m/s, if an object is one meter away, it will take 2.9ms for the pulse to arrive. Therefore 2ms delay was indeed a terrible idea.

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”:
/*
 * 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.
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().

Sorry for not checking out your answer in a while. I tried using the function you wrote in my code and the sensor gave back no values. I posted the code above in my question. Can you please take a look at it? Am I calling it at a wrong time?

@Edgar Is there any close example for us to try the input capture ?

@Shahabaz: I have no example at hand, but you can do a search for “input capture Arduino” or “input capture AVR”.

I posted a question and got answer as well. If incase anybody is looking for it https://arduino.stackexchange.com/questions/71434/implementing-plusein-using-interrupt?noredirect=1#comment155354_71434


text:
Power measurement on Pins
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. 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?

"We have to measure the power consumption of the Arduino AND all the sensors."  and "But this only gives the total consumed power of the Arduino and the sensors." So what's the problem?

For these sensor most/all pins are just for communication, so they hardly use any power. The only pin of interest is Vcc. You can deduce the power usage by temporarily removing the sensors, and seeing how much the current is reduced (though this can be inaccurate, as the arduino may behave differently when a sensor isn't present). Or connect the current sensor between Vcc on the Arduino, and Vcc on the sensor. You can also, just get the approximate values from the datasheets.

You can put a 1Ω resistor in series with each of the 5V supplies to all the sensors, then link the sensor side of each one to analog inputs on the Arduino. Measure the voltage drop, and there's your current.

@JRobert: 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.

adur, are the measurements to be made by the program using analog input pins, or by a person with a DVM?

"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.
.

Okay, thank you. That is what I was afraid of. But I think I will stick to this solution. Tank you :)


text:
Combine DHT22 and SI114X.h
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:

// 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.

Just a little question, are you getting accurate readings using the DHT22? What resistor value are you using?

The readings are accurate. I'm using the grove sensor so not resistor required (I assume) : https://www.seeedstudio.com/Grove-Temperature%26Humidity-Sensor-Pro-p-838.html.

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.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
DHT22: Library and Data accuracy
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

Did you try other libraries?

Did you try connecting the resistor?

Yes, when I tried other libraries, similar results giving me low humidity level.
I did not try the resistor. Is it mandatory?

have the same problem <20% and in real its 68%

For the DHT units (11 and 22 and AM2302) you want the Adafruit_Sensor and DHT libraries.  Have you tried those?  Plus, it would be very helpful to see your code in a question like this.


text:
How can a USB keyboard emulator (TrinketKeyboard) type Unicode characters?
I've got an Adafruit Trinket microcontroller set up using this USB keyboard tutorial, 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.)

Doesn't seem to be possible without the Unicode hex input setting.

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.

OP specifically mentions MacOS

Then it's anyone's guess what the keyboard combinations required might be then. Maybe something with the apple key (which is the same as the windows key). Either way the answer still stands - you have to find out the correct key sequences and send them as individual sequences.

If that involves making a change to the settings on the OS then that is what you have to do. There is no "magic wand" to type something that cannot be typed.

You could hack it.

Make it press CMD+SPACE
type terminal.app
press ENTER
type  echo -e
"\xC2\xAF\\_(\xE3\x83\x84)_/\xC2\xAF" | pbcopy
press ENTER
press CMD+Q
press CMD+V

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

That's just plain nasty...

@majenko ¯_(ツ)_/¯

He has a broken arm... ):

@majenko I did copy paste it. If I try to edit the comment it's still there. So SO is doing something weird. Extra nastiness for free. (-:


text:
Is Arduino stable enough to use it for a door lock?
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?

If you use the watchdog timer, I'd trust the Arduino part. I would be more worried about the mechanical parts. Just make sure you have an alternative way of access. Just like the digital vaults that still have a key.

About safety: in case of power out, will your door be left open or closed? And if closed, do you have a way to get out, for example in case of fire? Sorry for offtopic comment, but it might be a case of life and death for some.

@Molot in case of fire maybe I could prepare a mojito and enjoy the temperature

IMHO, manage your security and access to vital things only with really reliable and unaffected by external events systems, as a well-oiled good-quality mechanical door lock. Sorry to write that in an arduino post.

Software/hardware stability aside, you may want to check with your insurance company to ensure that they regard your setup as something that qualifies as a "lock". In case of a break-in, you need to be sure your insurance won't be void because "your door was not locked".

If this is intended to be secure against an actual attempt to break in, make sure the electronics are far enough away from access and that the connection to the lock is protected. Otherwise, a simple high-voltage discharge to the lock could fry the CPU and possibly trigger an unlock.

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 I use a Uno (and some additional parts) to unlock my door.
Since writing that I improved the software as described here so you can reprogram the valid list of cards "on the fly" (without uploading new code) as the valid cards are stored in EEPROM.

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.

Pretty useful info. +1. Source is nice and simple. Just to be clear; do you feed that Uno 5V to the 5V pin? What's the power supply for 5V?

@user2497 - the Uno is powered by a 12V wall-wart. That gives 12V on Vin which is used to activate the door lock (it is a 12V model). The Uno itself has a voltage regulator on-board which drops the 12V to 5V for the logic circuits.

Oh, I thought I saw 5V to the MCU. I use 7808s between 12V and Vin now, since I had a few devices die on me. What's your secret - do you heatsink those tiny regulators?

@user2497 - the current consumption of the logic (Uno) is low. The door lock doesn't go through a regulator.

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.

But not on the last day of leap year?

As far as Water ingress goes, look for enclosure's and connectors rated IP67 or better.

@MichaelKaras - very amusing!

@MichaelKaras That's the routine maintenance day :)

@BigHomie IP67?!?! Only a few months ago everyone was trying to migrate to IPV6!  Just shows you how fast the internet moves...

I had a similar system running for my garage door for about six years without incident. It only died when lightning struck the fence next to it. Planning for lightning is harder..

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.

Not to mention, try explaining to your insurance agent that the reason your house was broken in to was because you screwed up a pointer reference that caused your door to unlock at midnight. :) It's better to leave it up to a commercial lock—one that has been tested. The mere fact that the OP is questioning the board and their skills may suggest that they should get something already built, at least for securing their home.

The prices for the originals (Genuino here) are too high. Tell me how they are more reliable.

The last commercial lock I tried took almost a full minute to tell me anybody was at the door because it took a 27,000km detour to Amazon's servers first. Popular product, rhymes with bling, but was certainly not.

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.

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.


text:
Arduino Keyboard - print() works but println() does not
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) 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.

There are semi colons missing at the end of the print statement, is that just a typo?

How are you receiving this?   It may well be that the keyboard emulation is in fact sending a return or newline, and your receiving program isn't interpreting that in the way that you like.  That "." in your received output could be a control character, try to get a hexdump or better yet, look at raw scancodes rather than character interpretations.  Also look at the documentation (or failing that sourcecode) and see if the println() method is documented to do anything useful for this class.

@ChrisStratton You can see the periods in the output in my input, and the periods don't have any effect on this bug. If I leave them out, we still get no newline/carriage return.

@ChrisStratton I've added a link to the println docs in the question.

Again, state how you are capturing the output

@ChrisStratton The output is keyboard commands outputted to the computer the device is attached to (like a standard Arduino keyboard). I'm using OS X TextEdit. When it works (as it has before), you get Hello world. and the cursor moves to the next line. Now that it isn't, the cursor sits at the end of the statement.

I've never had this issue before and I've been playing with it for months. - on the Yun? It's been working for months and now it isn't?

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

Also try on another PC. It is possibly a configuration issue on OS/X. When it works ... you get Hello world. and the cursor moves to the next line. - the library hasn't changed, right? So maybe the testing environment changed.

@NickGammon That works. println still doesn't.

@NickGammon Yes, on the Yun. I had it working but now it isn't - I honestly don't know why. There is one thing that may be relevant - I'm going to include it in my question now.

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:
#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.


text:
How can I determine how many bytes an I2C master read from my Arduino acting as I2C slave?
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?

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.

I understand that the protocol doesn't specify that. I'm interested in getting the number of bytes that were actually sent by the slave until the master sent a NACK instead of an ACK, as I specified originally in the question (be it through another callback, by calling a Wire function, etc), after the send actually completes.

*actually completes at the physical level, after the master sends the NACK.

You have no access to that level of information through the API. You can count how many times your callback is called, but that's as close as you get. You would have to work out some way of knowing what is the first transfer though.

You would have to work entirely at the register level and implement your own I2C code.

OK, that clarification answers the question perfectly.


text:
How should I organize a 3-day Arduino beginners course?
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.

Alphabetically (case sensitive).

This question is being flagged as too broad, and I don't blame them. This isn't a site for suggesting a syllabus for a course. Good luck with the fair, I hope it goes well, but questions here need to be more focussed. See What types of questions should I avoid asking?. There doesn't seem to be a problem to be solved, as such.

Introduction, Blink, Serial, ADC, servos, more LEDs, I2C sensors / libraries, (WiFi with ESP?)...  You can pick some Starter Kit Manual for instpiration.

Good point @NickGammon. I would also question if the OP needs to ask this question are they qualified to teach the class. I am not trying to be mean, but I know the following to be true: to know how to do something is one thing, to teach it, is another. You need to know all about AVR and c/c++. You need to know the material inside and out.  However you may be prepared to do so. Either way, good luck.

well, I do know the stuff, as I am graduating from Control Engineering, and I am a teacher on other subjects already, so I was mainly wondering if there was any shortcut anyone more experienced could give me. I'll plan a little bit more and when my question becomes more specific I can edit it. Also, I couldn't find any tags for education, teaching, etc, so maybe that's an area not discussed much around here. Or I didn't look up in a proper fashion. Thanks, anyway!


text:
Help with a Memory Issue
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?

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.

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.

See but that's the thing, I have code extremely similar to this, it makes use of BOTH SoftwareSerial and Serial to control a Bluetooth module and provide constant debug feedback when testing. That code runs no problem, this code, which is broken up into classes, not separate methods like the Bluetooth code is, is what's having the issue. In fact, the Bluetooth code on compile time uses more memory by default, I would think this code would at the very least run, because initially nothing beyond some pointers, text, and the same strip used for the Bluetooth code are being loaded into memory.


text:
Will this SensorHub work?
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:

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?

By “measure the needed power”, do you mean like with a DVM?  That is, by manually taking meter readings of currents and voltages?

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

So, do you think this will work?

The current sensing part; yes. I haven't really looked at the rest of the circuit.

Okay, thank you. Let's see what others say to the remaining parts :)

Well, in the schematic both the red and black wire are connected to the GND pin on the INA219.

I was a bit worried about the I2C pull-up resistors on the boards, as  the INA pulls up to 5 volt and the other two boards run on 3.3V. But the VCNL doesn't mind 5v on it's I2C pins, even though it runs on 3.3V. And the 10-DOF uses a buffer between the chips and the I2C pins on the breakout. So that's fine too.

Marked this answer as solution since the solution is in the comments. Thank you :)


text:
Turning my GPS logger shield off and on
I have a Sparkfun GPS Logger Shield 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.

Please note that when the GPS is turned off, it is not tracking satellites. That means that when you turn it back on again, it doesn't have the faintest idea where it is. To find out, it has to listen on all channels looking for one satellite to at least tell it what time and date it is. Once it has that, it can start to calculate satellite orbits and guess as to which satellites are where. As it gets more and more information, it will finally start to resolve its location. According to the GP3906 datasheet, this can be as much as 35 seconds from Cold.

Yeah, I figured it would require a little run up time to determine where it is. I also have a GPRS module that will also need a run up time to obtain signal. I was planning to test out a number of different wake times to ascertain an effective, but still short duration.Thanks for the extra detail on the 35 seconds for this GPS module, that should come in quite helpful!

Take a look at SparkFun's datasheet. It's got all sorts of info: https://cdn.sparkfun.com/assets/learn_tutorials/4/6/8/GP3906-TLP_DataSheet_Rev_A01.pdf

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.

I'm just trying to understand your example and how an open drain works. So an INPUT of LOW is pulling down (0v)? How is an OUTPUT of LOW pulling up?

Sorry, other way around (coffee hasn't kicked in yet).  Output of LOW pulls down. Input of LOW floats (internal pullup disabled) allowing module's pullup to pull it high.

Ok that makes a bit more sense to me! Where you say 'internal pullup disabled', is that something I actively have to do?

I think I found the relevant information with the fact that using pinMode INPUT automatically disables the internal pullup.

INPUT with the output LOW has the pullup disabled. INPUT with the output HIGH has the pullup enabled. Or INPUT_PULLUP is the same.

When the pin is set as an input, it can be set to have a pullup or not to have a pullup. The difference is whether you pass INPUT or INPUT_PULLUP to pinMode()


text:
What power supply should I use?
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.

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).

It's not quite that simple as the loads will be highly variable, and the goal is a battery pack.  Fortunately, RC servos are designed to run on 4 NiCd cells, and those handle high temporary current from moving stalled servos pretty well.  So pack sizing is really more about how long it needs to work.  The question for the MCU is then a distinct supply, running it at 3.3v or so to leave headroom for dips under load, or a boost converter.

You may wish to consider how long youre using the rechargable battery. Basically ,since youre using rechargables you may want to consider how frequently you will need to recharge your batteries,  the more electrical power your using at once (e.g. every second)  the quicker your battery will run out and thus you may need to recharge it more.

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:

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

Actually RC servos are designed to run directly from an unregulated 4-cell battery pack, and they do not "jerk around" as a result - otherwise the planes would unintentionally.  That's the easy part.  The challenge is the arduino.

Am I missing something?-is he using RC (radio controlled servos) for a (air) plane - to make a robot arm?  It just says in the question hes using servos

Yes I am using an Mini Gear Micro 9g Servo Motor said to be for RC Helicopters, Airplanes, Cars, Boats, and Robots to make my robot arm. And  I am only wanting to be using the robot arm for around 10 minutes since I am not building the final project. @qwerty10

The servo motors' operating voltage is 3.0v~7.2v. @qwerty10


text:
RFID stops working when I place the servo
I've successfully implemented Door Unlock system described in this tutorial.
At first I used Arduino Uno and RFID RC522 Reader and MG90S Micro servo.
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.

Which voltage did you "downgrade"?

5v to 3v, so I can power the rfid reader

With resistors?!?!

I'm newbie in electronics.
What is the correct way to do it ?

With a voltage regulator. Resistors cannot do what you want.

so, when we use resistors ?

You use resistors when using resistors is a viable option and when the circuit demands resistors. They are not, can not be, never will be, nor ever have been, a way of changing a power supply voltage.

I found that this is possible:https://www.youtube.com/watch?v=zrq4n5tOoTI

The magic words there are written on the paper: "Logic to convert". It's only for changing logic levels not for converting power. If you try drawing more than a couple of microamps the voltage will rapidly drop to nothing.

https://hackingmajenkoblog.wordpress.com/2016/08/30/why-you-cant-use-resistors-as-a-voltage-regulator/

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.

The code you are using is not complete. You should check the second code given at Interfacing of RFID RC522 with Arduino UNO. 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.

The current may be not enough. Try using extra power supply for Servo Motor