message:
Arduino with 12 bit DAC (MCP4725) Not Working

I have an Arduino Mega AT2560 and need to have real DAC. I purchased the [Sparkfun 12 bit DAC][1], however I don't think it is working properly.

I am using the Arduino wire library to communicate with the DAC. When I write 0, I am expecting to see 0v from the DAC's OUT pin. However, I see some seemingly random constant voltage. In reverse, when I write 4095 to the DAC I see the same voltage as when I write 0. I expected to see 5v.

 1. Can someone verify that I hooked it up correctly?
 2. Can someone verify the code I am using?

[![12 Bit DAC with Arduino ATMega 2560][2]][2]

    #include <stdint.h>
    #include <stdio.h>
    #include <Wire.h>

    #define MCP4725_ADDR 0x60 // [0000 0110]
    /*
    * 12 Bit DAC MCP4725 gives a range of 4096 possible values.
    *
    */
    void setup() {
      Wire.begin();
      Serial.begin(9600);
    }

    void loop() {
      Wire.beginTransmission(MCP4725_ADDR);
      Wire.write(64);            // cmd to update the DAC [0100 0000]
      Wire.write(4095 >> 4);        // the 8 most significant bits...
      Wire.write((4095 & 15) << 4); // the 4 least significant bits...
      Wire.endTransmission();
    }

  [1]: https://www.sparkfun.com/products/12918
  [2]: https://i.stack.imgur.com/YXl7l.jpg

body:
Sorry I'm late -- I realize this question was asked 8 months ago, but it doesn't look like you fixed it, and I figure others can always benefit (or you might even, if you still want to try).

Your code looks correct (I compared it to the Sparkfun example, and also to the datasheet for the MPC4725).

However, it does look like you're using the wrong address for the part.
(The actual value for the address is not given in the Sparkfun example -- at least, I couldn't find it).

Your line:

    #define MCP4725_ADDR 0x60 // [0000 0110]

is wrong in two places:

1) 0x60 is 0110 0000, not 0000 0110

2) According to the datasheet (section 7.2), the address should begin with the device code 00, and then the address gets appended. So assuming an address of A2 = 0, A1 = 0, and A0 = 0 (default), the value for MCP4725_ADDR looks like it should be 0xC0 or 00 000x.  If you soldered the address line to Vcc instead of ground, the address should be 0xC2 or 00 001x.

The x in the address line represents the read/write bit.  If you're trying to command the DAC, it should not be asserted, so the addresses above are correct. If you're trying to read the current value, it should be asserted, which makes your address 0xC1 or 0xC3.

If you have the address wrong, even though the rest is correct, the part will ignore it, so that's probably the issue you're seeing.

Hope this helps someone!


sender: user

sender: assistant

body:
1. you want to make sure that there are pull-ups on the SCL/SDA lines;
2. you want to make sure that the address is correct. some routines use 7-bit notation for that, and others use 8-bit notation for that. end of the day, you want the transmission to be 0xc0 | (A2:A1:A0:R/W). so check the write.write() and see what it expects. I suspect that it expects 0xCx, rather than 0x6x.

having said that, here is your code running on an uno, with the dac configured as per sparkfun spec.

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

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

so I think it is fair to say that the code is ok but something happened on your end that prevented it from working.


message:
error: expected primary-expression before ',' token

I'm gettng an error "error: expected primary-expression before ',' token" in the following line of code - I have initialized an array with 220 ints. What am I doing wrong here?

    const PROGMEM int P7Val[] = {1635,1635,1635,1635,1635,1630,1630,1630,1630,1630,1625,1625,1625,1625,1620,1620,1620,1620,1615,1615,1615,1610,1610,1610,1605,1605,1605,1600,1600,1600,1595,1595,1595,1590,1590,1590,1585,1585,1580,1580,1580,1575,1575,1570,1570,1570,1565,1565,1560,1560,1555,1555,1555,1550,1550,1545,1545,1540,1540,1535,1535,1535,1530,1530,1525,1525,1520,1520,1515,1515,1510,1510,1505,1505,1500,1500,1495,1495,1490,1490,1490,1485,1485,1480,1480,1475,1475,1470,1470,1465,1465,1460,1460,1455,1455,1450,1450,1445,1445,1440,1440,1435,1435,1430,1430,1425,1425,1420,1420,1415,1415,1410,1410,1405,1405,1400,1400,1395,1395,1390,1390,1385,1385,1380,1380,1380,1375,1375,1370,1370,1365,1365,1360,1360,1355,1355,1350,1350,1345,1345,1345,1340,1340,1335,1335,1330,1330,1325,1325,1320,1320,1320,1315,1315,1310,1310,1305,1305,1305,1300,1300,1295,1295,1290,1290,1290,1285,1285,1280,1280,1275,1275,1275,1270,1270,1265,1265,1265,1260,12601635,1635,1635,1635,1635,1630,1630,1630,1630,1630,1625,1625,1625,1625,1620,1620,1620,1620,1615,1615,1615,1610,1610,1610,1605,1605,1605,1600,1600,1600,1595,1595,1595,1590,1590,1590,1585,1585,1580,1580,1580,1575,1575,1570,1570,1570,1565,1565,1560,1560,1555,1555,1555,1550,1550,1545,1545,1540,1540,1535,1535,1535,1530,1530,1525,1525,1520,1520,1515,1515,1510,1510,1505,1505,1500,1500,1495,1495,1490,1490,1490,1485,1485,1480,1480,1475,1475,1470,1470,1465,1465,1460,1460,1455,1455,1450,1450,1445,1445,1440,1440,1435,1435,1430,1430,1425,1425,1420,1420,1415,1415,1410,1410,1405,1405,1400,1400,1395,1395,1390,1390,1385,1385,1380,1380,1380,1375,1375,1370,1370,1365,1365,1360,1360,1355,1355,1350,1350,1345,1345,1345,1340,1340,1335,1335,1330,1330,1325,1325,1320,1320,1320,1315,1315,1310,1310,1305,1305,1305,1300,1300,1295,1295,1290,1290,1290,1285,1285,1280,1280,1275,1275,1275,1270,1270,1265,1265,1265,1260,1260,1255,1255,1255,1250,1250,1245,1245,1245,1240,1240,1235,1235,1235,1230,1230,1225,1225,1225,1220,1220,1215,1215,1215,1210,1210,1210,1205,1205,1200,1200,1200,1195,1195,1195,1190,1190,1185,1185,1185,1180,1180,,1255,1255,1255,1250,1250,1245,1245,1245,1240,1240,1235,1235,1235,1230,1230,1225,1225,1225,1220,1220,1215,1215,1215,1210,1210,1210,1205,1205,1200,1200,1200,1195,1195,1195,1190,1190,1185,1185,1185,1180,1180};

body:
Two things:

1. You have a comma missing: `1260,12601635,1635,`
2. You have an extra comma: `1180,1180,,1255,1255`

If you reformat your list into a nice regular table (say 10 entries per line) across multiple lines these things instantly become apparent.


message:
Can I run ESP8266 via Arduino using the PWM pins?

First question: Since we can control the volts that we can throw via PWM pins on Arduino, can we use it to power the 3.3 V ESP8266?

Second question: Can we also use these PWM pins as software serial pins i.e. they will be sending instructions at 3.3 V?

body:
>First question, Since we can control the volts that we can throw via PWM pins on Arduino, can we use it to power the 3.3v ESP8266?

No. The ESP8266 draws *far* too much current (in excess of 200mA) to use anything other than a proper supply.

>Second question, Can we also use these PWM pins as Software serial pins i.e. they will be sending instructions at 3.3v?

We'll drop the "also", since we've decided that you're not doing that.

You can use SoftwareSerial on any GPIO pins you like, provided the RX pin supports pin change interrupts.


message:
Arduino Interface with Serial device and LCD display

I want to connect my Arduino UNO to a serial device that once powered displays signature numbers. I want to then display those numbers on an LCD display. I have my 16x2 LCD wired correctly and it works fine even when I use the SerialDisplay example code from the library.

My questions are:

1. Can I use a USB to TTL serial cable to connect the RX/TX pins of the serial device to the TX/RX pins of the arduino?
2. The two numbers are more than 16 characters. How can I cut the numbers down and then display the two numbers on two seperate lines of the LCD display?

Let me know if I should provide further details.

body:
 1. If the device _is_ serial and you want to connect it to the Arduino _serial_ port, why would you use a usb-to-serial converter?
For a serial to serial connection, you have to connect TX, RX and GND.
This is the bare minimum for bidirectional communication, if your device is really read only, you can use just the TX and GND.

 2. it depends how you receive data from your "serial device" - btw, what is it? If the data comes as either ascii or individual characters, then it's easy: treat them as strings and display them separately. If the numbers arrive in binary format, you have to perform the conversion to string.

Questions like this should have attached at least a snippet, if not all, of code.


message:
How does this code move the bird sprite in this sketch?

I'm teaching this [sketch][1] in my class. I understand most of the sketch and can see the class that makes the bird move, but I still don't quite understand how the code makes the sprite "move." I can also see what generates the Pipes but I don't how the code creates them or randomizes them.

Here is the code for both:

Bird

    class Chym {

    private:
      int frameCount;
      int x;
      int y;
      int deltaIde;
      int delayFrame;

      int jumpCount;
      int maxJumpCount;
      int moveSpeed;

      bool _isDead;
    public:
      void respawn() {
        x = 24;
        y = 20;
        deltaIde = -1;
        moveSpeed = 1;
        jumpCount = 0;
        _isDead = false;
      }

      Chym() {
        frameCount = 0;
        delayFrame = 0;
        maxJumpCount = 20;
        respawn();
      }

      void render() {
        if (frameCount < ANIM_FRAME / 2) {
          display.drawBitmap(x, y, flappybird_frame_1, 16, 12, 1);
        }
        else {
          display.drawBitmap(x, y, flappybird_frame_2, 16, 12, 1);
        }
      }

      void update() {
        delayFrame++;
        if (delayFrame == DELAY_FRAME) {
          y += deltaIde * moveSpeed;
          delayFrame = 0;
        }

        if (y > 35) {
          _isDead = true;
        }

        frameCount++;
        if (frameCount >= ANIM_FRAME) frameCount = 0;
      }

      bool isDead() {
        return _isDead;
      }

      void die() {
        _isDead = true;
      }

      void cancelJump() {
        jumpCount = 0;
        flyDown();
      }

      void flyUp() {
        if (jumpCount < maxJumpCount) {
          deltaIde = -1;
          moveSpeed = 3;
          jumpCount++;
        }
        else {
          flyDown();
        }
      }

      void flyDown() {
        deltaIde = 1;
        moveSpeed = 1;
      }

      int getX() {
        return x;
      }

      int getY() {
        return y;
      }

    };
 Pipe

    class Bar {

    private:
      int x;
      int y;
      int delayFrame;
      int moveSpeed;
    public:
      Bar() {
        delayFrame = 0;
        x = 0; y = 24;
        moveSpeed = 2;
      }

      void setPos(int sx, int sy) {
        x = sx; y = sy;
      }

      void render() {
        display.drawBitmap(x, y - 30, bar_top, 8, 20, 1);
        display.drawBitmap(x, y + 10, bar_bottom, 8, 20, 1);
      }

      void update() {
        delayFrame++;
        if (delayFrame == DELAY_FRAME) {

          x -= moveSpeed;
          if (x < -10) x = 95;

          delayFrame = 0;
        }
      }

      int hitTest(int tx, int ty) {
        int hitX = ((tx >= x - 16) && (tx <= x))?1:0;
        int hitY = ((ty <= (y - 10)) || (ty + 12 >= y + 10))?1:0;
        if (hitX != 0) {
          return hitY;
        }
        return 0;
      }

    };

https://www.youtube.com/watch?v=04cY78Y2d3g

  [1]: https://www.dropbox.com/s/1hxxvueidqjoi09/flappyDuino.zip?dl=0

body:
This part of your code is what changes the sprite's y-value.

    y += deltaIde * moveSpeed;

When you click the "jump" button or when the bird falls the y-value is changed to reflect either an upward movement or a downward movement. When your `render()` method is called the bird will either be drawn higher up on the y-axis (it's flying) or lower on the y-axis (it's falling).

As for the bars, if you watch closely in the video you can see that they aren't actually randomized.

**Compound Assignment Operators**

`+=` is the "plus assign" operator. It adds whatever is on the right side to the variable on the left side. Here is a table of other compound assignment operators: https://en.wikipedia.org/wiki/Operators_in_C_and_C++#Compound_assignment_operators

    int x = 5;
    x += 2; // equals 7; equivalent to x = x + 2;
    x = 5;
    x = x + 2; // also equals 7; equivalent to x += 2;


message:
Arduno Uno voltage in via VIN pin or DC power?

I have an Arduino UNO. It has VoltageIN on a pin. Is there any difference between powering my UNO through VIN or powering it through the DC port?

The [docs only say this](https://www.arduino.cc/en/Main/ArduinoBoardUno),

> 5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

So it seems to imply VIN/USB/DC in all go through the voltage regulator? Is there any difference then?

Is there any advantage to running a variable power supply through an adapter like this:
[![DC-in][1]][1]

Or should I just go through VIN?

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

body:
DC Jack has a Reverse Protection Diode, that drops 0.7V at usable currents. The VIN does not. Both go through the on board LM7805 or similar linear regulator. The USB does not, but it does go through a P-Channel Mosfet used to switch between USB and DC/VIN power before connecting to the 5V rail. The 5V pin bypasses the regulator, Diode, and P-Channel Mosfet completely.

The advantage of the DC jack is that the Reverse Protection Diode is used, preventing reverse voltage problems if you wire it wrong.


body: If you have a "variable power supply" just set it to 5.00v and connect to the 5v pins.  Eg like the this http://blog.unixbigot.id.au/2015/10/make-5-volt-battery-supply-for-any.html?m=1


message:
Why does my analogRead work on Teensy but not Arduino Uno?

I have successfully made a voltage measurement circuit on my Teensy 3.1 that reads a voltage coming out of digital pin 0 set high and coming back into an analog pin A0 to read voltage.

Basically:

<!-- language: c -->

    int timer = 100;
    int ColA = 0;
    int Output;

    // Setting digital pin functions

    void setup()
    {
      Serial.begin(38400);
      pinMode(0, OUTPUT);

    }

    // Program

    void loop()
    {
      digitalWrite(0, HIGH);
      delay(timer);
      Output = analogRead(A0);
      Serial.println(Output);
      delay(timer);
    }

It works fine with my circuit on a Teensy 3.1 running 3.3v however when i run this code on an Arduino Uno running 5v wired exactly the same way I just get this print out of numbers that cycles back and forth from ~128 down to 0 and back constantly.

Any insight on the differences here would be great. I need the 5v micro-controller to run a 4051 multiplexer!

body:
If you're still using D0 as your output on the Uno then yes you are doomed to failure.

D0 and D1 are the serial port. You are using that to communicate with the PC. You cannot use them for any other purpose at the same time.

Pick a different IO pin to be your voltage source.


message:
Stuck on upload

**I just bought the SmartEverything FOX Board which is Arduino compatible** http://www.smarteverything.it/wp-content/uploads/2015/10/SmartEverything-User-Guide-Ver-1.01.pdf and simply tried to get started with it.

**My OS is Ubuntu 14.04, my laptop DELL XPS 13 bought in 2014**

**I cannot upload sketches on it, when I try, it gets stuck on uploading**, whether it is a basic script (blinkRBG) or even the default one with empty setup and loop methods, my laptop processor keeps running at 100% and nothing happens.
**The board does not do anything, tx/rx leds do not flash.**
**I can access to it with a Windows 7 laptop  (UPDATE: and another UBUNTU laptop) from a frien**d, I could upload the basic blinkRGB sketch. If I try to upload from my Ubuntu laptop after, it does erase the contents and stop the blinking but nothing follows.

When I try to upload, I only get the compiling logs:
Quote

    Sketch uses 13,368 bytes (5%) of program storage space. Maximum is 262,144 bytes.

**I could still upload sketches to another board from my Ubuntu laptop: to an Arduino micro.**

**I am connecting directly from my board to my laptop through USB 3.0**, I don't have USB2.0 plugs on my laptop, and I currently don't have any programmer device.

I tried with different versions of arduino IDE (1.6.4 1.6.5 nightly), same issue every time.
The IDE sees that my board is connected on /dev/ttyACM0

I tried to run in command line but it gets stuck as well
Quote
/home/jcharlet/.arduino15/packages/arduino/tools/bossac/1.6-arduino/bossac --port=ttyACM0

**I've been googling the world but could not find anything, could anyone help me to troubleshoot it please?**

body:
Moved to another board more suitable to our needs, but @sm4rteverything (Twitter) gave us the following solution (not tested):

> This is a known bug of the bootloader.
>
> to fix this U need to download the one i attach in this email with the
> ATMEL-ICE tool. http://www.atmel.com/tools/atatmel-ice.aspx
>
> Copy the attched file under: <your home
> Page>\Arduino15\packages\AMEL\hardware\samd\1.0.0\bootloaders\sme
> (Linux) C:\Users\<user log
> in>\AppData\Roaming\Arduino15\packages\AMEL\hardware\samd\1.0.0\bootloaders\sme
> (Windows)
>
> last follow these three simple step Connect the ATMEL-ICE on the SWD
> J1 connector (pin 1 on top-rigth , the pin on eon cabel is the red
> one)

[![Board picture][1]][1]

> select on Arduino IDE to connect to ASME via atmel-ice (board menu)
> tool->burn bootloader

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


message:
Algorithms to reduce measurement error from analogue sensors

When reading analogue sensors - e.g. load cells, accelerometers - via a microcontroller's Analogue to Digital Converter, there are many sources of potential measurement error including:
a) Warm-up time for electronics
b) Mechanical inertia and resonance
c) Spurious random readings (due to e.g. vibration, electrical interference).

My current software hack for a) and b) is to simply add a suitable time delay before reading the sensors; however there must be a more robust way of detecting and screening for resonance...

My hack for c) is to take the mean of a given number of consecutive readings, but discard any individual readings which exceed a given percentage range from the current mean (pseudocode example below). The trouble with this approach is that it requires an inital `baseline' sensor reading, and if this happens to be spuriously high or low, it can cause subsequent correct readings to be rejected.
Another approach might incorporate a weighted moving average, but this would still be skewed by spurious random readings.

Are there any robust and elegant approaches / algorithms for the above which are commonly applied in commercial devices (e.g. domestic or laboratory weighing scales) that I could include in my code to improve the accuracy and reliability of measurements?

Many thanks in anticipation

    // Take mean of multiple sensor readings excluding outliers:

    # define SAMPLES 100 // number of samples to take mean of
    # define TOLERANCE 0.1 // % range of allowable deviation
                           //between current mean and new values, expressed as decimal

    n = 1; // loop variable
    total = analogRead(analogPin); // Running total for calculation of mean & baseline reading
    mean = total; // mean of all current data

    while (n < SAMPLES) {
        new = analogRead(analogPin);
        if (new < (1 + TOLERANCE) * mean) and (new > (1 - TOLERANCE) * mean){
            total += new; // if new reading is within range, calculate new mean
            n += 1;
            mean = total / n;
            }
        // (else ignore new reading)
    }
    Serial.print mean;

body:
I use something very similar to what you are proposing to measure RSSI in an antenna pattern generator.  Say you have an array of 16 samples.  You start filling the array with samples but don't actually output a result until the array is full.  This will give you a startup period of 16 samples where no decisions are made.

After the array is loaded, set a semaphore that indicates that results may now be used to make decisions.  New samples overwrite the oldest sample in a recirculating buffer.  You will now get decision outputs at the same rate as the sample rate with a lag, i.e. when the inputs go to zero abruptly, it will take 16 sample periods for the output to catch up.  I call this a 16 sample rolling average.

For relatively stable inputs, simply take the mean of the array and output that result.

For inputs that are glitchy such as RSSI take the mean of the array and then find the sample(s) that is (are) the farthest away from that mean.  You then recalculate the mean without that sample included.  Note:  Do not discard that sample, simply ignore it for that cycle.  I call this a 15/1 outlyer average.  For my RSSI measurements, this gives me the equivalent of a 48 sample rolling average.  You can do an 8/1, 16/2 system etc requiring 9 and 18 samples per sample respectively, tuning the counts to your particular application.  I am able to get nearly anaechoic chamber results in the middle of a radio noisy office.

Again, note that the outlyers are NEVER discarded as they may represent a real trend.


body:
Thank you John! Your solution is what I was looking for: it resolves my conflict between preserving all the data and excluding the skewing effects of outliers; is simple enough to implement on a microcontroller; and seems to work perfectly. I'm guessing that the rolling mean will also smooth out any potential swings due to mechanical resonance.
I know this is an Arduino forum, but I find it quicker and easier to write interactive code in Python, so I've written a crude `test bed' implementation of your algorithm in Python so that I could get a feel for how it works in practice, with user keyboard input simulating real-life sensor readings. I've avoided any libraries or esoteric Python syntax, so this should be easy to adapt to C++/Arduino. I'm posting it here in case it is of interest to the community.
I've used the formula for Sample Std Deviation (n-1) rather than Population SD (n) which I think is correct in this context, but please let me know if not:
in LaTeX: $SD=\sqrt{\frac{\sum_{(i=1)}^{n}(x_{i}-\bar{x})^{2}}{n-1}}$

If there are any other algorithms or solutions to my post, I'd be very interested to know. Thanks again.

    #===================================================
    def SampleSD(data,bufLen):
        datasum = 0.0 # NB declare as float to prevent integer rounding error
        diffsum = 0.0 # NB declare as float to prevent integer rounding error
        for m in range (0,bufLen):
            datasum += data[m]
        mean = datasum / bufLen
        for m in range (0,bufLen):
            diffsum += (data[m] - mean) ** 2
        sd = (diffsum /(bufLen-1)) ** 0.5
        print "n: %d\tSum: %f\tMean: %f\tSD: %f" %(bufLen,datasum,mean,sd)
        return mean,sd

    #=====================================
    def addData(data,bufLen):
        print "\n------------------------------"
        new = input ("Sensor reading: ")
        for m in range(bufLen-1,0,-1):
            data[m]=data[m-1]
        data[0]=new
        return data

    #======================================
    bufLen = input ("Buffer Length: ")
    print
    data = [0] * bufLen # Declare an array of suitable length in Python
    n = 0

    # Fill buffer with initial data
    while n < (bufLen):
        new = input ("Initial sensor reading: ")
        data[n] = new
        n +=1
    print "\nBuffer initialised."
    print "Data: ",data

    while True:
        addData(data,bufLen)
        print "Data: ", data
        mean,sd = SampleSD(data,bufLen)
    #===========================================
    # Recalculate Mean only using data within range +/- 1 SD of mean
        if sd != 0: # Error trap to avoid divide by zero error if sd = 0
            print "\nChecking for outliers:"
            newSum = 0.0 # NB declare as float to prevent integer rounding error
            newLen = 0
            n=0
            while n < (bufLen):
                if ((data[n] < (mean + sd)) and (data[n] > (mean - sd))):
                    print "Data [%d] = %d Included" % (n, data[n])
                    newSum += data[n] # sum of data which is within +- 1SD of original mean
                    newLen += 1 # number of data whic are within +/- 1SD of original mean
                else:
                    print "Data [%d] = %d Excluded: Out of range" % (n, data[n])
                n+=1
        CorrMean = newSum / newLen
        print "New n: %d\tNew Sum: %f\tCorrected Mean: %f" %(newLen,newSum,CorrMean)


body:
... and here's my minimal working example for the Arduino. Feel free to adapt it for your own requirements, and please post any improvements or corrections to my script; or any alternative algorithms for the above.

Just noticed that my approach of using the SD to define and exclude outliers is a little more (? unnecessarily) complex than John's algorithm, which defines outliers in terms of the highest and lowest values from the mean; but both methods seem to work nicely.

Cheers!

    #define BUFFER 5 // Buffer size (number of readings to use in rolling Mean)
    #define SENSORPIN 3 // Analogue input pin from sensor
    int data[BUFFER]; // Make an array of appropriate size for Buffer

    void setup() {
      pinMode(SENSORPIN, INPUT);

      // Fill buffer with initial data
      int n = 0;
      while (n < BUFFER) {
        data[n] = analogRead(SENSORPIN);
        n++;
      }
    }

    void loop() {
      // Calculate Raw Mean & SD
      float datasum = 0;
      float diffsum = 0;
      for (int n = 0; n < BUFFER; n++) {
        datasum += data[n];
      }
      float mean = float(datasum / BUFFER);
      for (int n = 0; n < BUFFER; n++) {
        diffsum += ((data[n] - mean) * (data[n] - mean));
      }
      float sd = sqrt(diffsum / (BUFFER - 1));

      // Recalculate Corrected Mean only using data within range +/- 1SD of Raw Mean
      if (sd != 0) {      // Avoid divide by zero error if sd = 0
        float newSum = 0; // Sum of readings within acceptable range
        float newLen = 0; // Number of readings within acceptable range
        int n = 0;
        while (n < BUFFER) {
          if ((data[n] < (mean + sd)) and (data[n] > (mean - sd))) {
            newSum += data[n];
            newLen ++;
          }
          n++;
        }
        mean = newSum / newLen; // Corrected Mean
      }

      // Add your code here to do stuff with variable float 'mean' = the (Corrected) Mean

      // Read new sensor reading, append to buffer and delete oldest reading
      for (int n = (BUFFER - 1); n > 0; n--) {
        data[n] = data[n - 1];
      }
      data[0] = analogRead(SENSORPIN);
    }


message:
Can I reuse crystal frequency of Arduino?

If I use some IC which requires clock frequency like 16MHz, can I take one from Arduino?

Or this it too high frequency to travel to neighboring board?

body: The frequency is important. Make sure they are the same or it will probably not work.


message:
Arduino constant clock output

I am controlling an ADC with my Arduino Uno. I would like the clock of the ADC to be the same frequency of the Arduino.
Is there any way that I can have a constant clock output from one of the Arduino pin ?

Thanks,

Liam

body:
You can use one of the PWM pins on Arduino to output a PWM signal.
If you want a constant clock, you need to set the duty cycle of the PWM to be 0.5, i.e. 50%.

Syntax: analogWrite(pin, value) where the parameter "value" is the duty cycle ranges from 0 (always off) to 255 (always on) since it is a 8-bit PWM generator inside Arduino.

If you need a PWM wave with duty cycle of 0.5, you need to set the "value" above to be 127, which is exactly in middle of 0 and 255:

    analogWrite(clkpin, 127);


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

This outputs 8 MHz on pin 9:

    #ifdef __AVR_ATmega2560__
      const byte CLOCKOUT = 11;  // Mega 2560
    #else
      const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
    #endif

    void setup ()
      {
      // set up 8 MHz timer on CLOCKOUT (OC1A)
      pinMode (CLOCKOUT, OUTPUT);
      // set up Timer 1
      TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
      TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
      OCR1A =  0;       // output every cycle
      }  // end of setup

    void loop ()
      {
      // whatever
      }  // end of loop

---

> How can add a prescaler?

You change the prescaler bits. You can look at the datasheet or my cheat sheet here:

[![Timer 1 bits][1]][1]

You may not need a prescaler, depending on the frequency. Change OCR1A to some number between 0 and 65535 to slow it down.

Edit by Edgar: I tested the OCR1A values with an oscilloscope. At the end of this answer are the frequencies.

---

> you use TCR1A, COM1A0 and similar variables. Are these always present and implicitly defined when running code on the ATmega

Registers like TCCR1A and so on are defined in files which are automatically included by the Arduino IDE. If you use another toolchain they may be also automatically included. The start point is:

    #define <avr/io.h>

Inside that file it checks your processor type (from a symbol passed to the compiler) and then includes an appropriate sub-file. Inside those files are defines which relate the register names to their address in the address-space of that particular chip. For example:

    #define TCCR1A _SFR_MEM8(0x80)

The _SFR_MEM8 basically generates a pointer to a `volatile` address (because it might change without the compiler knowing it) and then dereferences that variable.

Notice that the number 0x80 in that define agrees with the number shown on my chart.

Underneath that define in the appropriate file are also the bit positions for the bits in that register, like this:

    #define TCCR1A _SFR_MEM8(0x80)
    #define WGM10 0
    #define WGM11 1
    #define COM1B0 4
    #define COM1B1 5
    #define COM1A0 6
    #define COM1A1 7

---

> Secondly, do I correctly understand that the output pin is defined in TCR1A, Output A and Output B, to be on Digital Pin 9 and 10 respectively?

Yes, in effect. The datasheet says that if you set the appropriate bits in TCCR1A (note the spelling) then OC1A (board pin 9 on the Uno) or OC1B (board pin 10 on the Uno) will be unchanged/toggled/cleared/set depending on the bits. You can find these names on the datasheet for the Atmega328P (and other devices) and then use the Arduino schematic to find which *processor* pins are connected to which *board* pins.

### Atmega328P datasheet snippet:

[![Atmega328P datasheet][2]][2]

### Uno datasheet snippet:

[![Uno datasheet][3]][3]

---

> Why do you set it to "Toggle" rather than "Set"?

Because every time the counter matches I want to flip the pin. That is, on/off/on/off etc.

---

> What does CTC stand for?

Clear Timer on Compare. What this means is that (unlike other modes) once the compare match is made, the timer is cleared, thus it starts counting up from zero again.

Edit by Edgar: OCR1A values and frequencies

    Value, MHz
     0 8.00
     1 4.00
     2 2.67
     3 2.00
     4 1.60
     5 1.33
     6 1.14
     7 1.00
     8 0.889
     9 0.800
    10 0.727
    11 0.667
    12 0.615
    13 0.571
    14 0.533
    15 0.500

  [1]: https://i.stack.imgur.com/Ftmib.png
  [2]: https://i.stack.imgur.com/bHk4y.png
  [3]: https://i.stack.imgur.com/a0MjE.png


message:
GSM GPRS module not getting any output from Rx , Tx

I am using a SIM800 GSM/GPRS module. I connected it using 4 wires: Vcc 3.7 volt (2 amp supply), RX and TX and GND.  Whenever I try to send a command it shows me nothing. Here is my code.

<!-- language: c -->

    //Serial Relay - Arduino will patch a
    //serial link between the computer and the GPRS Shield
    //at 19200 bps 8-N-1
    //Computer is connected to Hardware UART
    //GPRS Shield is connected to the Software UART

    #include <SoftwareSerial.h>

    SoftwareSerial GPRS(7, 8);

    unsigned char buffer[64];  // buffer array for data receive over serial port
    int count=0;               // counter for buffer array

    void setup() {
      GPRS.begin(19200);
      Serial.begin(19200);
    }

    void loop() {
      if (GPRS.available()) {
        while(GPRS.available()) {
          buffer[count++]=GPRS.read();
          if(count == 64)break;
        }
        Serial.write(buffer,count);
        clearBufferArray();
        count = 0;
      }
      if (Serial.available())
        GPRS.write(Serial.read());
    }

    void clearBufferArray() {
      for (int i=0; i<count;i++) {
        buffer[i]=NULL;
      }
    }

It is an independent module. I've already read the hardware manual and AT command manual. I did everything according to the manual.

body:
There doesn't seem to be anything wrong with your code.  I'm going to assume you have got the right VCC and the right Serial speed.

Do you have a way of connecting the device directly to your PC and then using a terminal emulator to see if the device is talking?

Is there a library that you could use?  Maybe there is some setting that you need that isn't documented.


body:
Are you sure the baud rate is correct? You could try 115200 and 57600. Is the serial monitor set to "Carriage Return" or "Both NL & CR"? If this isnt set, the modem won't respond to your commands since it requires a '\r' to terminate every command. Is there any indication that the modem is powered (like the net LED blinking)? Your code looks alright but, to be sure everything's okay, use this test program to interact with the modem using the serial monitor; just change your loop() to this:

        void loop(){
            while (Serial.available())
                GPRS.write(Serial.read());
            while (GPRS.available())
                Serial.write(GPRS.read());
        }

This way, everything you type in the monitor will be relayed to the modem and everything from the modem will be relayed to the PC, all via the arduino.


message:
Can't figure out how to send Motor Values over Bluetooth, Arduino Bluetooth-controller robot

I was trying to make an Arduino Robot that is Bluetooth controlled but I've some problems!

I can't figure out how to parse strings in Arduino like c++/java/python!
I tried this, If the first letter is L, set the next value to left motor, same for R

but for example "L255" is received as L - 2 - 5 - 5 and it sets L to 2 and ignores 5 - 5.

Any ideas on what I should do?

EDIT: Thought of something else, Sending L or R will toggle the motors! but that's just terrible, it'll be my last option

Update: This is how it works now:
L(0-5) means Left motor speed 5 * 51, 6-9 are backwards! its go backwards at (L(6-9) -5 * 51)

body:
A state machine is the right way to go if you are sending multibyte commands.

However do you need to send 4 bytes for every turn? Do you need accuracy to one degree? Are you going to make regular turns of greater than 60 degrees?  If not I would consider encoding the dAta into a single byte.  You will reduce the radio bandwidth by 3/4, it will improve the responsiveness of. Your software and it will remove the need to have a handler for incomplete messages.

Of course there are probably other requirements that I don't know that will stop you doing this, but in case you haven't thought of it.


message:
Can Arduino libraries be compiled for ARM MCU's?

I am looking for a very low power Micro-controller to interface with the RockBlock Iridium modem. The MCU I am thinking of purchasing is the Gecko Zero by Silicon Labs.

I want to know if it is possible to compile the Rockblock-IridiumSBD Arduino library for the Gecko Zero. The Gecko Zero is a 32 bit ARM MCU.

[IridiumSBD Library][2]

[Gecko Zero MCU][3]

  [2]: https://github.com/mikalhart/IridiumSBD
  [3]: http://www.silabs.com/products/mcu/lowpower/Pages/efm32zg-stk3200.aspx

body:
Depending on the rest of your application, you might find the easiest path is to use the Gecko with the mbed.org tools. There already seem to be [mbed Gecko development boards][1] so the task is, to port the [Rockblock-IridiumSBD Arduino library][2].

The benefit of using mbed with the Gecko is it looks like mbed have all of the libraries, including low-power control implemented.

The [Rockblock-IridiumSBD Arduino library][2] won't compile 'out of the packet' on mbed.

However, the [Rockblock-IridiumSBD Arduino library][2] appears to be a serial interface over a few wires. They recommend 'soft serial' which uses digitalWrite, under program control, and no deep access to Arduino peripherals. That should be relatively straightforward to port to mbed. Mbed has equivalent library calls for digitalWrite, so a first attempt might be a few global search and replace edits.

The alternative would be to use Gecko with an Open Source or commercial development system. However, mbed would provide a faster start, if you have good internet access and are not too paranoid about security, because the tools are 'cloud based', saving you time to set up the tools, and their is an mbed community who might help you over the initial hurdles.

  [1]: https://developer.mbed.org/teams/SiliconLabs/
  [2]: http://arduiniana.org/libraries/iridiumsbd/


message:
Arduino Uno R3 board dead

I have an arduino uno Rs board and when connected to USB the board is dead. Yet when connected to the external supply the board will come to live. Power LED on and led near pin 13 blink on and off all time. I tried another computer and other new usb lead. Still computer will not see the board. When usb lead is on checked the 5 volt on the board and it is ok. Even checked the usb lead with multi meter and all  four connection are ok
Can you give me some advice

---

1.Yes I bought the new board from different source but still waiting for it to arrive.
2.  My clone board Arduino uno using microcontroller Atmega329P-PU and interphase chip Atmega16U2]
3 but the video link is still of help as my new board is as the one shown in the video. Will use it late. Great!!!
There should be a similar explanation for the one I have in the picture[![Uno board as descripted][1]][1]

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

body: Does the Arduino show up at all in device manager or in mac/linux.(not sure what you are using)Is your board authentic or a clone? Did this happen the first time you plugged the arduino in or after uploading sketches etc? I had screwed up my firmware for my board that acted similar to what you describe.(I was trying to flash a different firmware) Eventually i ended up reflashing the right firmware and it went back to working again.Maybe it's that, maybe it isn't.


body:
You are happy the lead is ok. Good.

Can you test another Arduino on the PC? (Is it a driver issue?)

Can you connect to the serial pins on the Arduino and read the console output, is anything coming out on USB? (Is the USB socket on the board broken?)

Have you selected the right board type on the ide? (I know it's a dumb question but...)


body:
I had a similar problem. though it was easily solved but not obvious.

I couldn't connect my nano to the computer, but other devices worked fine. After a while other devices started to be faulty such as portable hard-drives and my CC3D flight controllers. After a cable replacement all the items started working again even the Arduino that i otherwise had discarded as broken.

It might not be the solution you are looking for but im leaving it here in case others comes for a solution.


message:
Separate Timer Instance

I'm trying my best attempt here after failing in Googling the answer, but here goes:

I'm trying to get a separate instance to start running *in the background* when a pin goes HIGH. How should I attempt this? PLEASE explain your answer, so that I can learn as well. I'm using an Arduino Uno R3 with a Commercial Ir RX-Tx.

**Basically:**

Sensor -> Low -> Loop

Sensor -> High -> Start Other Event for 5 min -> Loop while Counting down to reset state.

My thoughts here are:

Do this via 555-timer OR get some functional coding (anyone maybe want to share here what solutions they have found?)

Thanks.

body:
Arduino Uno has two interrupt pins: 2 and 3, and by hooking up the output of your IR, which goes from LOW to HIGH, it will trigger the function that you defined in the code.

For example this is a piece of code that runs when the pin 2 RISING:

    void setup() {
        attachInterrupt(0, doSomething, RISING);
    }

    void loop() {
    }

    void doSomething() {
        //Do your stuff
    }

Look here for further information [link][1]

  [1]: https://www.arduino.cc/en/Reference/AttachInterrupt


message:
using more than 8 temperature probe of DS18B20 on Arduino

I am trying to use more than 8 temperature DS18b20 on one bus. Is there any problem to make it work?

body:
As far as I can see there is no limit on the number of sensors you can have on a bus.

So if you are having problems does your code work with less sensors? Try one and work up.

Is it a current issue are you pulling to much from the board?

Is the problem with the one wire library?

Have you got 4.7k pull ups on each sensor?


body:
As long as you connect each sensor on a different pin, you should be able to collect the data without any problems.

Otherwise try to search for a I2C temperature sensor and use a demux to control 8 sensors.


message:
Sending Something to Serial and Writing it Returns a Correlated but Strange Number

I have an indescribable bug where read and write commands give back an array of numbers that are the digits of the input number except +48. Kinda hard to explain. Basically if I type 0 into this code:

        void setup(){
          Serial.begin(9600); //Begin serial connection
        }
        void loop(){
          if(Serial.available()){ //If serial available...
            double ser = Serial.read(); //Read serial value and write it to 'ser'
            Serial.println(ser); //Print 'ser'
          }
        }
I receive 48. 1 means 49, 2 means 50, 3 means 51... And then two digit numbers, which are the same except for each digit. 10 returns 49 48, 33 returns 51 51, 22 returns 50 50.

body:
Serial.read returns a character. The **character** '0' is 48 in decimal. So this is doing what you expect (or what I expect, anyway). I suggest not using `double` there, eg.

        char ser = Serial.read(); //Read serial value and write it to 'ser'


message:
Safely enabling voltage divider on a 12V battery

I'm planning to monitor voltage of a 12V battery with an Arduino's ADC pin connected via a voltage divider. Since I don't want the circuit itself to drain the battery when not in use, I want to use a transistor to "enable" it via an Arduino DIO pin like:

[![voltage divider][1]][1]

Is this a safe circuit to use?

If I set EN low to disable the divider, will that risk putting 12V directly on the ADC pin and burn it out? I've found [alternative designs][2], but they seem overly complicated.

Edit: The battery is a Lipo which is also powering the Arduino through a step-down DC converter.

  [1]: https://i.stack.imgur.com/TMzN2.png
  [2]: http://www.microbuilder.eu/Tutorials/Fundamentals/MeasuringBatteryVoltage.aspx

body:
I'd use some very large resistors (e.g. 1 and 2 Mega Ohm), and add a small capacitor to the center, to stabilize the value during sampling. Using 1 and 2 MOhm would result in 10uA of current loss, which is probably negligible in your cases.

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

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


body:
I use a similar system on a product I recently worked on to monitor the battery voltage - and of course I didn't want it on all the time to drain the battery.

The trick, though, is to do the exact opposite of what you are doing.  Instead of isolating the ground (*which leaves the battery then directly connected to the Arduino*) you need to completely isolate the battery from the divider.

This can be accomplished by using a P-channel MOSFET which you can then drive with an N-channel MOSFET:

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

The theory is, when the Arduino DOUT is either LOW or not connected (*pulled low by 10K resistor*) the N channel MOSFET is turned off.  That means the gate of the P channel MOSFET is being pulled up to the battery voltage by the other 10K resistor, so the P channel MOSFET is off, which isolates the whole divider from the battery.

When DOUT goes HIGH it turns on the N channel MOSFET which then pulls the gate of the P channel MOSFET down to ground which then turns it on, thus connecting the divider to the battery.

When the P channel is OFF the only circuit connected to the ADC is the connection between the ADC input and ground through a 10K resistor, so everything is happy and safe.

You should not use resistors greater than around 10K in size on the input to the ADC because the ADC itself has a resistance (the *impedance*) which is placed in parallel to the lower resistor of the divider.  If the divider's resistors are too large that impedance will affect the accuracy of your readings because the total resistance of the lower resistor will be skewed slightly.  Yes, it's possible to compensate in software, but as long as you keep to a limit of 10K or so for the resistors you won't need to worry about doing such things.

Note that it is important to use a P-channel MOSFET for this, not a PNP transistor.  A P-channel MOSFET, when on, looks like a very small resistor.  A PNP transistor is seen as a fixed voltage drop skewing your results.  The N-channel MOSFET can be replaced by an NPN transistor if you wish, it makes no real difference. I nearly always use MOSFETS these days instead of BJTs though as a matter of course.

As an aside, the only other way of achieving this whilst maintaining the isolation of the ADC from the battery would be to replace the P channel MOSFET with a small relay (say a reed relay), but then you still have to build a relay driving circuit which is just about as complex as this one.

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


message:
Get 25 kHz PWM on a 16 MHz Arduino

I am trying to output a 25 kHz software PWM on at least four pins simultaneously with variable duty cycles on each pin individualy.

I've got all the actual PWM outputs via internal timers 2x8 1x16 with variable duty cycles and am looking for a way to output a 25 kHz PWM on the four pins (any pins) via an external timer if necessary. How can I do that?

body:
At 16 MHz, your instruction cycle is 62.5 ns, and your PWM period is 40 \$\mu\$s. This is only 640 instruction cycles per PWM period.

To have any hope of doing this, the first thing you need to do is forget using anything Arduino other than the hardware. Download the datasheet for the AVR in question and start getting familiar with it. Your best bet is to use 8 bit timers to reduce the overhead of loading them.

My approach would be to use every 8 bit timer available, and divide the outputs up among the timers. Load the shorest pulse width output in the 8 bit tiemrs. Keep a 16 bit timer available to use for the PWM period. Start all the timers at once. On the first 8-bit timer interrupts, toggle the output, and reload the timers with the time between the next shorest pulse width. Rinse and repeat.

Alternatively you could run one timer, and write a little scheduler that puts the outputs in order from shortest to longest pulse width, constantly poll the timer, and toggle the bits as needed.

Both of these options have a ton of software overhead, and the pulse widths will all be semi-deterministic. Neither would be good for any application where the micro has to do anything else in a timely fashion, such as communication or drive a LCD.


body:
Look into using one of the AVR chips that have more PWM outputs. For example, [AT90PWM81][1] which includes six hardware PWM outputs.

  [1]: http://www.atmel.com/devices/AT90PWM81.aspx


body:
    void setup()
    {
        // Set the main system clock to 8 MHz.
        noInterrupts();
        CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
        CLKPR = _BV(CLKPS0);  // divide frequency by 2
        interrupts();

        // Configure Timer 0 for phase correct PWM @ 25 kHz.
        TCCR0A = 0;           // undo the configuration done by...
        TCCR0B = 0;           // ...the Arduino core library
        TCNT0  = 0;           // reset timer
        TCCR0A = _BV(COM0B1)  // non-inverted PWM on ch. B
            | _BV(WGM00);  // mode 5: ph. correct PWM, TOP = OCR0A
        TCCR0B = _BV(WGM02)   // ditto
            | _BV(CS00);   // prescaler = 1
        OCR0A  = 160;         // TOP = 160

        // Same for Timer 1.
        TCCR1A = 0;
        TCCR1B = 0;
        TCNT1  = 0;
        TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
            | _BV(COM1B1)  // same on ch. B
            | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
        TCCR1B = _BV(WGM13)   // ditto
            | _BV(CS10);   // prescaler = 1
        ICR1   = 160;

        // Same for Timer 2.
        TCCR2A = 0;
        TCCR2B = 0;
        TCNT2  = 0;
        TCCR2A = _BV(COM2B1)  // non-inverted PWM on ch. B
            | _BV(WGM20);  // mode 5: ph. correct PWM, TOP = OCR2A
        TCCR2B = _BV(WGM22)   // ditto
            | _BV(CS20);   // prescaler = 1
        OCR2A  = 160;
    }

    void loop()
    {
        analogWrite( 3,   1);  // duty cycle = 1/160
        analogWrite( 5,  53);  // ~ 1/3
        analogWrite( 9, 107);  // ~ 2/3
        analogWrite(10, 159);  // 159/160
    }


message:
Can I connect an output pin to an input pin to measure it's voltage on a single board?

So just bought an arduino Uno and I've been playing around with it. I want to connect one of the input pins to one of the PWM outputs and measure the output from there by sending it to my computer through `Serial` and then plot it in python.

Sorry if this is a basic question.
Thanks

body:
PWM are digital output pins, and it seems that you wish to measure analog equivalent voltage generated by PWM output. If so, you'd need a filter.

Construct a unity gain op-amp based RC filter with cut-off frequency significantly smaller than PWM clock frequency. This will generate a analog waveform that can drive analog circuits. You could connect this to ADC input pin.

You could Google "Active low pass filter" for a lot of schematics and formula.

BUT

To be able to faithfully reproduce analog signal captured through ADC on a computer screen graph, your ADC sample rate must be more than ~2.5 times analog signal's bandwidth.

If your sample rate is close to Nyquist rates,  you'd need to filter (interpolate) your digitized signal in software to generate a smooth graph. This is a bit involved in maths and software. Otherwise you'd only get a "spikey" waveform.

Or preferably have a sample rate > 10 times analog bandwidth. This will give large enough sample counts to reliably show analog data without much processing.


message:
How to change the usb name of Atmel 32u4?

I want to change my Arduino Leonardo's name that Windows shows me when it's plugged in.

I know that i have to change its firmware to change the name but I cant find firmware for it on the Internet.

On Arduino Mega, I have changed it with a downloaded firmware via flip, but I can't change the file because it's a .hex.

body:
The Arduino '32U4 bootloader, Caterina, can be found under `hardware/arduino/bootloaders/caterina`. It requires LUFA in order to build.

With the technical part aside, note that you are not allowed to use the USB IDs assigned to Arduino LLC with products you intend to distribute under another name. You will need to acquire your own vendor ID from the USB-IF if you want to do so.


message:
Program an ATMega328P and use it without Arduino board

I'd like to use an ATMega328P for my project, I hope to do it without the Arduino board.

I know with the Arduino IDE and an Arduino board I can program the microcontroller. However, would it be possible once I've programmed and debugged the program with Arduino IDE + Arduino board, to take away the microcontroller from the Arduino board and to use the ATMega328P separately, without the board?

If yes, what additional configurations I should do the ATMega328P to work correctly on the breadboard?

body:
Search for ["Build an Arduino"][1] - you'll find tons of how-to articles about doing just that. You'd need to be able to solder connections on a printed-circuit board (and not even that if you wanted to use a solderless breadboard), but it's really straightforward. You can even build it first and program the MCU on the PCB using an FTDI cable. I use an Arduino board and a solderless breadboard to experiment with unfamiliar parts, but I usually go immediately to a hand-built board once I'm familiar with all of the components I'll be using.

Prototyping with the Arduino board lets you throw together a bunch of parts and get something working quickly, and if the Arduino is more capable than your final target - f/ex, a Mega 2650 - you can temporarily ignore the memory and I/O constraints of the smaller device.

  [1]: https://duckduckgo.com/?q=build an arduino


body:
You can remove an ATMEGA from an Arduino and use it in your own board, however when used on a typical Arduino board the chip will be fused for an external crystal as a clock source, rather than the (simpler but less accurate) internal clock.

You cannot change the clock source over ISP unless the clock source the chip is currently expecting is operational, so if you want to change the clock selection you will want to do that before removing the chip from the Arduino.

However, you can also provide a clock crystal and its two capacitors (or a substitute resonator which often has this built in) on your external board.

Typically chips (even those pre-flashed with a bootloader as a convenience) are cheaper than boards, so it's unclear why you would want to move the same chip off the Arduino as opposed to using another.  You will want a USB-logical level serial adapter anyway, and once you have that you can do development on the bare chip on your board, even if you do initial testing on the Arduino.  In a pinch if you don't have the USB converter you can either pull the chip out of an Arduino board and run wires from its D1 and D0, or hold the on-board chip in reset to allow you to borrow those serial lines without interference.


body:
Yes you can use **`ATMega328P`** without arduino board. I always use the IC without arduino. There are two ways of doing it.

 1. You can use arduino board with the IC. Program the IC and then take it out and use it in your circuit. You will have to use **`16MHZ Oscillator`** with capacitors.
 2. If you don't have arduino board, you can use other programmers like **`USBasp`** to program your **`Atmega328p`**. In this case, do not use the direct upload button instead use the upload using programmer options from file menu. Do not forget to select board as **`Arduino Pro or Pro Mini (5v, 16mhz) With ATmega328`** and programmer as **`USBasp`**.

**NOTE**: Refer to [**Atmega328p Pin Mapping**](http://learn.qtechknow.com/Resources/Images/Tutorial1-8.jpg) and program your device accordingly. Enjoy!


body:
It's fairly easy to use a standalone Arduino chip. The one tricky thing about the chip used for the official boards is that they are fused to use the faster (and more accurate) external oscillator that's mounted on the board. This applies even when you purchase the loose chips, since most are resold with intention of being installed in an Arduino board to replace a burned-out one, with exception of perhaps the ones from Digikey.

Caveats: The Arduino is designed as a prototyping board, and few things do better than it does at this task. You may want to leave the chip on the Arduino board until you are done designing and testing your circuit. Only then do you connect it directly. It can be used in-place if you have a clock circuit in place, or you can change the fuses (see later) and reprogram the Arduino with an ISP adapter and a clock speed of 8mhz (PlatformIO lets you do this (*and* allows direct imports of an Arduino sketch) -- check their docs page for the Atmel AVR plugin, but you can also look up a number of guides on how to add a board file to Arduino to tell it to use the 8mhz option for a bare chip)

If you remove the chip for use in a different circuit, it either needs that clock circuit added back in, or to have its fuses changed (I'll get to that in a minute). It will also be hard to program, for a number of reasons, so you'll want to purchase a bit of fairly cheap hardware:

**Programming** a standalone chip: The Arduino's CPU is not natively designed to talk to a computer. You need an intermediary. On the Uno, this is done via a second Atmel chip that has USB capability, and a bootloader on the main chip. What that does, is that it uses the UART for upload of the program while the USB chip converts the PC's messages to UART signals. Since the bootloader is somewhat of a pain when the chip is on its own (since UART is picky and installing it sets the chip to use an external clock as a result), you'll want to buy an ISP programmer for the Arduino (or follow the Arduino-as-ISP sketch and instructions to make your own, which requires an Arduino with chip present, so you'd need a second to be programmed).

These can program the ATMega 328 directly over SPI, without a bootloader (there are many instructions on the Internet; search "program bare ATMega 328P with USBAsp", for instance). This makes it a lot easier to change and debug your program outside of popping the chip out and back into the original Arduino board. You also need one to change the clock settings if you don't want to use an external crystal.

If you want to **debug** the chip, it's useful to also purchase a FTDI adapter or other USB-to-UART converter. Note that without the reset circuit part of the board (or again, adding your own), this still won't let you program the ATMega even with the bootloader, though. For that, connect the ground, RX, and TX pins to the adapter. You may or may not want to connect the VCC line, but it's advised to not do so *if* there's a lot of things connected to the chip and/or it has its own power supply. Note that the RX and TX need to be swapped when you connect them; that is, RX to TX and TX to RX -- you want the chip to RX (receive) what the adapter is TX( transmit)ing, and vice versa.

The clock circuit is not hard to build, but it requires a few components you may not have. So, to **change the clock source**, go to http://www.engbedded.com/fusecalc/ and select the ATMega 328P. The defaults are good, but you may want to enable EEPROM keep-on-erase and disable the clock divide-by-8 or adjust the brownout settings. Don't touch anything else (disabling reset or SPI or enabling DebugWire result in "fun" that requires a HV programmer to fix). When done, paste the command it provides to the AVRDude command. You will need to change the -c options (-p is already set to the ATMega 328P, but will fail for non-P 328s -- don't buy those), and perhaps add the -P option (for Port). Do not omit the lowercase -u option, or it will refuse to update the fuses.

    avrdude -p m328p -v -c usbasp -B 100 -u [add extras here: (-P <PORT>) <fuse set command here>]

*Note* that if you purchase a USBASP (make sure it has three sets of jumpers!), for all that they are my favorite programmer, they may not have the updated firmware that supports the -B option (which you'll probably need). That means that you need to attach it to an Arduino via the six-pin programming port, in the exact same way that you'd use it to program the Arduino's bootloader, but then use the Arduino-as-ISP sketch to program the new firmware to the programmer (search "update the usbasp firmware via arduino-as-isp")! For reference, that *usually* means that the cable faces away from the body of the board, and you'll probably have to program the sketch **before** connecting the cable. Also enable the power-from-programmer jumper on the USBASP (5V), and the "self-program" one. (see https://forum.arduino.cc/index.php?topic=560719.0 for the location of the power and program jumpers (JP2)).


message:
two 7HC595 and only 12 outputs

im new to arduino and thinking to create a LED project.

im creating a LED project and i want to control 12 LED's. so i use two 7HC595 but problem i face is how can i only control 12 outputs ?

and i want to create multiple blink patterns with 12 LED, please be kind enough to provide blink patterns that i can modify and create different partners.

i have found many shift-out programs but i do not understand how to limit it to 12 outputs and create multiple blink patterns.

thanks

body: Do not worry about limiting it to 12 bits, send all 16 and use just the twelve you need.  You never know you may expand the project.  Whatever is on the unused bits is irrelevant. they do nothing.


body: If you use 74HC595, you have to send data to all the bits no matter what. Even if you only want to change 1 bit, you have to resend the whole bit sequence.


message:
Is it possible to create an interface between Teensy 3.2 and a DSP?

I realize that this is a forum for Arduino but since the Teensy 3.2 is compatible with the Arduino IDE I thought it would be appropriate to ask the question here.

Anyway, can I create an interface between the Teensy 3.2 and a DSP, more specifically the TMS320C5534-Fixed-Point Digital Signal Processor and how could I go about it?

What I am trying to do do is capture an EEG and EoG (electrooculogram) signal, amplify it, filter the signal, use the DSP for ADC and signal processing and finally get this information from the DSP to the Teensy 3.2, which will then make a decision based on the signal obtained from the DSP.

Maybe this is a simple question but I couldn't find any answers online. I am pretty new to the world of microcontrollers.

Thank you guys!

body: I would use one of the serial interfaces and connect them together that way.  If Asyinc run as fast as reliable.


message:
Arduino snake on 5110 screen - some help needed

I'm trying to make a snake game using the u8g lib. But for now, only the second body part of the snake follows the head, where I want the whole body to follow the snake's head and I don't understand why it doesn't work.
Here is the code:

    #include "U8glib.h"

    U8GLIB_PCD8544 u8g(13, 11, 10, 9, 8);    // SPI Com: SCK = 13, MOSI = 11, CS = 10, A0 = 9, Reset = 8

    const int SNAKEMAXSIZE = 10;

    bool title = true;
    bool gameRunning = false;

    enum direction {HAUT, BAS, GAUCHE, DROITE};

    int snakeDirection = GAUCHE;

    class snakeCell
    {
      private:
      int x;
      int y;

      public:

      snakeCell(int x, int y)
      {
        this->x = x;
        this->y = y;
      }

      snakeCell()
      {
        x = 42;
        y = 24;
      }

      void setX(int x)
      {
        this->x = x;
      }

      void setY(int y)
      {
        this->y = y;
      }

      int getX()
      {
        return x;
      }

      int getY()
      {
        return y;
      }

      void draw()
      {
        u8g.drawBox(x, y, 5,5);
      }
    };

    class Pomme
    {
      public:
      int x;
      int y;

      Pomme(int x, int y)
      {
        this->x = x;
        this->y = y;
      }

      Pomme()
      {
        x = 42;
        y = 24;
      }

      void randomSpawn()
      {
        x = random(48);
        y = random(84);
      }

      void draw()
      {
        u8g.drawCircle(x, y, 5);
      }
    };

    snakeCell snake[10] = {snakeCell(), snakeCell(47,24), snakeCell(52,24), snakeCell(57,24), snakeCell(62,24), snakeCell(62,29), snakeCell(62,34), snakeCell(57,34), snakeCell(52,34), snakeCell(52,39)};

    Pomme pomme = Pomme();

    void draw(void) {
      // graphic commands to redraw the complete screen should be placed here
      u8g.setFont(u8g_font_6x13);
      //u8g.setFont(u8g_font_osb21);
      u8g.drawRFrame(0, 0, 84, 48, 0);   //Screen frame
      printTitle();
      game();
    }

    void setup(void) {
      // flip screen, if required
       //u8g.setRot180();

      // set SPI backup if required
      //u8g.setHardwareBackup(u8g_backup_avr_spi);

      // assign default color value

      randomSeed(analogRead(0));

      if ( u8g.getMode() == U8G_MODE_R3G3B2 ) {
        u8g.setColorIndex(255);     // white
      }
      else if ( u8g.getMode() == U8G_MODE_GRAY2BIT ) {
        u8g.setColorIndex(3);         // max intensity
      }
      else if ( u8g.getMode() == U8G_MODE_BW ) {
        u8g.setColorIndex(1);         // pixel on
      }
      else if ( u8g.getMode() == U8G_MODE_HICOLOR ) {
        u8g.setHiColorByRGB(255,255,255);
      }

    }

    void loop(void) {
      // picture loop
      u8g.firstPage();
      do {
        draw();
      } while( u8g.nextPage() );

      // rebuild the picture after some delay
      delay(50);
    }

    void printTitle()
    {
      if(title == true)
      {
        u8g.setFont(u8g_font_6x13);
        //u8g.drawStr( 26, 30, "SNAKE");
        delay(2000);
        title = false;
        gameRunning = true;
      }
    }

    void moveSnake()
    {
      //move head accordingly to movement
      if(snakeDirection == GAUCHE)
      {
        snake[0].setX(snake[0].getX() - 1);
      }
      else if(snakeDirection == DROITE)
      {
        snake[0].setX(snake[0].getX() + 1);
      }
      else if(snakeDirection == BAS)
      {
        snake[0].setY(snake[0].getY() + 1);
      }
      else if(snakeDirection == HAUT)
      {
        snake[0].setY(snake[0].getY() - 1);
      }

      //tail follow head
      for(int i = 9; i > 0; i--)
      {
        snake[i] = snakeCell(snake[i-1].getX(),snake[i-1].getY());
      }
      delay(100);
    }

    void restart()
    {
      //snakeCell snake[10] = {snakeCell(), snakeCell(47,24), snakeCell(52,24), snakeCell(57,24), snakeCell(62,24), snakeCell(62,29), snakeCell(62,34), snakeCell(57,34), snakeCell(52,34), snakeCell(47,34)};
    }

    void drawSnake()
    {
      for(int i = 0; i < SNAKEMAXSIZE; i++)
      {
        snake[i].draw();
      }
    }

    void spawnApple()
    {
      pomme = Pomme();
      pomme.randomSpawn();
    }

    void checkCollision()
    {
      // detect if apple eaten
      for(int i = 0; i < SNAKEMAXSIZE; i++)
      {
        if((snake[i].getX() == pomme.x) && (snake[i].getY() == pomme.y))
        {
          pomme.randomSpawn();
        }
      }
      // detect if snake hit wall
      for(int i = 0; i < SNAKEMAXSIZE; i++)
      {
        if((snake[i].getX() >= 84) || (snake[i].getX() <= 0) || (snake[i].getY() >= 48) || (snake[i].getY() <= 0))
        {
          //gameOver();
          restart();
        }
      }
    }

    void gameOver()
    {
      gameRunning = false;
      //u8g.setFont(u8g_font_6x13);
      //u8g.drawStr( 14, 30, "GAME OVER");
      //delay(1000);
      restart();
      gameRunning = true;
    }

    void game()
    {
      if(gameRunning == true)
      {
        checkCollision();
        moveSnake();
        drawSnake();
      }
    }

Thanks in advance.

body:
There might be a problem with going through your snake array from the back.
I'm not sure if you're filling it from front or back, but you should read it from there aswell.

And, every time you re-draw your snake, you're creating a new snakeCell?

    //tail follow head
      for(int i = 9; i > 0; i--)
      {
        snake[i] = snakeCell(snake[i-1].getX(),snake[i-1].getY());
      }

You should differentiate between a snakeCell that is active or not. And just re-position and draw it when it's active.

Be sure to check if you're not placing them ontop of eachother. You should put each piece of the tail in the previous position of the preceding part.

Also: You shouldn't really be mixing up French and English naming in your code.


message:
How to read RC receiver channels without using pulsein() command with arduino

I am building a quad-copter, the problem is of stability and for better stability lesser sampling time is required. For lesser sampling time I need to have faster loop() function. But the Pulsein() command takes very large time which in turn expands the sampling time. Is there any method to read the rc channels in background and read them from an integer.

body:
The keyword you are looking for here is *interrupt*.  What is a pulse but a signal that goes from low to high followed by going from high to low, with some period of time between them?

Instead of sitting there waiting for the pulse to arrive then measuring how long it is, which is essentially what `pulseIn()` does, you need to attach the signal to an interrupt pin.  Then you write an interrupt routine that triggers when the signal changes from one level to another which looks to see what the level actually is.

If the signal has risen from low to high then you record the time it happened.  If the signal has fallen from high to low then you look what the time is, and subtract the time you remembered from when the signal rose.  That difference is then the width of the pulse, which you can store in an integer to read in your main loop.

If you have a number of signals you want to monitor you might want to look into using the *pin change interrupt* which allows you to use any pin as an interrupt source.


body:
You may find [my answer to another](https://arduino.stackexchange.com/a/18221/3917) question –  *[Read RC receiver channels using Interrupt instead of PulseIn](https://arduino.stackexchange.com/q/18183)* – useful.  It includes the sketch shown below, which is intended for background timing of four RC channels attached to pins A0-A3.  See the other answer for further comments about the code, example output, etc.

    /*  rcTiming.ino -- JW, 30 November 2015 --
     * Uses pin-change interrupts on A0-A4 to time RC pulses
     *
     * Ref: https://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
     *
     */
    #include <Streaming.h>
    static   byte rcOld;        // Prev. states of inputs
    volatile unsigned long rcRises[4]; // times of prev. rising edges
    volatile unsigned long rcTimes[4]; // recent pulse lengths
    volatile unsigned int  rcChange=0; // Change-counter

    // Be sure to call setup_rcTiming() from setup()
    void setup_rcTiming() {
      rcOld = 0;
      pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
      pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt
      pinMode(A2, INPUT);
      pinMode(A3, INPUT);
      PCMSK1 |= 0x0F;       // Four-bit mask for four channels
      PCIFR  |= 0x02;       // clear pin-change interrupts if any
      PCICR  |= 0x02;       // enable pin-change interrupts
    }
    // Define the service routine for PCI vector 1
    ISR(PCINT1_vect) {
      byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
      byte changes = rcNew^rcOld;   // Notice changed bits
      byte channel = 0;
      unsigned long now = micros(); // micros() is ok in int routine
      while (changes) {
        if ((changes & 1)) {  // Did current channel change?
          if ((rcNew & (1<<channel))) { // Check rising edge
            rcRises[channel] = now;     // Is rising edge
          } else {              // Is falling edge
            rcTimes[channel] = now-rcRises[channel];
          }
        }
        changes >>= 1;      // shift out the done bit
        ++channel;
        ++rcChange;
      }
      rcOld = rcNew;        // Save new state
    }

    void setup() {
      Serial.begin(115200);
      Serial.println("Starting RC Timing Test");
      setup_rcTiming();
    }

    void loop() {
      unsigned long rcT[4]; // copy of recent pulse lengths
      unsigned int rcN;
      if (rcChange) {

        // Data is subject to races if interrupted, so off interrupts
        cli();   // Disable interrupts
        rcN = rcChange;
        rcChange = 0;  // Zero the change counter
        rcT[0] = rcTimes[0];
        rcT[1] = rcTimes[1];
        rcT[2] = rcTimes[2];
        rcT[3] = rcTimes[3];
        sei();   // reenable interrupts

        Serial << "t=" << millis() << " " << rcT[0] << " " << rcT[1]
        << " " << rcT[2] << " " << rcT[3] << " " << rcN << endl;
      }
      sei();   // reenable interrupts
    }


message:
NRF24L01+ how much supply ripple is acceptable?

I'm trying to get a simple TX/RX pair to work. I've got identical Nanos and I'm using the example from:
http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo

I followed the advice about adding a cap across the Vcc GND on the nrf board, and added a 10uF electrolytic to both.

I still haven't received a packet yet, and I wondering how to eliminate the power supply as a cause. I scoped the power pins, and even without a cap I got about 250mV of ripple. With the cap it goes down to about 100mV. Is this within tolerance? What kind of caps does anyone else use, and has anyone scoped the result to see where the threshold lies?

Aside form that, are there any other clever ways to debug this issue?

Update 20160122. I finally tested using those cheap piggyback 3.3v regulator boards that plug straight into the nrf board. Works perfectly, not one lost packet over 5000 packets sent. Interestingly, the RX side appears to be the fussy one. Thanks to everyones' suggestions. For a total combined cost of about 4$ per node, I have a great wireless TX/RX solution.

body:
I would suggest using a different power supply, that appears to be your problem.  250mV is 1/4 of a volt, that is a lot of noise/ripple.  I am assuming it is ripple from the AC mains.  The series resister is way to large, try something about 0.1 ohm.  Also put a filter cap on the load side of the resister.  If you have high frequency noise add a 0.01 cap that will help.  Be sure the grounds between the units are solid.

Gil

I have a feeling it is narrow fast rising spikes.  If so the odds are very high it is the power supply.  Can you try an analog one and see if the problem goes away?  Try adding more bulk capacitance, at the rate of at least 1000uF per amp.


message:
Help making LEDs blink like blinkers in a car

I am trying to make blinkers and hazards lights for a car.  I can get
the left and right blinkers to work. I cannot figure out how to get
the lights to blink simultaneously like hazard lights would.

What I think I want is that when both inputs are HIGH then Both LEDs will
blink together at the same time.

I left the garbage and comments in the code so you can see what I have
tried.

Thanks for your help.

    /*
     Blinkers and Hazard Lights

     Simulates a vehicles blinkers and Hazard Lights
     left button connected to pin 2 using a pushdown resister
     right button connected to pin 3 using a pushdown resister
     left LED connected to pin 9
     right LED connected to pin 10
     Hazard LED is Pin 13 At one point I was trying to make pin 13 represent the hazard lights but that is not what I want to do.

     When left button is pushed Left LED will Blink
     When Right Button Is pushed Right LED will Blink

     If this worked the way I wanted it to. when both buttons where HIGH both LED 9 & 10 would blink simultaneously.

     created 2015
     by thomsl41@gmail.com

    */

    // constants won't change. They're used here to
    // set pin numbers:
    const int buttonPinLeft = 2;     // the number of the pushbutton pin
    const int buttonPinRight = 3;
    const int buttonPinHazard = 2 && 3;
    const int ledPinLeft = 9;      // the number of the LED pin
    const int ledPinRight = 10;
    const int ledPinHazard = 13;

    // variables will change:
    int buttonStateLeft = 0;         // variable for reading the pushbutton status
    int buttonStateRight = 0;
    int buttonStateHazard = 0;

    void setup() {
      // initialize the LED pin as an output:
      pinMode(ledPinLeft, OUTPUT);
       pinMode(ledPinRight, OUTPUT);
       pinMode(ledPinHazard, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPinLeft, INPUT);
      pinMode(buttonPinRight, INPUT);
      pinMode(buttonPinHazard, INPUT);
    }

    void loop(){
      // read the state of the pushbutton value:
      buttonStateLeft = digitalRead(buttonPinLeft);
      buttonStateRight = digitalRead(buttonPinRight);
      buttonStateHazard = digitalRead(buttonPinHazard);

      // check if the pushbutton is pressed.
      // if it is, the buttonState is HIGH:
      if (buttonStateLeft == HIGH) {
        // turn LED on:
      digitalWrite(ledPinLeft, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(500);              // wait for a second
      digitalWrite(ledPinLeft, LOW);    // turn the LED off by making the voltage LOW
      delay(500);              // wait for a second
      }
     else {
        // turn LED off:
        digitalWrite(ledPinLeft, LOW);
      }

    if (buttonStateRight == HIGH) {
        // turn LED on:
      digitalWrite(ledPinRight, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(500);              // wait for a second
      digitalWrite(ledPinRight, LOW);    // turn the LED off by making the voltage LOW
      delay(500);              // wait for a second

    }
      else {
        // turn LED off:
        digitalWrite(ledPinRight, LOW);
      }
    }

    /*if (buttonStateHazard == HIGH) {
        // turn LED on:
      digitalWrite(ledPinLeft, LOW);
      digitalWrite(ledPinRight, LOW);
      digitalWrite(ledPinHazard, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(2000);              // wait for a second
      digitalWrite(ledPinHazard, LOW);    // turn the LED off by making the voltage LOW
      delay(2000);              // wait for a second
      //}
     //else {
        // turn LED off:
       // digitalWrite(ledPinHazard, LOW);
     }

    }
    */

body:
It looks like you need to do something like:

    if ((buttonStateRight == HIGH) && (buttonStateLeft == HIGH)) {
        digitalWrite(ledPinRight, HIGH);
        digitalWrite(ledPinLeft, HIGH);
    }
    else if (buttonStateRight == HIGH) {
        digitalWrite(ledPinRight, HIGH);
    }
    else if (buttonStateLeft == HIGH) {
        digitalWrite(ledPinleft, HIGH);
    }
    //One delay for all
    delay(500);
    //Shut anything off that might be on after the delay
    digitalWrite(ledPinRight, LOW);
    digitalWrite(ledPinLeft, LOW);

Your code is really hard to read but it may mostly be because you need to insert four spaces at the beginning of each line of code to make it look right on this forum.


message:
Reading Arduino serial stream in Java using jSerialComm

I'm having issues reading the actual double values from my Arduino `Serial.println()` in my Java app. I've tried following usage examples found [here][1] but get what I guess is a hex value. The serial monitor within the Arduino program is displaying the correct values.

This is the code: I'm fairly new to this and would appreciate any comments regarding style/problems/inefficiencies within my code!

    import com.fazecast.jSerialComm.*;
    import java.util.*;
    import java.io.*;

    public class PortRead {
      public static SerialPort userPort;
      static InputStream in;

      public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        /*
         This returns an array of commport addresses, not useful for the client
         but useful for iterating through to get an actual list of com parts available
        */
        SerialPort ports[] = SerialPort.getCommPorts();
        int i = 1;
        //User port selection
        System.out.println("COM Ports available on machine");
        for (SerialPort port : ports) {
          //iterator to pass through port array
          System.out.println(i++ + ": " + port.getSystemPortName()); //print windows com ports
        }
        System.out.println("Please select COM PORT: 'COM#'");
        SerialPort userPort = SerialPort.getCommPort(input.nextLine());

        //Initializing port
        userPort.openPort();
        if (userPort.isOpen()) {
        System.out.println("Port initialized!");
        //timeout not needed for event based reading
        //userPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 100, 0);
        } else {
        System.out.println("Port not available");
        return;
        }

        userPort.addDataListener(new SerialPortDataListener() {
          @Override
          public int getListeningEvents() {
            return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
          }
          public void serialEvent(SerialPortEvent event) {
            if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
            return;
            byte[] newData = new byte[userPort.bytesAvailable()];
            int numRead = userPort.readBytes(newData, newData.length);
            System.out.println("Read " + numRead + " bytes.");
          }
        });
      }
    }

  [1]: https://github.com/Fazecast/jSerialComm/wiki/Event-Based-Reading-Usage-Example

body: Since you are reading received data into array `newData`, you should replace `System.out.println("Read " + numRead + " bytes.");` with `System.out.print(newData);` (not sure about the syntax, since I dont know Java) if you want to print the actual data received and not just the number of bytes received.


message:
VC0706 card failed, or not present

I'm trying to follow this tutorial here:

https://learn.adafruit.com/ttl-serial-camera/using-the-camera

Here's what my serial log is printing-- I've added a few commands for logging:

    Arduino version is: 10605
    Chip Select is: 4
    VC0706 Camera snapshot test
    Card failed, or not present

I know my SD card works because when I use this program: https://www.arduino.cc/en/Tutorial/ReadWrite

it works just fine. What am I messing up?

I'm using an arduino uno with wifi shield.

Thanks!

body:
Comparing and contrasting with the SD card file -- I've found that if you comment out the following -- it works. Maybe this will help someone.

    //#if !defined(SOFTWARE_SPI)
    //#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    //  if(chipSelect != 53) pinMode(53, OUTPUT); // SS on Mega
    //#else
    //  if(chipSelect != 10) pinMode(10, OUTPUT); // SS on Uno, etc.
    //#endif
    //#endif


message:
Driving multiple LED arrays with shift registers

The project I'm building requires multiple LED arrays. I'm going to wire these LEDs in parallel and then connect the arrays to individual pins on a shift register. In addition to the LEDs running in parallel I've connected resistors in series to each LED. I've been prototyping this on a couple of breadboards and I've noticed my parallel LEDs are much more dim then my LEDs I have in series. The resistors I'm using are around 550 OHMs and I'm powering the registers through my arduino uno. I think this may be part of the reason why they're so dim, as the arduino is only providing 5V. My question is, can I/should I have my registers connected to my arduino via the data connections and power them using an external source? Will this provide me with brighter LEDs? I don't want to dump the resistors, and I have around 21 arrays, if it matters, each with a varying number of LEDs

body:
You haven't provided enough information to allow definitive answers to your questions, but you can apply [LED resistor calculators](https://www.google.com/?gws_rd=ssl#q=led+resistor+calculator) and formulas to determine how much current is available to drive LEDs of various voltages.

Here is an example:  Suppose you hook up a red LED that drops about 1.6 V when it's on and operating at a current of 5 to 25 mA.  Suppose the LED is in series with a 550 Ω resistor, between a 5 V source and ground.  Current will be about (5-1.6)/550 A ≈ 0.0062 A = 6.2 mA.

If you wished to limit current through Arduino Uno pins to safe-area amounts like 25 mA, you could drive at most 4 such LEDs per output pin.  If you decrease the resistor to get more current, the number of LEDs allowed per pin decreases too.

Because pin voltage drops slightly as the pin drives more current, LED brightnesses will also decrease slightly as more LEDs are attached to a pin, so putting different numbers of LEDs on different pins is likely to make light levels uneven.

Limits on output currents from 74HC595 shift register pins are similar to those on Arduino Uno pins; eg 35 mA absolute max ratings for the Qn pins.

Rather than driving LEDs directly from Uno pins or '595 pins, you can use transistor driver stages.  Most transistor drivers will allow higher voltages (ie more LEDs in series, rather than in parallel) and higher currents.  Also consider using LED driver chips; many of them contain PWM circuitry for brightness control and registers for storing drive levels.


message:
How come the console prints error `avrdude: usbdev_open(): did not find any USB device "usb"`?

How come when I try to push a sketch to my Arduino I see this error on the console? The subsequent sketch does not work.

> avrdude: usbdev_open(): did not find any USB device "usb"

I've already added myself to the `dialout` group,

> sudo usermod -aG dialout $USER

And, I did that after I confirmed the `dialout` group owns the device (in my case `/dev/ttyACM0`:

    $ ls /dev/ttyACM0 -l
    crw-rw---- 1 root dialout 166, 0 Oct 12 03:15 /dev/ttyACM0

body:
This is because in the IDE I was using

* Sketch → **Upload Using Programmer [Ctrl + Shift + U]**

However, I should have been using

* Sketch → **Upload [Ctrl + U]**


body:
Try "Tools> Port:> then select your board"
Make sure your pc hasn't assigned new com port to the attached usb (Arduino)


message:
How to read 6 RC remote channels using Attachinterupt for every channel

How can i use the attach interupt command and read rc channels in background. I am in doubt that attach interupt is only applied to 2 pins just and cant be used to get data from other pins.

body:
I am not sure what you are asking but you can have as many interrupt sources on a single interrupt pin as you want.  When the interrupt happens in your ISR (Interrupt Service Routine) you simply check each one and process the ones that are valid.  Be sure to do one final check before exiting as another could happen while servicing the first one.

Gil


message:
How to cast float into four bytes?

I'm trying to save GPS coordinates to an EEPROM.

In this example I feed it the latitude of 56060066 as the argument float x

    void writeFloat(unsigned int addr, float x)
    {
      byte seriesOfBytes[3];
      *((float *)seriesOfBytes) = x;
      // Write all four bytes.
      for(int i = 0; i < 4; i++)
      {
        i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM
        Serial.println(seriesOfBytes[i],BIN);  // Debug line
      }
    }

I'm expecting to receive the following four bytes from the serial print:

    00000011
    01010111
    01101000
    10100010

Instead I'm getting these:

    00101000
    11011010
    01010101
    01001100

I've tried changing all sorts of parameters, but can't seem to find the problem. Can anyone spot the issue?

body:
If you were to enable the display of warnings you would most likely see it complain about *"dereferencing type-punned pointer will break strict-aliasing rules"* which is what you are doing here.

Basically you are trying to cast an array of four 8-bit values which can have any alignment they like (byte alignment) to a 32-bit float value which needs 4-byte alignment.  And the two just don't mesh.

Instead you need to work the other way around - cast a type that has smaller alignment requirements over the type that has larger requirements.

So instead of getting 4 bytes and trying to fill them as a float you get a float and read it as 4 bytes:

    byte *b = (byte *)&floatVal;

Then you can access b[0] to b[3] quite happily.

Another way to do it is with a union:

    union {
        float fval;
        byte bval[4];
    } floatAsBytes;

    floatAsBytes.fval = floatVal;
    EEPROM.write(0, floatAsBytes.bval[0]);
    EEPROM.write(1, floatAsBytes.bval[1]);
    EEPROM.write(2, floatAsBytes.bval[2]);
    EEPROM.write(3, floatAsBytes.bval[3]);

Also, in your code, you only allocated enough room for 3 bytes, not 4...


body:
You are getting exactly what you said you want. 4 bytes representing the number in float format.

What you are expecting to get, is 4 bytes representing the number in big-endian integer format.

Using Majenkos solution for casting, you need to change the types and reverse the `for` loop for big-endinaness.
I also used `int32_t` because the size of the [`int`][1] is 16-bit (2-byte) on the Arduino Uno (and other ATMega based boards) and on the Arduino Due it's 32-bit (4-byte). Its better to define the exact `int` in this case.

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

    union {
        int32_t ival;
        byte bval[4];
    } int32AsBytes;

    void writeInt32(unsigned int addr, int32_t x)
    {
        int32AsBytes.ival = x;
        for(int i = 3; i >= 0; i--) // reverse for big-endian
        {
            i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM
            Serial.println(int32AsBytes.bval[i], BIN);  // Debug line
        }
    }

  [1]: https://www.arduino.cc/en/Reference/Int


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

This mucking around with casts and arrays is far too complex.

See: [Reading and Writing Data Structures to EEPROM](http://playground.arduino.cc/Code/EEPROMWriteAnything)

The library EEPROMAnything.h will accomplish this.

---

## EEPROMAnything.h

The library just consists of this file. Save into your "libraries" folder under the folder name `EEPROMAnything`.

    #include <Arduino.h>  // for type definitions
    #include <EEPROM.h>

    template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
    {
        const byte* p = (const byte*)&value;
        unsigned int i;
        for (i = 0; i < sizeof(value); i++)
         EEPROM.write(ee++, *p++);
        return i;
    }

    template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
    {
        byte* p = (byte*)&value;
        unsigned int i;
        for (i = 0; i < sizeof(value); i++)
         *p++ = EEPROM.read(ee++);
        return i;
    }

---

### Example code

    #include <EEPROM.h>
    #include <EEPROMAnything.h>

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      float foo = 56060066;
      EEPROM_writeAnything (0, foo);

      float bar;
      EEPROM_readAnything (0, bar);

      Serial.println (bar);
      }  // end of setup

    void loop ()
      {
      }  // end of loop

---

### Output from above

<!-- language-all: lang-none -->

    56060064.00

Note you don't get exactly the same number back. This is because of the precision of 4-bytes floats.

---

After re-reading the question I see you are using I2C EEPROM. That changes the answer a bit, but you can see an adaptation of that library for I2C [here](http://www.gammon.com.au/forum/?id=10896&reply=8#reply8). The general idea is the same though.

---

> `i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM`

Your code seems to be writing all of the bytes to the same address, I don't know how that could work.


message:
How can program/arduino restarted by IDE?

I wrote my custom sketch, where I am printing some greeting text inside `setup()` method.

I found, that each time I am restarting IDE, and opening serial monitor, a greeting text is printed there again, i.e. `setup()` method running again.

How can this happen? I was thinking `setup()` method run once, when Arduino is powered up by connecting to the USB socket?

If it is possible to restart it already connected, then how this can be done?

**UPDATE**

Code is follows:

    #include <Wire.h>
    #include <Adafruit_BMP085.h>

    Adafruit_BMP085 bmp;

    String command;

    String awaitingMessage = "Temperature and pressure sensor awaiting commands\r\nCommand \'help\' is for help";

    void awaiting() {
      Serial.println(awaitingMessage);
    }

    void help() {
      Serial.println("Temperature and pressure sensor commands:");
      Serial.println("temp\t- output temperature in degrees Celsius");
      Serial.println("press\t- output pressure in Pascals");
      Serial.println("wait\t- print awaiting message");
      Serial.println("help\t- output this text");
    }

    void temperature() {
      Serial.println(bmp.readTemperature());
    }

    void pressure() {
      Serial.println(bmp.readPressure());
    }

    void unknown() {
      if( command.length() > 0 ) {
          Serial.println("Unknown command was \'" + command + "'");
        }
    }

    void setup() {
       Serial.setTimeout(50000);
      Serial.begin(9600);
      if (!bmp.begin()) {
       Serial.println("Could not find a valid BMP085 sensor, check wiring!");
       while (1) {}
      }
      else {
        awaiting();
      }
    }

    void loop() {
      command = Serial.readStringUntil('\n');

      if( command.startsWith("temp") ) {
        temperature();
      }

      else if( command.startsWith("press") ) {
        pressure();
      }

      else if( command.startsWith("wait") ) {
        awaiting();
      }

      else if( command.startsWith("help") ) {
        help();
      }

      else {
        unknown();
        //awaiting();
      }

    }

Video is here: https://youtu.be/-QBleGVxaus

body:
When you open the serial monitor (or even just go to the serial port menu) the serial port is opened. When the serial port is opened the DTR line is asserted.  This is the method that the Arduino uses to reset so that you can access the bootloader and upload a new sketch.

Every time you open the serial port - through whatever means you choose - you reset the board, whether you like it or not.

There are a number of "fixes" for this - the simplest is to add a large (say 10µF) capacitor between the RESET and GND pins of the Arduino to filter out the reset pulse that would otherwise reboot the board.

There are also ways of disabling the reset within Windows, but that requires you to write your own software to interface with the board instead of using the serial monitor.

Some boards also come with a method of completely detaching the reset signal from the USB interface, but modifying the board itself isn't for beginners.

Just remember that once you have disabled reset through whatever means you will have to re-enable it (resolder the track you cut, remove the capacitor, whatever) before you can upload a new sketch.


message:
Servos and ultrasonic at the same time

So recently I started making a sonar out of ultrasonic HC-SR04 sensor and servo motor. The idea was to slowly rotate servo 180 degrees while measuring distance.

Soon after I noticed that regular pulseIn() command could wait 20ms while doing nothing. So I started learning interrupts. I came up with a code which sends TRIG signal and records sending time with micros() function. When an interrupt occurs on ECHO pin, we subtract current time with TRIG time and get time of round trip of the sound.

The code works as intended without servos connected, but it behaves interestingly ! I always get distance which is 8 cm bigger than actual distance. So I had to subtract 8 cm every time ! Also I noticed that max reliable range decreased , using pulseIn() I could measure distance of 400cm, and with mine code it starts to show weird numbers after 150cm...

So i thought that 150cm is enough for me, and tried to run the code with servos attached. everything ran as intended, until the servos started to move. Now I was getting distance along with pretty much random numbers, periodically positive and negative.

I could just use one the fancy libraries out there, but I am curious what am I doing wrong, why i need to subtract 8cm each time , why my reliable range decreased so much, and most importantly why am I getting weird values while servos are on ?

CODE :

    #include <Servo.h>

    #define ECHO 2
    #define TRIG 7

     Servo servo;
     int distance;
     volatile long echoTime = 0;
     long trigTime = 0,sendTime = 0,timeServo = 0;
     bool scanning = false;
     byte servoDir = -1,servoAngle = 0;

    void setup()
    {
      servo.attach(12);
      Serial.begin(115200);
      pinMode(ECHO,INPUT);
      pinMode(TRIG,OUTPUT);
      attachInterrupt(digitalPinToInterrupt(ECHO), echo_interupt, FALLING);

    }
    void loop()
    {
      // SERVO

       if((millis() - timeServo > 10)){
         if(servoAngle <= 0 || servoAngle >= 180)servoDir = -servoDir;
         servoAngle += servoDir;
         servo.write(servoAngle);
         timeServo = millis();
       }

      // GETTING RESULTS
      if(echoTime > 0){
        distance = echoTime - trigTime;
        distance /= 58;
        echoTime = 0;
        trigTime = 0;
        Serial.println(distance - 8);
      }
      // SENDING PULSE
      if(millis() - sendTime > 20){
      digitalWrite(TRIG,LOW);
      delayMicroseconds(2);
      digitalWrite(TRIG,HIGH);
      delayMicroseconds(10);
      digitalWrite(TRIG,LOW);
      trigTime = micros();
      sendTime = millis();
      }
    }

     // INTERUPT
    void echo_interupt(){
      echoTime = micros();
    }

body:
8cm is 233µs of sound travel time.  There and back again would be 466µs.  466µs, at 16MHz, is around 7400 instructions.

When an interrupt is triggered you don't get an instant response.  First the built in interrupt function is called. That then looks to see if you have registered an interrupt function.  It then calls that interrupt function.

All that takes time, and when you're working with microseconds it makes a big difference.

And then you have to go and get the current micros() value, which again takes time to do.

So it all adds up to a delay.  Not ideal.

For greater accuracy you should investigate using *input capture* which will start a timer running when you send the trigger and the timer will automatically stop the nanosecond the echo is received.  From that you can calculate a much more precise distance.

As for why you are getting strange results with the servos on?  Most likely because you are moving the receiving head while the pulse is being received.  I made a similar system while playing once and found that the best results were achieved by moving the head to the desired position, waiting a moment for any vibration to settle, do the ping and get the result, then move the head to the next position.

Oh, and by the way, the HC-SR04 is (from memory) only really rated for up to 2m - I have never achieved anything more than around 1.8m with any accuracy.


body: I had problems with `Servo` library and `VirtualWire`. They both use the same internal timer. The solution was to change `Servo.h` to `ServoTimer2.h` lib.


message:
Can i run brushless ESC from any digital pin of arduino

{assume arming is done}
Can i connect the brushless ESC to any digital pin and give writemicroseconds() to it? Will this work. because i have connected my 4 ESC's to "~" pins. so i thinks that other will not work.

body:
It should work.

The [Servo][1] library doesn't use hardware PWM, so you can connect them to a non "~" (PWM) pin.

  [1]: https://www.arduino.cc/en/Reference/Servo