message:
Controlling a digital 12V addressable RGB led strip with Arduino?

I have a 12V addressable RGB strip that I want to control with an Arduino, the chips are ws2811s, is there a way to do this as the Arduino is 5V and 3.3V?

body:
<s>The only signal you need to worry about is DIN (data in) which is normally 5V from an Arduino. Use that to switch a MOSFET or transistor to convert the digital pulses to 12V. In other words, the Arduino switches the transistor, the transistor outputs 0 or 12 V.</s>

---

Judging by [this link](http://doityourselfchristmas.com/forums/showthread.php?23588-WS2811-5050-Pixels-at-12v-Signaling-at-5v) you still just send 5V digital switching to the strip.

> The data signal never needs to be 12 volts. The 12 volt pixels all drop the voltage down to about 5 volts to operate the chip. Usually just a resistor and a zener diode, sometimes just a resistor.

In other words, connect the "power" pin to +12V, and the ground pin to Gnd from your power supply.

Connect the Din (data in) to your Arduino pin directly. Of course, *also connect the Arduino ground to the ground pin*.

---

Also see [this Youtube video](https://www.youtube.com/watch?v=pu1kzJGMZyA). On the comments he says:

> These 12v WS2811 "pixels" still use 5v signalling. You simply connect the 12v source power directly to the strip, tie the ground to the arduino and then treat them as if they were a 5v strip.


sender: user

message:
How many sensors can be supported by a single Arduino unit?

I am a beginner in the Arduino world. I made some basic projects of the book that comes with the starter kit (it's was borrowed by a friend of mine) and also I used a humidity, a temperature sensors and a LCD display.

I want to buy an Arduino Uno for measure **room temperature, humidity, carbon monoxide, carbon dioxin and maybe a couple more variables. I will to use 4 sensors, 1 buzzer, 1 LCD display and 1 ESP8266 serial WIFI wireless module**.

After this work I will add for functionalities but as I have a lot of components I am not sure if the Arduino Uno can supports them because it has a limited quantity of pins.

Do I need an Arduino with more pins? what if I use all these pins and I need more? Can the Arduino Uno be expanded with more pins?

As the Arduino Uno is a very small computer, can its processor support all these components and their operations?

sender: assistant

body:
I think you want to know how many sensors 1 Arduino can support.  But just in case, I am answering both interpretations of the title of your question:

 1. How many different types of sensors can an Arduino support?:

With the correct software and hardware, the Aruidno can interface with almost any kind of sensor.  The exceptions include but are not limited to sensors which produce more data than an Arduino can process (such as a video camera) or sensors that require fast responses (such a time of flight laser distance sensors (LIDAR)).

 2. How many sensors can an Arduino support at the same time?:

This depends on what processor resources are needed.  If the sensor needs the ADC there 6 channels on most Arduinos.  If you need more, there are hardware solutions.  But many here have suggested to simply add a 2nd Arduino.

To specifically address your laundry list:

> room temperature

Thermistor connected to ADC.  But most are not linear, so you will have to create a look up table.

> humidity

I think there is a SPI module on the market to do this.

> carbon monoxide

These sensors usually require an amplifier.  And change with age & temperature.  So a lot of software here as well as hardware.

> carbon dioxin

Not sure about this one.

> buzzer

Self osculating? Then you only need a logic output.

> 1 LCD display

Alpha & numeric? Most have 4 or 8 pin Hitachi interfaces.  But you can look for a SPI or serial port LCD so as to conserve on Arduino pins.

> ESP8266

This is just a serial device.  You will need the Ardino's serial port.

I'll leave it up to you to make a detailed assessment of the necessary processor resources.  Because you need to first pick out the specific hardware you will be using.

That's half the battle.  The other half is verifying the libraries for all these sensors and communication devices will not interfere with one another.  That I will leave up to you as it is not an easy task to wade through all the code for all the different libraries you will be using.  And, again, until you pick out exactly what sensors and devices you will be using it is impossible to even start analyzing as we wouldn't know which libraries to look at.


body:
The question itself is a bit broad, but I'll try and provide some insight here.

The number of sensors that can be supported, and the number of pins they require, will depend on what sort of interface they use.

 - If your sensor has an **analog** interface, you will need an analog input pin for each sensor.
 - If your sensor has an **I2C** interface, you can have multiple devices sharing the same pins (a bus) provided that they have different I2C addresses (often configurable with jumpers on the device).
 - If your sensor has an **SPI** interface, you can have multiple devices using the same pins (a bus), except that each will need a _chip select_ PIN connected to a digital I/O pin on your Arduino so that it can 'select' each device.
 - If your sensor has a **serial** interface, you can generally only have one device.

To add complexity to the problem, you can get expansion modules for the Arduino that will give you extra analog pins or other communication interfaces.

With the long list of sensors you have above, you may also be hard-pressed for program space, as most sensors will need code and/or libraries to interface with them. The Arduinos with more pins (such as the MEGA) also have more program space.

I would encourage you to do some further research on the sensors you want to use, and finding out what interface they use, and what Arduino libraries are available for them. This way, you can fully understand the requirements and limitations of any parts you want to use.

Further reading:

 - https://www.arduino.cc/en/Reference/Wire (I2C interface)
 - https://www.arduino.cc/en/Reference/SPI (SPI interface)
 - https://www.arduino.cc/en/Reference/Serial (Serial interface)
 - https://www.arduino.cc/en/Guide/Libraries (Using libraries)
 - https://www.arduino.cc/en/Tutorial/HomePage (Arduino tutorial)


body:
An Uno has more than enough pins for the devices you described.

 - A DHT22 Relative Humidity and Temperature sensor needs only one digital pin for both variables.
 - An MQ-7 Carbon Monoxide sensor needs one analog pin.
 - An MG-811 Carbon Dioxide sensor needs one analog pin (and an amplifier).
 - A Piezo buzzer needs one PWM pin.
 - The LCD with a Hitachi interface needs four digital pins.
 - The ESP module needs two digital pins.

That's 7 digital pins, one of which needs to be a PWM pin, and 2 analog pins. I did not make any choices about best or cheapest devices, just ones I either knew about or could find quickly by searching. But with this pin requirement doesn't come close to exhausting the available pins on an Uno so there's plenty of capacity left unassigned for you to make other choices that might require different interfaces or more pins.


body: Look at the MUX Shield, I just used one to add 48 Inputs to a MEGA making it capable of having 98 Inputs or Outputs


message:
Should I buy a retired Arduino?

I am a beginner who would like to buy an Arduino Yún (58 dollars).

It is retired so will I have any problem?

Else I can buy an Arduino Uno and an Arduino Yún Shield. But in this case I don't understand the difference between an **Arduino Uno + Arduino Yún Shield** and an **Arduino Uno + ESP8266 serial WIFI wireless module**.

Arduino Yún Shield: I can't find the price. I only found an Iduino.
[![Arduino Yún Shield][1]][1]

ESP8266 serial WIFI wireless module: 7 dollars.
[![WiFi Module - ESP8266][2]][2]

  [1]: https://i.stack.imgur.com/QnX0E.jpg
  [2]: https://i.stack.imgur.com/LTufu.jpg

body:
It is retired so will I have any problem?

It depends on what you want to do with your arduino. If you need a project that requires future support then dont buy a retired board. If you just want to do basic beginners stuff (like blinking LEDs, controlling motors, sending serial information wired or with an add on shield to send wireless information)-then any arduino can do these basic projects and probably at a cheaper price than 58 dollars.


body:
When a board is retired, it may:
- get no support (never had support from Arduino zelf though)
- not be readily available.

Which may or may nog be a problem.
The biggest problemen with retired boards is that they often didn't sell very well.

So they may:
- target niche applications.
- not have a lot of people post tutorials on it.
- not have/get elaborate answers on Arduino.se

I believe you should only get something that fits your needs.
Usually you van get away with an Uno, and since there are millions if (beginner) tutorials, i'd pick that as my first Arduino.

If you want to do anything more "pc-like" like USB, camera or a "server", my first pick would be a raspberry pi.
Also, since there are hundreds of tutorials.
You can choose to do it with a yún, and it may work, but you should check if there are tutorials/documentation for whatever you'd like to do with it.


body:
The question of the Arduino Yun being retired can be answered here:
http://www.arduino.org/forums/yun/retriered-boards-894?p=3495&hilit=Retired#p3495
At least regarding Arduino.org the answer is no. The Yun is **not** retired.


message:
Arduino project feasibility

*<sup>**Question completely rewritten**</sup>*

Trying to assess an Arduino project feasibility. New to Arduino... but did a lot of controller programming (assembly), Roboteq (C) and Phidgets (C++) , using various kinds of motors and sensors ; and reading the Arduino documentation makes me feel confident interfacing and programming shouldn't be an issue.

However, before investing time (and some money) in the project, I thought it'd be better to ask here if Arduino is the right choice, considering

- a non-latching [Hall sensor](https://en.wikipedia.org/wiki/Hall_effect_sensor) is to be connected to Analog 0, `analogRead()` to return a [0,1023] value, used as a proximity sensor. This should be straight forward.

Question →

- while the Arduino runs my program, and is still connected to the PC (USB), is it possible to synchronously or asynchronously send commands from the PC to the Arduino. I.e. can the Arduino poll if there is something coming from USB (synchronous), or is there a way for the PC via USB to have Arduino do something (asynchronously)?

Thank you.

body:
It's perfectly doable. As Chris Stratton puts it, it's all about
implementing _non-blocking_ serial communication:

* whenever you receive a character, you store it in a buffer
* whenever you have a complete command in the buffer, you process it and
  reset the buffer

For a line-oriented protocol, it may look something like:

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

    /* Process incoming characters if any. */
    while (Serial.available()) {
        static char buffer[BUF_LENGTH];  // incoming command
        static int length = 0;           // command length

        int data = Serial.read();
        if (data == '\r') {              // complete command
            buffer[length] = '\0';       // terminate the string
            if (length)
                exec_command(buffer);    // process
            length = 0;                  // reset buffer
        }
        else if (length < BUF_LENGTH - 1)
            buffer[length++] = data;     // buffer incoming character
    }

For a more complete example, you may want to take a look at this [simple
Arduino command line interpreter][interpreter]. You connect a terminal
emulator to the Arduino at 9600/8N1, type the "help" command and it
displays:

    mode <pin> <mode>: pinMode()
    read <pin>: digitalRead()
    aread <pin>: analogRead()
    write <pin> <value>: digitalWrite()
    awrite <pin> <value>: analogWrite()
    echo <value>: set echo off (0) or on (1)

You can use it as a template, replace existing commands or add new ones
(the interpreter is just a long `if ... else if ...`) and – since
it's all non-blocking – add whatever you want to `loop()`.

[interpreter]: https://gist.github.com/edgar-bonet/607b387260388be77e96


message:
A more elegant way to deal with timers without using delay()?

I am looking for a more elegant way to write a function that performs timer-based tasks as in the case of the code below, which essentially collects 5 sample values from a microphone module over a given period of time and then computes their average. It is important that it does not use the `delay()` function because other tasks are supposed to run in the background which should not be affected by the delay.

      int sensorPin = A0;
      int ledPin = 13; //  pin for the LED
      int sensorValue = 0; // variable to store the value coming from the sensor
      unsigned long timer;
      int interv = 50;
      unsigned long sampleArray[] = {0, 0, 0, 0 , 0};
      unsigned long millisaver;

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

      }

      void loop ()
      {

        if (millis() > 2000) {
          if (millis() < 2050) {
            millisaver = millis();
            timer = (int) millisaver;
            Serial.println(timer);
          }
          if ( millis() > timer && millis() < timer + interv ) {
            sampleArray[0] = sensorValue = analogRead (sensorPin);
          }
          else if ( millis() > timer+interv && millis() < timer + interv*2 ) {
            sampleArray[1] = sensorValue = analogRead (sensorPin);
          }
          else if ( millis() > timer+interv*2 && millis() < timer + interv*3 ) {
            sampleArray[2] = sensorValue = analogRead (sensorPin);

          }
          else if ( millis() > timer+interv*3 && millis() < timer + interv*4 ) {
            sampleArray[3] = sensorValue = analogRead (sensorPin);

          }
          else if ( millis() > timer+interv*4 && millis() < timer + interv*5 ) {
            sampleArray[4] = sensorValue = analogRead (sensorPin);
          }
          else if ( millis() > timer+interv*5) {
            unsigned long averageVal = (sampleArray[0] + sampleArray[1] + sampleArray[2] +sampleArray[3] + sampleArray[4])/5 ;
            Serial.println(averageVal);
            millisaver = millis();
            timer = (int) millisaver;
          }
        }
      }

body:
You need to make a function which is pretty much completely self contained. Within the function should be a counter so it knows which sample it is on, and a timestamp to know when it should next run. The function should also inform the caller when it has a full sample set to process.

I haven't tested this (don't know if it even compiles) but something like this might work:

    bool getSample(uint8_t pin, unsigned long *samples) {
        static uint32_t ts = millis();
        static uint8_t sampleNumber = 0;

        if (millis() - ts >= 50) {
            ts += 50;
            samples[sampleNumber++] = analogRead(pin);
            if (sampleNumber == 5) {
                sampleNumber = 0;
                return true; // We have 5 samples
            }
        }
        return false; // We don't have 5 samples yet.
    }

    // ... later ...

    if (getSample(sensorPin, sampleArray)) {
        // Process Samples
    }


body:
For excact timing there is feature called ADC Auto Trigger mode. For example millis() are usually counted by timer 0 overflow (on AVR based Arduinos) every 1024us (I suppose it's because of PWM - otherwise it could be set exactly to 1ms). So if you don't mind that little offset, you can configure
ADC with Timer 0 Overflow and use every 20 measure only.
But don't forget that analogRead on another pin changes ADC channel and you will get something else if you don't check it.

As an auto trigger source can be used one of these:

* Free Running Mode
* Analog Comparator
* External Interrupt 0
* Timer/Counter 0 Compare Match A
* Timer/Counter 0 Overflow
* Timer/Counter 1 Compare Match B
* Timer/Counter 1 Overflow
* Timer/Counter 1 Capture Event

For ATMega328 it can be something like this:

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

        // ADC setup is done by arduino framework, but it's possible to change it slightly (for ATMega328) :
        ADCSRB  = _BV(ADTS2); // ADTS2..0 = 100, Timer 0 overflow as trigger source
        ADCSRA |= _BV(ADATE); // enable auto trigger mode
        ADCSRA |= _BV(ADIF); // reset conversion interrupt flag (by writing log 1)

        analogRead(A0); // dummy read to set correct channel and to start auto trigger mode
    }

    int8_t sample_count = 0;
    int8_t sample_index = 0;
    uint16_t  samples[] = {0, 0, 0, 0, 0};
    uint16_t sample_sum = 0;

    void loop() {
        if (ADCSRA & _BV(ADIF)) {
            ADCSRA |= _BV(ADIF); // reset ADIF flag by writing logic 1 into it (mentioned in datasheet)
            if (++sample_count == 20) {
                sample_count = 0; // reset sample_count, as we wan't every 20th

                sample_sum -= samples[sample_index];
                samples[sample_index] = ADC; // read value
                sample_sum += samples[sample_index];

                if (++sample_index == 5) { // reset index and count and send average
                    sample_index = 0;
                    Serial.println(sample_sum);
                }
            }
        }
    }


body:
You didn't say what you want to do with those samples. If you want to
estimate the level of sound intensity, your whole approach is completely
wrong. First, your sampling rate (20 Hz) is way too low: you should
sample at least at twice the frequency of interest, typically at
8 kHz or more. Then you have to subtract the DC offset added by the
microphone module, then square the result in order to get an
instantaneous intensity, then low-pass filter to get a usable intensity
reading. As Majenko said, if you average (or low-pass filter) the
samples _before_ squaring, you would detect zero sound.

I've written a sound meter program for an Arduino Uno that does exactly
that, and it's available as a GitHub Gist:
[sound-meter.ino](https://gist.github.com/edgar-bonet/e693799f58a545ca89a2).
It uses the auto-trigger mode as explained by KIIV, but with free
running mode instead of a timer. This gives 9.6 kHz sampling rate.


message:
Can I use a DAC with an L293D driver?

I'm trying to provide analog control to a Bluetooth controlled car, via Arduino. I have joystick app (as the pot).
It send values between 0 to 255
So I'm thinking... Whether this flow down here  will work?

Joystick app --> Bluetooth Rx --> DAC --> Vs pin of L293D. Or motor?

Is Arduino required at all? Or is the serial word enough to translate into voltage via DAC?

body:
No, you cannot. A DAC cannot provide enough current to either directly drive a motor or to power a motor driver (which is basically driving the motor directly through a switch anyway).

A motor driver requires a PWM signal to rapidly switch a high current source on and off to set the motor speed.

You *could* feed the DAC output into the input of a voltage-to-PWM converter chip which would then feed the motor driver's EN pin, but that is pretty pointless when you could just use a small microcontroller to receive the digital speed value and directly generate a PWM signal.

After all, that is the kind of job that small microcontrollers are designed for...


message:
Identify connected PC per Arduino

**Question:**
Is there a way to collect any data (e.g. MAC addresses, installed devices, driver versions, etc.) from a PC by simply connecting an Arduino via USB to it, so that this PC can be clearly identified?

**Background:**
Basically, I`m using an Arduino to send some text to a computer by emulating a keyboard, but I don´t want the text to be sent to any computer I connect the Arduino with. That is why I want the PC to be identified first.

*To be clear: this should be done without having to install programs on the PC in the first place.*

body: No you cannot. Arduino communicates to pc via UART so there must be a host which can send or receive the data. You have to install software on the host computer which can send and receive data to the com port to which arduino is connected to.


message:
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

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

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

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

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

Bí cúramach!


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


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

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

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

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

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


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

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

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

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

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

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

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

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

Here is the code:

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

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

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

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

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

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

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


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

body:
Just split the print into three parts:

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


message:
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.
[![enter image description here][1]][1]
The setup is an MCP23S17 I/O expander on a Teensy LC controller.
MCP23S17 port B pins are alternately grounded and energized.
I confirmed the pin voltages with a multi-meter.
Variable portBState is a bitwise reading of port B, and printed.

Expected output is:

    10101010

Actual output is:

    11111111

Sketch:

    #include <SPI.h>

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

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

    uint8_t portBState = 0;                 //bit wise

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

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

        //IODIRB register is already configured to input by default

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

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

    void loop() { }

Why is the output not "10101010"?

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

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

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

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

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

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

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


message:
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?

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

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

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


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

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

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

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

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


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

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


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


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

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

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

To answer the question:

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

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

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

3) Move to a larger Arduino.

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

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

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

There are also larger devices in the AVR family.

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

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


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

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

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

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

    ESP8266WebServer server(80);

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

      page += "\n\n
Some heading

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

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

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

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

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

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

      server.onNotFound(handleNotFound);

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

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

You can write something like:

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

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

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


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

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

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

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

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

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

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

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

    void wip () {
      delay(900);
    }

    void wah () {
      delay(2100);
    }


message:
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?

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

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


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

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

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


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

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

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

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


message:
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?

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

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

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

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

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

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

        last_state = state;
        return pulse_length;
    }

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

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


message:
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](https://learn.adafruit.com/adafruit-ina219-current-sensor-breakout). But this only gives the total consumed power of the Arduino and the sensors.

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

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

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

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

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

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

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

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

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

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

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

Similar formula for more sensors.

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

.


message:
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:
<!-- language-all: lang-cpp -->

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

    SI114X SI1145 = SI114X();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      isstreamer.addParameter("-d");

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

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

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

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

Any ideas are appreciated.

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


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

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

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

My naive solution was:

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

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

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

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

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

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

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

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

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


body:
You could hack it.

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

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


message:
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?

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

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


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

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

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

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


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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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


message:
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)][1] is so 'core' to Keyboard function. I've never had this issue before and I've been playing with it for months. I am running IDE 1.6.11.

### A possibly relevant detail

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

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

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

...

>  That works. println still doesn't.

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

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

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

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

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

However I thought that the Print class outputted both:

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

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


message:
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?

body:
You can't.

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


message:
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?

body:
In short:

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

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


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


message:
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:

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

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

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

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

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


message:
Turning my GPS logger shield off and on

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

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

    pinMode(pin, OUTPUT);

    //turn off
    digitalWrite(pin, LOW);

    //turn on
    digitalWrite(pin, HIGH);

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

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

body:
Yes, it is as simple as that.

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

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

    // Turn off
    pinMode(pin, OUTPUT);

    // Turn on
    pinMode(PIN, INPUT);

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

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

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


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

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

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

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

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

And the answer is:

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

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

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


message:
RFID stops working when I place the servo

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

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

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

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

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


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

> void dump_byte_array(byte *buffer, byte bufferSize)

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

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


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

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


message:
PWM generation for inverter by Arduino

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

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


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

    void setup()

    {

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

    }

    void loop()

    {

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

    }

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

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

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


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

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

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

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

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

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

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

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

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

DC Ground

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

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

i.e.:

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

AC Ground

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

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

Other stuff

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

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

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


message:
producing sine wave variable in amplitude and frequency

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

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

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


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

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

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

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


message:
Arduino IDE programming help

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

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

What would the best way to go about this?

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

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

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

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

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

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