body:
I'm working on a project that uses an Arduino Uno to listen for a bell ring and then uploads to a web server the exact time the bell was rung using a WiFi Shield.

I want to know how I can listen for the bell ring (a three second long high pitch tone) and be able to detect that that's what the Arduino heard. I think the best way may be to pre-record the sound and then the Arduino will constantly try to match the incoming sounds to the prerecorded sound. I'm wondering how I could go about doing this (or are there better methods).

The bell sounds kind of like this: [bell sound](http://onlinetonegenerator.com/?waveform=square&freq=332)

title: How do I listen for a sound that matches a pre-recorded sound?

Answers: 1

body:
About the simplest starting point is to use an FFT ([fast Fourier transform](http://en.wikipedia.org/wiki/Fast_Fourier_transform)) library (like [ArduinoFFT](http://wiki.openmusiclabs.com/wiki/ArduinoFFT) at openmusiclabs.com) to characterize the spectrum of an audio stream.

[*Edit:* An alternative method (digital bandpass filter) is mentioned below.]

Audio typically is made up of many frequencies of many amplitudes and phases, mixed together.  FFT sorts some of that out; it estimates the amplitudes of the various frequencies that make up a bit of audio.

The general idea is to use an Arduino ADC to take readings of an audio voltage for a fraction of a second, then use FFT to convert the large set of readings to a small set of numbers, in eg a set of 32 or 64 frequency-bins, to represent amplitudes in given frequency ranges.  For example, if the sound during a sample is a mix of five sine waves at five frequencies, the bins those five frequencies are in should have large numbers assigned, while other bins should have small numbers.

The approach would amount to sampling at 10KHz for 0.1 second or so, computing an FFT with 32, 64, etc. bins in the next 0.1 second, and comparing bin counts to a training pattern.  Whenever bin count patterns match reasonably well, start a three-second timer; if several seconds of matching samples occur, declare a match.

If the bell is electronically generated and mostly a mix of pure sine waves, then its sound will have an easily recognized spectrum.  But if the sound source is buzzy and there is background noise, it may be difficult to compare spectra.  See eg
• [Comparing an audio signal with a previous 'taught/profiled' signal](https://dsp.stackexchange.com/q/15105/comparing-an-audio-signal-with-a-previous-taught-profiled-signal)
• [How do I compare chords played on a guitar with a known sample?](https://dsp.stackexchange.com/q/14827)
• [How do I compare 2 audio files, returning a percentage of difference](https://dsp.stackexchange.com/q/1867)
• [What does the phase of a FFT bin of an audio signal represent?](https://dsp.stackexchange.com/q/15239/what-does-the-phase-of-a-fft-bin-of-an-audio-signal-represent)
• [Sound pattern matching using Fast Fourier Transform in Windows Phone](http://developer.nokia.com/community/wiki/Sound_pattern_matching_using_Fast_Fourier_Transform_in_Windows_Phone)
• [How do I go about detecting whistles, pops and other sounds in live audio input?](https://dsp.stackexchange.com/q/9358)
• [The Frequency Domain
Section 3.4: The DFT, FFT, and IFFT](http://music.columbia.edu/cmc/musicandcomputers/chapter3/03_04.php)

**An alternative: digital bandpass filter**

Digital bandpass filters are based on processing a signal in a way that detects the amplitude of the signal's frequency component within designated limits.

For theoretical background see wikipedia's *[Digital filter](http://en.wikipedia.org/wiki/Digital_filter)* article.  Also see [Vaseghi, Chapter 5, Digital Filters](http://dea.brunel.ac.uk/cmsp/Home_Saeed_Vaseghi/Chapter05-DigitalFilters.pdf), (eg section 4.6.6, Design of Band-Pass FIR Filters) pdf file and
[ECE438 digital filter design lecture notes](https://engineering.purdue.edu/~ece438/lecture_notes/legacy_notes/module_1/1.7_dig_filter_design/1.7.3_iir_filter_design.pdf)
pdf file.

You can use MatLab or Octave to do most of the work of designing a filter.  For example, if you have the Signal package installed and loaded into Octave, commands like

    v=cl2bp(30, 0.48*pi, 0.52*pi, [0.02, 1.02, 0.02], [-0.02, 0.98, -0.02], 2^11);
    freqz(v);
    v

will compute coefficients for a [Constrained L2 bandpass FIR filter](http://octave.sourceforge.net/signal/function/cl2bp.html), plot the freqency response (as below), and display the 60 coefficients.  To use the filter, copy the 30 non-zero coefficients into a program, set up a rolling array of readings, and at each sample compute a new filtered value.  If at some point high filtered values occur, and if they recur for about three seconds at the bell's frequency or twice its frequency, then the bell is ringing.  Note, there are other kinds of bandpass filters; the Constrained L2 bandpass FIR filter is shown for convenience, but other kinds may be better.

![Octave graph of freqz][1]

If you are unfamiliar with signal processing, you might need to try the following approach:
1, On your development system, obtain a few seconds of audio to use for tests. (Eg, allocate two buffers of several dozen bytes each; fill one buffer while using the other buffer to send data from the Uno to your development system.  Use (eg) [Serial.write(buf, len)](http://arduino.cc/en/Serial/write) and a high data rate, eg 115200 bps, to send binary data, with three ADC readings packed per four bytes.)
2, Use Octave or similar software to try out several different FFT or filter approaches.  You would use FFT to determine the bell's fundamental frequency and then could try out digital bandpass filters while developing a recognizer.  You can also use [mkfilter](http://www-users.cs.york.ac.uk/~fisher/mkfilter/) to design filters to try out in C programs on your system, and should be able to iterate more quickly while developing your approach than if you were developing it using the Uno.  When you get satisfactory results on your development system, you then can code a sketch to test the technique on your Uno.

Note, for a given filter order, filters implemented using fixed-point integer arithmetic on an Uno can handle more samples per second than those implemented using floating arithmetic.  An Uno might support 50000 to 100000 floating multiplies and adds per second ([1](http://forum.arduino.cc/index.php?topic=40901.0),[2](https://gist.github.com/projectgus/8279947),[3](http://www.engblaze.com/faster-code-fridays-understand-division-and-speed-of-operations/),[4](https://robotics.stackexchange.com/questions/535/how-computationally-powerful-is-an-arduino-uno-board)), vs. two to four times as many fixed-point operations per second.  If your filter uses a dozen floating point ops per sample, your sample rate probably would have to be under 5000 samples per second.  If it uses half as many floating ops or uses fixed point instead of floating point, your sample rate could be twice as much.

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


body: I'd like to use Timer1 to measure the time between rising edges of two input signals.  Specifically, use Tn to start the timer counter and IPCn to latch the elapsed time since the rising edge of the Tn input signal.  The goal is to measure the time between the rising edges of two input signals.   Is there a Timer1 library out there that alread does this?  Code suggestions welcomed.

title: How to use Timer1 (AT328Mega) to measure the time between rising edges of two input signals

Answers: 2

body:
It is not perfect for your simpler task, but here is a link to a [sketch](https://gist.github.com/mpflaga/4404996) that I have used to record pulses, using the Timer1 Input Capture.

In short setup the Interrupt

    void initTimer(void) {

      // Input Capture setup
      // ICNC1: Enable Input Capture Noise Canceler
      // ICES1: =1 for trigger on rising edge
      // CS10: =1 set prescaler to 1x system clock (F_CPU)
      TCCR1A = 0;
      TCCR1B = (0<<ICNC1) | (0<<ICES1) | (1<<CS10);
      TCCR1C = 0;

      //catchFallingEdge(); // initialize to catch
      { TCCR1B &= ~(1<<ICES1); TIFR1 |= (1<<ICF1); rising = 0; }

      // Interrupt setup
      // ICIE1: Input capture
      // TOIE1: Timer1 overflow
      TIFR1 = (1<<ICF1) | (1<<TOV1);  // clear pending
      TIMSK1 = (1<<ICIE1) | (1<<TOIE1); // and enable

      // Set up the Input Capture pin, ICP1, which corresponds to Arduino D8
      pinMode(8, INPUT);
      digitalWrite(8, 0);  // leave floating to count 60 Hz etc.
      //digitalWrite(8, 1);   // or enable the pullup
    }

Then service it

    ISR(TIMER1_CAPT_vect) {
      union twobyte {
        uint32_t word;
        uint8_t  byte[2];
      } timevalue;

      timevalue.byte[0] = ICR1L;  // grab captured timer value
      timevalue.byte[1] = ICR1H;  // grab captured timer value

      // watch for the other edge to catch the half-pulse width
      //rising ? catchFallingEdge() : catchRisingEdge();
      if (rising) {
        TCCR1B &= ~(1<<ICES1);
        TIFR1 |= (1<<ICF1);
        rising = 0;
      }
      else {
        TCCR1B |= (1<<ICES1);
        TIFR1 |= (1<<ICF1);
        rising = 1;
      }
    }

body:
For more help and info, and many examples of various detailed aspects of timers, check out Nick Gammon's articles here: http://www.gammon.com.au/interrupts
and here: http://www.gammon.com.au/timers

Under the first link, do a search for **"The sketch below times intervals between RISING interrupts,"** for example, to find one code segment.

**Now, important question: what is the minimum time you need to measure between events?**  Are we talking milliseconds, microseconds, or nanoseconds?  For the former, you can use pin polling, external interrupts, or pin change interrupts, and the millis() or micros() Arduino functions to grab timestamps. For microseconds resolution, it depends. Even the micros() function only has a 4us resolution, so you'd have to custom-configure the timer if you want better than 4us resolution time-stamps, or you could use the timer2_counter library (http://electricrcaircraftguy.blogspot.com/2014/02/Timer2Counter-more-precise-Arduino-micros-function.html), or your own custom timer solution, for 0.5us resolution timestamps.

For nanosecond resolution (down to 62.5ns time steps), youd prob. need to use Timer1's input capture, as the other answer shows. You can also do a search for **"Timing an interval using the input capture unit"** under the 2nd link above, for another code segment on that.


body:
I'm new so I might be making a stupid mistake, but I'm declaring:

char dollars;

at the begging of file, afterwards I'm reading a data from a web page, printing it to my serial. That part work well. The data returned from the web page is a number, 55 for instance.

The number get's printed correctly to the serial. But when I try to save the complete number it changes. for instance, when I get 0 from the server. The printed result is 10.

here is the important part of my code:

    unsigned long lastRead = millis();
      while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
        while (www.available()) {
          char c = www.read();
          Serial.print(c);
          dollars = www.read();
          lastRead = millis();
        }
      }

      www.close();
      Serial.println(dollars);

while the www.read is repeating each of the returned characters it works fine `Serial.print(c);` but when I save it to the dollars char var, it get garbled up into something different. What am I doing wrong?

I'm planning to show that number from the web page onto my 4 digit screen at the end.

title: Arduino UNO + CC3000 Wifi Shield, Reading webpage data

Answers: 1

body:
Webpages usually return data in text format with new line characters at the end.
In case of 55 you would get "55\r\n" or [53, 53, 13, 10] in bytes.
You need to parse the characters, like [Serial.parseInt()](http://arduino.cc/en/Reference/ParseInt) does.

You are also only sending every second byte back to the serial monitor and only saving the last byte from the other every second byte.
After you read a byte with Serial.read() you can't read the same byte again, you get the next one.
In case of 55 you would send back "5\r" to the serial monitor and only store "\n" or 10 into dollars.
In case of 0 you would send back "0\n" to the serial monitor and store some unknown value into dollars, because you read more bytes that was sent.


body:
I'm attempting to drive 300 TM1803 RGB LEDs from an Arduino Uno using the FastLED library. My code works fine for 100 LEDs, but when I go to 150, the arrays that store LED values and my sensor data get corrupted, causing the LEDs to flash colors randomly every few seconds. From what I've read these are exactly the symptoms of running out of RAM, leading to something overwriting the RAM that contains my arrays.

However, with 150 LEDs, the MemoryFree library says I'm only using 920 bytes of RAM, no matter where in my code I measure, and the IDE says 880. Does anybody know what's going on? Is there something using 1100 bytes of RAM for a very short amount of time, so that I can't measure it?

My code:

    #include "FastLED.h"
    #include <MemoryFree.h>

    const byte ledsPin = 3;
    const byte sensorPin = A1;

    const int numLeds = 300;
    const int ledTime = 1000;

    const int sensorMin = 0;
    const int sensorMax = 512;

    const CRGB correction = CRGB(80,255,70); // Cool white
    //const CRGB correction = CRGB(160,255,20); // Warm white
    const byte hOffset = 170; // baseline hue value
    const int8_t hDirection = -1; // 1 or -1, direction of rainbow
    const byte s = 255; // saturation (colorfulness)
    const byte v = 255; // value (brightness)

    const unsigned int arrayLength = numLeds+1;
    byte hues[arrayLength];

    CRGB leds[numLeds];
    byte h = 0; // hue (color)

    unsigned long sensorSum;
    unsigned int loopCounter;
    unsigned int arrayCounterLed;
    unsigned int updatesPerLed;
    char sp = ' ';
    int arrayCounter;

    unsigned long time;
    unsigned long timeNextLed;
    unsigned long timeLeft;
    unsigned long time1;
    byte route;

    void setup() {
      FastLED.addLeds<TM1803, ledsPin, RBG>(leds, numLeds).setCorrection(correction);
      FastLED.setDither(0);
      pinMode(ledsPin, OUTPUT);
      Serial.begin(115200);
    }

    void loop() {
      delay(10);
      time=millis();
      sensorSum += analogRead(sensorPin);
      loopCounter++;
      if(time >= timeNextLed) {
        timeNextLed = (time/ledTime+1)*ledTime;
        arrayCounter = (arrayCounter +1) % (arrayLength);
        hues[arrayCounter] = (constrain(map(hDirection*sensorSum/loopCounter, sensorMin, sensorMax, 0, 239), 0, 239)+hOffset)%6;
        updatesPerLed = loopCounter;
        loopCounter=0;
        sensorSum = 0;
      }
      for(int led = 0; led < numLeds; led++) {
        time1=micros();
        arrayCounterLed = pseudoMod(arrayCounter - led -1, arrayLength);
        timeLeft = timeNextLed-time;
        byte dist = abs(hues[arrayCounterLed]-hues[(arrayCounterLed+1)%(arrayLength)]);
        if(abs(hues[arrayCounterLed]-hues[(arrayCounterLed+1)%(arrayLength)])<=128) { // if it doesn't cross through 0
          h = (hues[arrayCounterLed]*timeLeft + hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft))/ledTime;
        }
        else if(hues[arrayCounterLed] > hues[(arrayCounterLed+1)%(arrayLength)]) { // if it crosses through 0 forwards
          h = ((hues[arrayCounterLed]*timeLeft + (hues[(arrayCounterLed+1)%(arrayLength)]+256)*(ledTime-timeLeft))/ledTime)%6; // Causing flashing on red pixels?
        }
        else { // if it crosses through 0 backwards
          h = (((hues[arrayCounterLed]+256)*timeLeft + hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft))/ledTime)%6;
        }
        time1 = micros() - time1;
        if(led == 0) {
          Serial.print(dist);
          Serial.print(sp);
          Serial.print(route);
          Serial.print(sp);
          Serial.print(timeLeft);
          Serial.print(sp);
          Serial.print(hues[arrayCounterLed]);
          Serial.print(sp);
          Serial.print(hues[(arrayCounterLed+1)%(arrayLength)]);
          Serial.print(sp);
          Serial.print(hues[arrayCounterLed]*timeLeft);
          Serial.print(sp);
          Serial.print(hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft));
          Serial.print(sp);
          Serial.println(h);
        }
        leds[led] = CHSV(h, s, v);
      }
      FastLED.show();
      Serial.print(updatesPerLed);
      Serial.print(time1);
      Serial.println();
    }

    int pseudoMod(int a, int b) {
      if(a<0) {
        return a+b;
      }
      else {
        return a;
      }
    }

title: Am I Running Out of RAM Or Not?

Answers: 1

body: I found it! I was returning an int8_t variable from my mod function, causing me to not be able to iterate over more than 126 LEDs. Now this little Arduino Uno is maxing out it's RAM at 409 LEDs!


body:
I community! I need put ATcommand to my XBee from my atmega using a "xbee library" and a function that I have found in internet. I think the ATComand is "ATD50" to change the DIO5 to value "0" (disabled). My intention is to turn off a led connected into DIO5 (digital input/output 5 (associated led)) after X second/minutes of turning on the device (so that it doesn't turn one again after initial check).

This is a part of my code:

    #include <XBee.h>
    XBee xbee = XBee();
    uint8_t atdCmd[] = {'A','T','D','5','0'}; //<---command to put DIO5 to "0" (disabled)
    AtCommandRequest atRequest = AtCommandRequest();
    AtCommandResponse atResponse = AtCommandResponse();
    void setup()
    {
    delay(30000);
    atRequest.setCommand(atdCmd);
    xbee.send(atRequest);
    }
    void loop()
    {}

...but it doesn't work!
Thanks guys!

title: AT command XBee from atmega to disable DIO5 (associated led)

Answers: 1

body:
finally I solved the problem with this code:

    uint8_t atdCmd[]={'D','5'};
    uint8_t value[]={4};///pongo DIO5 a output LOW
    uint8_t length=1;
    AtCommandRequest atRequest = AtCommandRequest(atdCmd, value, length);
    xbee.send(atRequest);

The problem was that I tried to put command with 5 caracters,... and only accepts 2 caracters for "AT command"


body:
I'm trying to send data from an ATtiny84 [1mhz] to Arduino Uno using a 433Mhz rf module and Manchester lib.
Now I came across a weird problem, no matter what value I transmit, When I receive it on the arduino and to the Serial monitor, it always shows value of 806,No matter what I have really transmitted.

ATtiny side

    void setup()
    {
      man.workAround1MhzTinyCore(); //add this in order for transmitter to work with 1Mhz Attiny85/84
      man.setupTransmit(transmit_pin, MAN_1200);
    }

    // And how I transmit
    // RGBread is int, I also tried man.transmit((uint16_t)RGBread[i]); same result.
      for(int i=0; i<3; i++)
      {
        man.transmit(RGBread[i]);
      }

Uno

    void setup()
    {
      man.setupReceive(reciever_pin, MAN_1200);
      man.beginReceive();
    }

      if (man.receiveComplete()) {
        Serial.println(man.getMessage());
        man.beginReceive(); //start listening for next message right after you retrieve the message
      }

Thanks to all helpers.

title: Arduino and ATtiny84 w/RF

Answers: 0


body:
Ok, i know professionals generally hate Arduinos, but I would like to know if it would be possible to program Atmel ARM chips using the Arduino IDE. By which I mean, not needing to modify the source code, just add another entry into the "hardware" folder and that's it.

We already know the Atmel ATSAM3X8EA (Arduino DUE) is compattible, but how about a similar chip, like the Atmel ATSAM3X8CA. Or maybe a Cortex-M4 one, like the Atmel ATSAM4E16EA or the Atmel ATSAM4S8CA.

The Atmel ATSAM3X8CA is the closest one to the Atmel ATSAM3X8EA the Arduino Due uses, a bit smaller and with less I/O.

If it isn't possible without much source code modding, I would like to know what would it take to make it work.

Thanks for your answers.

title: Programing other Atmel ARM chips using Arduino

Answers: 1

body:
Yes it is possible. IDE 1.5.+ support different platforms, as they call it. Where the AVR and sam are provided by stock. Others are possible.

It is fairly involved setup. In short; within each platform there are the following files:

 - boards.txt, defines the individual boards using the similar processor.
 - platform.txt, defines the compiler arguments
 - programmers.txt, defines how to program it.

With corresponding sub directories to match, under the variants/ folder.
I have not found an complete tutorial on the matter. However, their

[Arduino IDE 1.5 3rd party Hardware specification](https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification)

[An overview of the platform architecture proposed for Arduino 1.5](https://code.google.com/p/arduino/wiki/Platforms1)

are a great place to start.

I have not done much with SAM. I do notice that programmers.txt is empty. So it must be done another way.


body:
I want to use one an push button with an led in middle, similar to this [one][1] on eBay.
The push button has a 12v input I want to hook it up to an Aduino Uno or Nano.

Is there a way to hook it up and receive the signal?

Specifications from the eBay page:

>  - Latching type, push it—on, push it again — off
>  - Switch Rating: 3A/250VAC
>  - LED voltage: 12V only
>  - Contact Configuration: 1NO1NC
>  - Pin Number: 5

  [1]: http://www.ebay.com/itm/16mm-12V-Blue-LED-Power-Push-Button-Switch-Black-Aluminum-Metal-Latching-/231234288662?pt=LH_DefaultDomain_0&hash=item35d6a33c16

title: Hooking up 12v Push button to arduino uno/nano

Answers: 1

body:
Most likely, there will be a push button, and on separate wires, there is a light. If this is the case, you can hook the push button part up to the arduino. You can test this - find two random wires, test the resistance with a multimeter, then press the button and see if the resistance changes. Keep trying until you find two wires that change when you press the button.

Once you find the pair, you can hook one of those two to a digil pin on the Arduino, and via a resister (large, anything 10kilo-ohm or larger is fine) to ground (GND). Then, connect the other side of your pushbutton to 5V. See http://arduino.cc/en/tutorial/button for photos and a circuit diagram - their wiring is more complicated than it needs to be, and their button has 4 pins in two pairs (left pair, and right pair in the picture with the breadboard; the left-top and left-bottom are permanently connected, and the right-top and right-bottom are permanently connected). Have a look at the circuit diagram - that's a lot simpler. The zig-zag at the top is the resistor, and the disconnected looking thing is the switch (open). There is sample code there too.

Note that push buttons typically "bounce" - that is, when you push them, they will go (starting off) on-off-on-off-on-off-on, so if you're counting the number of pushes you will get a result which is way too high. If you delay long enough in between (10ms?) then you won't get these. The code I linked to already has debounce built in.

The other part is the light. This is a little more tricky. The light will probably use too much current for the arduino to supply directly. You will need a transistor and a resistor (again, at least 10 kiloOhm is good).

The transistor should be an NPN transistor, and should look like the top one in http://www.reprise.com/host/circuits/transistor_pinouts.asp. The easiest one is the base - this is the middle one. Connect this via your resistor to another digital pin on your arduino (pin 13 is great for testing this, because it will also light up the led on the Arduino). Next, connect your emitter to ground (GND). Then, IF YOUR POWER SUPPLY IS NO MORE THAN 12 VOLT! you can connect VIN to the + side of the light, and the - side of the light to the collector.

Next, load a sketch - the "blink" sketch is good to test this. Adjust the pin as necessary.

Note that, these switches have a resistor already built in to the light; if you want to do the same with an ordinary led, you will have to add one yourself. Check out http://ledcalc.com/ to tell you which resistor you need.


body:
I have DATA_READY, Activity and Inactivity interrupts mapped from INT1 to INT0 on the arduino. DATA_READY works fine, the problem is Activity and Inactivity are always set to 0 in the INT_SOURCE register. I have set up the threshold for activity and inactivity and the time of inactivity. I would like the algorithm to run when DATA_READY and Activity interrupts are 1 and do nothing when Inactivity is 1 (activity is 0). When Activity is 0 the accelerometer should go automatically in sleep mode and wakes up if activity is detected.

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_ADXL345_U.h>
    #include <avr/io.h>
    #include <avr/power.h>

    #define F_CPU 16000000UL

    int state=0; //0--active detecting; 1--sleeping
    int state_count=0; //sleeping trigger between 2 states
    double mag[40];
    int i=0;
    double acc_rate[39];
    int hunt_sub=0;
    int exit_marker=-10,trough_marker=-30,peak_marker=-10;
    volatile int sensor_update=0, active_mode=0;//active_mode=0, inactive; 1--active;      sensor_update=0, no new data; 1--new data comes
    byte buff[1] ;

    volatile unsigned long time=0, time0=0,time_dis=0,time_array[40]={0};

    //----------------------------------------------------------------------------------------------

    //Read ADXL345 registers
    void readFrom(int device, byte address, int num, byte buff[]) {
    Wire.beginTransmission(device); //start transmission to device
    Wire.write(address);        //sends address to read from
    Wire.endTransmission(); //end transmission

    Wire.beginTransmission(device); //start transmission to device (initiate again)
    Wire.requestFrom(device, num);    // request 1 byte from device

    int i = 0;
    while(Wire.available())    //device may send less than requested (abnormal)
    {
    buff[i] = Wire.read(); // receive a byte
    i++;
    }
    Wire.endTransmission(); //end transmission
    }

    //Write to ADXL345 registers
    void writeTo(int device, byte address, byte val) {
    Wire.beginTransmission(device); //start transmission to device
    Wire.write(address);        // send register address
    Wire.write(val);        // send value to write
    Wire.endTransmission(); //end transmission
    }

    //----------------------------------------------------------------------------------------------

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

    //ISR function

    void interrupt(void){

    readFrom(0x53, 0x30, 1, buff);

    if(buff & 0b00010000){
      active_mode=1;//active state
    }
    if(buff & 0b00001000){
      active_mode=0;//inactivity state
    }

    if(buff & 0b10000000){
    sensor_update=1;//DATA_READY each 10ms
    }

    }

    /* Assign a unique ID to this sensor at the same time */
    Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12345);

    void setup(void)
    {
    if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
    Serial.begin(9600);
    //Serial.println("Accelerometer Test"); Serial.println("");

    pinMode(4, OUTPUT);// buzzer output pin
    pinMode(2, INPUT);

    /* Initialise the sensor */
    if(!accel.begin())
    {
    /* There was a problem detecting the ADXL345 ... check your connections */
    //Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
    while(1);
    }

    /* Set the range to whatever is appropriate for your project */
    accel.setRange(ADXL345_RANGE_8_G);
    accel.setDataRate(ADXL345_DATARATE_100_HZ);
    // displaySetRange(ADXL345_RANGE_8_G);
    // displaySetRange(ADXL345_RANGE_4_G);
    // displaySetRange(ADXL345_RANGE_2_G);

    /* Display some basic information on this sensor */
    //displaySensorDetails();

    /* Display additional settings (outside the scope of sensor_t) */
    //displayDataRate();
    //displayRange();
    //Serial.println("");

    //Create an interrupt that will trigger when a tap is detected.

    writeTo(0x53, 0x2D, 59);//POWER_CTL  auto sleep, link, 1hz rate
    writeTo(0x53, 0x2C, 10);//BW_RATE low power mode off rate 100Hz
    writeTo(0x53, 0x2E, 0);// disable interrupt

    attachInterrupt(0, interrupt, RISING);

    writeTo(0x53, 0x2F, 0); //map to to INT1
    writeTo(0x53, 0x2E, 152); //enable data_ready, activity, inactivity
    writeTo(0x53, 0x25, 18); //THRESH_INACT  ((11/9.8)*1000)/62.5
    writeTo(0x53, 0x26, 60); //TIME_INACT    one minute
    writeTo(0x53, 0x24, 21); //THRESH_ACT    ((13/9.8)*1000)/62.5
    writeTo(0x53, 0x27, 0); //ACT_INACT_CTL   dc coupled, use only magnitude.

    }

    void loop(void)
    {

    readFrom(0x53, 0x30, 1, buff);
    Serial.print("buff: "); Serial.print(buff); Serial.print("  ");

    sensors_event_t event;
    do{ //clear DATA_READY
    accel.getEvent(&event);
    readFrom(0x53, 0x30, 1, buff);
    }while(buff & 0b10000000);

    if(sensor_update==1 && active_mode==1){
    //When sensor_update is set to 1 in the ISR,the algorithm process the data from the accelerometer being updated every 10ms(100Hz)
    //rest of algorithm is here
     sensor_update=0;//reset

    }

    }

Edit:

I have modified the program to check in the loop whether the different flags are set and only the DATA_READY is. Activity and Inactivity are never set.

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_ADXL345_U.h>
    #include <avr/io.h>
    #include <avr/power.h>

    #define F_CPU 16000000UL

    int state=0; //0--active detecting; 1--sleeping
    int state_count=0; //sleeping trigger between 2 states
    double mag[40];
    int i=0;
    double acc_rate[39];
    int hunt_sub=0;
    int exit_marker=-10,trough_marker=-30,peak_marker=-10;
    volatile int sensor_update=0, active_mode=0;//active_mode=0, inactive; 1--active;     sensor_update=0, no new data; 1--new data comes
    byte buff[1] ;

    volatile unsigned long time=0, time0=0,time_dis=0,time_array[40]={0};

    //----------------------------------------------------------------------------------------------

    //Read ADXL345 registers
    void readFrom(int device, byte address, int num, byte buff[]) {
    Wire.beginTransmission(device); //start transmission to device
    Wire.write(address);        //sends address to read from
    Wire.endTransmission(); //end transmission

    Wire.beginTransmission(device); //start transmission to device (initiate again)
    Wire.requestFrom(device, num);    // request 1 byte from device

    int i = 0;
    while(Wire.available())    //device may send less than requested (abnormal)
    {
    buff[i] = Wire.read(); // receive a byte
    i++;
    }
    Wire.endTransmission(); //end transmission
    }

    //Write to ADXL345 registers
    void writeTo(int device, byte address, byte val) {
    Wire.beginTransmission(device); //start transmission to device
    Wire.write(address);        // send register address
    Wire.write(val);        // send value to write
    Wire.endTransmission(); //end transmission
    }

    //----------------------------------------------------------------------------------------------

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

    //ISR function

    void interrupt(void){

    //
    //    if(buff & 0b00010000){
    //      active_mode=1;//active state
    //    }
    //    if(buff & 0b00001000){
    //      active_mode=0;//inactivity state
    //    }
    //
    //    if(buff & 0b10000000){
    //    sensor_update=1;//DATA_READY each 10ms
    //    }

    }

    /* Assign a unique ID to this sensor at the same time */
    Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12345);

    void setup(void)
    {
    if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
    Serial.begin(9600);
    //Serial.println("Accelerometer Test"); Serial.println("");

    pinMode(4, OUTPUT);// buzzer output pin
    pinMode(2, INPUT);

    /* Initialise the sensor */
    if(!accel.begin())
    {
    /* There was a problem detecting the ADXL345 ... check your connections */
    //Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
    while(1);
    }

    /* Set the range to whatever is appropriate for your project */
    accel.setRange(ADXL345_RANGE_8_G);
    accel.setDataRate(ADXL345_DATARATE_100_HZ);

    //Create an interrupt that will trigger when a tap is detected.

      writeTo(0x53, 0x2D, 59);//POWER_CTL  auto sleep, link, 1hz rate
      writeTo(0x53, 0x2C, 10);//BW_RATE low power mode off rate 100Hz
      writeTo(0x53, 0x2E, 0);// disable interrupt

      attachInterrupt(0, interrupt, RISING);

      writeTo(0x53, 0x2F, 0); //map to to INT1
      writeTo(0x53, 0x2E, 152); //enable data_ready, activity, inactivity
      // writeTo(0x53, 0x25, 18); //THRESH_INACT  ((11/9.8)*1000)/62.5
      writeTo(0x53, 0x27, 119); //ACT_INACT_CTL   dc coupled, use only magnitude.
      writeTo(0x53, 0x25, 5); //THRESH_INACT  ((3.0625/9.8)*1000)/62.5
      writeTo(0x53, 0x26, 1); //TIME_INACT    one minute
      writeTo(0x53, 0x24, 21); //THRESH_ACT    ((12.8625/9.8)*1000)/62.5

      }

      void loop(void)
      {

      if(digitalRead(2)) {

      readFrom(0x53, 0x30, 1, buff);

      //Serial.print("### ");

      //Serial.println(interruptSource, BIN);

      if(buff[0] & 0b10000000) {

      Serial.println("### DATA_READY");

      }

      if(buff[0] & 0b00001000) {

      Serial.println("### Inacitivity");

      }

      if(buff[0] & 0b00010000) {

      Serial.println("### activity");

      // we don't need to put the device in sleep because we set the AUTO_SLEEP bit to 1 in R_POWER_CTL

      // set the LOW_POWER bit to 1 in R_BW_RATE: with this we get worst measurements but we save power

    }

    delay(150);

    }

    sensors_event_t event;
    do{ //clear DATA_READY
    accel.getEvent(&event);
    readFrom(0x53, 0x30, 1, buff);
    }while(buff & 0b10000000);

    if(sensor_update==1 && active_mode==1){
    //When sensor_update is set to 1 in the ISR,the algorithm process the data from the accelerometer being updated every 10ms(100Hz)
    //rest of algorithm is here
     sensor_update=0;//reset

    }

    }

title: ADXL345 Arduino UNO Activity Inactivity interrupt

Answers: 0


body:
For my next project I'd like to use a battery pack to power my Arduino.
I would also like to get a small solar panel and charging module to charge these batteries when possible (during the day).

1. What is the right type of battery for this kind of application?
2. What are the differences given this context?
3. What are the factors I need to consider when choosing a rechargeable battery for this application?

title: How to choose between Lithium-ion vs NiMH batteries to power Arduino on the go.

Answers: 1

body:
Look at [**Battery University**](http://www.batteryuniversity.com/) for many good ideas.

Both NimH and LiIon are viable for your application.

LiIon are easier to manage well **if** managed well.
ie do it right and they are easy to manage, but cut corners and they are easier to destroy.

NimH can be abused more with a slow degradation in capacity - although complete destruction is possible.

As a LiIOn cell has a ~= 3.0V to 4.2V range you'd probably probably need a step up inverter with 1 cell, or a buck regulator with 2 cells, which is 'annoying'. If you are prepared to use the cell over say a 3.4V to 4.2V range with an LDO regulator for a 3.3V system then you lose a significant amount of available capacity but increase battery cycle life substantially.

Nimh give 1.0 - 1.2 V/cell so eg

 - 6 cells give 6 - 7.2V for a 5V system,

 - 5 cells give say 5.25V - 7V if run down to 1.05V for a 5V system with a suitable LDO regulator, and

 - 4 cells give 4 - 4.8V for a 3V3 system.

NimH are easier overall to build half well and get half good results.

LiIon are slightly harder to get going with in most cases, work very well if treated well, and are VERY unforgiving of bad treatment past a certain point.


body:
I'm looking to drive two DC motors (on a toy RC car) using a Seeeduino and Seeed Motor Shield V2, but can't manage to get the power scheme right. Right now, a 9V battery connected to the shield powers everything (i.e. LEDs are illuminated on the shield and seeeduino), but when I try running the motors everything flickers and the motors don't move (I assume this is because there isn't enough current). I've managed to get them working when plugging a USB and 9V battery (at the same time) into the seeeduino, as well as when plugging a 9V into the seeeduino and another into the shield (at the same time). Both of these configurations leave me feeling uneasy, as I'm not sure how the power sources will interact.

Further, there is a jumper (MB_EN) on the shield which, according to my research, should isolate the shield from the seeeduino when removed. The documentation (http://www.seeedstudio.com/wiki/Motor_Shield_V2.0) alludes to the fact that this jumper doesn't work, however. Indeed, when I try removing it, power is lost altogether.

I've found conflicting answers to this problem, none of which seems definitive. I've also found tutorials where people did exactly the same thing (with a proper arduino, mind you...) by plugging a single 9V battery to the shield. This should be possible.

I've exhausted just about every resource I can think of, and have spent innumerable hours searching up a solution -- nothing yet. Any help would be great.

title: Seeeduino Motor Shield Power Supply

Answers: 0


body:
Is there any reason why is my `/dev/cu` port always busy? How can I fix that?

It happened on both Uno clone and Spark Core.

The problem is, I'm having issues doing serial communication. Where (as a programmer) I'm seeing something like dropped packets with `/dev/tty` port. I did a quick test running it on Win 7 (a loaner PC), it works fine...

The code for now is extremely simple. It waits for a command, and write a response.

    String str = String(30);

    void setup()
    {
        Serial.begin(9600);
        str = "";
    }

    void loop()
    {
        if (Serial.available() > 0) {
            char inChar = Serial.read();
            if ((inChar == '\n') || (inChar == '\r') || (inChar == 'z')) {
                str.trim();
                if(str == "READ") {
                    String x = String(random(27, 45)) + "," + String(random(45, 300)) + "," + String(random(35, 250));
                    Serial.println(x);
                }
                str = "";
            }
            else {
                if (str.length() < 30) {
                    str += inChar;
                }
                else {
                    str = "";
                    str += inChar;
                }
            }
        }
    }

title: /dev/cu port resource always busy on OS X 10.10

Answers: 1

body:
Finally figured it out. I need to call [Serial.flush()][1].

> Waits for the transmission of outgoing serial data to complete.

  [1]: http://arduino.cc/en/Serial/Flush


body:
Is it possible to delay a task inside a function that is called only once (meaning, it's not inside the loop) without using delay()?

[This library][1] I'm using, for reading sensor measurements via serial has a delay() in it. I want to get rid of it, but I don't how to do it, because the library's function is not looped.

I guess the simple solution would be to move the library functions inside the loop, so I can do a simple check with millis() and run the delayed part as soon as 250 ms have passed. I would like to improve this library though and do a simple, single call for sensor data that doesn't not hold up the entire program.

This is the function with the delay:

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

    uint16_t COZIR::Request(char* s)
    {
      Command(s);
      // empty buffer
      buffer[0] = '\0';
      // read answer; there may be a 100ms delay!
      // TODO: PROPER TIMEOUT CODE.
      delay(250);
      int idx = 0;
      while(CZR_Serial.available())
      {
     buffer[idx++] = CZR_Serial.read();
      }
      buffer[idx] = '\0';
      uint16_t rv = 0;

      switch(buffer[1])
      {
        case 'T' :
                rv = atoi(&buffer[5]);
                if (buffer[4] == 1) rv += 1000;
                break;
        default :
                rv = atoi(&buffer[2]);
                break;
      }
      return rv;
    }

I've had a look at the SoftTimer library, but it requires sketches to be written very differently (without a loop). I'm also not sure if I can even pass arguments to delayed tasks with that library.

  [1]: https://github.com/kslstn/cozir

title: How to wait outside the loop without delay()?

Answers: 2

body:
You could split `Request()` into two separate functions: You call `sendRequest()`, then go do other stuff, then, some time later, you call `getResponse()`. If you get `RESPONSE_NOT_READY`, then you know you have to call it later:

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

    #define REQ_WAIT_DELAY     250  // Wait for 250 ms
    #define RESPONSE_NOT_READY ((uint16_t) -1)

    uint32_t time_request_sent;

    void COZIR::sendRequest(char* s)
    {
      Command(s);
      time_request_sent = millis();
    }

    uint16_t COZIR::getResponse()
    {
      if (millis() - time_request_sent < REQ_WAIT_DELAY)
          return RESPONSE_NOT_READY;
      buffer[0] = '\0';  // empty buffer
      int idx = 0;
      // From here, same as original COZIR::Request()
    }

This assumes that `RESPONSE_NOT_READY` (`0xffff`) is not an otherwise valid response. If all 2^16 values of an `uint16_t` may be valid, then you need another way for the library to signal that the response is not ready. Also, make sure you never compare timestamps, because of the `millis()` rollover problem. Taking the difference between two timestamps and comparing this with a specified delay (as in the example above) is rollover-safe.

**Update**: Here is an example of how this could be used:

    COZIR cozir(some_serial_connection);

    void loop()
    {
        static bool waiting_for_a_cozir_response = false;

        if (time_to_get_another_cozir_reading()) {
            if (waiting_for_a_cozir_response) {
                report_something_is_wrong("This COZIR is too slow!");
            }
            else {
                cozir.sendRequest("Hi Cozir! Pliz send me another reading.");
                waiting_for_a_cozir_response = true;
                /* We won't get the response on this iteration. *
                 * We will ask next time.                       */
            }
        }
        else if (waiting_for_a_cozir_response) {
            uint16_t response = cozir.getResponse();
            if (response == RESPONSE_NOT_READY) {
                /* Nothing to do now, really. We will just try again *
                 * at the next loop() iteration.                     */
            }
            else {
                waiting_for_a_cozir_response = false;
                do_something_with_the_cozir_response(response);
            }
        }
        do_whatever_else_has_to_be_done_in_the_loop();
    }

body: You can look at the BlinkWithoutDelay example sketch (under Digital).  Basically you store the current millis as a variable, then have an if statement to check that it has been more than x milliseconds.


body:
I have created my own custom Arduino Micro, but I am experiencing problems when I attempt to upload an sketch via USB in Arduino IDE.

Here is how I program the Arduino Micro:

    avrdude  -c atmelice_isp  -p m32u4 -P usb -u -v -e -U flash:w:Caterina-Micro.hex

And the result:

    $ avrdude  -c atmelice_isp  -p m32u4 -P usb -v -e -U flash:w:Caterina-Micro.hex
    avrdude: Version 6.1, compiled on Mar 23 2014 at 04:42:55
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "/usr/local/Cellar/avrdude/6.1/etc/avrdude.conf"
             User configuration file is "/Users/aUser/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : usb
             Using Programmer              : atmelice_isp
    avrdude: usbdev_open(): Found Atmel-ICE CMSIS-DAP, serno: J41800023270
    avrdude: Found CMSIS-DAP compliant device, using EDBG protocol
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : JTAG3_ISP
             Description     : Atmel-ICE (ARM/AVR) in ISP mode
             Vtarget         : 4.9 V
             SCK period      : 125.00 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x1e9587
    avrdude: safemode: lfuse reads as FF
    avrdude: safemode: hfuse reads as D8
    avrdude: safemode: efuse reads as CB
    avrdude: erasing chip
    avrdude: reading input file "Caterina-Micro.hex"
    avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
    avrdude: writing flash (32730 bytes):

    Writing | ################################################## | 100% 38.80s

    avrdude: 32730 bytes of flash written
    avrdude: verifying flash memory against Caterina-Micro.hex:
    avrdude: load data flash data from input file Caterina-Micro.hex:
    avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
    avrdude: input file Caterina-Micro.hex contains 32730 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 133.93s

    avrdude: verifying ...
    avrdude: 32730 bytes of flash verified

    avrdude: safemode: lfuse reads as FF
    avrdude: safemode: hfuse reads as D8
    avrdude: safemode: efuse reads as CB
    avrdude: safemode: Fuses OK (E:CB, H:D8, L:FF)

    avrdude done.  Thank you.

The error in Arduino IDE when flashing sketch via USB:

    Sketch uses 23.994 bytes (83%) of program storage space. Maximum is 28.672 bytes.
    Global variables use 1.145 bytes (44%) of dynamic memory, leaving 1.415 bytes for local variables. Maximum is 2.560 bytes.
    Forcing reset using 1200bps open/close on port /dev/tty.usbmodem1411
    PORTS {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } / {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } => {}
    PORTS {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } / {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } => {}
    Uploading using selected port: /dev/tty.usbmodem1411
    /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/tty.usbmodem1411 -b57600 -D -Uflash:w:/var/folders/64/6n0yv9515hz1n6z3bdzcwv6h0000gn/T/build2162381950044145986.tmp/IMUNode.cpp.hex:i

    avrdude: Version 6.0.1, compiled on Apr  3 2014 at 22:00:33
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/Users/aUser/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/tty.usbmodem1411
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding
    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

title: Unable to upload sketch after bootloader has been flashed on Arduino Micro

Answers: 1

body:
Your problem is that your board doesn't have the bootloader loaded into the chip.

You have success with the ATMEL-ICE ISP because it is an in-system programmer (ISP) and you are downloading the code directly into the chip.

When you use the USB, I see from your output that the programmer is "butterfly" and the description indicates AVR109. These both indicate that the program is trying to be loaded through a bootloader.

A bootloader is a bit of code that resides in the codespace section of flash. It allows you to send the program through the UART. The bootloader then saves it to the codespace section of flash such that both the bootloader and your program co-exist.

To fix this, use the Arduino IDE along with your ATMEL-ICE ISP to load the bootloader into the microcontroller. This can be done by going into `Tools` and then `Burn Bootloader` (of course with the correct programmer selected).

This will then allow you to download your code through the Arduino IDE.

PS. You can program your sketch straight to your Arduino using your ATMEL-ICE ISP without downloading the bootloader. Do this by selecting the `Upload Using Programmer` option in the menus.


body:
Is anyone out there building serious metal detectors with the Arduino? By "serious" I mean metal detectors with phase sensitivity to discriminate between ferrous and non-ferrous metals, etc.  Seems like the Uno is a good platform for a smart metal detector project.

Update:
Arduino allows me to control phase discrimination which allows ferrous metals to be rejected.
I already know it can be done with an analog phase shift circuit.
Also Arduino can perform target ID function with readout to 16x2 LCD display.

title: Metal detector using Arduino

Answers: 1

body:
A set of posts on Instructables uses an Arduino Nano to generate a Phase Induction pulse, with a capacitor instead of a dump resistor to set up a decaying oscillation, which is then limited with diodes and detected by the analog comparator with interrupts.  The comparator interrupts then count the frequency of the decaying ringing oscillation producing some ferrous/non-ferrous discrimination, and the duration of the ringing, producing some signal strength and size information.

* Nano doing Pulse induction with LC-trap oscillation: https://www.instructables.com/id/Arduino-Based-Pulse-Induction-Detector-LC-Trap/
* Nano meta detection software with high-frequency ADC sampling: https://www.instructables.com/id/How-to-Program-an-Arduino-Based-Metal-Detector/
* Nano doing Pulse Induction, shifting the recovery pulse to match the arduino's analog comparator: https://www.instructables.com/id/Arduino-Based-Pulse-Induction-Detector/

The tricks in the Pulse Induction LC-trap system of using the analog comparator would be applicable to detecting phase shifts and detecting crossings in sync with a timer-based output.


body: Any one know a **component library** for Arduino UNO (**Atmega328**, etc) for **Protel 99 SE** PCB design software?

title: Atmega328 component library for Protel 99 SE

Answers: 2

body: All arduino design schematics are available from the Arduino website, e.g. for the [Uno](http://arduino.cc/en/uploads/Main/arduino_Uno_Rev3-02-TH.zip). However, these are in EAGLE format, I don't know if it's possible to convert.

body:
Found it here with 94 chips.

The author states, "I have made a little library for Protel 99SE with schematic sybols of AVR chips."

[http://www.avrfreaks.net/forum/avr-8bit-microcontrollers-protel-99-library][1]

  [1]: http://www.avrfreaks.net/forum/avr-8bit-microcontrollers-protel-99-library


body:
So I just bought my first Arduino (an Uno r3), and dove right in.

All I have currently is the base board (I didn't want to invest too heavily and then realize arduinos weren't for me), so I made a quick script that translates input letters to morse via the LED on the top.

Now that I'm done with that, I figured I'd come here to ask: do you guys have any random ideas for things I can make with JUST the uno? I understand that I should probably just start buying kits and shields, but I'm just curious as to what I can make with the most minimal of items. I consider it a test :)

Thanks in advance guys!

title: Arduino Uno - What can I make with just the base board

Answers: 1

body:
Well,

Your question is very broad. But the Arduino essentially needs controlling gadgteers to make things easy ( and funny ).

However if you know a bit of electronics, then you may be able to use the IN/OUT analog ports and build other interfaces to control, for example the lights of your home, or even better. You can measure and control priate things should be linked. Increasing the power of your home.

If you have interest in cars, then you can perform to connect the on-board computer of your car to the Arduino, like [this][1].

Well, there are numerous ideas, none of these I'm saying is new and there are even libraries ready to be used in these segments mentioned above.

Regards,
Andrew Paes

  [1]: http://arduinodev.com/connect-arduino-to-a-car-through-obd-ii-port/


body:
On an Arduino Uno, the PWM pin 3 is connected to the `gate` pin of an [N-channel MOSFET STP16NF06L][1]. The source pin is connected to ground of a 12 V power supply and drain pin connected to a multimeter. The other end of the multimeter is connected to the positive terminal of the power supply.

**Question:** When Arduino varies its PWM output from 0 to 255, the multimeter reading goes from 11.50 V to 12.10 V. Why isn't it 0 to 12 V?

When the FET gate is connected to the Arduino pin that outputs either 0 V or 5 V, the multimeter reading is as expected at 0 V and 12 V respectively.

  [1]: http://www.farnell.com/datasheets/1690175.pdf

title: Arduino PWM output cannot drive MOSFET 0-12V

Answers: 3

body:
When the FET is saturated (pin 3 is high), I would expect the instantaneous voltage to be the full 12 v. When pin 3 is at 0v, there should be no connection across the FET; I would expect the voltage to fluctuate randomly. you might see the same if you measure voltage with nothing touching the probes, especially if the probes move relative to each other.

I'm fairly new to FETs, so I may be on completely the wrong track.

body:
Assuming you have a suitable FET You should have a circuit in line the following.
http://elinux.org/RPi_GPIO_Interface_Circuits#Using_a_FET

You should have some kind of load (a multimeter will have too high an impedance). Use a resistor 4.7k or smaller. You should also have a resistor on the gate

body: Also put a LED with a resistor connected trough drain, then you read the voltage across the resistor and also have visual feedback with the LED. Resistor should be with 0V when your pin is LOW. It's easier to work with transistor knowing if there is current or not.


body:
I have a project that turns a LED strip on and off using capacitive touch.  The project uses an [Arduino Micro](https://www.adafruit.com/products/1315) as the brain and a [12v wall wart](https://www.adafruit.com/products/352) to power everything.  I have the Arduino ground and negative from the power supply running to a common ground.

Everything works as expected during testing and the Arduino is connected via USB to my computer; however, when I unplug the USB and connect the circuit to the light installation, the lights just flicker on and off.  When I touch my finger to the negative/ground (and presumably provide common ground), everything works as expected.

It seems obvious to me that I have a grounding issue, but really do not know how to proceed. Is there a specific technique for grounding from a wall wart? Do I need to somehow pull the ground/negative down? I feel like there is something obvious that I am missing.

Thank you in advance for any and all help.

title: Arduino Grounding Issue

Answers: 1

body: Seems like there is a problem in your wall wart, actually some people are having problems using wall wart with arduino. The problem is with the circuit of thre arduino regulator and with sime ripple variances with de wall wart, i sugest you to setup in your project a regulator (7805) and see if the problem is gone. This is by far problem not just with grounding, but with the power suply in general. I was used to make PIC projects and once it was happening exatly the same that happaned to you but the microcontroller started to work when i put my hand or finger close without even touching it :x. Crazy thing. If the power supply isn't well suited, the arduino enter in continous reset looping because of supply noise. So just put an external regulator, an maybe an extra capacitor (generally 10 nF) in arduino micro power supply rais (VCC-GND). Here's my tip. Good look man, tell me if it worked :)


body:
I'm building a project that will connect to users' phones (Android at first, but iPhone too, if there's enough interest) via USB. Of course, this means that I need a USB host in the project. The total size of the device has to be about the size of the phone, so answers that seriously suggest shields aren't going to be helpful - they'd put me over my size budget by at least a factor of 3.

I'd also rather not require an adapter to go from the USB Mini B connector type to the Micro B connector type.

Gravitech has a USB Host board for the Nano 3 that has a USB Type A connector, and the combination of a Nano and Gravitech Host is about the right size (maybe a little thick, once the whole thing is soldered to my own board), but the USB host is $25. I can get the Nano for about $4 each and would like to keep the USB host in the neighborhood of $8 each. Are the solder fumes getting to me, or is there such a specimen out there and I'm just not finding it?

title: What's the smallest (cheap) USB Host solution for Arduino?

Answers: 2

body:
The Arduino Due and Arduino Mega ADK can both serve as a USB Host. You can also use the [chip that the Mega][1] uses yourself

  [1]: http://www.maximintegrated.com/en/products/interface/controllers-expanders/MAX3421E.html

body:
Cypress makes very small usb chips capable of host mode. Does this board meet your size requirements? http://www.mouser.com/ProductDetail/Cypress-Semiconductor/CY8CKIT-049-41XX/?qs=FSHIiqjonm0YmFbmBQfo1A==&kpid=1159933375&gclid=CPjl6KOm4cQCFYGUfgodJh4A_g

You may also consider ditching the arduino and running everything on the cypress


body:
I am using a Arduino Due. I am doing a project on Visible Light Communication. I need to convert a binary data into a PWM Signal. Can anyone suggest me a method of generating that PWM Signal based on the binary data given?

Thank You.

title: Converting Random Binary Data to PWM Signal

Answers: 3

body: Count the amount of time a signal is high over a certain period, and use the ratio of on time to period as the duty cycle for the PWM signal.

body:
So, if you simplu has to convert the binary data to PWM signal there are few things you need to cover:

 1. If the binary data that you are receiving from the sensor is linear or non linear.

 2. What is the size of binary byte. Ex: int(16 bits),char(8 bits),long (32 bits).

 3. If it is linear, then if the data is multiplied by some number it will output a value betwen 0-255.
 4. If the data is not linear than you just need to create an giant array with the pwm intensite value direct without any particular mathematical function. Ex: array[1024] = {0,1,1,2,3,4,5,5,6,6,10,9,...}; (1024 values because if you are using analog input. Then you can direct output the values from array:

        analogWrite(3,array[x]); //x being your data

Here's the linear Example:

       //map(value, fromLow, fromHigh, toLow, toHigh);
        y = map(x, 0, 1023, 0, 255);

Doing this, y will receive a value from 0 to 255. You just need to first do a simple serial program that prints you through arduino serial window the binary data and see if the data increases or decreases conform your light project.

 - I don't know about your programming levels or if you are using a digital sensor or analog sensor, but if you are using a digital sensor, so you are probaly using SPI communication or i2c. Then you just need to read that binary data and take where the values bits are with bit wize manipulation.

        y=(x & (0xfff<<3))>>3;

Tell me more about the source of data, how this data is and how is the behavior of the data so i can help you a lot more. Thanks

body:
Rather than completely build everything from scratch,
perhaps you can use some already tested and debugged Arduino library designed for free-space optical communication, such as

* Ken Shirriff. ["A Multi-Protocol Infrared Remote Library for the Arduino"][2].
* A1RONZO at Sparkfun. ["IR Communication tutorial"][3]
* Dave. ["EEVblog #506 - IR Remote Control Arduino Protocol Tutorial"][4]
* ["Multitasked IR transmission"][5]
* ["Arduino universal remote"][6] (has 2-way communication, both send and receive)
* ["IR Remote Control Theory"][7] (links to many different "standard" infrared protocols)

Practically all of these systems convert expand arbitrary binary data to structured "frames" or "packets" of information including some sort of checksum.
Each packet is repeated several times; hopefully the receiver catches at least one of them.
Each bit of the packet is expanded to either the "pattern representing a 0 bit" (typically turning the LED off for the full bit time) or the "pattern representing a 1 bit" (typically blinking the LED at 38 KHz for the full bit time, typically using a PWM).

To make the hardware and the software simpler and cheaper, most of these systems transmit only a few dozen bits per second.
A few free-space optical communication systems are designed to run much faster, such as [RONJA][1].

  [1]: http://en.wikipedia.org/wiki/RONJA
  [2]: http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html
  [3]: https://learn.sparkfun.com/tutorials/ir-communication
  [4]: http://www.youtube.com/watch?v=BUvFGTxZBG8
  [5]: http://playground.arduino.cc/Main/MultiIR
  [6]: http://playground.arduino.cc/UniversalRemote/UniversalRemote
  [7]: http://www.sbprojects.com/knowledge/ir/


body:
I recently bought an Arduino Pro Mini(3.3V 328p, 8MHz) along with a CP2102 USB to TTL UART convertor. When I try to upload a sketch to the Pro Mini using it, I get a `avrdude:stk500_recv(): programmer is not responding` error. My connection was like

    Arduino pro mini                CP2102
    TXO  ----------------------------> TXD
    RXI  ----------------------------> RXD
    VCC  ----------------------------> 3V3
    GND  ----------------------------> GND
    DTR  ----------------------------> DTR

I tried inter-connecting the TXO and RXI pins and had no luck. Also pressing and releasing the reset button on the Pro Mini doesn't seem to work either.  I also tried programming it with my Arduino Uno, by removing the 328 and connecting correspondingly. Still no use.

Does any one have any ideas?

title: Getting "avrdude:stk500_recv(): programmer is not responding" while uploading sketch to Arduino Pro Mini

Answers: 8

body:
If this is a cheap clone it may be that there is no bootloader installed. You might try using a programmer or an [Arduino as ISP][1] to reprogram the device if this is the case. Using ISP programming will avoid any problem with serial connections as it is using SPI wiring instead and the Arduino IDE allows you to load the necessary bootloader using this method to enable programming over serial. You will need either an ISP programmer or another Arduino however.

  [1]: http://arduino.cc/en/Tutorial/ArduinoISP

body:
You should try another USB port, install the right drivers for the TTL/uart chip and reboot your PC. That worked for me.

----

Also, you should consider getting an arduino nano usb, these have an built in ttl/uart converter, ICSP header and can be placed on a breadboard easily.

body:
In the Arduino IDE for my Pro Mini I have to select the board:
"Arduino Deumilanove or Diecimila"

I'm not sure why this is or if this could cause any potential damage to your Pro Mini but I do know for sure this is the solution I used to program my pro mini and it works every time.

body:
Change baudrate to

    UPLOAD_RATE=57600

in `Makefile` (or via the GUI). I have seen your error many times and this fixes it, albeit on the 5V/16MHz mini USB variant. If 57600 does not work, try other values. I use this rate on my USB serial - may be different on bare Rx/Tx pins.

You have probably not messed up your bootloader, that is rarer than people think. I think your Arduino has some invalid code running, and it keeps resetting until it finds valid code - when I had that problem, I pressed reset just before punching enter for 'make upload'. Even if it does that, you've got perhaps 0.5s to initiate an upload after reset.

Do correct me if I'm wrong.

body:
I had the same problem and I used a magnifying glass to check the processor.  I bought my clones off of eBay and they are using the ATMega168 (3.3V, 8 MHZ) processor.  Once I realized my mistake and switched to the correct processor version, the upload was seamless.

I'm using an "FTDI FT232RL USB to TTL Serial Converter Adapter Module 5V and 3.3V For Arduino" for the programming connection, with

 - DTS-DTS;
 - Rx-Tx;
 - Tx-Rx;
 - VCC-VCC;
 - GND-GND, and;
 - GND-CTS.

I didn't even need to use the "reset" workaround of holding down the reset button before pressing the upload button and releasing when the words "Maximum is ..." appear in the output window.

body:
rx -> tx
tx -> rx

Please check your connections.

body:
The problem is crystal clear in the picture
[![enter image description here][1]][1]

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

body:
1. Check connections, make sure RX-TX lines are crossing over.
2. **Arduino** -> **Preferences** -> **Show verbose output during** - check **upload** will give you better visibility what is happening.
3. When Arduino says "Uploading..." briefly press reset. The upload should start.

But one thing that helped me was... try different USB-UART adapter. For some reason the one which looked like (and was) cheap knockoff worked like a charm.

As a general advice, when sourcing parts from Chinese manufacturers I learned to be redundant - I usually order a bit more than I need and from mixed sources.


body:
Just starting with Arduino and have gotten stuck at the first hurdle: trying to connect an Arduino Nano with my Mac Book Pro which runs 10.10. I can't seem to find the right port as all suggestions have bluetooth in the name and none with USB anything. Also the post list does not change when I plug/unplug the Arduino. Looking at http://arduino.cc/en/guide/macOSX#toc3 it says that I need to install FTDI software to get the USB port to show, however, having done this it still does not work. Any suggestions?

Thanks,
Calum

title: Installing Ports for Arduino Nano on Mac OS X Yosemite

Answers: 2

body:
Had exactly the same problem. Also using 10.10 and just got an Arduino. What worked for me was using a different cable. The one that came with my Arduino Uno only provided power not data. If you have a printer, it might have the right cable, just test it quickly.

Edit: In addition, whilst trying to find solutions, I also installed 64bit mac FTDIUSBSerialDriver_v2_2_18.dmg. I'm not sure if it made a difference. As after installing it and using the original cable the problem persisted.

body: Are you using a USB hub? I had problems with my MBP when the Arduino was on a hub. Attached directly to the mac it was fine.


body:
I am having problems uploading my code to my Arduino Uno. The code that's already up, is running normally. The error code I get is:

    ioctl("TIOCMSET"): Connection timed out
    avrdude: stk500_recv(): programmer is not responding
    ioctl("TIOCMSET"): Connection timed out
    [Stino - Error 1]

title: Problem uploading code to Arduino Uno using stino

Answers: 0


body:
I'm using Arduino UNO, and today I upgraded my IDE from 1.0.6 to 1.6, just to upgrade, nothing special.

I got my libraries again but I got an error with a code that was working OK.

The error was:

    In file included from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:223:0,
                     from C:\Program Files (x86)\Arduino\libraries\ModbusMaster-master\ModbusMaster.h:53,
                     from C:\Program Files (x86)\Arduino\libraries\ModbusMaster-master\ModbusMaster.cpp:32:
    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h: In member function 'HardwareSerial& HardwareSerial::operator=(const HardwareSerial&)':
    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h:83:7: error: non-static const member 'volatile uint8_t* const HardwareSerial::_ubrrh', can't use default assignment operator
     class HardwareSerial : public Stream
           ^
    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h:83:7: error: non-static const member 'volatile uint8_t* const HardwareSerial::_ubrrl', can't use default assignment operator
    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h:83:7: error: non-static const member 'volatile uint8_t* const HardwareSerial::_ucsra', can't use default assignment operator
    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h:83:7: error: non-static const member 'volatile uint8_t* const HardwareSerial::_ucsrb', can't use default assignment operator
    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h:83:7: error: non-static const member 'volatile uint8_t* const HardwareSerial::_ucsrc', can't use default assignment operator
    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h:83:7: error: non-static const member 'volatile uint8_t* const HardwareSerial::_udr', can't use default assignment operator
    C:\Program Files (x86)\Arduino\libraries\ModbusMaster-master\ModbusMaster.cpp: In member function 'void ModbusMaster::begin(uint16_t)':
    C:\Program Files (x86)\Arduino\libraries\ModbusMaster-master\ModbusMaster.cpp:139:16: note: synthesized method 'HardwareSerial& HardwareSerial::operator=(const HardwareSerial&)' first required here
           MBSerial = Serial;
                    ^

I couldn't find the real error, can someone help me?

title: Arduino Upgrading from 1.0.6 to 1.6, code doesn't work anymore

Answers: 2

body:
You should not have added libraries to the Arduino files in the "C:\Program Files (x86)\Arduino" folder in the first place.
That is only for the Arduino program files and standard libraries that are included with the Arduino IDE.

Could you uninstall the Arduino and serial drivers. Remove also the "C:\Program Files (x86)\Arduino" folder, to be sure that absolutely nothing is left behind, because that will interfere with a new version that will be installed. Remove also the hidden "arduino15" folder(s).
Do you know the location of your sketches, it is in the preferences and is often "Documents\Arduino". Go to that folder and go into the "libraries" folder. Remove unused libraries or libraries that have been included in the Arduino files.
Do you have Java installed ? Some Java versions are not compatible with the Java files of the Arduino. If you don't need Java, then uninstall it.

Install the newest Arduino 1.8.3 from [Arduino.cc Software][1].
Use the Library Manager in the Arduino IDE, and search for modbus. Install the "ModbusMaster by Doc Walker" with the Library Manager. The modbus library that will be installed is this one: [Github 4-20mA ModbusMaster][2].

There has been a few changes, for example with PROGMEM. All PROGMEM data must now be 'const'. You might have to make a few adjustments.

  [1]: https://www.arduino.cc/en/Main/Software
  [2]: https://github.com/4-20ma/ModbusMaster

body:
Judging by the error messages you were using a ModbusMaster library from GitHub such as [this one][1] and the HardwareSerial library from the Arduino IDE.

I think the key is in the statement:

> I got my libraries again

I would suggest that you have downloaded a different library to what you originally used. Even if you did get the same repository, these libraries are also constantly changing and your code sometimes has to evolve with the library.

You have several errors (with the SoftwareSerial library): `non-static const member, can't use default assignment operator`. Essentially the program is trying to assign a value to a const or perhaps assigning a constant pointer to non-const data. Find more information on the error [here][2] and [here][3]. All of these errors stem from line 83 of HardwareSerial.h.

The last line(s) give the clue. You are assigning your instance of your Serial object to you MBSerial object.

  [1]: https://github.com/4-20ma/ModbusMaster
  [2]: https://stackoverflow.com/questions/15030972/type-non-static-const-member-cant-use-default-assignment-operator-what-does
  [3]: https://stackoverflow.com/questions/634662/non-static-const-member-cant-use-default-assignment-operator


body:
I have 4 rotary encoders connected to an MCP23017 which in turn is connected to interrupt port 0 on the arduino (and to I2C of course). Everything works fine: I get interrupts for all 4 rotary encoders, can read the values for them and even store these values in the EEPROM and load them in setup.

![Fritzing schematic of the (initially) working setup][1]

Now, I connect a WS2812 LED to the arduino (with a resistor and a capacitator in front of it). I connect the UNO and the led lights up. I attach the serial console (resetting the UNO) and it stops working (LED does not light up). This could just be simple wiring mistake and is not my real problem.

I remove the LED (and the capacitor) from the board and start everything up again. I can see via the serial console that the UNO works, however it does not receive any interrupts anymore. I exchange the MCP23017 thinking I fried it somehow but that doesn't change anything either...

Is there some sort of state the UNO has I could have affected?

Or could I have fried the interrupt "sub-system" on the UNO (again: all the other stuff still works)?

EDIT: The code is here: https://github.com/qollin/Liting/blob/master/src/Liting.cpp

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

title: What could cause interrupts from MCP23017 suddenly stop working?

Answers: 1

body: I think I figured out whats wrong: you need to reset the interrupt handling of the MCP in setup() (by reading from both INT pins). Otherwise the MCP may start in a state where it does not generate new interrupts, because it waits for the old ones to be handled...


body:
I'm trying to transfer data beetween the two scripts. I'm already using the YunMesseger library (https://github.com/plotly/YunMessenger). But it only make the

Arduino -> Python

communication.
I would like to know how to make the reverse way.

I would like to point that I'm search for a solution that doesn't involve the use of the Bridge, because I don't want to have concurrency problems.

title: Communication between python script and Arduino sketch

Answers: 1

body:
One option is to use [spacebrew](http://docs.spacebrew.cc/). This is a cloud-based service, however you can run your own [server](https://github.com/spacebrew/spacebrew) which is based on node.js, so it should work on the Yun.

Your Arduino can then send or receive data using [yunSpacebrew](https://github.com/julioterra/yunSpacebrew), and you can connect it to python using [pySpacebrew](https://github.com/Spacebrew/pySpacebrew). This is a pure python library, so it ought to run fine on the Yun.


body:
Background:

I am looking into automation and I have realized that many of the devices I have around my house transmit 315mhz to their specific controllers.  I know this from reading the labels on the back that say 315mhz

Question:

Is there a way I can use a 315mhz receiver with an arduino to view the signals and log the data based on what happens and mimic certain actions with the transmitter?  In other words can I program the reciever to display every bit passed through 315mhz that is in range?

I know the virtual wire library parses the data before I receive it, but I don't know to what extent?  If I just dedicate the arduino to watch that pin and print results will that tell me what is being sent?

Thanks Very Much,

Joel

title: How to access 315mhz signals from household devices, with an arduino 315mhz kit?

Answers: 1

body:
**The Short Answer:**

In theory it is possible to do what you are asking.
There are examples of using an Arduino to send and receive messages at 315 MHz. Such as [this example][1].

Although these devices might not even be compatible with the ones you are using. They may be modulating their signal differently or framing their data differently or at different baud rates or encoding bits differently or a number of other fundamental differences that would make them incompatible.

**The Long Not Quite An Answer:**

There is more to the problem than just being able to get bits at 315 MHz.

For one you would need to know how the bits are encoded. See some of the answers on [this][2] post.

Even if it was a simple high low stream of even width bits. You also need to know what baud rate the bits are being transmitted at so you can sync with it. (Consider 4800 vs 9600 baud, slow I know but just an example. You just got a bit stream, was it 1010 at 4800 baud or 11001100 sent at twice the speed of 9600.)

Not to mention that the lowest level of data is probably not just a stream of bits, but is probably framed in some way and grouped into a byte/bytes. Or has a leader to help lock onto the signal.

Even once you are getting reliable data you would need to know the data structure. Is the data arranged in packets? Do they have a packet header? Does the header contain these packet destination address? Where in the header is this data? How is  the data apart from the header structured? What does it mean?.

Knowing the answers to these questions defines, or is defined by, the protocol that is being used by the transmitter (as others are saying in comments.) But these are only a few simple questions that **start** to define a protocol. Often this information is difficult to come by. Often in the case of proprietary protocols it is very very difficult.

  [1]: http://www.buildcircuit.com/how-to-use-rf-module-with-arduino/
  [2]: https://electronics.stackexchange.com/questions/81399/reverse-engeneering-a-home-automation-rf-315mhz-transimtter


body:
I'm trying to interface with a serial device utilizing Serial1 (pins 18,19) on the Arduino Due. The normal serial port (Serial) is working just fine and is acting as a debug port at the moment - It's also able to communicate with the serial device without a problem when using the normal port.

I noticed that within the libraries for the Arduino hardware, the avr directory contains HardwareSerial files for the Mega's multiple serial lines, but the header file under the sam director does not. Simply a declaration of the HardwareSerial class with no elaboration on Serial1,Serial2 or Serial3 like the Mega's header contains.

Has anyone modified the libraries to set up the Arduino Due's multiple serial lines? Thanks in advance!

title: Arduino Due - Multiple Serial Lines

Answers: 0


body:
In this forum thread on arduino.cc http://forum.arduino.cc/index.php?topic=107375.0 they talk about it not being possible to get 800 x 600 video in color with the arduino.

My case is a bit different:

 - I don't care about color, it can be black and white / grayscale.
 - I don't need 800 x 600 just 640 x 480.
 - I can do with something like 2-5 frames per second.
 - I don't need it to be processed by the arduino, just transmitted through an ethernet shield.

In other words, it is possible to transmit simple video (just enough to handle eg. bios) remote?

title: Is it possible to read VGA with an arduino

Answers: 2

body:
Well, it's very possible, but actually you'll stress the arduino. You can use it perfectly but the problem is, it takes a lot of time of Arduino. The reason is actually simple: Horizontal syncronization takes each 32uS of arduino, so the code is interrupted a lot, and if you use other codes the screen may flick. But i have a solution for you. I found software libraries:
http://forum.arduino.cc/index.php?topic=102181.0
or:
http://labdegaragem.com/profiles/blogs/gerando-sinal-vga-colorido-com-arduino-completo

The last link is in portuguese but you can always ask me anything.

OK, what people do is to use for example 2 arduinos to aliviate de stress, you can buy a arduino bare metal chip and put it in a protoboard to reduce costs. Buuut, ther's another very very easy way to work with vga in arduino. Using a isolated hardware:
http://www.hobbytronics.co.uk/serial-vga

You just need to send serial commands to the vga driver and it will do whatever you want. It comes with a library so you can use in arduino. It's perfect, aliviates the arduino, so you can use your ethernet communication and the price is great (for you, here in Brazil the fees kill a lot of children every day :-( ).

body:
Trying to *capture* analog video such as VGA and transmit it over Ethernet is going to be technically challenging, and of questionable wisdom (at least without compression).  A conventional ATmega-based Arduino is just about the *worst* contemporary platform you could choose for this job - even aside from the VGA issue, it is a poor choice for Ethernet requiring an expensive add-on.  But just for the sake of "can it be done" ....

If you can threshold your signal to a digital level (assuming a high contrast image) this probably can be done, crudely, but will be quite tricky.  The display is likely to be very blurred horizontally - really, it would only be worth doing for bragging points.

The first thing to realize is that the standard VGA 640x480x60 mode has a pixel clock of 25.175 MHz, and most others will be even faster.

One approach would be to try to write a program which samples a digital pin (directly, no Arduino abstractions) to memory as fast as possible.  This would not capture every pixel, but rather something like every 10th.  You would then have to send these over the network before you fill up your available memory.

The tricky part is that you then have to go back, and scan another frame of video with a slight offset, so that by getting every 10th pixel again, you effectively get the pixel adjacent to the first.   And then you do it again, and again, until you have collectively transmitted the entire screen, which hopefully hasn't changed much as you did it.

It's going to be tricky as you will have to work your delays from the sync signals, and you really want a delay which is a fraction of ATmega's clock - which won't happen without external circuitry (programmable delay buffer, etc)

The whole project would be a lot more feasible on an 80+ MHz ARM Cortex part, as you could then use a counter/timer to generate pixel-or-less-adjustable starting delays relative to the sync pulse.  An FPGA would likely be an even better choice.


body:
So far, I have connected plus to VIN and minus to GND, but I am curious what would happen if I do it the other way around. And I am not going to try in case I break someting.

So, what will happen?

title: What happens if I connect an external power supply, plus to GND and minus to VIN?

Answers: 1

body:
Some systems have protection against people connecting things in reverse.
Some don't.

On unprotected systems you MAY destroy the powered system and/or you MAY destroy the power supply - both these depend on happenstance, system design and luck.

Possibly worse - you may damage the target system in an inobvious way so that it subsequently behaves incorrectly or damages other equipment.

Systems which are designed to be protected may not be protected in all cases. eg if you have a "shield" connected that accesses the Vin pin outside the protection diode the reverse polarity voltage may damage the shield AND current may travel via the shield circuitry back into the Arduino via other connections.

______________

Advice on You tube may just sometimes very very occasionally be wrong. Or more often.

If [**this "Reference Schematic"**](http://www.google.co.nz/imgres?imgurl=https://electrosome.com/wp-content/uploads/2014/07/Arduino-Uno-R3-Schematic-Diagram.jpg&imgrefurl=https://electrosome.com/arduino-uno/&h=1739&w=3144&tbnid=_4QHyB6a-usdPM:&zoom=1&docid=DagWDjCRj--l2M&ei=3eHtVITPL4XZ8gWW_IK4DA&tbm=isch&ved=0CCEQMygFMAU)  is correct (as you'd hope it was) then Vin is connected to the "inside" of protection diode D1 - so D1 does not protect against reversed polarity. See lines and boxes in red.
[Larger version of diagram **here**](https://i.stack.imgur.com/3gNVF.jpg)

D1 does protect against reversed polarity on "PWRIN".
How PWRIN relates to shield feeding I know not.

![enter image description here][1]

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


body:
I have some code that generates random numbers on the Arduino, it then sends these random numbers firstly, using `Serial.print(float data,int lenght)` and as a floating point number using the following function

    void send_float (float arg)
    {
      // get access to the float as a byte-array:
      byte * data = (byte *) &arg;

      // write the data to the serial
      Serial.write (data, sizeof (arg));
      Serial.println();
    }
I then receive this data using python, take the absolute difference of the two values, discard any differences less than the length with which I send the string and output the rest to the screen.

I observe two things, a) Fluctuations of the order with which I send the data (ie. if I send to 6 decimal places then I see fluctuations of ~1e-6), this is reasonable and b) I see fluctuations of absolute value 1e-8 or lower **independent** of what accuracy I send the string.

Even if I send the string to 11 decimal places, when I compare against the float I see fluctuations up to but not above 1e-8.

Why? This doesn't make any sense. My full code is actually the answer to an old [unanswered stack exchange question][1]

  [1]: https://stackoverflow.com/questions/12664826/sending-float-type-data-from-arduino-to-python/28719607#28719607

title: Serial, Numbers sent as Floating Point and Characters are different at 1e-8 level

Answers: 1

body:
This is a somewhat dumb question but, in case anyone else searches it as pointed out:

> The precision of a float is around 7.2 decimal digits. en.wikipedia.org/wiki/Single-precision_floating-point_format –  BrettAM

So in python the number goes float -> double -> decmial, whereas on the arduino the number goes float -> decimal. The additional step of the double in the case of python causes the discrepancies. But anything after the 7th decimal place is nonesense anyway.


body:
How do I send SMS from an Ethernet shield via SMS Gateway?

The site [Clickatell][1] provides free SMS.

Does anyone know how to do this or is there some other way to do it?

  [1]: https://www.clickatell.com/

title: How to send SMS from an Ethernet shield via SMS Gateway?

Answers: 3

body:
First contact Clickatel's support and ask them how to use their API, make yourself familiar with it.

Then when you know that you connect your Arduino to your ethernet shield, I'm just gonna assume you got Arduino's original shield, because you want to support the arduino foundation.

http://arduino.cc/en/Main/ArduinoBoardEthernet if you have the standalone board.
http://arduino.cc/en/Main/ArduinoBoardEthernet if you have the shield board.

body: Open an account and try to implement their API using something like Chrome REST client. Then do the same through the ESP8266. I would personally relay it through my own web service/ url. You could also take a look at: http://www.instructables.com/id/Send-SMS-from-Arduino-over-the-Internet-using-ENC2/

body:
Thanks to the moderator for telling me to give an improved answer, Here it goes->

From your question I infer that you want to send a SMS from your Arduino with an Ethernet Shield.

My suggestion to you is to use a service "CAYENNE".
It's a cross platform service for IOT.

You can create a **FREE** account on it by visiting their website :[here][1]

  [1]: https://mydevices.com/

You will be provided with a **KEY** to use with your devices

Then all you have to do is connect your Ethernet Shield and upload Cayenne's BASIC code to your Arduino so that it would link the key assigned to you to the account.

You can now Control your Arduino from any APP or directly through their website as provided above.

As far as SMS is concerned all you'll have to do is to add a trigger (GO TO OPTIONS -> TRIGGERING AND ALERTS  ) and select the notify option(Add SMS here)

Then you just have to enter the country code along with the phone number and when a particular event of your choice occurs you will be notified via SMS.

Hope this helps :)
Feel free if you have any further doubts.


body:
I am working on home automation project. A network consists of one master device and many (maybe 10-20) slave devices, all communicating via these [RF modules](http://cdn.instructables.com/F4L/W6X0/HM8DG3PI/F4LW6X0HM8DG3PI.LARGE.jpg). I am using arduino in slave devices. Master will be based on raspberry Pi (most probably). Slave nodes can be sensors or switches(to control household electronics). To and fro communication will include data such as : a) Turn off bulb 1, b) Turn on TV, c) Set the bulb brightness to 34%, d) Temperature reading is 23 degree Celsius etc.

From security point of view, imagine there are similar other networks in the range and one network must not interfere with another. As such, I need to implement some sort of authentication whenever each data transfer takes place between master <---> slave. **What logic do you suggest for this process?**

There can be cases when data has not been received successfully by the receiving end. In such cases, I am planning to use some sort of checksum and acknowledgement system. If acknowledgement is not received, data will be resend in time intervals of 1s, 5s, 10s, 30s, 30s. If these 5 resends fail, the slave/master will be considered as unavailable/powered down. **Your opinions/suggestions on this?**

Slave arduino will be busy controlling appliances/sensors connected to it (real busy when controlling appliances). As such, it won't have much time for communication. Less time required for communication == Awesome. **How much time do you think the arduino will take to complete one such data transfer?**

Another solution I could think of was using two arduinos connected via i2c in each slave module. One arduino will be busy controlling the lights/sensors. Other one will take care of RF communication. If it receives some valuable info which was meant for this particular module, it will transfer the same to the other one using i2c bus. **Is this a feasible backup plan?**

**Am I doing wrong by selecting RF modules for this purpose? Should I switch to Zigbees?**

Thanks guys for reading. Any constructive suggestions from your side will be very helpful.

title: RF network using Arduino

Answers: 1

body:
The NRF24s are great, but limited to communication only.

Digi's [XBee 2mW][1] module has got great indoor range, but more to the point **it's got 8 I/O lines and 6 10-bit ADCs on board**. It's also built for mesh networks (or you can get star-network equivalents) and has security encryption to boot. This means that, for some of your nodes, you don't need any other hardware to have a fully functioning control point (not including relays and sensors of course), so you can ditch having arduinos at every node.

They're so easy to use, very low power, and have plenty of support and documentation available online.

Do it!

  [1]: https://www.sparkfun.com/products/10414 "XBee 2mW"


body:
I know that it's fairly easy to change the emulate keyboard and mouse by Arduino. But I'm quite specific about the goal I would like to achieve hence I would appreciate if you could advise me which components (Arduino compatible) I am going to need to have such a built:

Physical usb keyboard --> Arduino via usb IN --> keys remapping (for example pressing q will return ctrl+3 or more advanced action) --> Arduino USB OUT (which I can directly plug in to my computer and receive modified keyboard commands).

To sum up I  just want Arduino to work as intermediary.

Will simple Arduino Uno + USB shield do the work?

Thank you a lot for your support!

title: Which components to built remapping keyboard via USB in + out (remapped)

Answers: 0


body:
How to get a One-Wire address of a given WS2812B pixel? I bought several of these, and I cannot make them light. On the other hand, when I connect the addressable LED strip made of these diodes, I have no problem controlling it.

Here is my set-up:

![enter image description here][1]

I tried many programs, e.g. AdaFruit_NeoPixel -> simple, setting number of LEDS to 1, but no effect. No blinks, nothing - as if the diodes were dead.

If every One-Wire device is identifiable by 64 bit ID, how does the Arduino know the correct "order" of the LEDS on the ribbon? How to tell the Arduino the new sequence of the LEDS on the strip that would result if I replace one (broken) LED with another?

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

title: ws2812b NeoPixel - how to address it? How Arduino knows the correct order of LEDS on the stripe?

Answers: 2

body:
The WS2811/2812/2812B is not a 1-Wire device but is in fact a timing-based shift register with 3 LEDs (external in the case of the WS2811) connected to it.

As long as valid bit pulses are sent to the input of one of these devices it will shift the data through it and subsequently out of its data output. Connecting this output to the input of another device will shift data into that device as well, with the latest data sent being transmitted towards the furthest device in the chain.

Provided 24 bits per device are sent before the latch signal, The first 24 bits will be shifted into the first device, the second 24 bits into the second device, and so on until the last 24 bits into the last device in the chain. Once the latch signal is received, the devices will switch to the color indicated by the 24 bits currently shifted into them.

Since all of the devices use the same signaling (the only differences being supply level and the presence of a built-in RGB LED), they can be replaced freely with devices of the same or different make between the three.

body:
Just one correction. The the first 24 bits of the data are shifted into the first WS2812. That device loads those 24 bits into its PWM registers. If more data is transmitted, the first WS2812 shifts that out to the following WS2812. So the first data sent stays in the first WS2812, the 2nd data stays in the 2nd WS2812, and so on. This is explained in the data sheet.
Data-wise, it's a one-wire device. Power connections don't count.