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

I'm new to arduino and currently trying to build a small program with multiple screens and buttons and a counter. when I try to convert a int to a chararray it messes up the world. with out it what I have so far works any suggestions on what I'm doing wrong? with the code to convert the int to chararray it seems to lock up the program when I switch from main screen to options screen then back. I put some serial outs to narrow down where the flaw is.

My results are it is between

       test1++;  Serial.println("oops check");
       str = String(test1); Serial.println("sanity check");

Something hangs it up after it outputs "oops check" so I figure it is `str = String(test1);` I have been searching and trying every thing I can find. if someone can give me a kick in the right direction. I'm usin the tft seedstudio v2 display with the modified tft library for text direction.

       /*
      Title: TouchScreenButton Tutorial
      About: Example/tutorial file for how to create buttons with the TouchScreenButtons library
      Author: Richard Kirkpatrick
      Date: 20 July 2014
    */

    // Libraries
    #include <stdint.h>
    #include <SeeedTouchScreen.h>  // Library for the Seeed Studio TFT Touch Shield
    #include <TFTv2.h>      // Library for the Seeed Studio TFT Touch Shield
    #include <TouchScreenGeometry.h> // Library for drawing geometric shapes for the touch screen
    #include <TouchScreenStrings.h> // Library for drawing strings for the touch screen
    #include <TouchScreenButtons.h> // Library for creating buttons for the keypad
    #include <SPI.h>

    //Measured ADC values for (0,0) and (210-1,320-1)
    //TS_MINX corresponds to ADC value when X = 0
    //TS_MINY corresponds to ADC value when Y = 0
    //TS_MAXX corresponds to ADC value when X = 240 -1
    //TS_MAXY corresponds to ADC value when Y = 320 -1
    #define TS_MINX 890*2
    #define TS_MAXX 116*2
    #define TS_MINY 913*2
    #define TS_MAXY 83*2

    TouchScreen ts = TouchScreen(XP, YP, XM, YM);

    // Global variables
    String str;
    Button bigButton;
    Button buttons[12];
    Button reset;
    Button back;
    int screen = 1;
    int test;
    int test1 = 0;
    char b[5];

    void setup()
    {
      // Initializes the TFT library
       Tft.TFTinit();

      // Start the Serial port. Used to determine which button was pressed.
      Serial.begin(9600);
     screen = 1;

    }

    void loop()
    { test1++;  Serial.println("oops check");
      str = String(test1); Serial.println("sanity check");
      str.toCharArray(b,5);

      Serial.print("screen = "); Serial.print(screen );
      // A point objects holds x, y, and z coordinates
      Point p = ts.getPoint();
      p.x = map(p.x, TS_MINX, TS_MAXX, 240, 0);
      p.y = map(p.y, TS_MINY, TS_MAXY, 320, 0);

      // Determine which button was pressed
      int userInput = -1; // -1 means no button is pressed
      if (p.z > __PRESURE){
        userInput = getButtonNumber(p.x, p.y);
         Serial.print("X = "); Serial.print(p.x);
         Serial.print("\tY = "); Serial.print(p.y);
         Serial.print("\tPressure = "); Serial.println(p.z);
      }

       // Show which button was pressed on the Serial monitor

       if (userInput == 13) {
        Serial.println("Options button was pressed!");
        bigButton.buttonDisplay();
      }
       if (userInput == 15) {
        Serial.println("back button was pressed!");
        back.buttonDisplay();
      }
      else if (userInput == 14) {
        Serial.println("reset button was pressed!");
        reset.buttonDisplay();
      }

      delay(10);

    if (screen == 1)  {

    if (test == 1) {

        Tft.fillScreen();    }

      Serial.print("test1 =  "); Serial.println(b);      // prints "Hello String"

        // Draw reset button
       reset.setValues(75, 215, 35, 100);
      reset.draw();

     // Draw the big button
      bigButton.setValues(15, 185, 35, 130);
      bigButton.draw();
    Tft.drawRectangle(40, 15, 70, 120,BLUE);

    Tft.setDisplayDirect(UP2DOWN);

      Tft.drawString("Frays",100,20,2,RED);

       Tft.drawString(b,65,20, 2, BLUE);

      //Draw reset buttons text
      TouchScreenString resetText("RESET", 100, 230, 2, RED);
      resetText.drawText();
     Serial.println("a");      // prints "Hello String"

      // Draw the big button's text
      TouchScreenString bigButtonText("OPTIONS", 40, 197, 2, WHITE);
      bigButtonText.drawText();
    test = 0;

    }

    if (screen == 2)  {

      if (test == 0) {Tft.fillScreen();}
     // draw back button
      back.setValues(15, 15, 35, 85);
      back.draw();

    Tft.setDisplayDirect(UP2DOWN);

       // Draw the back button's text
      TouchScreenString backText("BACK", 40, 30, 2, WHITE);
      backText.drawText();
    test = 1;
    }}

    // Gets which button was pressed.  If no button is pressed, -1 is returned.
    int getButtonNumber(int xInput, int yInput)
    {

    if (screen == 1) {
      if (bigButton.isPressed(xInput, yInput)) {
        screen = 2;
        return 13; // Signifies big button was pressed
      } }
      if (screen ==2) {
      if (back.isPressed(xInput, yInput)) {
        screen = 1;
        return 15; // Signifies big button was pressed
      }}
      if (screen == 1) {
      if (reset.isPressed(xInput, yInput)) {
        test1 = 0;
        return 14; // Signifies reset button was pressed
      }}
      else {
      return -1; // Signifies no button was pressed
      }
    }

title: problem with using String()

Answers: 1

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

My guess is you are running out of RAM. Your various string constants alone take up 202 bytes. Then there is this:

      test1++;
      str = String(test1);
      str.toCharArray(b,5);

That is very likely to fragment memory, as `test1` gets larger and larger. So you are fragmenting RAM, of which you don't have much to start with.

Why are you even converting test1 into a String object? And then converting it back into an array?

The array `b` can only hold 4 digits as it needs one byte for the trailing null-terminator.

I suggest you stop doing that String stuff, and also use the `F()` macro like this ...

Change:

        Serial.println("Options button was pressed!");

to:

        Serial.println(F("Options button was pressed!"));

Ditto for all the other places you are displaying stuff.


body:
I have an amplifier circuit for a microphone.The output of the circuit(the microphone signal amplified) is connected to the arduino A0 .Now the circuit works(I think ,the output voltage is 4.30 V) and the arduino serial monitor output 875 874... fluctuates with one or 1,2 or more points.The problem is that this value just goes down from 875....800.... .

 Is it a correct value?(circuit taken from here http://wiring.org.co/learning/basics/microphone.html)

EDIT: If I put my finger on it the values go up a bit like 792 ,794,800

title: Microphone input into Arduino uno R3

Answers: 2

body:
[This schematic][1] contains also the OpAmp stage for a microphone.
You could take it as reference against the design you are using.
The LM386 is basically a more integrated version, iirc.

  [1]: https://courses.edx.org/asset-v1:BerkeleyX+EE40LX+2T2015+type@asset+block/robot_schematic.pdf

body:
The amplifier circuit you refer to puts out 2.5 volts even without input from microphone. The LM386 has internal circuitry to make the output 1/2 of the +5 volts. Then, audio signal goes above and below the 2.5 volts.

The amplifier circuit will only be putting out the PEAK of your audio signal (because D1 and C2 is a peak detector)

So, when all is quiet, take that ADC value as meaning zero microphone input.


body:
I would like to make a device that can take a photo, and send it to a website over wifi. I'm using an Arduino Uno, a ArduCam OV2640 module, and ESP8266 Serial WIFI module. Eventually I'd like to take it off the board as a stand alone project for permanent use.

The wifi works fine, but requires a serial communication to configure. I would like to make it so that I can plug the device into a computer (via something like micro usb), change the WIFI settings, and save those settings for future reboots.

If there anyway I can do this with an Arduino interface? If not, what could I use instead?

title: How can I configure Arduino after programming it (for post upload wifi configuration)?

Answers: 1

body:
I like Gerben's suggestion about putting the ESP8266 into Wireless Access Point mode and then providing access to your configuration settings via a web interface.  I've been dealing with the same question myself and this might be a workable solution.  The only downside is the amount of code required to get an ESP8266 to function as a WAP, provide a web-based UI, switch between configuration and running mode, etc.

Another idea that isn't as elegant, but would require a lot less code: Just store your configuration on an SD card, and add an SD card to your project using a separate board or shield.  You could edit the configuration by plugging it into a PC and editing the configuration file, then plug the card into your project which would read its configuration from the SD Card.


body:
I am looking for a simple way to detect nitrogen gas flow through a tube. I don't even need any sort of precision, just really need to know if flow exists or not.

What are some options I could pursue to easily measure this with the arduino?

title: How to measure nitrogen flow through a tube?

Answers: 2

body: You can use a [pressure sensor](http://www.trossenrobotics.com/p/phidget-differential-gas-pressure-sensor.aspx?feed=Froogle&gclid=CjwKEAjwmZWvBRCCqrDK_8atgBUSJACnib3l5u8e1KI9v_tjJWO6weY6IH03922kPj8-jWhzubchsBoCtErw_wcB) for gas and measure the pressure differential between two points and if there is a large pressure differential then you know a flow exists.

body:
What you are looking for is a mass flow sensor[ (MAF)](https://en.wikipedia.org/wiki/Mass_flow_sensor), or something along those lines as you mention wanting to know if there is flow, this gives you the *'speed'* of the flow. There are various types available according to size, flow rate, type of element, and accuracy. Just search for mass flow sensor, you can even hack them off cars.

If you just want to detect only the presence of the N2 as you say then you can split your pipe somewhere,and then add a T-piece to that. You then put a gas sensor in the T part, and seal it off so there is no leaks. You would then hook that up to the Arduino board and interpret the signal.

Can't recommend any specific sensors though.

Here is an image for the idea:

![RSM_design][1]

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


body:
I'm trying to controll an AC unit but the issue is space - right now, I store the data like this:

    consts PROGMEM unsigned int Signal_Heat_Fan0_Temp30[] = {233,636,17884,3032,8944,500,496,492,1496,524,472,548,452,544,448,552,444,552,444,548,444,552,444,552,1436,556,444,552,444,548,1440,552,472,524,472,520,1472,492,1496,520,1468,556,1436,552,1440,552,444,548,448,548,444,552,448,548,448,548,448,548,472,524,468,524,472,524,476,520,472,520,476,520,476,520,472,524,472,552,444,548,452,548,444,552,444,548,448,548,444,552,448,544,452,544,448,552,472,524,468,524,472,524,472,524,472,520,476,520,476,520,472,524,1468,552,1436,556,1436,556,1436,552,2944,3028,8920,548,1440,552,448,548,472,524,468,524,472,524,472,472,524,516,476,552,444,548,1444,552,444,548,448,552,440,556,440,556,1432,556,1440,548,452,544,1444,552,1464,524,1464,472,1520,524,1464,556,1436,552,1440,552,1436,556,440,552,448,548,444,552,1440,552,1440,552,1464,524,472,496,496,472,524,520,476,548,444,552,448,552,1440,548,1440,556,1432,556,1440,548,448,548,444,552,448,548,472,524,472,524,1464,472,524,472,524,516,476,552,444,552,444,552,1440,552,1440,552,1436,556,1436,552};
    consts PROGMEM unsigned int Signal_Heat_Fan0_Temp29[] = {233,636,17896,3032,8916,552,468,524,1468,524,468,500,496,472,528,520,476,544,448,552,444,552,444,548,1440,556,440,552,448,548,1440,552,444,548,452,544,1444,548,1468,524,1464,472,1520,520,1468,552,444,552,448,548,444,552,444,548,448,548,444,552,444,556,444,548,448,548,444,552,448,544,472,524,472,524,472,524,472,468,528,520,476,544,448,552,444,552,444,548,444,556,440,556,444,548,448,548,444,552,444,552,444,548,452,544,476,524,472,524,468,524,472,492,1496,520,1472,548,1440,556,1440,548,2944,3032,8916,552,1436,552,444,552,444,548,452,544,448,548,476,524,468,524,472,524,472,492,1496,520,476,524,472,548,448,552,444,552,1440,548,1440,548,448,548,1440,556,1440,548,1440,552,1464,524,1464,500,1496,520,1468,552,1440,548,444,556,444,552,444,548,1440,552,1440,548,1444,544,476,524,472,524,472,524,468,524,472,492,1496,524,476,548,1444,548,1440,548,1444,552,444,552,444,548,448,548,444,552,448,544,1448,544,476,524,468,524,472,524,472,492,504,516,1472,548,1444,552,1440,548,1440,548};
    consts PROGMEM unsigned int Signal_Heat_Fan0_Temp28[] = {233,636,17880,3056,8912,524,476,544,1444,552,444,548,448,552,440,556,440,556,444,552,444,548,444,552,1440,552,444,552,468,524,1468,524,468,472,524,520,1476,544,1444,548,1440,556,1432,556,1440,548,448,548,444,552,448,548,448,548,472,524,472,520,472,524,472,496,500,472,524,492,504,544,452,548,444,552,444,552,444,548,448,552,440,556,444,548,448,548,444,552,448,544,452,544,476,524,472,524,468,524,472,524,472,492,500,520,476,548,452,544,448,552,444,552,1440,548,1440,552,1440,552,1440,548,2944,3028,8924,544,1444,552,468,524,472,496,500,492,504,516,476,552,444,548,452,548,444,552,1440,548,444,552,444,552,1444,548,444,552,1440,548,1444,544,476,520,1472,492,1496,520,1468,552,1444,548,1440,552,1436,552,1440,552,1440,552,444,548,452,544,476,520,1468,524,1468,492,1496,520,480,544,448,548,448,552,444,548,444,552,444,548,452,548,1440,552,1436,552,1444,544,476,520,476,524,468,524,472,496,500,492,1496,524,476,544,452,548,444,552,444,548,448,548,1444,548,1440,552,1440,548,1444,520};
    consts PROGMEM unsigned int Signal_Heat_Fan0_Temp27[] = {233,640,17892,3032,8916,552,448,548,1464,528,468,528,468,468,528,468,528,520,472,552,444,552,444,552,1440,548,448,548,444,556,1436,552,444,552,444,552,1436,552,1444,548,1468,492,1496,472,1516,552,448,548,448,548,448,548,444,552,444,552,444,552,440,556,444,552,444,548,444,552,448,548,448,548,472,524,472,524,468,468,528,472,524,520,472,524,472,552,448,548,448,548,444,552,444,548,448,548,444,556,440,552,448,548,444,552,444,552,448,544,472,524,472,528,1464,468,1520,520,1472,552,1436,556,2944,3028,8912,556,1440,548,448,548,444,552,448,548,448,548,444,552,472,520,472,524,472,524,1464,472,528,488,508,544,448,552,444,552,1436,556,1436,552,448,548,1440,548,1440,556,1440,548,1440,552,1464,524,1464,472,1524,544,1444,552,444,552,448,548,444,552,1440,548,1440,552,1444,548,444,552,448,544,472,524,472,524,468,500,1492,492,1500,548,452,544,1440,556,1436,552,444,552,444,552,444,548,448,548,448,548,1444,548,472,524,468,524,472,524,472,472,528,468,1520,520,1468,552,1440,552,1436,552};
    consts PROGMEM unsigned int Signal_Heat_Fan0_Temp26[] = {233,640,17884,2980,8992,528,472,524,1464,472,524,520,476,548,444,556,440,556,444,548,444,552,444,552,1440,552,440,556,444,548,1440,552,444,552,468,524,1468,528,1460,472,1520,548,1444,548,1440,556,444,548,448,548,444,552,444,552,444,552,444,552,444,552,444,548,448,548,472,524,468,524,472,472,528,468,528,488,504,548,448,552,444,548,444,556,440,556,444,548,444,552,444,552,444,548,448,548,448,552,444,548,448,548,472,524,472,520,472,524,472,472,524,520,1468,548,1444,552,1440,552,1436,556,2944,3024,8920,552,1440,552,444,548,444,552,448,548,468,524,472,528,472,468,524,468,528,520,1472,548,444,556,444,548,1440,552,444,548,1440,556,1440,548,444,552,1440,548,1444,552,1464,492,1496,520,1472,548,1440,556,1440,548,1440,552,444,552,444,552,444,548,1440,552,1444,548,1440,548,472,524,472,472,524,472,520,520,480,544,452,548,1440,548,448,548,1440,552,1440,552,444,548,448,548,448,552,444,552,468,524,1464,524,472,472,528,468,524,468,528,544,452,548,1440,556,1436,552,1440,548,1440,556};
    consts PROGMEM unsigned int Signal_Heat_Fan0_Temp25[] = {233,644,17892,3028,8916,552,444,548,1440,556,440,552,448,548,444,552,444,548,448,548,448,548,472,528,1464,468,528,520,472,548,1448,544,444,556,440,556,1440,548,1440,548,1440,556,1440,548,1440,552,448,544,472,528,472,524,468,468,528,468,528,544,448,552,444,552,444,552,444,552,444,552,444,552,444,548,444,552,444,552,444,552,448,548,444,552,468,524,472,524,472,524,468,472,524,472,528,520,476,544,448,552,444,548,448,548,444,556,440,556,444,548,444,552,1440,548,1440,556,1440,548,1468,548,2920,3052,8920,472,1516,548,452,548,444,552,444,548,448,548,444,556,440,556,444,548,448,548,1440,548,452,544,448,552,1440,548,472,524,1464,472,1516,552,448,544,1444,552,1444,548,1440,552,1436,552,1440,552,1440,552,1440,548,1464,528,472,496,500,468,524,520,1472,548,1440,556,1436,552,444,552,444,556,440,552,444,552,444,552,1436,552,448,544,452,548,1468,524,1464,468,528,520,472,552,448,548,448,548,448,548,1440,548,448,548,444,552,444,556,444,548,444,552,1440,548,1440,552,1464,500,1496,548};

The first item is the length of the array and the rest is data I can send with IRemote library with the raw send libray. I've mapped most of the buttons and now I'm at

    Sketch uses 95.286 bytes of program storage space

Is there a better encoding that could take less space? I'd like to add at least 3 times more commands to the Sketch, but I'm already at 37% on an Arduino Mega.

I know ideally I should generate the array, not store it, but I haven't gotten that far (yet, I'm working on it) and for me this is an interesting issue.

Thank you!

---
Edit 1: Code uploaded on GitHub - https://github.com/vladbabii/SamsungACIrControll/tree/master/AC_IrControll

title: How to store IR data needed for AC controll in less space?

Answers: 3

body:
Do you need all of the data accessible at once? How about storing it on a file device or external memory? SDcards are slow but huge. [FRAM][1] devices a fast but not as huge and typically aren't formatted for a file system. They act more like an independent memory space accessed by a function. (The Adafruit product is one example; I'm sure there are more).

  [1]: https://www.adafruit.com/products/1895

body:
I have analysed your codes with a small Lua script:

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

    function pairsByKeys (t, f)
      local a = {}
      -- build temporary table of the keys
      for n in pairs (t) do
        table.insert (a, n)
      end
      table.sort (a, f)  -- sort using supplied function, if any
      local i = 0        -- iterator variable
      return function () -- iterator function
        i = i + 1
        return a[i], t[a[i]]
      end  -- iterator function
    end -- pairsByKeys

    nums = {233,636,17884,3032,8944,
    -- and so on ...
    548,444,552,444,556,444,548,444,552,1440,548,1440,552,1464,500,1496,548}

    uniq = { }

    for k, v in ipairs (nums) do
      if uniq [v] then
        uniq [v] = uniq [v] + 1
      else
        uniq [v] = 1
      end -- else
    end -- for

    count = 0

    for k, v in pairsByKeys (uniq) do
      print (string.format ("%8i = %3i", k, v))
      count = count + 1
    end

    print ("count = ", count)

---

Results:

         233 =   6
         440 =  18
         444 = 154
         448 =  86
         452 =  20
         468 =  42
         472 = 103
         476 =  27
         480 =   2
         488 =   2
         492 =  15
         496 =   8
         500 =  10
         504 =   4
         508 =   1
         516 =   4
         520 =  41
         524 =  97
         528 =  26
         544 =  39
         548 = 189
         552 = 196
         556 =  56
         636 =   3
         640 =   2
         644 =   1
        1432 =   3
        1436 =  24
        1440 =  91
        1444 =  26
        1448 =   2
        1460 =   1
        1464 =  21
        1468 =  16
        1472 =   8
        1476 =   1
        1492 =   1
        1496 =  12
        1500 =   1
        1516 =   3
        1520 =   5
        1524 =   1
        2920 =   1
        2944 =   5
        2980 =   1
        3024 =   1
        3028 =   4
        3032 =   4
        3052 =   1
        3056 =   1
        8912 =   2
        8916 =   4
        8920 =   3
        8924 =   1
        8944 =   1
        8992 =   1
       17880 =   1
       17884 =   2
       17892 =   2
       17896 =   1
    count =  60

---

Assuming there is some jitter I rounded them to the nearest 50:

    for k, v in ipairs (nums) do

      v = math.floor (v / 50)    -- <--- add this
      v = v * 50                 -- <--- add this
      if uniq [v] then
        uniq [v] = uniq [v] + 1
      else
        uniq [v] = 1
      end -- else
    end -- for

---

Results:

         200 =   6
         400 = 258
         450 = 219
         500 = 411
         550 = 252
         600 =   6
        1400 = 146
        1450 =  60
        1500 =  10
        2900 =   6
        2950 =   1
        3000 =   9
        3050 =   2
        8900 =  11
        8950 =   1
       17850 =   6
    count =  16

So, 16 different lengths.

---

So now you can use 4 bits per code (and a lookup table) rather than 16 bits.

Also see [TV-B-Gone design notes](https://learn.adafruit.com/tv-b-gone-kit/design-notes) for how they compressed the IR codes for lots of TV brands into a small table in an ATtiny85.

body:
Another form of storage is the EEPROM. There are between 512 bytes and 4K of EEPROM per Arduino, depending on the model of Arduino - see https://www.arduino.cc/en/Reference/EEPROM

EEPROM is persistent when the power gets cut, and MAY or may not be overwritten when the program is changed - I have not tried. If it is not overwritten, you can write a sketch just to set it, then overwrite it with your IR sketch; otherwise, you may have to set up some way to "upload" the data into your sketch (e.g. if you press a special button, it will listen on the serial port, any bytes it reads it will write to the EEPROM.

If you have an ISP (aka ICSP) programmer such as the USBasp (see google), which are very inexpensive, then you can read/write the EEPROM directly - all you need is 6 pins exposed. You can also use the USBasp to reprogram an AtMega/AtTiny which is not on an Arduino board (this also gives you a little extra program space, since it no longer requires a bootloader).


body:
Burning question:

So, I'm trying to burn the Arduino Leo bootloader onto a ATmega32U4 that's on 3.3V and the internal 8MHz clock.  Do I have to modify and rebuild the bootloader to set the fuses correctly, and can this be done with AVR Studio?

All of the references on doing this are dated.  The folder structure for the Arduino IDE has changed. I've done it in the past with 5V 16MHz 32U4s using an Arduino as ISP, but never with the AVRISP mkII on the Arduino IDE.

On the good side, I do have it up and running with Atmel Studio.

Thanks!

title: Burning Arduino Leonardo Bootloader to ATmega32U4 with 8MHz internal clock

Answers: 1

body:
If you have an appropriate crystal attached then you can do this in the Arduino IDE. Select your board and programmer in the IDE menu, connect the programmer to the board, and choose `Burn Bootloader` from the menu. This will both burn the prebuilt bootloader image and set the fuses in a single operation.

Note that you cannot use USB on the '32U4 if you are running off either a ceramic resonator or the internal oscillator, and so you should not attempt to use the Leonardo bootloader in either case.


body:
I will like to implement a serial communication protocol, using javascript in a mobile browser to make the browser background blink (alternating the color from black to white) according to the bits, to communicate a few bytes to an Arduino using some kind of light sensor (photo diode or resistor) to parse. Electric Imp did something with https://electricimp.com/platform/blinkup/ .

Is there any library or implementation or where to start guide?, if not, how would you implement it?

I fear one of the problems of using a mobile browser with javascript to light-encode the bits will be timing issues, since setTimeInterval is not perfect, I could split the screen, one half blinking continuously (clock) and the other half the data, but that will require two light sensors.

title: Light communication from pc/app to arduino

Answers: 2

body:
Doing bit stuffing can prevent timing problems when you are sending a lot of `0`s or `1`s in an row. Alternatively use Manchester encoding (slower).

On the browser side, I'd suggest using `<Canvas>`. Combine this with `requestAnimationFrame` which gives you a very accurate timestamp as an argument. Though you have to check for support as older browsers don't support that.

body:
You should investigate communication protocols and encoding techniques that embed the clock signal into the same data stream as the data signal.

One common method is called *[Manchester Coding][1]*.  This entails splitting each bit into two halves.  A 1 sends light followed by dark, and a 0 sends a dark followed by a light.  It's then up to you to work out which transitions are which and where in a bit they occur (is a high transition the start of a 1 or mid-way through a 0?)

Another popular method (used in things like Ethernet) is called 8b/10b.  That involves sending 10 bits to represent every 8 - more efficient than manchester coding (that could be considered 8b/16b) and can be read about here: https://en.wikipedia.org/wiki/8b/10b_encoding It's somewhat harder to implement than Manchester Code, so although it's less efficient I'd recommend the simplicity of Manchester Code.

  [1]: https://en.wikipedia.org/wiki/Manchester_code


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

I am working on a project where the end result is to count the number of cycles of a moving piece of metal using an inductive sensor.

For now I am using an Arduino Uno and have created a breadboard version for testing. The sensor has been replaced by a momentary push button. To check the count data I am viewing the number using Serial Monitor

All the elements of this set-up are working, apart from one major issue. When pressing the button the incrementer (++) occasionally adds 2 instead of 1 from only one button press. As a rough guide to the error frequency, it seems to count 11 for every 10 button presses. The error has never presented as not counting enough.

I am new to software, as such I cannot seem to see the error

Any help and guidance would be greatly appreciated

Here is the code I have written so far:

    //Libraries
    #include <EEPROM.h>

    //Constants
    const int counterPin = 2;   //Input from counter (looking for HIGH as external pulldown resistor is used)
    const int EEPROMadress = 3; //holds the EEPROM address

    //Variables
    int counterState = 0;       //current button state
    int counterStatePrv = 0;    //previous button state
    int storedValue;
    int presetCount = 100;

    unsigned long countNumber;      //unsigned 32bit variable

    void setup() {

     for (int i = 0; i < 255; i++) {
      // this performs as EEPROM.write(i, i)
      EEPROM.update(i, i);
     }
     for (int i = 0; i < 255; i++) {
      // write "presetCount" value to cell "EEPROMaddress" only the first time
      // will not write the cell the remaining 254 times
      EEPROM.update(EEPROMadress, presetCount);
     }

     pinMode(counterState, INPUT);
     Serial.begin(9600);

     countNumber = EEPROM.read(3); //Start the counter at the presetCount value
    }

    void loop() {

     counterState = digitalRead(counterPin);   //Read the status of the counter input
     storedValue = EEPROM.read(EEPROMadress);

     if (counterState != counterStatePrv) {      //check that pulse went off
      if (counterState == HIGH) {             //check for pulse
       countNumber++;      //increment (add 1) to the stored count value
       delay(10);
       Serial.print("Count  Value: ");
       Serial.println(countNumber);

       Serial.print("Stored Value: ");
       Serial.println(storedValue);
       Serial.println();

      }
     }
     counterStatePrv = counterState;

    }

title: Can anyone identify why this incrementer is losing count?

Answers: 1

body:
Buttons bounce (at least they appear to, electrically), meaning that if you're fast enough, you can detect multiple pulses per button-press. Usually we don't count the button as being pressed until we read the same value {n} times in a row or for {m} mSec, or some similar technique.

Because you call `EEPROM.read()` immediately after testing the button, perhaps most times the bouncing will have ceased when the call returns, but once in a while one last bounce slips through.

Nick Gammon, a regular contributer here, has a good discussion of [de-bouncing][1] on his web site. Have a look at that and pick a technique that's compatible with what you're trying to do.

  [1]: http://www.gammon.com.au/switches


body:
Servo goes to one end, and immediately travels back without a 2s delay inbetween. After it travels back there is a 2s delay before it loops. Why isn't there a 2s delay before the travel back?

    Servo testservo;

    void setup() {
        testservo.attach(9);
    }

    void loop() {
        testservo.writeMicroseconds(700);
        delay(2000);
        testservo.writeMicroseconds(2300);
        delay(2000);
    }

title: 'Simple' problem. Delay not working?

Answers: 1

body:
Your description (“Servo goes to one end, and immediately travels back without a 2s delay... After it travels back there is a 2s delay before it loops”) implies an overall cycle time of 2 seconds, which appears to be inconsistent with the overall 4-second cycle implied by the code shown.

Here are things you can do to debug the problem:

1. Turn on an LED before one `writeMicroseconds()` call, and turn it off before the other.  For example, add `pinMode(13, OUTPUT);` in `setup()`, and revise `loop()` as follows:

void loop() {
    testservo.writeMicroseconds(700);
    digitalWrite(13, HIGH);
    delay(2000);
    testservo.writeMicroseconds(2300);
    digitalWrite(13, LOW);
    delay(2000);
}

This may allow you to find out which end the servo is going to.

2.  Besides adding LED signals, try slightly-less extreme times in the `writeMicroseconds()` calls; eg 1000 and 2000 microseconds rather than 700 and 2300.

3.  See if a neutral servo setting works, eg via code like the following.

enum { LEDpin=13, dtime=2000}
void stest(angletime, tHi, tLo) {
    testservo.writeMicroseconds(angletime);
    digitalWrite(LEDpin, HIGH);
    delay(tHi);
    digitalWrite(LEDpin, LOW);
    delay(tLo);
}
void loop() {
    stest(1000, dtime-50, 50); // Go CCW
    stest(1500, 50, dtime-50); // Middle
    stest(2000, 50, dtime-50); // Go CW
}

When this code runs, the LED should stay on about 2 seconds with the servo fully (or nearly so) counterclockwise.  Then the LED should blip and the servo should move to center position and stay there about 2 seconds.  Then the LED should blip and the servo should stay fully clockwise about 2 seconds.  This three-part cycle should repeat every six seconds.  If it works ok, then try modifying it, eg by changing 1000 us to 700, 2000 to 2300, etc, or by decreasing the `dtime` value to see how quickly the servo can respond, etc.


body:
I'm having some difficulty assigning a value to a variable in a struct array outside the loop and setup functions. Assigning a value to an int or char array works completely fine but this doesn't.

The example code and error message returned after trying to compile are below. Any help is greatly appriciated. Thanks

    void setup()
    {
    }

    struct trap_game_detail {
        byte flush_quantity;
        byte flush_interval;
        byte random_min;
        byte random_max;
        byte random_quantity;
    } trap_game_details[2];

    trap_game_details[0].random_min = 1;

    void loop()
    {

    }

src/sketch.ino:13:5: error: ‘trap_game_details’ does not name a type
     trap_game_details[0].random_min = 1;
     ^
.build/uno/Makefile:166: recipe for target '.build/uno/src/sketch.o' failed

title: Assigning value inside structure array outside setup and loop functions

Answers: 2

body:
You can't access array contents in the global scope like that.  You have to assign the entire block of data in one go:

    struct trap_game_detail {
        byte flush_quantity;
        byte flush_interval;
        byte random_min;
        byte random_max;
        byte random_quantity;
    };

    struct trap_game_details trap_game_details[2] = {
        { 10, 5, 1, 100, 4 },
        { 8, 23, 5, 95, 8 }
    };

Items in the *global scope* aren't executed - only things in functions are executed.  Accessing individual parts of an array or struct like you are trying to is a programatic operation, so can't be executed since it's not in a function.

body:
> Assigning a value to an int or char array works completely fine but this doesn't.

It only works fine if you do it on the declaration.

eg.

This works:

    int foo = 42;  < ---- declare and define with initial value

This doesn't:

    int foo;   // < ---- declare and define

    foo = 42;  // < ---- assignment statement

Your code was like the second example.

---

Majenko has shown one way. He split the declaration into two parts. The first part declared the **type** trap_game_detail, and the second part is an **instance** of that type, like this:

    struct trap_game_detail {
        byte flush_quantity;
        byte flush_interval;
        byte random_min;
        byte random_max;
        byte random_quantity;
    };

    struct trap_game_details trap_game_details[2] = {
        { 10, 5, 1, 100, 4 },
        { 8, 23, 5, 95, 8 }
    };

---

Alternatively, and a bit closer to what you were doing, just keep going with the initialization values after you define the structure, like this:

    struct trap_game_detail {
        byte flush_quantity;
        byte flush_interval;
        byte random_min;
        byte random_max;
        byte random_quantity;
    } trap_game_details[2] =
      {
        { 10, 5, 1, 100, 4 },
        { 8, 23, 5, 95, 8 }
      };


body:
I didn't find answers which solves my problem with the max232 yet.
I connected it like this to my Arduino uno, so my Arduino provides the +5V VCC and the ground:
[max232 connection][1]
[![Connection on board][2]][2]

The only thing what is differences are that I do a loopback at the RS232 side and I use 1µF for every capacitor even for the bypass one. I did a loopback so I can see if the max232 works. I don't get anything out of it when I send some data to it.
I measure +8.7V on pin2 and -8.15V on pin 6.

My Arduino code:

    /*
      Software serial multiple serial test

     Receives from the hardware serial, sends to software serial.
     Receives from software serial, sends to hardware serial.

     The circuit:
     * RX is digital pin 10 (connect to TX of other device)
     * TX is digital pin 11 (connect to RX of other device)

     created back in the mists of time
     modified 25 May 2012
     by Tom Igoe
     based on Mikal Hart's example

     This example code is in the public domain.

     */
    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
    }

    void loop() // run over and over
    {
      if (mySerial.available())
        Serial.print(mySerial.read());
      if (Serial.available())
        mySerial.write(Serial.read());
    }

What did I do wrong or is my max232 broken?

**EDIT**

I think the serial monitor (same baudrate) doesn't write to the ports so I rewrite some code.

loop code:

    int i = 0;
    void loop() // run over and over
    {
      if(i == 10)
        i = 0;

      mySerial.write(i);
      Serial.print(mySerial.read());
      i++;
      delay(3000);
    }

In serial monitor I get strange values back for a cascade counter.

Values:
-1 45 49 52 53 52 57 53 ...

These numbers aren't ascii code for ectual numbers I think.

**EDIT 2**

Now the loopback works thanks to the answer below.
Now I replaced the loopback with the module FUM DCF-U.
The loop code has changed to this:

    void loop() // run over and over
    {
      if(Serial.available())
        Serial.println(Serial.read());
    }

The problem is that the result is '000000000000000000000000000000000...' in a fast rate and not every second.

The module gets its 3.3V and is connected to the same GND as the MAX232.

Pin connections:

Arduino - MAX232

11 - 11

0 - 12

MAX232 - FUM DCF-U

14 - 3

13 - 4

Thanks in advance

  [1]: https://www.google.be/search?q=max232&biw=2144&bih=1127&tbm=isch&imgil=fyy0lqGALI9HtM%3A%3BcH09mn8Z6FvbpM%3Bhttp%253A%252F%252Fsodoityourself.com%252Fmax232-serial-level-converter%252F&source=iu&pf=m&fir=fyy0lqGALI9HtM%3A%2CcH09mn8Z6FvbpM%2C_&dpr=0.9&usg=__KByygPTJOBdI1tDfqv3X0dFdvZ4=&ved=0CDEQyjdqFQoTCOG0i8i32McCFYtVPgodYpMMFg&ei=pfbmVaHODour-QHiprKwAQ#imgrc=fyy0lqGALI9HtM:&usg=__KByygPTJOBdI1tDfqv3X0dFdvZ4=
  [2]: https://i.stack.imgur.com/B2iBp.jpg

title: Can't get values of max232 with loopback

Answers: 1

body:
SoftwareSerial cannot both send and receive at the same time, as it does receiving inside an ISR, and turns interrupts off when sending. Thus this will never work properly.

I suggest you switch to HardwareSerial. Or, if you want to see the results, send using SoftwareSerial and receive using HardwareSerial. For example:

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

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial (10, 11); // RX, TX

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

    unsigned long lastSend;
    char c = ' ';
    void loop ()
      {
      // time for another test send?
      if (millis () - lastSend >= 500)
        {
        mySerial.print (c++);
        if (c > 'z')
          {
          c = ' ';
          Serial.println ();
          }
        lastSend = millis ();
        }

      // check for response
      if (Serial.available ())
        Serial.print (char (Serial.read ()));
      }  // end of loop

I tested that as a simple loopback and it worked fine. Connect pin 11 (Tx) to pin 0 (Rx). Disconnect the wire to pin 0 whilst uploading.


body:
I am building a Travis CI job to test my Arduino Library and it needs to install external board definitions.

Is there a way that I can set the boardsmanager.additional.urls from the command prompt like it would have been done in the Preferences window?

Or should I create preferences.txt file? (If so where does that live in a Linux environment)

title: Arduino Command Line Interface - How to change boardsmanager.additional.urls

Answers: 1

body:
Found the solution:

    arduino --pref "boardsmanager.additional.urls=http://arduino.esp8266.com/stable/package_esp8266com_index.json"


body:
[![arduino][1]][1]
Please, iam a junior in arduino and i want to know what is the importance of the resistors that connect to push buttons? can i replace them by wires?
thanks in advance.

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

title: what is the importance of the resistors that connect to push buttons ? can i replace them by wires?

Answers: 1

body:
They are what is known as Pull-Up resistors.  The circuit will not work if you replace them with wires.  Not only that but you will short circuit the power supply when you press a button.

Why don't you want to use resistors?

The value is not important - you could use the same value as you are using for the LED if you don't have the 10k resistors shown in the drawing.

Having said that an alternative is to leave them out and instead activate the internal pull-ups within the processor on the Arduino:

    pinMode(pin, INPUT);           // set pin to input
    digitalWrite(pin, HIGH);       // turn on pullup resistors


body:
Burning question:

So, I'm trying to burn the Arduino Leo bootloader onto a ATmega32U4 that's on 3.3V and the internal 8MHz clock.  Do I have to modify and rebuild the bootloader to set the fuses correctly, and can this be done with AVR Studio?

All of the references on doing this are dated.  The folder structure for the Arduino IDE has changed. I've done it in the past with 5V 16MHz 32U4s using an Arduino as ISP, but never with the AVRISP mkII on the Arduino IDE.

On the good side, I do have it up and running Atmel Studio.

Thanks!

EDIT:  Sorry for double posting, I posted in electronics before I noticed there was an Arduino specific section.

title: Burning Arduino Leonardo Bootloader to ATmega32U4 with 8MHz internal clock

Answers: 1

body:
If you have an appropriate crystal attached then you can do this in the Arduino IDE. Select your board and programmer in the IDE menu, connect the programmer to the board, and choose `Burn Bootloader` from the menu. This will both burn the prebuilt bootloader image and set the fuses in a single operation.

Note that you cannot use USB on the '32U4 if you are running off either a ceramic resonator or the internal oscillator, and so you should not attempt to use the Leonardo bootloader in either case.


body:
i want to know that if i use atmega328-pu instead of atmega8 on this design provided by "https://www.arduino.cc/en/Main/ArduinoBoardSerialSingleSided3", will it works fine on this design or i have to use only atmega8 ?

[![ArduiniBoardSerialSingleSided][1]][1]

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

title: Replacing atmega8 with atmega328 on Arduino Single-Sided Serial Board

Answers: 1

body:
Yes and no. It will work on this board, but won't get programmed by arduino IDE directly.

ATmega328 and ATmega8 are fully pin compatible. ATmega328 is like bigger and powerful in terms of onchip resources. However, if you want to program ATmega328 on the arduino board, you must install bootloader. Otherwise you will have to program it everytime using ISP programmers such as USBASP. This will connect to the ICSP socket shown on the above board.

Refer to: http://tutorial.cytron.com.my/2011/09/30/how-to-program-arduino-by-using-avr-usbasp-programmer/


body:
I have one PC running Visual Studio and a program that will be sending commands to Arduinos via serial COM Ports. So, in 11 Nano MCUs, I will have motor drivers L293D/L298N ICs, while in other Nanos I will have sensors.

What I would like to do is have a program in Visual Studio which sends commands via serial to actuate motors to each and every MCU on board. This is a robotic application and everything I mentioned above will be enclosed within the Humanoid.

Here are some examples of what I'm thinking of doing:

    char data = Serial.read();
    if (data == 'A')
    {
      digitalWrite(13, HIGH);
    }

Or something like this:

    servodata = Serial.read();
    if (servodata == '1') // Single Quote! This is a character.
    {
      SERVO.write(pos);
    }

As you can see, Arduinos will have something like this running and waiting for Visual Studio to send commands via serial to one or multiple MCUs simultaneously. I'm thinking 30 char dividing/spiting that number across each Rx Arduino.

title: I'm looking for a way to serially communicate with a multi mesh Arduino slave network

Answers: 2

body:
It's not obvious what the exact query is but answering the subject line question:

You can easily multidrop connect multiple serial / RS232 COM ports by having all slave RX inputs and the master TX output on one line, and all slave TX outputs connected by an OR network to a single line to the master's RX input.   The master 'talks' to all slaves at once. Each slave talks to only the master. Only one slave can usefully talk at once. Message destination assignment and slave-talking arbitration is carried out in software.

As shown below, the OR network at each slave can be as simple as a diode with cathode (bar side) to TX line and anode to common line to master RX.  A single pullup resistor (or an internal pullup in the master on the RX line) pulls the line high when all slave TX lines are high.

This diagram shows how simple multidrop communications can be.
**NB - As shown the diodes polarity is for true RS232 with logical 1 = low = negative.**
**When connecting directly between UART TTL lvel (5V/0V) outputs reverse the diodes.**

Also, add a pullup from +5V to the Blue RX line to the master - 10k to 5V is probably OK.

[![Multidrop network for RS232][1]][1]
From here - [**Multidrop network for RS232**](http://cool-emerald.blogspot.co.nz/2009/10/multidrop-network-for-rs232.html).

When a slave TX pin is high its diode is "blocked" and it does not affect the common slave to master level. When any slave TX line goes low the common line is pulled low via its diode and the master sees the low. Normal RS232 COMs can occur between slave and master.

When the master sends all slaves see the transmission at once. A basic protocol must be established to allow messages to be handled by the intended recipient. This could consist of, e.g. sending an address word + command word or words. You can have a single slave act on a message or all slaves or a sunset, based on your addressing system.

The slave to master direction allows only one slave to send at one and you must ensure either that only one slave ever sends at a time and/or that collisions are able to be resolved.

Despite the obvious limitations of such a system it can work very well and is cheap and simple to implement. If there are many slaves the loadings should be checked so that e.g. the master TX is able to drive all slave RXs at once. As the circuit is unidirectional it is easy to add a basic buffer.

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

body:
[RS-485](https://en.wikipedia.org/wiki/RS-485) or [RS-422](https://en.wikipedia.org/wiki/RS-422) are the normal industrial ways of having one serial port talk to many devices, especially in noisy environments with lots of motors.  It requires a driver chip for each device to get the right electrical interface.

RS-485 provides bi-directional communication if you want to receive data back from your remote nodes, and RS-422 provides "simplex" or uni-directional communication if you just want to blindly send commands with no feedback.

As for software, my [ICSC library](http://github.com/MajenkoLibraries/ICSC) would probably be the easiest route to take - it allows you to address individual devices on an RS422 or RS485 bus and send commands to them.


body: I am using my Arduino UNO rev 3 to control other devices via the digital output pins. On startup or reset, I find that these pins are all briefly turned on (perhaps as part of a self test). This interferes with my application. How can I suppress this?

title: How can I stop my Arduino UNO rev 3 from briefly turning on digital output pins on startup or reset?

Answers: 1

body:
Digital pin 13 will be turned on briefly as part of the bootloading process (it flashes a few times). Thus this is not a good choice of pin for a device like a motor to be connected to. Also if you are uploading a new sketch the Tx pin (digital pin 1) will be turned on and off.

You can change the processor fuses to not use the bootloader, which would avoid these issues, however then you have to change them back to upload a new sketch - unless you upload using ICSP instead of the bootloader.

As Gerben and Majenko have pointed out, any other issues could be from "floating" pins which some devices might interpret as having a HIGH on them, possibly. Pull-down resistors could help there (or pull-up if that is more appropriate).

The ideal thing could be to structure your system in such a way that the two pins (1 and 13) which come on during the bootloading process are connected to something "harmless" (eg. an LED) rather than "harmful" (eg. a motor).


body:
Just a quick question. Picking up some stepper motors, but confused at what voltage/current things are running off.

Ordering:
2 x [Stepper Motor][1]
2 x [EasyDriver][2]

An article says

> You need some 12V source to the EasyDriver (the motor in this article
> is 12V) - This will be powering the stepper - Im using a 12V adapter -
> similar to the one in the illustration. Just make sure it is rated at
> least 750ma - A higher rating is better, and just means it wont burn
> out.

So does that mean if I got a plug which is regulated 12V 1A and powered the Arduino from that I could power a rail with VIN pin and that would safely supply the EasyDrivers? And I could then use the 5V pin to power everything else?

Just don't want to break anything! Thanks

  [1]: https://www.sparkfun.com/products/9238
  [2]: https://www.sparkfun.com/products/12779

title: Stepper Motor Power Supply

Answers: 3

body:
As generic rule: avoid powering one device through another.
It can cause strain on the middle-man device and it _will_ be inefficient.
The only few cases where this might make sense are when it's topologically inconvenient to connect everything to the centralized power supply.
Or if the cascaded device requires a voltage that is not available from the power supply.

In your case you can power both the easy driver and the Arduino from the regulated 12v.

And you won't risk drawing too much current through the Arduino.

body:
The Vin pin is after the M7 protection diode, so you won't get quite 12 V out of Vin. Also, depending on the load, the diode might get warm.

I've also found that powering an Arduino from 12 V input (the maximum recommended) tends to get the voltage regulator hot.

Your other issue is that the motor power will be going through the Arduino board, to an extent (in the plug, through the diode, and out Vin) so any noise generated by the motor will be close to the processor.

I don't think your idea would *break* anything, it just might not be particularly reliable.

body:
Stepper Motor Control - one step at a time

This program drives a unipolar or bipolar stepper motor.
The motor is attached to digital pins 8 - 11 of the Arduino.

The motor will step one step at a time, very slowly. You can use this to test that you've got the four wires of your stepper wired to the correct pins. If wired correctly, all steps should be in the same direction.

Use this also to count the number of steps per revolution of your motor, if you don't know it. Then plug that number into the oneRevolution example to see if you got it right.

<!-- language: lang-cpp -->

    #include <Stepper.h>

    const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
    // for your motor
    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
    int stepCount = 0;         // number of steps the motor has taken

    void setup() {
        // initialize the serial port:
        Serial.begin(9600);
    }

    void loop() {
        // step one step:
        myStepper.step(1);
        Serial.print("steps:");
        Serial.println(stepCount);
        stepCount++;
        delay(500);
    }


body:
My attempt is to know how to identify the board I'll be sending parameters to in a serial connection like rs485.  I'm asking because I will have about 11 or so mcu's as "Rx slaves" while my pc is the Master "Tx". I want to know how my code block is being sent to a specific board will be received by just that board and not all the other boards connected to that Rx port COM?

If I send 'LT2|LP3|LM5|LR4|LI6' and I want that to be for one specific Arduino, I don't want all the other 10 arduinos to take those parameters in this serial Rx line.

@Federico Fissore you mentioned in another post "Some boards, when connected to a computer, publish their serial number. My Arduino Uno R3 says"

    [16818.451423] usb 3-2: SerialNumber: 85235353137351E02242

how and where can i find this info?

title: How can I get a unique address for all my Arduino boards while in RS485?

Answers: 2

body:
Just assign every node a variable like "const int ID = 5" and so on and then before sending the instructions send a line terminator, the ID, line terminator and the data you need to send to the nodes. Every device listens but they all wait their ID to accept the commands. For example:

    Serial.write('\n');
    Serial.print(ID);
    Serial.write('\n');
    Serial.print(|LT2|LP3|LM5|LR4|LI6);
    Serial.write('\n');

NOTE: This is the easiest way. Most likely not the most reliable or optimized.

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

> I dont think that could have sounded more advanced for me then anything thus far. Any links on how to go about that?

First, run a sketch like this for each board:

    #include <EEPROM.h>

    const int SERIAL_NUMBER_ADDRESS = 1023;
    const byte SERIAL_NUMBER = 42;
    void setup ()
      {
      // don't do it if it has been done before
      if (EEPROM.read(SERIAL_NUMBER_ADDRESS) != SERIAL_NUMBER)
        EEPROM.write(SERIAL_NUMBER_ADDRESS, SERIAL_NUMBER);
      }  // end of setup

    void loop () { }

The serial number **address** can be any address in range for that chip - a Uno has 1024 bytes. I chose 1023 to leave the other addresses free, but it could be 0. Anything you don't need for any other purpose.

Then write a different serial number to each board (eg. 42, 43, 44, 45). Obviously you change the sketch each time you upload to a different board.

---

Once you have done this (once per board) now each board "knows" its serial number. You can detect this in your main sketch:

    #include <EEPROM.h>

    const int SERIAL_NUMBER_ADDRESS = 1023;
    byte serialNumber;
    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      serialNumber = EEPROM.read(SERIAL_NUMBER_ADDRESS);
      Serial.print (F("Serial number of this board is: "));
      Serial.println (int (serialNumber));
      }  // end of setup

    void loop () { }

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

Output for me in this case was:

    Serial number of this board is: 42

---

Also I have a post about [RS485](http://www.gammon.com.au/forum/?id=11428) on my forum.


body:
I am using both Arduino nano and Arduino mega boards in my projects.  I got a nasty surprise the other day when I learned that, on the nano, Analog pins 6 and 7 can not be used as digital pins.

Are there any Analog pins on the mega that can not be used as Digital?

Answers: 2

body:
On <https://www.arduino.cc/en/Main/ArduinoBoardNano> it says:

>  Analog pins 6 and 7 cannot be used as digital pins.

There is no such corresponding statement on <https://www.arduino.cc/en/Main/ArduinoBoardMega2560> and judging by the datasheet all of the analog pins can be used as digital pins.

body:
No, the ATmegaXXX0 has no analog pins without GPIO capability.

Additionally, the ATmegaXX8P**B** *adds* GPIO capability to the other analog pins plus a couple of the supply pins, so if you can convince someone to slip one of those on instead then you will gain two GPIOs (a respin will be required to access the ones on supply pins). Note that the core will also need to be modified, but it's only a couple of quick changes.


body:
I am new to the Leonardo, having only used a duemilanove before, and I am interested in using it's USB capabilities for a project.

Basically I need it to be an input and output device, communicating to an app on the PC (probably written in C#). I need to be able to handle button presses on the arduino and get data back from the PC to display on a display connected to the arduino.

I already have the basics done hardware wise (getting the keypad and displays working as I want them to), but now the tricky part is the USB communication. The only things I can find seem aimed at emulating a keyboard and mouse - I need 2 way communication data wise.

Are there any examples of something like this? I am sort of looking for the arduino equivalent of this: http://www.waitingforfriday.com/index.php/Building_a_PIC18F_USB_device

An alternative would be to just use serial, but I don't want to be fiddling with COM ports on the PC side - it just needs to be plugged in and work.

Would be grateful for any input on this subject, if it is even possible!

title: Using USB on a Leonardo to receive data from PC

Answers: 0


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

I'm trying to obtain the sensors' readings as well as making the LED strips to light up at this particular pattern, if the sensor readings reaches certain values. But since both of these codes are inside the void `loop()`, there will be a problem. How can I do this correctly?

    void loop()
    {
        currentSensorReading = analogRead(sensorPin);
        Serial.println(currentSensorReading );

        if(currentSensorReading is in range of certain values){
            rainbowCycle(20);
        } else { turn LEDs off }
    }

    void rainbowCycle(uint8_t wait) {
      uint16_t i, j;

      for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
        for(i=0; i< strip.numPixels(); i++) {
          strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
        }
        strip.show();
        delay(wait);
      }
    }

title: Running both sensor and addressable LED strips at a same time?

Answers: 1

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

Rewrite without using `delay()`. Or alternatively, do the test inside the `for` loop as well, eg.

    void rainbowCycle(uint8_t wait) {
      uint16_t i, j;

      for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
        for(i=0; i< strip.numPixels(); i++) {
          strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
        }
        strip.show();
        delay(wait);

        // ----------- ADD THESE THREE LINES ---------------
        currentSensorReading = analogRead(sensorPin);
        if(currentSensorReading is NOT in range of certain values)
            return;

      }
    }


body:
Recently I've started playing around with an Arduino Uno (rev 3), and I've set up a communication bridge between the Arduino and my computer using Python. So I send a command in Python ("ping" for instance), which is then read and interpreted. I've had it working before, using the Python commands to control a motor, but today it became non-responsive. However, only if I boot the serial monitor from the Arduino IDE, it suddenly accepts my commands again. Further inspection reveals that the Arduino is probably reading empty or corrupted data, interpreting it as `ð`, `à` and `ÿ` and such.

Here is an excerpt of the Python code I'm using:

    import sys, glob, serial, time, re

    class interface:

      timeout = 2 # 10 second time-out

     def __init__(self):
      port = "/dev/ttyACM0"
      self.connect(port)
      pass

     def connect(self, port="/dev/ttyACM0"):
      global arduino
      arduino = serial.Serial(port, baudrate=115200, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=0.1) # Establishing connection
      time.sleep(3) # Allowing the connection to settle
      arduino.flush()
      print "Connection established..."

     def ping(self):
            arduino.flush()
            arduino.write("ping")
            msg = self.listen_arduino()
            print msg
            if msg == "ping_ok":
                print "pinged"
                return True
      return False

        def listen_arduino(self):
      timeout = self.timeout
      matcher = re.compile("\n")
      buff = ""
      t0 = time.time()
      buff += arduino.read(128)

      while (time.time() - t0) < timeout and (not matcher.search(buff)):
       buff += arduino.read(128)
      return buff.strip()

And here is the Arduino C code:

    String readString;

    void setup() {
        Serial.begin(115200); // use the same baud-rate as the python side
    }

    void loop() {
        readString = listen(); // listen for any commands
        if (readString.length() > 0) {

            Serial.println(readString); // print the command

            if(readString == "ping") {
              Serial.write("ping_ok");
            }
        }
    }

    String listen() {
        String readString;
        while (!Serial.available());
        while (Serial.available()) {
            delay(1); // Allow the buffer to fill
            if (Serial.available() > 0) {
                char c = Serial.read();
                readString += c;
            }
        }
        return readString;
    }

I suspect there is something fishy with the connection I'm making on the Python side, as the Arduino IDE serial monitor works just fine. I hope anyone can spot the problem in this code, I'm willing to provide more details on request.

Thanks

title: Arduino reads bogus from serial

Answers: 1

body: I've discovered that there was another program trying to access the Arduino, interfering with the code above and causing corruption of the signal. After terminating the intrusive program, the code worked just fine.


body:
is there another way to replace **delayMicroseconds(BassTab[note_index])** as I cannot have delays in my loop due to the need of having multi-tasking in my sketch.

Grove speaker: http://www.seeedstudio.com/depot/Grove-Speaker-p-1445.html

    /*macro definition of Speaker pin*/
    #define SPEAKER 8

    int BassTab[]={1911,1702,1516,1431,1275,1136,1012};//bass 1~7

    void setup()
    {
      pinMode(SPEAKER,OUTPUT);
      digitalWrite(SPEAKER,LOW);
    }
    void loop()
    {
        sound(5);
        delay(5000); //Wait 5second and play the sound again
    }

    void sound(uint8_t note_index)
    {
      for(int i=0;i<100;i++)
      {
        digitalWrite(SPEAKER,HIGH);
        delayMicroseconds(BassTab[note_index]);
        digitalWrite(SPEAKER,LOW);
        delayMicroseconds(BassTab[note_index]);
      }
    }

title: How to use a grove speaker without using delayMicroseconds?

Answers: 1

body:
It's just a small amplifier and speaker - what you put into the SIG pin gets amplified and sent out the speaker.

Instead of doing the audio generation manually like that I would suggest using the `tone()` function which will generate an audio tone at a desired frequency in the background.

* https://www.arduino.cc/en/Reference/Tone


body:
I am very much new to Arduino. I recently bought an adruino uno. i can blink an LED alternately. Such as, 1st blink red, then blink green, then blue like that. once only one LED should blink.

I have provided the code blinking an LED. How to modify this to blink multiple LED one after another.

    void setup() {

      pinMode(13, OUTPUT);

    }

    void loop() {

      digitalWrite(13, HIGH);
      delay(1000);
      digitalWrite(13, LOW);
      delay(1000);
    }

title: How to blink a series of LED alternately only one at a time

Answers: 2

body:
Have you considered connecting another LED and turning one on and the other off sequentially?

    void setup() {

      pinMode(13, OUTPUT);
      pinmode(NewLEDPin, OUTPUT);

    }

    void loop() {
      digitalWrite(NewLEDPin,LOW);
      digitalWrite(13, HIGH);
      delay(1000);
      digitalWrite(NewLEDPin,HIGH);
      digitalWrite(13, LOW);
      delay(1000);
    }

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

You could always copy and paste:

    void setup() {

      pinMode(11, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(13, OUTPUT);

    }

    void loop() {

      digitalWrite(11, HIGH);
      delay(1000);
      digitalWrite(11, LOW);
      delay(1000);

      digitalWrite(12, HIGH);
      delay(1000);
      digitalWrite(12, LOW);
      delay(1000);

      digitalWrite(13, HIGH);
      delay(1000);
      digitalWrite(13, LOW);
      delay(1000);
    }

---

A bit better would be to learn about functions:

    void setup() {

      pinMode(11, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(13, OUTPUT);

    }

    void blink (const byte which)
      {
      digitalWrite(which, HIGH);
      delay(1000);
      digitalWrite(which, LOW);
      delay(1000);
      }  // end of blink

    void loop() {
      blink (11);
      blink (12);
      blink (13);
    }

---

And you could learn about loops:

    void setup() {
      for (int i = 11; i <= 13; i++)
        pinMode(i, OUTPUT);
    }

    void blink (const byte which)
      {
      digitalWrite(which, HIGH);
      delay(1000);
      digitalWrite(which, LOW);
      delay(1000);
      }  // end of blink

    void loop() {
      for (int i = 11; i <= 13; i++)
         blink (i);
    }

---

There is a whole world of stuff to learn. Enjoy the process!


body:
 - Grove speaker:
   http://www.seeedstudio.com/depot/Grove-Speaker-p-1445.html
 - ws2812-led strip

Hi, I have been working to produce tones on a speaker and it works with the following code

        int melody[] = { NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3, NOTE_B3, NOTE_C4};
        ...
        ...
        tone(pin, melody[pitch]);
After I included my addressable LED strip sketch codes, the speaker does not produce the same tone as normally it does. It sounded distorted this time round.

    void loop()
    {
      strip.Update(); //NeoPatterns strip(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800, &StripComplete);
    }

Class:

    // NeoPattern Class - derived from the Adafruit_NeoPixel class
    class NeoPatterns : public Adafruit_NeoPixel
    {
      public:

    // Member Variables:
        ...
        ...

    void (*OnComplete)();  // Callback on completion of pattern

    // Constructor - calls base-class constructor to initialize strip
    NeoPatterns(uint16_t pixels, uint8_t pin, uint8_t type, void (*callback)())
      : Adafruit_NeoPixel(pixels, pin, type)
    {
      OnComplete = callback;
    }

    // Update the pattern
    void Update()
    {
      if ((millis() - lastUpdate) > Interval) // time to update
      {
        lastUpdate = millis();
        switch (ActivePattern)
        {
          case RAINBOW_CYCLE:
            RainbowCycleUpdate();
            break;
          default:
            break;
        }
      }
    }

    // Initialize for a RainbowCycle
    void RainbowCycle(uint8_t interval, direction dir = FORWARD)
    {
      ActivePattern = RAINBOW_CYCLE;
      Interval = interval;
      TotalSteps = 255;
      Index = 0;
      Direction = dir;
    }

    // Update the Rainbow Cycle Pattern
        void RainbowCycleUpdate()
        {
          for (int i = 0; i < numPixels(); i++)
          {
            setPixelColor(i, Wheel(((i * 256 / numPixels()) + Index) & 255));
          }
          show(); // When I comment this line, the speaker will work properly. What is happening?
          Increment();
        }

title: Speaker not producing the right sound after a led strip was introduced

Answers: 1

body:
The `tone()` command is interrupt driven.

To get the tight timing needed by the LED strips interrupts are disabled while sending the data.

That means the tone() command stops while you're updating the LED strips and starts again afterwards.

The end result will be the sound is corrupted - maybe sounding like it's bubbly or underwater or just "rough".

The two basically can't work together and I'm not sure what to suggest to make them work together on a low-end MCU like the AVR.


body:
Four our project, I want to send data mesured by an Arduino due to a computer via Pyton very vast. So I tried to make a simple benchmark by sending 10240 int datas to determine the time it take. In order to do this, I first try using the programming port and execute this simple script:

    int i=1;
    int maxv=10240;
    int value[10240];
    int deb, fin;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(250000); //serial initialisation
      for (i=0 ; i<maxv ; i++){
        value[i]=i;
      }
      delay(200);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.println("starti"); //flag
      deb=micros();
      for (i=0 ; i<maxv ; i++) { // sending loop
          Serial.println(value[i]);
      }
      fin=micros();
      Serial.println("stopi");
      Serial.println((fin-deb)/1000000.0);
      delay(2000); //waiting
    }

So with this I can mesure the time it take to send all the datas. And I receive it with this Python's script:

    import numpy as np
    import serial
    ser = serial.Serial('/dev/ttyACM0', 250000)

    value=np.empty(10240)

    temp=ser.readline()

    while temp!='starti\r\n': #search for the flag
        temp=ser.readline()

    for j in range(10240):
        value[j]=int(ser.readline())

    ser.readline()

    time=float(ser.readline())
    print time

with this beaudrate, it take nearly 2.4s which too slow for my purpose. If  try another baudrate, 500000 for example I read data like this : `�Ë`$Pd@s`¥š... I have this for all baudrate higher than 250000.

So I tried the native port which normaly send the data as fast as he can, but we this it took nearly 1.3s, and it's again too slow for my purpose.

I checked that it is not python wich is too slow, by doing the same than in the last example:

    import time
    import numpy as np

    value=np.empty(10240)

    deb1 = time.clock()

    for j in range(10240):
        value[j]=j

    fin1= time.clock()
    print fin1-deb1

and it took only 4ms. So is it clearly the arduino wich send the data to slowly.

So how can I increase the data flux? I have seen the serial.write(buf,len) function which seems does not convert the data into ascii caracters. Does this function will be faster by putting the correct arguments? And, if it's the cas, how can I read this with Python?

title: arduino due-Python interfacing for high speed data rate

Answers: 1

body:
There's two things you need to know:

1. The Serial.write(buf, len) function sends the raw data - one byte for every "len" count.
2. On the Due integers are 32-bits, so each one takes 4 bytes.

So first you need to define how big the numbers are you'll be dealing with and use data types that are big enough without being wasteful - you have 3 choices: char, short and int - 8, 16 and 32 bits respectively.

* Values between 0 and 255 use an unsigned char (uint8_t)
* Values between -128 and 127 use a signed char (int8_t)
* Values between 0 and 65535 use an unsigned short (uint16_t)
* Values between -32768 and 32767 use a signed short (int16_t)
* Values between 0 and 4,294,967,295 use an unsigned int (uint32_t)
* Values between −2,147,483,648 and 2,147,483,647 a signed int (int32_t)

One very tricky thing with this kind of *binary* data transfer is knowing where a value starts and ends.  You don't get that kind of issue with ASCII representations as you have a line feed and/or a carriage return after each full value and the range of valid characters that make up a value is very narrow and can never contain the delimiting character.  You don't have that luxury with binary transfers as there is no byte value that can't appear in a data stream.  However, there could be byte sequences that could never appear in the data stream - numbers you know you'll never be using that could form part of a synchronizing header (say, in hexadecimal, 0xFF 0xFF 0xFF 0xFF 0x00 0x00 0x00 0x00 - or in signed shorts that would be a sequence of 65535 65535 0 0) - once you see that sequence of bytes you know you're lined up with your data stream and can receive it byte by byte and build up the right sized values from that.

You can estimate your transfer time by working with the baud rate and knowing the data size.  For instance, to transfer 1000 short (16 bit) values at 250000 baud should take around:

* 1000 * 2 = 2000 bytes
* 250000 baud = 25000 bytes per second (8 bits for the byte, 2 bits for the start and stop bit)
* 2000 / 25000 = 0.08s


body:
I am quite new to the Arduino stuff. I have got the Arduino IDE installed side by side with Eclipse. I am using Eclipse with the Arduino plugin, which is working well for me, including the SerialMonitor.

If you're using Eclipse with the Arduino plugin, it'll also add two new views. One is the serial monitor, the other one is called scope. Scope is a 6 channel Oscilloscope. But I don't know how to get values displayed there.

I am just curious how to use the scope there. I can't find any tutorial for this.

Can somebody explain how to show something inside the scope?

title: How to use the eclipse arduino scope?

Answers: 4

body:
Given that two bytes are short, you send:

1. `SCOPE_START_DATA` `short` flag: `0xCDAB`
2. `short` number of following bytes to read (for example, `0x0002` for only one channel)
3. one `short` per channel

P.S. This is shamelessly stolen from it.baeyens.arduino.monitor.views.ScopeListener

body:
Try the [simplot library][1].

It is from the author of the plugin and works with both 32 and 8 bit processors. There is an example included that should get you going.

The plotter itself automatically connects to the first serial connection so there is no connect needed for the plotter like there is for the serial connection.

  [1]: https://github.com/jantje/libraries/tree/master/simplot

body: The plugin FAQ links to a defunct website. However the internet wayback machine reveals some good info (https://web.archive.org/web/20150321054307/http://www.negtronics.com/simplot). In particular a link to the arduino forums that has some code samples: http://forum.arduino.cc/index.php?topic=58911.0

body:
The simplot library (referenced below) is an excellent example of how to use the scope which works as advertised.
Firstly, readers should note that there are two different Arduino plugins for Eclipse ("Eclipse C++ IDE for Arduino" and "Arduino Eclipse plugin named Sloeber V3"). Only the latter has a scope and a seriel monitor that allows data to be sent.
Getting simplot and the scope to work, however, can be a problem depending on the platform. On a Mac, with the latest version of Eclipse (Neon.2 Release Candidate 2) and the Sloeber V3 plugin, the default path to the Private Library is Users/yourname/Arduino/libraries. Unfortunately, this path doesn't (necessarily) exist.
One could spend hours trying to figure out how and where to import a library when the critical library folder doesn't exist.

The solution (at least on a Mac):

 - Create a folder (arbitraily) named "Users/yourname/Eclipse/libraries".
 - Include this folder in Eclipse - Preferences - Arduino - Private Library Path
 - Download jantje's [entire Github Arduino Library][1], unpack it and move the "simplot" folder into your Private Library Folder. "simplot" should now show up in the libraries.
 - Use: Arduino - Add a Library to the Selected Project
 - Or build a project using the simplot.ino example.

It should work beautifully.

  [1]: https://github.com/jantje/ArduinoLibraries


body:
First time Arduino user here.

We have a microphone set-up which feeds back loudly on particular frequencies and need an equalizer to (preferably automatically) detect spikes in particular frequency bands and attenuate them before sending them on to the speakers. The dB level that has been cut from that frequency channel would then be displayed on an LED matrix such as this one:

[![LED Matrix][1]][1]

Does the Arduino have the processing capabilities to keep up with the audio without noticeable lag? As the LEDs will only be a visual indication of the affect the attenuation is having on the frequencies, it is not particularly important that these be fast. Unfortunately, as the audio stream will be vocals, even a slight delay will render the thing useless. What delay might I expect with a single mono channel going through the arduino?

I expect that I will eventually have to revert to the less-interesting project of an RTA which takes a split of the audio sends to the speakers and simply displays the frequency band intensities rather than altering them.

I'd appreciate any thoughts.

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

title: Advice on setting up a real-time audio equaliser

Answers: 1

body:
Somewhat possible if you accept that the Arduino won't be doing most of the work:

* Yes, the Arduino can sample audio and perform FFT on it, though not fast and not at high frequencies
* Yes, the Arduino can decide what to do depending on the power of different buckets
* Yes, the Arduino can display the results
* No, the Arduino cannot do realtime audio filtering.

If you accept that the filtering will have to be done with a bank of analogue band-cut filters that the Arduino turns on and off as needed then it may be possible.

The Arduino Due might be a more suitable candidate since it will be able to sample and do the FFT much faster so you'll be able to respond to the peaks much quicker, and the displaying won't get in the way so much, but actively filtering inside the chip really requires a DSP.


body: I have a 30 button matrix and I would like to use a keyboard encoder to decipher what button was pressed. I would like that information (what button was pressed) to be wirelessly sent to my arduino uno nearby. What is the easiest solution? Can/how can I incorporate Arduino's Bluetooth shield to achieve this?

title: Creating a keypad matrix that will communicate wirelessly with an Arduino Uno

Answers: 0


body:
I wrote a simple serial program using Arduino Mega 2560, it is connected to COMPORT 10. Here is the program I Wrote,

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

    void loop()
    {
      Serial.println("HELLO");
      delay(1000); //Send every one second
    }

Now, I tried to send this message "Hello" to TeraTerm (COMPORT 1, for this I just hooked up Tx and Rx to the Arduino's Rx0 and Tx0. Doing this I do receive message in my TeraTerm screen but the received message doesn't make sense, its receiving garbage. Its not the case of mismatch of baud rate I am using 9600 on both the side.

However I do receive message "HELLO" in the serial monitor. Is there something I am doing wrong that I am not receiving message on TeraTerm.

title: Serial communication using Arduino and TeraTerm

Answers: 2

body:
> ... I just hooked up Tx and Rx to the Arduino's Rx0 and Tx0.

But neither device knows what voltage they are. You need to connect ground as well so that they have a common reference.

body:
Hello everyone thanks for your reply,

I found the problem :D and was also able to solve it.

I was directly connecting the Tx and Rx pin of Arduino to the Rx and Tx pin of DB9 connector on PC. Since, DB9 on the PC operates on higher voltage than the operating voltage of the Arduino which is 5V. This mis-match of the voltage was causing the problem, So in order to solve this i added a level shifter in between (MAX232) and now it works perfect.

Thanks everyone for replying.