message:
ATTiny85 433Mhz with sleep

I would like to micromize my Arduino project and move it to ATTiny85. The first step was using sleep functions because I just want it to run once a day. Now I need to connect the 433Mhz stuff but I'm getting into a fight with cores vs. libraries vs. missing functions.

No matter what core and library combination I pick, there always seems to be something missing.

    /home/thijs/Documents/Arduino/libraries/VirtualWire/VirtualWire.cpp:260:18: error: 'WGM12' was not declared in this scope
         TCCR1B = _BV(WGM12) | _BV(CS10);

I have tried `Tiny` cores, `high lowtech` cores and Manchester and VirtualWire libraries. I don't want to dive into the libraries and make them 'suitable' for ATTiny because I have more than one project.

How do I approach this dependency problem?

[**edit**]
Found a better core here:
https://github.com/SpenceKonde/ATTinyCore

body:
The error you posted has nothing to do with an Arduino core. This is just plain avr-libc stuff. In order to use this kind of functionality, you need to

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

    #include <avr/io.h>

In the Arduino core, it is common to have this done by default. But if this is not the case with your chosen core, just add the `#include` yourself in the program.


sender: user

message:
Not enough pins on Uno?

I'm making touch-sensitive, light up tic-tac-toe board.

That means 9 LEDs + 9 capacitive sensors.

Each LED needs 1 pin and each sensor needs 2...meaning I'd need 27 pins to properly control each touch-and-illuminate sequence.

There aren't enough inputs on the Uno for this, so what sort of workarounds should I explore to pull this off?

sender: assistant

body:
There are a number of common solutions to "not enough pins".

1. Reduce the number of pins you need. This option is often discarded out of hand, but may be the best. For example, you may be able to reduce the 18 individual pins for the on/off capacitive sensor, with a different part, which may be able to give you an X,Y co-ordinate of where it is touched, with fewer pins.

2. Multiplex the pins. This seems to be the most likely to work in this case - you will use (for example) 9 Uno pins to power the LED and capacitive sensor on each cell, one at a time. So, for example, you might attach D1 to the top left cell, D2 to the top-center, and so forth. Then you use another pin (e.g. D10) to connect to ALL the cathodes of the LEDs (via a single transistor, to protect the Uno from too much current), D11 and D12 to connect to one of the data pins of ALL of the capacitive sensors. So, you "select" cell one, by switching D1 from LOW to HIGH. Then, you put D10 to LOW, so current will from across the LEDs. Read the capacitive sensor, which is now also powered on. Although all of the censors are connected to D11 & D12, only one will be powered on, so you will only be reading that one. Once read, you probably want to delay a few milliseconds, to make sure the light shows up. Then move on to the next cell. Go round and round all cells. The LEDs will be off 8/9ths of the time, but it will still be visible. NOTE: reading more about capacitive sensors, I see that one is input, the other output. You would need a transistor for each of the "select" pins, used as a switch to connect D11 to the correct sensor.

3. Do the same thing, but using a decade counter. Connect 2 pins from the Arduino to the decade counter - one to "count", and one to reset. First, strobe the reset - this will set the first output of the decade counter high - connected to cell 1. Then, when you want to move to the next cell, drop the "count" low, then high again. You are now on the next cell. Repeat until you get to cell 9, then send the "reset" (which guarantees you know where you are up to) to get back to cell 1.

4. Charlieplexing (mostly suitable for output only). This is a somewhat complicated, but very efficient (pin-count wise) way of running lots of LEDs off only a few Arduino pins, by using them in combination. For example, 3 pins could run 6 LEDs - if you have pins A, B and C, run one LED from A to B, one from B to C, and one from C to A; then, run 3 more LEDs in the OPPOSITE direction (don't forget your resistors!). Depending on which LED you want lit, you might want pin A high, B low, and C high impedance (INPUT). 4 pins will get you 12 LEDs, 10 will get you 90 LEDs. If you think this might be useful, check out the Wikipedia

5. Use chips that are designed specifically for the application you need. For example, TLC5940 chips will run up to 16 LEDs each, controlling the brightness of each LED independently. You set the brightness of each LED, then let the TLC5940 take care of the work. SIPO chips such as the 74HC595 (8 outputs) are similar, but only allow "on" or "off" for each pin. Both of these can be "daisy chained" - with the same number of Arduino pins, you can connect the output of one to the input of the next, to control more outputs.

6. Use multiple Arduinos. Yes, this might sound expensive, but you can use an AtMega (e.g. AtMega328, which is the same chip used in the Arduino) for a fraction of the cost. You might even use an AtTiny - even cheaper (but less memory). All of these can run the same code. This is the most flexible, but is also the most work - you would need to think about which chip does what, how they interact, and how they talk to each other. This also has the advantage that, rather than a chip that runs at 16mhz, you can now have multiple chips that each run at that speed, and have more memory each. Some applications work well with one "master" chip controlling one (or more) "slaves", whereas other applications work really well as peer-to-peer, either with each node running the same code, or each doing their own thing, and passing information to other nodes. For this example, you might use one AtTiny85 for each of the 9 cells, with an Arduino to be the master. Or, use an AtTiny84, for each row of 3 cells, with one Arduino to rule them all. The AtTiny84 has 14 pins: power, ground, reset, and 11 data pins - 2 is enough for a shared data bus, such as i2c, leaving 3 pins for each of 3 cells.

7. (not relevant for this example) For multiple on/off sensors (e.g. pushbuttons, switches), you can attach them through different values of resistors, and connect them to an ADC pin as a voltage divider. For example, connect ground via R0 to an analog pin; then connect to the same pin: pin -> resistor 1 -> pushbutton 1 -> +5v; pin -> resistor 2 -> pushbutton 2 -> +5v, and so forth. Build the circuit, and test each combination of switches/pushbuttons on/off, what the output will be. Then, in your code, figure out which combination it is closest to. Each resistor will need to be different resistance. If you only expect one switch to be on at once, it's a lot easier.


body: 7. Shift registers. A single shift register is typically 8 bits, so for nine cells you will need two parallel-in/serial-out (for the sensors) and two serial-in/parallel-out (for the leds). You can chain shift registers together to manage any number of bits, at the price of speed. Each chain of registers needs two pins - data and clock, and the parallel input needs a third pin to latch the data. 5 pins all up, for any number of inputs and outputs. You could even combine the clocks by combining 'read the sensors' and 'refresh the display' as a single operation.


body:
As noted in Paul's comment, you could use NeoPixels instead of ordinary LEDs for the display.  Each NeoPixel contains RGB LEDs and a microcontroller that accepts a serial stream of bits in, cleans up the waveform, and passes what it doesn't need on through, to the next NeoPixel.  This would reduce the necessary number of pins by 8, since a string of NeoPixels uses one signal pin, independent of the number of NeoPixels in the string.

For the touch-sensitive (capacitive) buttons, rather than two wires per button, you can use one sense wire per button, and one drive wire per set of buttons, thus 10 pins to sense nine buttons, rather than the 18 pins mentioned in the question.  A sketch is shown below that samples nine capacitive buttons about 1300 times per second.  Here is some sample output from the sketch:

    At t=2354 button 0 on at level 274  xoooooooo  nr= 3121
    At t=2975 button 1 on at level 283  xxooooooo  nr= 3943
    At t=3056 button 2 on at level 271  oxxoooooo  nr= 4048
    At t=3235 button 3 on at level 280  oooxooooo  nr= 4283
    At t=3272 button 4 on at level 278  oooxxoooo  nr= 4331
    At t=3418 button 5 on at level 284  ooooxxooo  nr= 4521
    At t=3460 button 6 on at level 275  ooooooxoo  nr= 4575
    At t=3507 button 7 on at level 278  oooooooxo  nr= 4636
    At t=3632 button 8 on at level 290  oooooooxx  nr= 4799

Each entry like “level 278” shows the value of a running average of counts for a button; since the program is using 270 as a threshhold value for a button being on, it's reasonable for the numbers to be slightly above 270.  (Note, if the call to `secondlyReport()` were uncommented, one would see that the running averages go on up into the 300 to 500 count range when a button is pressed.)  The strings of o's and x's show which buttons are on and which are off.  The numbers after `nr=` are the number of button readings taken so far.

The program implements smoothing (via a running average with exponential decay), debounce (via “holdoff” counts, as explained in detail in a [previous answer](https://arduino.stackexchange.com/a/22621/3917)), and hysteresis (going from off to on at a high count (270) and from on to off at a lower count (170)).

The program may need tuning to work with a given set of capacitive buttons.  The tuning variables used here (such as `ButtonIsOn = 270`, `ButtonIsOff = 170`, `usSettle=60`, `usPreWait=5`, and `nsamp = 40`) work ok with my nine-button setup where each capacitive button is attached to an input pin (like 4,5,...12) and to a 619K resistor (a size I have a number of).  The other end of each of those resistors attaches to Uno pin 13.  By changing `ButtonIsOn` and `ButtonIsOff`, one should be able to accomodate resistor sizes from a megohm on up to perhaps 4 or 5 megohms.

Note, to install `Streaming.h` (which doesn't increase code size) unzip [`Streaming5.zip`](http://arduiniana.org/Streaming/Streaming5.zip) from [arduiniana.org](http://arduiniana.org/libraries/streaming/) in your `sketchbook/libraries` directory.

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

    /* Via serial port, tell the current time when capacitive readings on
      various digital pins show a button has been "pressed" or "released".
      This version reads buttons using 13 as a drive pin, and two groups
      of pins as capacitive switches: group D = pins 4,5,6,7, group B =
      8,9,10,11,12.  Each of those pins should be connected to the drive
      pin via (eg) a 1M ohm resistor.   JW - April 2016

     See eg refs at http://playground.arduino.cc/Code/CapacitiveSensor and
     http://www.arduino.cc/en/Reference/PortManipulation and
     http://garretlab.web.fc2.com/en/arduino/inside/arduino/Arduino.h/digitalPinToPort.html
     */
    #include <Streaming.h>      // provides nicer syntax for printing
    enum { pinsMax = 9 };      // upper size on pins count per sample;
    enum { nPortReads = 40 };    // # bit samples saved per reading;
    enum { bundleSize = 16 };    // 2^j samples carried in running average
    enum { drivePin = 13 };      // # of pin to drive capacitors
    enum { ButtonIsOn = 270 };   // button-on level, with hysteresis
    enum { ButtonIsOff= 170 };   // button-off level "    "
    enum { usSettle = 60 };      // Hold sense pins low this long.
    enum { usPreWait = 5 };      // Ignore probably crosstalk this long.
    enum { nKeys=9 };      // # of keys in PinSet. Cannot be > pinsMax
    #define PinSet "4,5,6,7,8,9,10,11,12"
    unsigned int AvCount[nKeys]={0};
    unsigned long int nSamples; // # of samples taken
    //-----------------------------------------------------------
    // Use delta=0 for startup, vs delta=1 for exponential averaging
    void makeSample(int delta) {  // Take a sample, add it to AvCount
      byte counts[nKeys], j, nc;
      unsigned int bundle;
      nc = countPins7(drivePin, PinSet, counts);
      for (j=0; j<nc; ++j) {
        bundle = AvCount[j] * (bundleSize-delta);
        AvCount[j] = bundle/bundleSize + counts[j];
      }
      ++nSamples;
    }
    //-----------------------------------------------------------
    void setup() {
      Serial.begin(115200);  // initialize serial port
      nSamples = 0;
      // Initialize AvCount[] with a bundle of samplecounts
      for (byte j=0; j<bundleSize; ++j)
        makeSample(0);  // Add sample directly to total
    }
    //-----------------------------------------------------------
    // portSampler7(): countPins7() calls this routine, which holds
    // drivePin and involved pins on current port low for usSettle
    // us, then makes them inputs and turns on drivePin.  It waits
    // usPreWait us (to weed out crosstalk), then reads the port
    // nPortReads times as the pins recharge.
    // The set of nPortReads port readings is returned in portReadings.
    //
    // Inputs:  drivePin, portCode, pinsMask.  Constant nPortReads.
    // Output:  array of nPortReads portReadings.
    //
    // This version takes 8 cycles per reading.  Inputs switch
    // on after about one RC time constant.  On a 16MHz Arduino an
    // m-count result (that is, a zero bit in m of the nPortReads reads)
    // suggests RC is about m/2 us + usPreWait us.

    void portSampler7(byte drivePin, byte portCode,
        byte pinsMask, byte *portReadings) {
      volatile byte *pin, *port, *ddr;
      // pin, port, and ddr are pointers to registers with volatile
      // contents: input port, output port, direction register.
      pinMode(drivePin, OUTPUT);
      digitalWrite(drivePin,LOW);
      pin =  portInputRegister (portCode); // eg points to PIND
      port = portOutputRegister(portCode); // eg points to PORTD
      ddr =  portModeRegister  (portCode); // eg points to DDRD
      *port &= ~pinsMask;      // Turn off our pins
      *ddr  |= pinsMask;      // Make our pins be outputs, briefly
      delayMicroseconds(usSettle); // Delay to let pins settle low
      *ddr &= ~pinsMask;      // Make our pins be high-impedance inputs
      digitalWrite(drivePin,HIGH); // Turn on driver pin
      delayMicroseconds(usPreWait);
      for (byte i=0; i<nPortReads; ++i) // Take and store nPortReads readings
        portReadings[i] = *pin;
    }
    //-----------------------------------------------------------
    /* Decode a pins-list into one list per involved port.
       Use portSampler7() to get rise-time counts for each port.

       If pins are spread across k ports, countPins7()  will make
       k calls to portSampler7().  Results are in counts array.
       Note, make pinsMax larger if pinsMax < #(pins in list).

       pinsList can look like "2,3,4,5,6" or "2,4,5,12,9,23,17,7"
       etc.  A list may contain digits and commas only.  Pins may be
       listed in any desired order.  Elements of counts[] will be in
       list-order.  Eg, in the "2,3,4,5,6" example, counts[0] is the
       count for pin 2, counts[1] is the count for pin 3, etc.  A
       larger count implies longer rise time and larger capacitance.
     */
    byte countPins7(byte drivePin, char *pinsList, byte *counts) {
      byte pnum, pomask, pocode, potem, i, j, mul;
      byte sampl[nPortReads], pim[pinsMax], pat[pinsMax], bout=0, nat=0, pcon;
      char *c, cc;
      int usedPorts=0; // To track which ports are done
      for (c=pinsList, counts[0]=pcon=0; *c; ++c) // Zero the counts array
        if (*c < '0' || *c > '9') counts[++pcon] = 0;
      // In each pass, group bit numbers by port and sample the port
      while (nat<pcon) { // Each loop pass sets one bit in usedPorts
        pnum = pocode = pomask = bout = pcon = 0;
        c = pinsList;
        while ((cc=*c++)) {  // Loop until c is at end of string
          if ('0' <= cc && '9' >= cc) {
            pnum = 10*pnum + cc - '0';
            if ( *c < '0' || *c > '9') { // See if pin # is complete
              potem = digitalPinToPort(pnum);  // Get port #, in range 1 to 12
              if (!(usedPorts & (1<<potem))) { // Is potem's port already done?
                if (!pocode)     // If pocode not set, set it
                  pocode = digitalPinToPort(pnum);
                if (pocode == potem) {  // Process pin if it's in current port
                  pomask |= (pim[bout] = digitalPinToBitMask(pnum));
                  pat[bout++] = pcon; // Save location of pin's bit in results
                }
              }
              pnum = 0; // Clear # accumulator
              ++pcon;   // Count pin numbers
            }
          }
        }
        // Now pomask is a mask for all bits to be read from port pocode
        // and we are ready to sample current port.

        // Get nPortReads port readings into sampl array.
        portSampler7(drivePin, pocode, pomask, sampl);
        usedPorts |= 1<<pocode;    // Mark the port finished
        // Count up # of zeroes (ie rise times) in sampled bits
        for (j=0; j<bout; ++j) {
          int count;
          byte m=pim[j];
          for (count=i=0; i<nPortReads; ++i)
            count += sampl[i] & m;
          counts[pat[j]] += nPortReads - count/m; // Return the number of Zeroes
        }
        nat += bout;  // Count number of pins done so far
      }
      return pcon;   // Return # of pins processed
    }
    //-----------------------------------------------------------
    // Measure rise times at designated pins and report
    // current running averages of rise times, once per second
    void secondlyReport() {
      unsigned int seconds=0, now;
      while (1) {
        now = millis()/1000;
        makeSample(1);  // Add a sample to running average
        if (now > seconds) { // See if next second started
          Serial << "Counts: ";
          for (byte j=0; j<nKeys; ++j) // Show output
            //for (byte j=1; j<nKeys; j+=2) // Show output
            Serial << AvCount[j] << " ";
          Serial << " t=" << now << " sec." << endl;
        }
        seconds = now;
      }
    }
    //-----------------------------------------------------------
    // Frequently sample rise times on designated pins, to
    // find and report capacitive key press times & levels.
    void keypressReport() {
      // Old-state and holdoff-count vars
      byte ostate[nKeys] = {0}, holdo[nKeys] = {0}, j, k;
      while (1) {
        makeSample(1);  // Add a sample to running average
        for (k=0; k<nKeys; ++k) {
          if (holdo[k]) {  // Ignore an on button during holdoff
          --holdo[k];
          } else {
     if (AvCount[k] > ButtonIsOn ||
        (AvCount[k] > ButtonIsOff && ostate[k])) {
       if (!ostate[k]) { // Were we off?
                ostate[k] = 1; // New button press
                holdo[k] = 40; // Start a holdoff period
                Serial << "At t=" << millis() << " button " << k;
                Serial << " on at level " << AvCount[k] << "  ";
                for (j=0; j<nKeys; ++j)
                  Serial << (ostate[j]? 'x' : 'o');
                Serial << "  nr= " << nSamples << endl;
              }
              ostate[k] = 1;     // We detected button is on
            } else {
              ostate[k] = 0;     // We detected button is off
            }
          }
        }
      }
    }
    //-----------------------------------------------------------
    void loop() {
      if (0) secondlyReport();
      keypressReport();
    }


body: Oh - capacitative sensors. I was fooling about with transistors (BD149s, I think) hooked up into darlington pairs, and I found that just touching the resistor on the base was enough to make them switch. No extra capacitor timing whatsamajig required.


message:
Assembled redboard PTH kit, when I turn it on the led flashes increasingly fast and stops

I assembled the following sparkfun redboard: **https://www.sparkfun.com/products/retired/10776**

When I plug the board in it start to blink but increasingly fast until the LED stops.

I'm very new to this and not sure what could be the issue or what to look. Any tips on how to debut this?

Here are images of the assembled board:
[![Front][1]][1]
[![Back][2]][2]

  [1]: https://i.stack.imgur.com/UDcfG.jpg
  [2]: https://i.stack.imgur.com/M1gpc.jpg

body:
The board seems to be working. After I plugged in an ftdi connector (adafruit FTDI friend) and uploaded blink to it, it started blinking every second instead of really fast.

The documentation was a bit confusing as it implied that blink was pre-loaded on the device but instead it would just blink extremely fast until it went all the way on and then turn off the green led.


message:
Why is my pushbutton always reading LOW?

I know this is ridiculously simple task but I spent the last two hours trying to get this to work and it is not working.  I don't have an Arduino but I have an ESP8266 Huzzah Feather which is programmable via the Arduino IDE.  So, I don't think I can provide a Fritz diagram but in any case, I'm just trying to hook up a pushbutton and be able to read a HIGH or LOW (via my Serial monitor).  Currently, everything is 0.

As best I can describe it is:

5V from Feather into resistor into one terminal of the pushbutton.  Out the other terminal of the pushbutton is a wire connecting to pin 12 of the Feather, and also a wire leading to ground.  Feather is also grounded.

My code is:

<!-- language: c -->

    void setup()
    {
      Serial.begin(9600);
      pinMode(12, INPUT);
    }

    void loop()
    {
      int button_val = digitalRead(12);
      Serial.println(button_val);
    }

It shouldn't be this hard for me.  Whenever I open and run the serial monitor, it reads 0s.  What am I missing?

Oh, an issue that I faced is determining which 2 out of the 4 terminals of the pushbutton to use.  Some resources I find say that it is the same side as the terminal the voltage is flowing into; other resources say it is the terminal opposite to the side the voltage is flowing into.  I currently have it opposite.

body:
The pins on each side of the button are shorted, the "button" is between the *sides* of the button. Else your code looks alright.

Edit: Here's an image which shows how a push button is connected internally, make sure you're using the correct pins.

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

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


body:
> Out the other terminal of the pushbutton is a wire connecting to pin 12 of the Feather, and also a wire leading to ground.

That sounds to me like you have connected the IO pin direct to ground.

The IO pin should connect to the same pin as the resistor that connects to +5v. The other side of the button should connect to ground only.

For instance using @HansNeve's button picture you could connect pin A to the IO pin and via a resistor to +5V, and pin B to ground.


message:
Connecting ethernet shield to computer

What configuration settings do I need to change on my computer to use the ethernet shield mounted on my Arduino UNO as I don't want to connect the ethernet shield to the router?

body:
First off you need a basic understanding of TCP/IP networking. One you have that you need to:

1. Allocate yourself a new subnet - one that's not your normal local network (say 192.168.1.0/24)
2. Assign an IP in that subnet to your Arduino (say 192.168.1.1)
3. Assign a different IP in that subnet to your PC (say 192.168.1.2)
4. Configure your Arduino's sketch with it's IP address and netmask
5. Configure the PC's Ethernet interface with it's IP address and netmask
6. Connect the two together with a suitable cable.  If the PC's Ethernet port doesn't have auto-direction sensing you will require a special cross-over cable where TX+/TX- and RX+/RX- are swapped over.


body:
You can try the easy way
This always works for me :D

 1. Connect the shield to the Arduino and plug in the cables to the
    PC(RJ45/Ethernet).
 2. Go to network communication center.
 3. Go to change adapter settings.
 4. Select Ethernet(Arduino) and wireless(Wifi) /(internet source) and
    right click.
 5. Click bridge connections.
 6. Wait for a few seconds.
 7. **Enjoy**.


message:
Wire Library send/receive

I'm doing a project that includes an Arduino Uno and custom hardware made by me. Everything is working perfectly independently, and I'm trying to implement a way for them (the Arduino and my hardware) to work together. In order to achieve that, I am using the Wire protocol (Arduino side) and I2C (custom hardware side). From now I can send data from **my hardware** to **my Arduino** in a **master-slave** relation, and I have no problem with that. Please take a look at my Arduino code for better understanding:

<!-- language: c -->

    void setup(void) {
      Wire.begin(7);
      Wire.onReceive(receiveEvent);
    }

    void receiveEvent(int howMany) {
      int x = Wire.read(); // receive byte as an integer
      Serial.print(x);
      if (x==0)
        state = 0;
    }

So far so good. Now I want to send data from the **Arduino** to my **custom hardware** full duple, and for that I am adding this code:

<!-- language: c -->

    void frame(void){
      Wire.write('x');
      Wire.write('\r');
    }

    void loop() {
      if (state == 0){
        frame();
        state = 1;
      }
    }

In order to receive the 'x' char in my custom hardware I have switched the I2C protocol bit from Write to Read using `I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, _address, I2C_WRITE);` to `I2C_FORMAT_7_BIT_ADDRESS(SlaveAddress, _address, I2C_READ);` in my custom hardware code.

I don't know why, I am not receiving the data from the Arduino. Am I missing any configuration on the Arduino side?

body:
I've not done events on an Arduino so this could be a bum steer, but shouldn't the state variable be volatile and protected with a semaphore?
You are accessing it in the main program and in your event/ISR.

Secondly, no offence intended, could you replace your hardware with a bit of tried and trusted hardware to eliminate the remote possibility that your hardware is at fault.


body:
You use the `onReceive()` and `onRequest()` methods of the Wire library to implement an Arduino slave. In your case, something like this:

    void setup(void){
      Wire.begin(18);
      Wire.onReceive(receiveEvent);  # register receive handler
      Wire.onRequest(requestEvent);  #register request handler
      Serial.begin(9600);
    }

    void receiveEvent(int howMany){
      int x = Wire.read();    // receive byte as an integer
      Serial.print(x);
      if (x == 0)
        state = 0;
    }

    void requestEvent(){
      Wire.write("x\r");
      state = 1;
    }

See [Slave Receiver][1] and [Slave Sender][2] examples for more details.

  [1]: https://www.arduino.cc/en/Tutorial/MasterWriter
  [2]: https://www.arduino.cc/en/Tutorial/MasterReader


message:
MCP4725 not working

I tried using a MCP4725 DAC with an Arduino (M0 Pro, Duemilanove and Diecimila) and it is not outputing any voltage (just random noise).

I've been using the 2 tutorial codes fount here : https://learn.adafruit.com/mcp4725-12-bit-dac-tutorial/using-with-arduino which are supposed to generate a sinus wave and a triangle wave.

I am pretty sure it doesn't come from the Arduino because basic examples have been working so far.

Anybody had the same issue or can help on this ?

    #include <Wire.h>
    #include <Adafruit_MCP4725.h>

    Adafruit_MCP4725 dac;

    void setup(void) {
      Serial.begin(9600);
      Serial.println("Hello!");

    // For Adafruit MCP4725A1 the address is 0x62 (default) or 0x63 (ADDR pin tied to VCC)
      // For MCP4725A0 the address is 0x60 or 0x61
      // For MCP4725A2 the address is 0x64 or 0x65
      dac.begin(0x62);

      Serial.println("Generating a triangle wave");
    }

    void loop(void) {
        uint32_t counter;
        // Run through the full 12-bit scale for a triangle wave
        for (counter = 0; counter < 4095; counter++)
        {
          dac.setVoltage(counter, false);
        }
        for (counter = 4095; counter > 0; counter--)
        {
          dac.setVoltage(counter, false);
        }
    }

body:
I finally got this example to work.

Details:

My A0 line was tied to ground using the solder jumper (through a 10k SMD resistor on the board it appears).
I used . . .

# define MCP4725_ADDR 0x62

. . . as the base address of the chip.
My CMD to update the DAC was . . .

Wire.write(64);

. . . (64 in decimal i.e. 0b01000000)

This YouTube video helped out a lot:
https://www.youtube.com/watch?v=ngvqgIeaS9M

All the best
KenLaszlo


message:
Cheapest Arduino wireless solution for home automation

I am from programming background and newbie to this field.

Couple of days ago I brought **Arduino Uno (5V)**. I want to control light bulb and fan from my **Android**. So I thought, I will buy **relays** and **ESP8266** module and its done.

But now read somewhere that ESP8266 works with **3.3v** and my Arduino supplies **5v**.

Should I go for different Arduino board (like Arduino pro or Arduino mini) or is there any **reliable & cheap** solution that will work my **Arduino Uno (5V)** ?

body: If you want to go for cheap just use a ESP8266 no arduino needed.


message:
Which GSM-shield is most efficient for GPRS communication?

I tried Google, I tried a bunch of forums and I searched here. This question needs a final answer:

**Which GSM-shield is most efficient for GPRS communication?**

Since Arduino is the amateurs best friend for home automation and IoT, an "efficient" shield has a very low power consumption.

I am currently developing a system that collects some data from different sensors at a place far, far away, with limited access to power (e.g. it has a very small solar panel and a battery). It is also in pocket-size which makes a car battery a bad option.

Anyway, this specific device reads these sensors every 20 minutes, and if there's a deviation since the previous reading it starts the GSM module to send the new data to my API.

**SMS and call features are of absolutely no interest at all.**

Since these GSM-power-absorbing-current-eating-devils really like power I must think outside the box and compare different alternatives. So besides the primary question in this post, is there any way you can limit the power consumed, for example by limit the connection speed or anything like that? I'm using a M590 module at the moment, and that beast can eat around 2A if it's hungry.

Thanks in advance :)

body:
GSM, by its very nature, is power hungry.  Even the most "efficient" one will blow your power budget many times over.  Since everything on GSM goes down the same digital transmission channel there would be no real difference between one with call and SMS and one without. It's all just data at the end of the day.

That said, the most efficient GSM module is one that consumes absolutely now power. And that is, at least for most of the time, perfectly possible.  By making the Arduino control the power supply to the GSM modem it can be literally turned off until an update is needed to be sent. Worst case that is on for maybe a minute (give it time to register on the network and what have you) and then off for 19 minutes. That's only on for 5% of the time - less if there isn't a change since the last time, of course.


body:
Three main things come to mind here...

**Overall hardware power consumption**: if you can make the arduino sleep for those 19ish minutes and are willing to do some of the things below/linked. Adding a RTC module using the alarms to trigger a GPIO to wake the arduino might be something depending on your hardware options as well.

**Software / clock speed / timing**: having the perfect code will make all the difference here as well. if your test code takes say 30 seconds to wake up, read the sensors, arrange the data, wake up gprs and transmit then fall asleep again. that might be pretty good. But say for example FONA shields have a 7second wake up.. This time can be used to sample sensors and arrange the data. Then transmit straight away when it wakes up.. could save a few seconds. also switch it off asap before any other code n so on.

**GPS/GPRS Reception**: If you can establish a connection quickly, you will be able to put it all back to sleep quicker and draw less power. Also possibly pre-select your providers baud rate to stop it trying and waiting.

As for point 1 above,

If you are powering it via the DC jack, then it is simply using a regulator (at least on the arduino side) that is not efficient (7805)...

So one suggestion is to get a 5v switching power supply and power it via the header pins or cut/splice a usb cable. this could gain you about 20% give or take.

Finding power hacks and running mini arduino's and alternatives can get you down even lower on power consumption.

I'm not going to give references from these listings, there just a quick few results. but basically from memory and glance its a case of removing resistors/regulators/redirecting/modifying/all that stuff and then also some software hacks along with changing the clock rate as well.

https://playground.arduino.cc/Learning/ArduinoSleepCode

http://www.home-automation-community.com/arduino-low-power-how-to-run-atmega328p-for-a-year-on-coin-cell-battery/

https://learn.sparkfun.com/tutorials/reducing-arduino-power-consumption

https://github.com/petervojtek/diy/wiki/Arduino-with-Very-Low-Power-Consumption

https://www.hackster.io/techduino/reducing-arduino-power-consumption-9bcaf1

**Atmega328 with minimal circuit schematics**
[![Atmega328 with minimal circuit schematics][1]][1]

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


message:
LCD readout is odd

I want it to display the current temperature in the middle of the screen, fade out for two seconds, display new temperature, rinse repeat.  This is current (see images)[![all over the place![![\]\[1\]][1]][1]][2]

    /*
     * File:    readTemperature.ino
     * Author:  Andy Gelme (@geekscape) & Angus Gratton (angus at freetronics. com)
     * License: GPLv3
     *
     * For more information see www.freetronics.com/irtemp
     *THIS NOW WORKS!!! Except for reading to LCD.
     */

    #include "IRTemp.h"
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 9, 8, 7, 6);

    static const byte PIN_DATA    = 2; // Choose any pins you like for these
    static const byte PIN_CLOCK   = 3;
    static const byte PIN_ACQUIRE = 4;

    static const TempUnit SCALE=CELSIUS;  // Options are CELSIUS, FAHRENHEIT

    IRTemp irTemp(PIN_ACQUIRE, PIN_CLOCK, PIN_DATA);

    void setup(void) {
     // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // initialize the serial communications:
      Serial.begin(9600);
    }

    void loop(void) {
      float irTemperature = irTemp.getIRTemperature(SCALE);
      printTemperature("",irTemperature);
     delay(1000);
       // when characters arrive over the serial port...
      if (Serial.available()) {
        // wait a bit for the entire message to arrive
        delay(100);
        // clear the screen
        lcd.clear();
        // read all the available characters
        while (Serial.available() > 0) {
          // display each character to the LCD
          lcd.write(Serial.read());

      // delay at the end of the full loop:
      delay(1000);

    }
      }
    }

    void printTemperature(
      char  *type,
      float  temperature) {

      lcd.print(type);
      lcd.print(" temp: ");

      if (isnan(temperature)) {
        lcd.println("Failed");
      }
      else {
        lcd.print(temperature);

      }
    }

  [1]: https://i.stack.imgur.com/aH2Gn.jpg
  [2]: https://i.stack.imgur.com/xNoG4.jpg

body:
Before you write the first character of your temperature text, set the cursor to where you want that first character to display.

For example, use `lcd.setCursor(col, row);` to set the cursor at a specified column in a specified row.  Row and column numbering starts from zero.

You can also use `lcd.home();` to set the cursor at (0,0).

The output cursor advances a column each time you write a character.


body:
    /*
     * File:    readTemperature.ino
     * Author:  Andy Gelme (@geekscape) & Angus Gratton (angus at freetronics. com)
     * License: GPLv3
     *
     * For more information see www.freetronics.com/irtemp
     *THIS NOW WORKS!!! Except for reading to LCD.
     */

    #include "IRTemp.h"
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 9, 8, 7, 6);

    static const byte PIN_DATA    = 2; // Choose any pins you like for these
    static const byte PIN_CLOCK   = 3;
    static const byte PIN_ACQUIRE = 4;

    static const TempUnit SCALE=CELSIUS;  // Options are CELSIUS, FAHRENHEIT

    IRTemp irTemp(PIN_ACQUIRE, PIN_CLOCK, PIN_DATA);

    void setup(void) {
     // set up the LCD's number of columns and rows:
      lcd.begin(16, 1);
      // initialize the serial communications:
      Serial.begin(9600);
    }

    void loop(void) {
      float irTemperature = irTemp.getIRTemperature(SCALE);
      printTemperature("",irTemperature);
     delay(1000);

      }

    void printTemperature(
      char  *type,
      float  temperature) {

      lcd.print(type);
      lcd.setCursor(1,1);
      lcd.print(temperature);
      lcd.setCursor(7,1);
      lcd.print("celcius");

    }


body:
    /*
     * File:    readTemperature.ino
     * Author:  Andy Gelme (@geekscape) & Angus Gratton (angus at freetronics. com)
     * License: GPLv3
     *
     * For more information see www.freetronics.com/irtemp
     *After much playing around this is the finaL result.
     */

    #include "IRTemp.h"
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 9, 8, 7, 6);

    static const byte PIN_DATA    = 2; // Choose any pins you like for these
    static const byte PIN_CLOCK   = 3;
    static const byte PIN_ACQUIRE = 4;

    static const TempUnit SCALE=CELSIUS;  // Options are CELSIUS, FAHRENHEIT

    IRTemp irTemp(PIN_ACQUIRE, PIN_CLOCK, PIN_DATA);

    void setup(void) {
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 1);
      // initialize the serial communications:
      Serial.begin(9600);
    }

    void loop(void) {
      float irTemperature = irTemp.getIRTemperature(SCALE);
      printTemperature("",irTemperature);
     delay(1000);

      }

    void printTemperature(
      char  *type,
      float  temperature) {

      lcd.print(type);
      lcd.setCursor(1,1);
      lcd.print(temperature);
      lcd.setCursor(7,1);
      lcd.print("celcius");

    }


message:
IR remote unstable button numbers

**Question**

Is there a reason for unstable button numbers of an IR remote?

**Desciption**

I wrote a remote class where I identify the pressed number of the remote to set states. But however I get never the same number of the pressed key.

For example I press the number '1' and on the serial interface shows this:

    3588650484
    2740290906
    3148594742
    689746115
    2396927248
    2934053595
    4294967295
    3876827360

And it should look like this:

    16724175 // Button 1
    4294967295
    16724175 // Button 1
    16724175 // Button 1
    16724175 // Button 1
    16724175 // Button 1

**Hardware**

I am using an arduino UNO board and the standart remote of the starter kit. There is no name just 'SPECIAL FOR MP3'.

**Some more infos**

Ok, in my first project I used the code from Noreddine Kessa([Example Project][1]) which works fine. Next I copied some code in my new class 'IRControl.cpp' ( you can see below). Then I created an object IRControl in the main.cpp and run the menu() in the loop.

h-File:

    /*
     * IRControl.h
     *
     *  Created on: 04.04.2016
     *      Author: David
     */

    #ifndef IRCONTROL_H_
    #define IRCONTROL_H_

    //Remote Defines
    #define buttonON 16753245
    #define buttonMode 16736925
    #define buttonSoundOff 16769565
    #define buttonPlayStop 16743045
    #define buttonTrackBack 16712445
    #define buttonTrackForward 16761405
    #define buttonEQ 16769055
    #define buttonMinus 16754775
    #define buttonPlus 16748655
    #define button0 16738455
    #define buttonRepeat 16750695
    #define buttonJSD 16756815
    #define button1 16724175
    #define button2 16718055
    #define button3 16743045
    #define button4 16716015
    #define button5 16726215
    #define button6 16734885
    #define button7 16728765
    #define button8 16730805

    #include "IRremote.h"
    #include "wiring_private.h"

    enum zustaende{Motor1, Motor2, Motor3, Sleep};
    extern int zustand;

    class IRControl {
    private:
     IRrecv *irrecv;
     decode_results remoteValue;
    public:
     IRControl(int RECV_PIN);
     virtual ~IRControl();
     void menu();
    };

    #endif /* IRCONTROL_H_ */

cpp-File:

    * IRControl.cpp
     *
     *  Created on: 04.04.2016
     *      Author: David
     */

    #include "IRControl.h"

    IRControl::IRControl(int RECV_PIN) {
     // TODO Auto-generated constructor stub
     irrecv = new IRrecv(RECV_PIN);
     pinMode(RECV_PIN , INPUT);
     irrecv->enableIRIn();
    }

    IRControl::~IRControl() {
     // TODO Auto-generated destructor stub
     delete irrecv;
    }

    void IRControl::menu() {
     if (irrecv->decode(&remoteValue)) {
         //lReceived = remoteValue.value ;
         Serial.println(remoteValue.value);
         /*
         switch(remoteValue.value)
              {
              case button1:
               zustand = Motor1;
               //digitalWrite (LED1, HIGH); // for control
               break;

              case button2:
               zustand = Motor2;
               //digitalWrite (LED2, HIGH);
               break;
              case button3:
               zustand = Motor3;
               //digitalWrite (LED3, HIGH);
               break;

              case button0:
               zustand = Sleep;
               break;

              default: break;
              }
              */
         irrecv->resume(); // Receive the next value
       }
    }

**Where the problem could be**

I think there could be a problem with the `IRrecv *irrecv;`. But i'm not sure.

Thanks for your help

  [1]: http://www.instructables.com/id/Controlling-an-Arduino-Board-Using-an-Infrared-Rem/

body:
Please post the code where you call the library. In particular where do you make an instance of IRControl?

I am guessing you are doing it at global scope which means you are probably running into the *C++ static initialization order fiasco*.

What it is: <http://www.parashift.com/c++-faq/static-init-order.html>

How to prevent it: <http://www.parashift.com/c++-faq/static-init-order-on-first-use.html>

To prevent this, you should **not** be doing this in the class constructor:

    irrecv = new IRrecv(RECV_PIN);
    pinMode(RECV_PIN , INPUT);
    irrecv->enableIRIn();

Instead, make a `begin` function (like most Arduino classes do) and call that from `setup`.


message:
What would be the architecturally-right place to put custom -D defines?

What I am trying to accomplish is to include information about the state of my environment at build time in my code. For example, I may want the `setup()` code to print the git sha it was built against, and the time of build.

There are two related issues here:

 1. How to include that information in the code
 2. How to specify to the build environment what to generate in the first place.

The first can be addressed in a number of ways:

* -D options can be generated at build time, and the corresponding defined macros expanded in the code. For example, the compiler could be invoked as `g++ -DGIT_SHA=$(git rev-parse HEAD) -DDATE=$(date '+%Y%m%d-%H:%M:%S')`, and my code could have something like `#define strfy(_x) #_x` followed by `Serial.println(strfy(GIT_SHA));`. Or the build tool could generate a header file that would define these as external string variables, which the main sketch could then include and print. Or any other number of tricks.

The question I am really asking is: **how should I specify this sort of stuff for `arduino-builder`?**

Ideally, it would be a custom recipe in `platform.txt`, but if there is a way to invoke shell commands in recipes and use the results to modify other variables (such as `preproc.macro.flags`), I haven't been able to find it (if there is documentation, it's really well hidden). Ideally I would want to be able to say `preproc.macros.flags=-w -x c++ -E -CC -DGIT_SHA=$(git rev-parse HEAD)` and have the shell command be executed at the point.

So, before I set out to hack arduino-builder, do people have any opinion on this? My main criterion is something that would be of general value and has a chance of being incorporated in the code, rather than a kludge that only works for me and which I have to patch every time I upgrade. Please do not suggest workarounds. I can think of several myself!

I *did* try to search, and this sort of issue has come up before, but I didn't see any satisfactory answers from people who knew what they were talking about.

Thanks!

/ji

body:
That is a tough one...  Because arduino-builder is basically a custom go script you don't get the facilities you get in a Makefile, like shell execution.

I would be inclined to do this kind of thing outside that environment - use some external program or tool to generate a config.h file (maybe use something like GNU Autotools) that contains your custom defines. That can then be #included in your sketch.


body: For the date and time of compilation there are predefined preprocessor symbols: `__DATE__` and `__TIME__`.


message:
How do I connect a vibration motor to Arduino?

I'm trying to figure out how to connect a vibration motor to my Arduino.  I've come across [this resource][1] and it seems pretty straightforward though for a while my eye glazed over at how complicated the circuit was (do I really need all of that to run my vibration motor?).

My real question is that I have a vibration motor similar to the picture in the link and I'm trying to figure out how to actually connect it to my breadboard.  Do I have to solder wires onto those flimsy ends or is that a better way to get this to work?

Thanks!

  [1]: http://learningaboutelectronics.com/Articles/Vibration-motor-circuit.php

body:
I've never used a vibration motor, but I think you do need all of the circuit.  Its says in the text, but the transistor is needed because the Arduino 'doesn't supply enough current through the output port' and the diode and cap are required to prevent spikes.

As to the flimsy wires you could solder them onto a bit of strip board and then solder "proper" wires of connectors onto the board too.


body:
You could make a simpler circuit by removing the diode, capacitor.  BUT this comes at the cost of having a circuit that could kill your arduino.

Stick with it and build the entire thing.  This isn't a shortcut worth taking.


body:
Lets break down the circuit and have a look why everything in that circuit is there and what it does.

First we have the 33R resistor before the motor which limits the current to the motor. This particular motor is rated at 75mA and has a starting of 85mA. The 33R resistor limits the current to 130mA maximum through the motor. If the risk of the motor pulling too much current is an issue then stick a fuse in-line

Then there's the motor, not much to say here really. It's whatever motor you're using.

We then have both a diode and a capacitor across the motor. I find this a bit strange, I've seen the use of flyback diodes, I've seen the use of snubbers, but both? The purpose of the diode is to allow a return path for any spikes caused by switching off power to the inductive load (the motor) which stops them from damaging the transistor. For the capacitor, just remove it, it's not got any use here really.

Then comes the transistor, it might be easier to think of a transistor as a switch (especially in this example). When you put a little bit of current on the base, the transistor 'opens' allowing the motor to connect to ground. The reason we have to use a transistor is because the outputs of an arduino are only able to supply a maximum of 40mA, we need more than that to run our motor. Fortunately, the transistor is not going to need any more than 5mA on it's base which is why we use it to 'switch in' components that require more voltage/current. The 1K resistor on the base is to limit the current coming from the arduino and preventing it from killing our poor transistor.

tl;dr - You need everything except the capacitor


body:
There are actually a number of things wrong with that circuit.

First the motor runs from 2.5 to 3.8V, yet they show it running off the 5V supply pin.

Secondly they include a 33Ω resistor to "limit the current". It doesn't! It drops a voltage depending on the current flowing through it, and the current flowing through it depends on the speed and load of the motor at the time.  So the motor itself will be getting a fairly random voltage applied to it, which at times will be below the specifications.

E.g.:

* The start current is 85mA.  V=RI, 33*0.085 = 2.805V. 5 - 2.805 = 2.195V: way below the 2.5V required minimum.

* The run current of 75mA calculates as: 33*0.075 = 2.475. 5 - 2.475 = 2.525V: only just enough for it to run.

So it should be powered from a 3.3V supply that has enough current capacity to drive it (85mA) and the 33Ω resistor should be removed entirely.


message:
Arduino Uno + Jaguar Speed Controller + CIM Motor (12V DC)

I have connected a CIM motor to a Jaguar speed controller, powered by a 12V battery. The Jaguar is connected to an Arduino Uno via the signal and ground. Also, I have two switches connected to the Arduino, for forward and reverse of the motor.

In the code, for speed of the motor, I have set 90 as the mid point and 100 for forward and 80 for reverse. When I push the reverse button, the motor runs smoothly in the reverse direction at the set speed. However, the problem is, when I press the forward button, the motor runs seemingly **slower** in the forward direction than the set speed.

My logic here was, if I have set speeds in forward and reverse at +/- 10 from the mid-point, the motor should run at the same speed in the forward and reverse direction, but this is not happening.

I am pasting my code below. Any help would be much appreciated. Thank you!

    #include <Servo.h>

    int forwardPin = 2;
    int reversePin = 4;
    int motorPin = 10;
    int fwdReading = 0;
    int revReading = 0;

    Servo myservo;

    void setup() {
      TCCR1B = TCCR1B & 0b11111000 | 0x04; // PWM Freq. at 122Hz
      pinMode (forwardPin, INPUT);
      pinMode (reversePin, INPUT);
      myservo.attach(motorPin);
      myservo.write(90);  // set servo to mid-point
    }

    void loop() {
      fwdReading = digitalRead(forwardPin);
      revReading = digitalRead(reversePin);
      if (fwdReading == HIGH) {
        myservo.write(100); // forward
      } else if (revReading == HIGH) {
        myservo.write(80); // reverse
      } else
        myservo.write(90); // neutral
    }

body:
I searched for the library you're using and the arduino website mentions :

> 0 being full-speed in one direction, 180 being full speed in the other, and **a value near 90 being no movement**

From this we can take that the value 90 is not perfectly in the middle of the speed range therefore 10 points under 90 won't necessarily be equivalent to 10 points above 90.
My only advice is to try and find the equivalence point yourself by trail and error.
Even though 90 seems to cause no movement, try 89 or 91 see if they also have the result and so on.

Or simply try different values to get same speeds in different directions, it's ok if you use different values (away from 90) for the two different directions :P.

Gd Luck


message:
Is it safe to power an MQ-7 gas sensor with a 9V D.C supply?

I'm looking for a portable power source for an MQ-7 gas sensor. According to my research - it needs 5V D.C power with at least 0.3A of current. I'm not really good with electronics so I need to know if I can use a 9V battery instead which produces 0.5A. Will the cell damage my sensor and if it does may you please recommend me something else.

body:
You can, but you will have to reduce the voltage to the 5V the sensor needs, otherwise you will blow up the sensor.

To that end you require a voltage regulator. You can use a linear regulator like the Arduino has on-board, but they are very wasteful of power and will dissipate the excess 4V of electricity as heat.

Better would be to use a switching regulator (commonly and cheaply available on eBay and other sites) to step the voltage down to 5V more efficiently.


message:
How do I use SNAP protocol, correctly?

[I've reviewed the documentation][1]

  [1]: http://www.hth.com/filelibrary/pdffiles/snap.pdf

I'm still a little lost when it comes to applying the functions. Each of the redundancy check methods take in an unsigned char and return an unsigned char.

Shouldn't there be some sort of boolean return somewhere confirming that the data is accurate?

I've been trying to debug `unsigned char* tempData = "snap"` to the terminal, writing it directly to the register, according to the doc it should return `h17`:

      UDR0 = crc8(tempData,sizeof(tempData));

The terminal outputs '?' - as if it cannot be read.

body:
The `crc8` function calculates the Cyclic Redundancy Check (8-bit) value for the data you provide. It is then up to you to compare that calculated value with the CRC you have received.

The `?` you are seeing in the serial terminal is an *unprintable* character. It is representing an 8-bit value that doesn't lie within the 32-127 range of normal ASCII characters, or 32-255 of the extended ASCII character set.


message:
Extracting a substring from original string

I am trying to extract a substring out of another string, but it doesn't seem to be working. I am new to programming in arduino and c++ in general. Here is my code:

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

    char rfid;

    void loop()
    {
      while (Serial.available() > 0)
      {
        rfid = Serial.read();
        String cardnum(rfid);
        cardnum.replace("", "");
        cardnum.replace("", "");
        String id = cardnum.substring(0,2);
        Serial.print(id);
      }
    }
The first argument in `cardnum.replace("", "");` and `cardnum.replace("", "");` replaces the start and end bit with nothing, but it somehow doesn't display it correctly here.
Now on to the problem at hand. The output for `cardnum` is <i>1F006B471F2C</i> which it should be, but the ouput for `id` is the same, when i want it to be only the first two characters of `cardnum`. How would i go about achieving that.
Thanks in advance for any answers you can provide.

body:
Let's dissect your program a moment and see why it's not doing what you want:

    while (Serial.available() > 0)
    {

So while there are characters available to read in the serial buffer

      rfid = Serial.read();

read one character into the `rfid` variable.

      String cardnum(rfid);

Convert that character into a string.

      cardnum.replace("", "");

Replace nothing (`""`) with nothing (`""`)

      cardnum.replace("", "");

Do the same again,

      String id = cardnum.substring(0,2);

Take the first two characters of the string that contains the single character that you have read.

      Serial.print(id);

Print it.

So basically you have read one character, made it into a string, done nothing to it, copied it to another string, then printed it.

Instead of this method, which does nothing useful, you should read the whole ID into a string (I'd use a C string [i.e., char array] rather than an Arduino String object) then perform operations on that string once you have read the whole ID code.

There's many methods of doing that, but how you do it is heavily influenced by exactly how the data is presented to you. Does it have a terminating CR or LF to indicate the end of the string? If not you will have to use some form of timeout to determine when the string has been completer.


message:
Looking for a Mega 2650 drawing or picture that shows the components labeled

I am Looking for a Mega 2650 drawing or picture that shows the components labeled.

I've seen the schematics but didn't find a labeled assembly drawing yet.  Should this exist?

Thanks

body:
Yes, it exists, but not (commonly) as an "image" in the traditional sense.

You need to install Eagle PCB design software and open the PCB file downloadable from the Arduino site from where you can see exactly which component is where.


message:
Trying to start a timer to change lights when a button is pressed

I am trying to setup a series of lights (traffic lights) that change based on a timer that begins when a button is pressed.  The goal is to use the lights to track how long its been since you pressed the button.

The issue I am running into is trying to use the "TimeAlarms" library.  I am getting an error
'Timer' was not declared in this scope

I think it may be an issue with the version of Arduino I am using (1.6.8) but I am not sure.

Board: Arduino Leonardo

**Here the code**:

    #include <TimeAlarms.h>
    #include <Time.h>
    #include <TimeLib.h>

    int redPin = 2;
    int yellowPin = 3;
    int greenPin = 4;
    int buttonPin = 5;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      while (!Serial) ;
      pinMode(redPin, OUTPUT);
      pinMode(yellowPin, OUTPUT);
      pinMode(greenPin, OUTPUT);
      pinMode(buttonPin, INPUT);
      // set timers in seconds, yellow = 24 hours, red = 48 hours)
      // http://www.pjrc.com/teensy/td_libs_TimeAlarms.html
      Alarm.timerOnce(86400, YellowTimer);
      Alarm.timerOnce(172800, RedTimer);

    }

    void loop() {
      // put your main code here, to run repeatedly:
      if (digitalRead(buttonPin))
      {
          setLights(LOW, LOW, HIGH)
          void YellowTimer(){
             setLights(LOW, HIGH, LOW)
             }
          void RedTimer(){
             setLights(HIGH, LOW, LOW)
             }
      }
      delay (1000);
      }

    void setLights(int red, int yellow, int green)
    {
      digitalWrite(redPin, red);
      digitalWrite(yellowPin, yellow);
      digitalWrite(greenPin, green);
    }

Any help would be greatly appreciated.

body:
You must first declare your timer functions. I have placed them above so they are visible when you call the timer. Also in the loop() you want probably to call timer.
I have changed the code to reflect what I told above. I do not have ability to test this, so please try. There may be some syntax errors, but I think you can handle it.

    #include <TimeAlarms.h>
    #include <Time.h>
    #include <TimeLib.h>

    int redPin = 2;
    int yellowPin = 3;
    int greenPin = 4;
    int buttonPin = 5;

    void YellowTimer()
    {
        setLights(LOW, HIGH, LOW)
    }

    void RedTimer()
    {
        setLights(HIGH, LOW, LOW)
    }

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      while (!Serial) ;
      pinMode(redPin, OUTPUT);
      pinMode(yellowPin, OUTPUT);
      pinMode(greenPin, OUTPUT);
      pinMode(buttonPin, INPUT);
      // set timers in seconds, yellow = 24 hours, red = 48 hours)
      // http://www.pjrc.com/teensy/td_libs_TimeAlarms.html
      Alarm.timerOnce(86400, YellowTimer);
      Alarm.timerOnce(172800, RedTimer);

    }

    void loop() {
      // put your main code here, to run repeatedly:
      if (digitalRead(buttonPin))
      {
          setLights(LOW, LOW, HIGH)
          Alarm.timerOnce(86400, YellowTimer);
          Alarm.timerOnce(172800, RedTimer);
      }
      delay (1000);
      }

    void setLights(int red, int yellow, int green)
    {
      digitalWrite(redPin, red);
      digitalWrite(yellowPin, yellow);
      digitalWrite(greenPin, green);
    }


message:
Why does the arduino respond so slow to serial input

I have this really simple sketch where I blink a led light.
If I send another value threw the serial monitor then first there is always a brief second where the light doesn't blink anymore. Why is that, and how can I get rid of that?

    int the_delay = 300;

    void setup() {
      Serial.begin(115200);
      pinMode(12, OUTPUT);
    }

    void loop() {
      digitalWrite(12, HIGH);
      delay(the_delay);
      digitalWrite(12, LOW);
      delay(the_delay);
    }

    void serialEvent() {

      if (Serial.available()) {
        the_delay = Serial.parseInt();
        Serial.println(the_delay);
      }
    }

In case it helps, eventually I would like to send values with 60fps.

body:
It's because you're using `Serial.parseInt()`.  It uses a timeout to find the end of the data on the serial port, and while it's waiting for that timeout it can do nothing else.

You would be better off manually reading the serial data a character at a time to build up an input string (C-string, not Arduino String) with a proper line terminator (line-feed, `\n`) and then convert that into an integer with `atoi()`.


body: Try typing a non-digit character after the delay value; even `Enter` should work if your terminal is configured to send any kind of end-of-line. `Serial.parseInt()` waits the full timeout (default: 1000 ms) after each digit, for the next one. A non-digit will end the input value immediately.


body:
See [How to process incoming serial data without blocking](http://www.gammon.com.au/serial). An interim solution is to get the Serial Monitor to send a newline automatically when you press Send.

Here is example code that processes input without blocking:

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

    // Example of processing incoming serial data without blocking.

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

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

    // here to process incoming serial data after a terminator received
    void process_data (const char * data)
      {
      // for now just display it
      // (but you could compare it to some value, convert to an integer, etc.)
      Serial.println (data);
      }  // end of process_data

    void processIncomingByte (const byte inByte)
      {
      static char input_line [MAX_INPUT];
      static unsigned int input_pos = 0;

      switch (inByte)
        {

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

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

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

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

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

        }  // end of switch

      } // end of processIncomingByte

    void loop()
      {
      // if serial data available, process it
      while (Serial.available () > 0)
        processIncomingByte (Serial.read ());

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

      }  // end of loop


body:
Edit as follows:
Serial.begin(115200);
Serial.setTimeout(10); //Maximum time in ms that it should wait for data

The default delay is 1000ms.
The code above sets it to 10ms.
Play around with the Timeout value and check for faults.
https://www.arduino.cc/reference/en/language/functions/communication/serial/settimeout/


message:
a mega 2650 power supply mystery

Something happened to my mega2650 as I was experimenting the other day.  It no longer turned on when powering from the 2.1mm jack or from Vin, regardless of the voltage applied.  A plastic bubble had formed on the 5V regulator, I assumed I had shorted something and fried it.  If I applied 5V to the 5V pin everything worked fine.  It also works fine when powered from USB.  So I replaced the 5V regulator with a NCP1117 version.  But I have the same situation.  If I apply voltage directly to the 5V regulator input pin I get 5V on the output pin and everything is fine.  I tested up to 12V and it is dead on at 5V.  I also checked the PNP switching transistor, and found it was working correctly.  As far as I can tell, the only thing remaining is that the trace is severed somewhere between just after the Vin pin and the 5V regulator, maybe the regulator input is not soldered well to the trace?  But this was one of the better solder joints I made, so I thought.  Any other ideas as to the root cause?

Thanks

body:
You obviously have some form of DMM or volt meter at your disposal, since you know the voltages around the regulator.

Some places you should, therefore, probe for voltages, and what voltages you should expect.  With the barrel jack connected and powered up, and assuming a 12V supply, you should expect:

1. At the rear of the socket: 12V
2. At the socket side of the M7 diode: 12V
3. At the header side of the M7 diode: 11.4V
4. At the right-hand (VIN) pin of the regulator: 11.4V
5. On the tab of the regulator: 5V

If you find any of those are wrong then the component that comes before it may well be faulty.


body: Well the answer is ... I fried the rest of the board when I was trying to troubleshoot it further :(  I think 12V went to the 328p, it got hot.  Oh well, thanks everyone!


message:
Forensic security of Arduino (SRAM)

Pardon the double post, but I'm not getting much traction with this question over at arduino.cc so I'm looking for answers here now.

Original post: http://forum.arduino.cc/index.php?topic=391698.0
> I get the idea of uploading a "stop" sketch for the purpose of
> overriding a previously uploaded program in Flash memory space.
>
> Then of course we have EEPROM for "long-term" storage.
>
> However, let's say an Arduino: Read user input as secret key and store
> in memory (SRAM) Performed a signing operation with secret key
> Subsequently powered off
>
> We know that computers introduce a wide range of complications to
> security because data can still be recovered, even after being erased
> or overwritten in some cases, variables stored in memory float around
> (unless pinned for decryption in SecureString contexts, etc.), etc.
>
> To establish context for the following questions, let's [overly]
> simplify the attack vector in saying this would be a scenario where an
> Arduino used in a security application is physically disconnected,
> stolen, and then powered on sometime later.
>
> Question 1: Obviously we're not talking about storing keys on disk
> necessarily (i.e. EEPROM). How likely (or difficult) would it be to
> analyze SRAM with the intent to recover keys that may have been
> previously stored in memory?
>
> Question 2: Similarly, let's say sensitive information was in fact
> stored in EEPROM.  Does the same hold true of data previously stored
> in EEPROM that has since been overwritten with new (i.e. zero) data?

Any help would be greatly appreciated. Thanks!

body:
Uploading a new sketch using the IDE does "page erases" which means that a small sketch will not completely replace a larger one. However using a ICSP programmer starts with a complete flash erase, so that would be more secure. Or you could probably (and it would be better to) upload a new sketch containing mostly random data (eg. a large array in PROGMEM).

Rewriting EEPROM should be pretty secure, especially if you replace the EEPROM with random data, and preferably do it a number of times.

As for SRAM, I would be surprised if you could recover much after a power-off. If the attacker manages to keep the power on that would be different. If possible, write over sensitive data with random bytes as soon as you don't need it any more.

If the data has to stay in RAM, I could envisage a scenario where if I got access to the processor (still powered on) I would upload a small sketch which would simply dump RAM to (say) the serial port a byte at a time, to avoid needing much RAM to do the dumping.

I think the AVR processors at least would be comparatively safe. After all they don't have disks, virtual memory, or fancy remapping of sectors like a USB stick might.

> Read user input as secret key and store in memory (SRAM) Performed a signing operation with secret key. Subsequently powered off.

Sounds pretty safe once you specify "powered off".

---

<https://xkcd.com/538/>

[![Scurity][1]][1]

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


body:
RAM memory looses its contents when it's powered off. However, this
natural erasure process is not instantaneous: it can take several
seconds, or even minutes. It has been demonstrated that cooling down a
memory chip can extend its data retention time to _hours_, which enables
a type of attack known as [cold boot
attack](https://en.wikipedia.org/wiki/Cold_boot_attack).

This type of attack has been studied mostly on DRAM computer modules.
The Arduino memory, however, is based on SRAM, which is physically very
different from DRAM (a transistor feedback loop vs. a capacitor). There
seems to be very little research on cold boot attacks against SRAM. I
found nonetheless a technical report from the computer laboratory of the
University of Cambridge: [Low temperature data remanence in static
RAM](http://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-536.pdf), by Sergei
Skorobogatov. Quoting from the conclusion:

> Contrary to the established wisdom, there are several chips that
> retain data for dangerous periods of time at temperatures above −20°C.
> The temperature at which 80% of the data are retained for one minute
> varies widely between devices. Some require cooling to at least −50°C,
> while others retain data for this period at room temperature.
> Retention times can be significantly reduced by shorting VCC to ground
> rather than by leaving it floating.

From this perspective I would say that, although the attack seems non
obvious, your secret key is not completely safe even in SRAM. Since the
data retention time varies widely between devices, it could be worth
testing on your Arduino. If possible, I would suggest you overwrite the
key after the signing operation.

------------------------------------------------------------------------

**Update**: I did a quick test on my Arduino Uno, at room temperature,
by just unplugging and plugging back the board. Here is my test code:

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

    // This memory buffer will not be zeroed at startup by the C runtime.
    uint8_t __attribute__((section(".noinit"))) buffer[1024];

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

    void loop()
    {
        switch (Serial.read()) {
            case 'i':  // Initialize the buffer with pseudo-random bits.
                srand(42);
                for (size_t i = 0; i < sizeof buffer; i++)
                    buffer[i] = rand();
                Serial.println(F("Buffer initialized."));
                break;
            case 'f':  // Report number of flipped bits.
                int count = 0;
                srand(42);
                for (size_t i = 0; i < sizeof buffer; i++) {
                    uint8_t mask = buffer[i] ^ rand();
                    while (mask) {
                        count += mask & 1;
                        mask >>= 1;
                    }
                }
                Serial.print(F("Flipped bits: "));
                Serial.print(count);
                Serial.print(F(" / "));
                Serial.println(8 * sizeof buffer);
        }
    }

And this is the output, with my comments on the right:

    Program started.            ← fresh boot
    Buffer initialized.         ← pressed 'i'
    Program started.            ← pressed the reset button
    Flipped bits: 0 / 8192      ← pressed 'f'
    Program started.            ← unplugged and plugged back
    Flipped bits: 4166 / 8192   ← pressed 'f'

It appears the RAM is preserved across a warm reboot (pressing the reset
button), but it is completely lost after a power cycle: half the bits
flipped is a total loss of information. I tried to do this as fast as I
could, which is slightly less than one second. It would seem the SRAM in
the ATmega chips decays pretty fast, at least at room temperature.

------------------------------------------------------------------------

**Update 2**: I found an enlightening story about an unpowered AVR
keeping data in RAM for more than 10 minutes, but only on mornings:
[The mystery of the Zombie
RAM](http://wp.josh.com/2014/03/03/the-mystery-of-the-zombie-ram/).


message:
SMS Receiving problem - Arduino Uno and SIM900A GSM Module

My intention is to control an LED according to the content of the SMS received. For example, if the SMS is "ON", turn on the LED and if it is "OFF", turn it off. I referred many sites and got the below code.
The digital pins 9 and 10 are used instead of Rx and Tx to avoid the code uploading problem.

(I have kept the different versions of AT commands commented in the code because I'm not sure which one is correct. With the current one, I'm able to get some kind of output which I've mentioned after the code.)

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(9, 10);

    char msg;
    void setup()
    {
      Serial.begin(9600);
      mySerial.begin(9600);   // Setting the baud rate of GSM Module
      delay(1000);
      //mySerial.print("AT+CMGF=1r"); // set SMS mode to text
      mySerial.print("AT+CMGF=1\r");  // set SMS mode to text

      delay(100);
      //mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
      //mySerial.print("AT+CNMI=2,2,0,0,0r");

      mySerial.print("AT+CNMI=1,2,0,0,0\r"); // AT Command to receive a live SMS
      delay(100);
      Serial.println("Ready");
    }

    void loop()
    {
      if (mySerial.available()>0)
      {
        msg=mySerial.read();
        Serial.print(msg);
      }
    }

This is the output I'm getting..

    Ready
    AT+CMGF=1
    AT+CNMI=1,2,0,0,0

    OK

    +CMTI: "SM",31

    +CMTI: "SM",32

    +CMTI: "SM",33

    +CMTI: "SM",34

The issue is, I'm not able to retrieve the message content. What I'm getting is

"+CMTI: "SM",31"

"+CMTI: "SM",32"

and the number keeps on incrementing. (33, 34 and so on).

I do understand that I have to parse the message to get the exact content, but here I'm not getting the content at all. What exactly should I do to get the SMS content? Could anybody help me to solve this?

One more thing, the GSM module I'm using is a SIM900A type (from elementzonline.com). It's not a shield type, so I've made connections using wires; the Rx, Tx connections and the ground one.

(Sorry for the bad explanation, I'm a complete noob in Arduino, a hobbyist.)

Thanks in advance.

body:
Instead of using At commands use the GSM library of Arduino it easier to understand and implement.
the code to recieve SMS

        #include <GSM.h>

        // PIN Number for the SIM
        #define PINNUMBER "" //sim pin incase the sim is kept locked

        // initialize the library instances
        GSM gsmAccess;
        GSM_SMS sms;

        // Array to hold the number a SMS is retreived from
        char senderNumber[20];

        void setup() {
          // initialize serial communications and wait for port to open:
          Serial.begin(9600);
          while (!Serial) {
            ; // wait for serial port to connect. Needed for native USB port only
          }

          Serial.println("SMS Messages Receiver");

          // connection state
          boolean notConnected = true;

          // Start GSM connection
          while (notConnected) {
            if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
              notConnected = false;
            } else {
              Serial.println("Not connected");
              delay(1000);
            }
          }

          Serial.println("GSM initialized");
          Serial.println("Waiting for messages");
        }

        void loop() {
          char c;

          // If there are any SMSs available()
          if (sms.available()) {
            Serial.println("Message received from:");

            // Get remote number
            sms.remoteNumber(senderNumber, 20);
            Serial.println(senderNumber);

            // An example of message disposal
            // Any messages starting with # should be discarded
            if (sms.peek() == '#') {
              Serial.println("Discarded SMS");
              sms.flush();
            }

            // Read message bytes and print them
            while (c = sms.read()) {
              Serial.print(c);
            }

            Serial.println("\nEND OF MESSAGE");

            // Delete message from modem memory
            sms.flush();
            Serial.println("MESSAGE DELETED");
          }

          delay(1000);

        }


body:
You should download the SIM900 command set (Google away) and read it. According to your CNMI settings, sms notifications are pushed to the Arduino not the sms content, thus the +CMTI data you're receiving. `SM` tells you the sms is stored on the SIM and the number that follows tells you the index of the sms in the SIM memory. With that index, you use the command `AT+CMGR=<index>` to get the sms content (as well as the sender number and timestamp) from the modem.

So basically, you must parse the CMTI notification, get the number at the end, and use that number to retrieve the SMS content from the modem with the CMGR command. You could also change your CNMI settings to (2,2,0,0,0) i think, if you want the content of the messages to be sent by the modem, and not the notifications alone.

In either case, the SoftwareSerial Receive buffer will most likely overflow when receiving the sms content from the modem; because you cant read() fast enough. This will make the message appear truncated. You have to increase the size of the SoftwareSerial RX buffer to prevent this. [Here's][1] a link to an answer where this is explained. Good luck.

  [1]: https://arduino.stackexchange.com/questions/21210/how-to-set-delay-on-gsm-shield


body:
use cnmi 2,2,0,0,0 to get the SMS contents
use cnmi 1,2,0,0,0, to get only the notification with CMTI+.... if you want to read the cont then u need to parse and check wht number u get in SM and then read that numbered msg using CMGR


message:
Regarding use of software serial two times

Can we configure two digital pins as serial pins using software serial library?

body:
Kind of, yes - however you can't use them both at once. SoftwareSerial is blocking. That is, while one port is receiving or sending data the other port will be completely locked out so won't be able to receive anything. So it kind of breaks it in a nasty way.

Personally I never advocate the use of software serial unless there is absolutely no choice whatsoever, and that is something I have never found.

If you need more than one UART then pick a chip with more than one UART.


message:
How to measure water turbidity with arduino

I would like to measure water turbidity in the sea. The sensor does not need to measure it in an accurate way, I just need to know if water is clear or very turbided. I know that there could be used a light scatter but I do not know what kind of sensor should I use. Could anyone help how to measure turbidity?

body:
http://uk.farnell.com/ams/tsl257-lf/sensor-light-voltage-converter/dp/1226886
is a good one according to http://forum.arduino.cc/index.php?topic=299993.0

But it might be easier to buy a COTS sensor, its a bit more expensive but much easier.  http://www.aliexpress.com/item/Turbidity-Testing-Sensor-Module-Suite/1903197650.html?spm=2114.01010208.3.17.OSVwdj&ws_ab_test=searchweb201556_9,searchweb201602_2_10017_9868_10005_10006_10034_10021_507_10022_10020_1000020_10018_10019,searchweb201603_8&btsid=6dbcca61-3e0a-4e34-9359-a6c26b268509

BTW for everyone else Turbidity is the amount of muck in the water, so it would be no good looking at the crystal clear waters off the UK coast :)


body: I used an array of cheap light dependent resistors hermetically sealed and used a torch. For dark water, it clearly shows a lower value than for cristal water. It is kind of a binary sensor, but I was proud of my basic invention!


message:
How can I power an Arduino Nano with a LiPo battery, preferably 3.7v

I am a newbie to Arduino, so please bear with me. I am trying to figure out how to power an Arduino Nano with a LiPo battery. I want to use a 3.7v if possible, as my project needs to be lightweight. There are two possibilities I know *could* work:

-Taking a USB to Mini-B USB, cutting off the normal USB end, and soldering a connector (based on the battery I use) to that end. I would then plug the Mini-B USB into the Nano, giving it power.

-Using the 5v and Ground pins.

I would prefer to use the USB cable solution, however the 5v/Ground or any other solution is perfectly usable.

Also, would 3.7v be enough to power the Nano, two Infrared LEDS (Launch and Receiver), and a 7-segment LED display. I also have a button.
                                                             Thanks, saddlepiggy!

body:
In short: not reliably.  The Arduino Nano expects either a 5V regulated supply or a 6-20V unregulated supply (https://www.arduino.cc/en/Main/ArduinoBoardNano).  Even if you plugged it in and it worked initially, the battery voltage will decrease gradually as it discharges (LiPo cells can drop as low as ~3.2V), making it more and more unreliable.  You'd technically be overclocking the processor, since the Nano runs at 16 MHz and the [datasheet for the microcontroller](http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet_complete.pdf) requires at least a 4.5V supply to run above 10 MHz.

A safer solution would be to use a 2S LiPo battery (~7.4V), which would be plenty to supply the regulated input pin (VIN).  On the other hand, if you're set on using a 3.7V LiPo, other Arduino boards (like certain versions of the Pro Mini) run at 3.3V.

As for your second question, 3.7V is plenty to power a few LEDs so long as they are connected in parallel (or to separate pins).  The only thing you need to be aware of is current draw--more current means shorter battery life.  For example, if your circuit draws 100 mA total from the battery, and your battery is specified at 500 mAh, you will get approximately (500 / 100) = 5 hours of battery life.


body: Late to the convo but quick comment in case anyone else reads this thread still. Arduino uses a linear regulator on Vin. In that case the “extra” voltage gets wasted. You’d get a much more efficient battery use by using a buck or boost circuit to provide it the correct 5V on the 5V pin (or usb) rather than feeding a 2S LiPo into Vin. It would work both ways but you’d get noticeably longer run time with a switching power converter.


message:
Why does this method return an unprintable character, how do I convert it to display correctly?

[Page 14][1] says that the method should return the value 'h17'

    typedef struct  {
      uint8_t data;
      uint8_t timestamp;
      unsigned char crc;
    } tData;

    int main(void)
    {
      unsigned char* tempData = "snap";

        for(;;)
        {
          tData payload;
          payload.crc = crc8(tempData,sizeof(tempData));
          UDR0 = payload.crc;
        }

        return 0;
    }

  [1]: http://www.hth.com/filelibrary/pdffiles/snap.pdf

body:
Because “h17” is an unprintable character, namely ASCII ETB. The 'h' in “h17” stands for “hexadecimal”, like the `0x` usually used in C.

You should convert the value to an ASCII number if you want to print it, using for example `Serial.print(payload.crc, 16);` or – if you are not using Arduino core – `(s)printf()`.

----------------------------------------------------------------------

**Edit**: here is an implementation of my comment “_sprintf() into a
buffer and dump the buffer to UDR0 one byte at a time_”:

<!-- language: c -->

    #include <stdio.h>

    void print_byte_in_hex(uint8_t byte)
    {
        // Print the byte in ASCII into an internal buffer.
        char buffer[8];
        sprintf(buffer, "x\r\n", byte);

        // Send it one byte at a time through the USART.
        for (char * p = buffer; *p; p++) {
            loop_until_bit_is_set(UCSR0A, UDRE0);
            UDR0 = *p;
        }
    }


message:
Arduino controlling a heavy solenoid water valve

So after burning up a couple Arduinos, I'm running out of ideas...

I am trying to power both a Solenoid valve and the Arduino(nano) with the same 12V-2amp power supply. I've tried it with both a relay breakout board, and via transistor switching, and both are giving me sporadic behavior for the Solenoid.

Early failures came from realizing that the solenoid water value was actually a coil (duh), and thus needed some kind of diode placed over its connections, so I'm assuming the back voltage spike is what fried the first two boards.

At first I added a small diode that helped but wasn't enough, so I beefed it up to a 3 amp "rectifier diode" 200PIV, which stopped the board frying.

Here is a link to the [solenoid water valve][1]. Not much to go on I'm afraid. 12V 0.02-0.8Mpa.

The behavior that I'm seeing now, is that the solenoid will engage, but it won't disengage.

Do I need to add a Capacitor for the solenoid?  If so, any recommendations on sizing?

[![Fritzing Schematic][2]][2]

    int relayPin = 2;

    void setup()
    {
      pinMode(relayPin, OUTPUT);
      Serial.begin(115200);
    }

    void loop()
    {
      Serial.println("starting");
      digitalWrite(relayPin, HIGH);
      delay(2000);
      digitalWrite(relayPin, LOW);
      delay(2000);
    }

  [1]: http://www.ebay.com/itm/281784710402?_trksid=p2060353.m2749.l2648&ssPageName=STRK:MEBIDX:IT
  [2]: https://i.stack.imgur.com/arA8E.png

body:
I have setup Arduino UNO and succeeded turning solenoid on when pot soil moisture dry, I was adding rain sensor when I mistakenly disvmcoonected the diode it fried my board, but atleast I had it working . I am using 24 volt normally closed solenoid , since I was monitoring over web I also had ethernet shield attached. And I was powering over ethernet using splitter and extracter.

![enter image description here](https://i.stack.imgur.com/hYpDy.jpg)

The vin should only feed in 3.3 volt which you can get using stepdown buck converter , and use remains power to connect to solenoid. The transistor should be on the ground same as arduino nano the ground
The top became messy later
![enter image description here](https://i.stack.imgur.com/gcemW.jpg)


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

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

Try This Circuit...

1. I think you are overpowering Arduino Board.

2. Transistor Will not Carry heavy current for long duty period.

3. It easy to use Simple 5v relay board then you don't have to worry about Current limits and all...


body:
The fact that the solenoid turns on but not off makes me think the Arduino might just not switch off the GPIO. This could happen if the current drawn by the solenoid is so high that the power supply voltage drops below the threshold needed for the Arduino, resulting in a reset.

The result would be that the Arduino repeatedly switches on the solenoid but is reset before it can switch it off again.

Try to flash the built in LED in the same main loop to verify that the loop is still alive.


message:
Program nodeMCU Over the Air (OTA)

I have a Lolin NodeMCU V3 with a broken USB port: no power, no data.

It does show up on WIFI as `AI-thinker_xxx`, I can connect, but what can I do next?

Is there a way to program the NodeMCU Over the Air (OTA), or through some pins?

[Description found here][1] under V3

[1]:http://frightanic.com/iot/comparison-of-esp8266-nodemcu-development-boards/

body:
If powering over Vin pin is working, you can use the board without USB.

ESP8266 is bootloaded over UART pins. These are pins marked RX or D9 and TX or D10 on the NodeMcu board. You can use USB to TTL serial adapter to bootload (flash) the esp8266. To put the esp in flashing mode hold the FLASH button and click the RST button and then release the FLASH button.

You can then upload a sketch with ArduinoOTA library and do following uploads over OTA. After USB upload of a sketch, reset the board with RST button before doing the first OTA upload.


message:
Can I measure velocity from an accelerometer? How accurately?

I've bought this module

[Kootek GY-521 MPU-6050 MPU6050 Module 3 Axis analog gyro sensors+ 3 Axis Accelerometer Module][1]

  [1]: http://www.amazon.com/Kootek-MPU-6050-MPU6050-sensors-Accelerometer/dp/B008BOPN40?ie=UTF8&psc=1&redirect=true&ref_=od_aui_detailpages00

My project will involve affixing this to a moving object, moving at velocities varying from 0.1 to 1.0 meters per second.

From what I understand, this module will allow me to infer rotation and acceleration, will I be able to derive velocity?

How much accuracy can I expect?

body:
I don't think that will be possible. If my understanding of accelerometers is correct, they measure acceleration. Then you have a situation when the speed is constant. Acceleration = 0, according to Newton's laws.

You would have to keep track of changes in acceleration then perform math to maintain the state. As @Chris Stratton suggest, that will lead to keep integrating the error to the very likely situation of getting a meaningless value.

However, I have never worked with an accelerometer before, so it can be possible at a certain extent.

It would be great to hear from someone who actually tried this.


body:
I work with Arduino-based autopilot modules, which usually use similar sensors in addition to GPS data to maintain a reasonable estimate of its position/velocity/acceleration.  If you were to add other sensors (i.e. a GPS) to your project, it might be worth looking into Extended Kalman Filters (https://github.com/simondlevy/TinyEKF), which are usually able to provide fairly accurate results.

If you're only using an accelerometer, EKF would probably be overkill, so you could look into other noise-reduction techniques.  For example, using a weighted average of the last two readings:

    // alpha is value between 0 and 1
    acceleration = alpha * readAccelerationSensor() + (1 - alpha) * lastSensorReading

Another strategy to filter out noise would be to take multiple sensor readings at each time step and use the median value to integrate for velocity.


body:
The sensor in itself can't provide you the velocity. I have used it accelerometers in a couple of projects the easiest way to get the velocity is to constantly monitor acceleration changes and calculate velocity instantaneaously.

In order to do so follow these instruction. Pleas note that this is only 1 axis reading in actual case you will have to perform this for all three axis i.e. x,y and z.

I hope you are aware of the equation of motion (V = Vo + at)... The sensor will provide you value of acceleration at any given time. But acceleration can vary quite significantly during a huge time intervals so keep the time intervals 't' small. Lets say t = 10ms (depends on you). So calculate V after every 10ms intervale and this will give you current velocity at any given time. But what about Vo? As you know it is refered to as initial velocity so in the beginning it will be 0. Immediately after first reading when you are about to take second reading the Vo will change to the previous V calculated and hence forth.

This means Vo at any given interval is actually the V calculated in the previous interval.

I tried this method in my project when using accelerometer. hope it helps you as well.


body:
I think that calculating the instantaneous velocity as described by Usama is the correct method so long as you can deal with the cumulative error. I would also suggest that you provide regular recalibration to deal with that (like a return to home).

However, if you are trying to calculate velocity the best method would be to use a gyroscope, not an accelerometer.

Gyroscopes were (are?) how submarines navigate underwater. To measure acceleration with gyro sensors it is of course the rate of change of the velocity. V = Vo + at and d = Vo.t + (a.t^2)/2 are your two most important formulas.

Which you choose depends upon your application.  I would chose either based on whether my application is more likely to have constant velocity or frequently accelerating and decelerating. Maybe even have both...

I have not experimented with digital gyro sensors but note that there are a couple of Arduino shields available.


message:
Removing Element From Array While Keeping Order

I'm building a wireless mechanical keyboard. There is an array of 6 elements that stores the keys pressed by the user (since 6 is the max number of keys you can send at once over Bluetooth). An example would be `02-05-03-00-00-00`. Notice the "00" at the end, these are just "placeholders" and don't have a meaning other than to indicate that there are no more keys pressed. When the user releases key 05 for example, the array should become this `02-03-00-00-00-00`. I don't know how to do this however, since you can't just remove and item from an array and there doesn't seem to be a polished option for lists in Arduino.

Does anyone have any idea for an algorithm that finds the 0's in an array, places them at the end of the array and keeps the order of the other elements?

body:
You need to compact the vector: First search for the first non-zero element and then move all non-zero elements. It could look something like below:

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

      char vec[] = { 2, 5, 3, 0, 0, 1 };
      print(vec, sizeof(vec));

      compact(vec, sizeof(vec));
      print(vec, sizeof(vec));

      vec[1] = 0;
      print(vec, sizeof(vec));

      compact(vec, sizeof(vec));
      print(vec, sizeof(vec));
    }

    void loop()
    {
    }

    void compact(char* vec, size_t len)
    {
      int i = 0;
      for (; i < len && vec[i] != 0; i++);
      if (i == len) return;
      int j = i;
      for (; i < len; i++) {
        char c = vec[i];
        if (c != 0) {
          vec[j++] = c;
          vec[i] = 0;
        }
      }
    }

    void print(char* vec, size_t len)
    {
      for (int i = 0; i < len; i++) {
        unsigned c = vec[i];
        if (c < 16) Serial.print(0);
        Serial.print(c, HEX);
        if (i + 1 < len) Serial.print('-');
      }
      Serial.println();
    }

This give the following output:

    02-05-03-00-00-01
    02-05-03-01-00-00
    02-00-03-01-00-00
    02-03-01-00-00-00

Cheers!


body:
**Remove Zeros**

    void removeZeros(uint8_t array[], size_t length) {
    // Sanity check.
    if(array != nullptr && length > 0) {
        for(size_t i = 0; i < length; i++) {
          if(array[i] == 0) {
            for(size_t j = i + 1; j < length; j++){
              if(array[j] != 0) {
                array[i] = array[j];
                array[j] = 0;
                break;
              }
            }
          }
        }
      }
    }
Usage:

    uint8_t keyBuffer[] = { 2, 0, 3, 0, 4, 0 };
    removeZeros(keyBuffer, sizeof(keyBuffer)/sizeof(keyBuffer[0]);

New value of keyBuffer: { 2, 3, 4, 0, 0, 0 }

<br />
**Remove a single indexed value**

    void removeIndex(uint8_t array[], size_t length, size_t index){
      // Sanity check.
      if(array != nullptr && length > 0) {
        for(size_t i = index; i < (length - 1); i++){
          array[i] = array[i + 1];
        }
        array[length-1] = 0;
      }
    }

Usage:

    uint8_t keyBuffer[] = { 2, 5, 3, 0, 0, 0 };
    removeZeros(keyBuffer, sizeof(keyBuffer)/sizeof(keyBuffer[0], 1);

New value of keyBuffer: { 2, 3, 0, 0, 0, 0 }


message:
Send newline through serial monitor

I know I can send a newline using the option in the bottom right:

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

But why doesnt it work to use the option 'No line ending', and send a '\n' or '\r\n' after the text using the arduino serial monitor?

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

body:
The backslash escape encoding for special characters is a feature of double quotes in some programming languages, shells, and other parsers.  It is not normally a feature of live text input - an "end user" human typing a backslash is assumed to mean it literally.

"Live" input of a carriage return or newline is more traditionally done with the return/enter key, or with the corresponding control codes - CTRL-J for newline and/or CTRL-M for return.  I don't know that the Arduino IDE's Serial Monitor supports either of these, at least once you select "no line ending"


message:
How do I connect a vibration sensor/switch to a breadboard?

I have the following vibration sensor:

[![Vibration Sensor][1]][1]

It has one short/firm-er terminal and one long/flimsy terminal.  Now the shorter terminal slides easily into my breadboard but the flimsy one clearly does not.  A few related questions:

1) How do I go about connecting this to my breadboard (simply plugging it in doesn't work)?  Do I have to solder a wire onto the flimsy end?

2) Why is this switch manufactured this way (with a flimsy end)?

3) Is it right to assume that the longer end is positive (+) and the shorter end is negative (-)?

Thanks!

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

body:
It appears from this information source:
http://www.electrodragon.com/product/vibration-switch-sensor-sw-18020p/
that the sensor is an electrical contact on the firmer side surrounded by a very sensitive spring within the enclosure. The coil spring is by design made of a smaller diameter wire to provide sensitivity to movement. Rather than manufacture a translation to a heavier piece of material, the thinner lead is brought out of the enclosure.

I suspect that it will not work on your breadboard, due to the flimsy end being too small to make solid contact within the breadboard. You could resolve that aspect by soldering on a heavier segment.

Because it is designed as a simple switch, there is no plus or minus.