message:
How to compile an official VS1003 / VS1053 example for Arduino / ESP8266?

Have anyone ever successfully run any of the [official playback and recording examples][1] for **VS1003** or **VS1053** on Arduino / ESP8266? I mean, I was able to play sound with VS1003, but I just can't make the official example compile on Arduino IDE... It looks like it should be no problem (just provide a few methods and copy the main method code from the PDF file to the `setup()` in sketch) but I'm just getting a bunch of stupid compiler or linker errors, like "undefined reference to 'VSTestInitHardware()' " while the player.h header file (containing it) is included. I'm not a C / C++ expert so it's either something stupid I do or it's just not possible on Arduino. Can anyone provide a compilable example? I'm trying it with [ESP8266][2] currently (and it is my desired target CPU), but an Arduino Uno version could help too (it throws different errors but doesn't compile neither). Thank you.

  [1]: http://www.vlsi.fi/en/support/software/microcontrollersoftware.html
  [2]: https://github.com/esp8266/Arduino

body:
Ok, after long battle with C++ compiler I have a **working example** (at least for VS1003 and ESP8266) with a checklist how to recreate it (with minimal changes to the example files). I'm sure someone else will have this problem so I'm attaching it:

**The things that you need to do in player1003.c**:

 - rename to player1003.h (change file extension only)
 - remove all 5 includes from the top (stdio, string, stdlib, ctype, "player.h")
 - turn off `REPORT_ON_SCREEN` (change `#if 1` to `#if 0`) if you don't want to have a lot of serial output
 - mass replace "FILE *" to "File " - mind the space (change type of file variables in all methods, mark "Case sensitive" to avoid errors in player1053!)
 - mass replace `fopen(` to `fopen2(`
 - mass replace `printf(` to `Serial.printf(`
 - mass replace `fflush(stdout);` to `//fflush(stdout);` (or `Serial.flush();`)
 - remove method: `VSTestInitHardware(void)`
 - remove `SM_SDISHARE` flag from `WriteSci(SCI_MODE, SM_SDINEW|SM_SDISHARE|SM_TESTS|SM_RESET);` line  (in `VSTestInitSoftware(void)` method)
 - in `VSTestHandleFile()` at the bottom add `fp.close();` after `VS1003PlayFile(fp);` and `VS1003RecordFile(fp);` lines (especially after the record!). We don't want unclosed files on SD card.

**The main sketch (.ino):**

    #include <SPI.h>
    #include <SD.h>
    #include "player.h"

    using namespace std;

    // I use these values below for ESP-12 (ESP8266):
    #define MP3_xCS 2
    #define MP3_xDCS 4
    #define MP3_DREQ 5
    #define MP3_xRESET 16
    #define SD_CS 15
    #define SPI_MOSI 11 //SPI
    #define SPI_MISO 12 //SPI
    #define SPI_CLK  13 //SPI

    #define  WAIT_DREQ()  while(!digitalRead(MP3_DREQ))

    File song;

    int VSTestInitHardware()
    {
      pinMode(MP3_DREQ, INPUT);
      pinMode(MP3_xCS, OUTPUT);
      pinMode(MP3_xDCS, OUTPUT);
      pinMode(MP3_xRESET, OUTPUT);
      pinMode(SD_CS, OUTPUT);

      digitalWrite(MP3_xCS, HIGH);
      digitalWrite(MP3_xDCS, HIGH);

      digitalWrite(MP3_xRESET, LOW); // chip off!
      delay(100);
      digitalWrite(MP3_xRESET, HIGH); // chip on!

      Serial.begin(115200);

      if (!SD.begin(SD_CS))
      {
        Serial.println("Can't initialize SD!");
        return -1;
      }
      Serial.println("SD OK!");

      SPI.begin();
      SPI.setClockDivider(SPI_CLOCK_DIV32);  // Bus SPI at 1MHz (for Arduino: 16MHz / 16 = 1MHz)
      SPI.transfer(0xFF);  // Write something to the bus
      delay(10);
      return 0;
    }

    void setup()
    {
      if (VSTestInitHardware() || VSTestInitSoftware())
      {
        Serial.printf("Failed initializing VS10xx, exiting\n");
        exit(EXIT_FAILURE);
      }
      /* ... */
      /* Playback example. You can call these functions many times in a row
      because they leave VS1003 in a stable state. */
      VSTestHandleFile("TEST.mp3", 0);  // remember to use 8.3 file names format on SD!
      /* Recording example */
      VSTestHandleFile("RECORDED.WAV", 1);  // original example for VS1003 has a bug here (OGG extension)

      Serial.println("Playing recorded file...");
      VSTestHandleFile("RECORDED.WAV", 0);

      Serial.println("THE END");
    }

    void loop()
    {
    }

    void WriteSci(unsigned char reg, unsigned char hsb, unsigned char lsb)
    {
      // for debugging:
      Serial.printf("Setting %s to: %d (%X, %X)\n", RegName(reg), (hsb<<8) + lsb, hsb, lsb);

      WAIT_DREQ();
      digitalWrite(MP3_xCS, LOW);

      SPI.transfer(0x02);
      SPI.transfer(reg);
      SPI.transfer(hsb);
      SPI.transfer(lsb);
      WAIT_DREQ();
      digitalWrite(MP3_xCS, HIGH);
    }

    void WriteSci(u_int8 addr, u_int16 data)
    {
      WriteSci(addr, data >> 8, data & 255);
    }

    uint16_t ReadSci (unsigned char reg)
    {
      WAIT_DREQ();
      digitalWrite(MP3_xCS, LOW);

      SPI.transfer(0x03);
      SPI.transfer(reg);
      delayMicroseconds(10);

      char response1 = SPI.transfer(0xFF);
      WAIT_DREQ();
      char response2 = SPI.transfer(0xFF);
      WAIT_DREQ();

      digitalWrite(MP3_xCS, HIGH);

      unsigned int resultvalue = response1 << 8;
      resultvalue |= response2;

      // for debugging:
      if (reg != SCI_HDAT0 && reg != SCI_HDAT1)  // these registers are filtered out because they are intensively used during recording
        Serial.printf("%s is: %d (%X, %X)\n", RegName(reg), resultvalue, resultvalue >> 8, resultvalue & 255);

      return resultvalue;
    }

    int WriteSdi(const u_int8 *data, u_int8 bytes)
    {
      WAIT_DREQ();
      digitalWrite(MP3_xDCS, LOW);

      for(int y = 0 ; y < bytes ; y++)
        SPI.transfer(data[y]);

      digitalWrite(MP3_xDCS, HIGH);
    }

    const char* RegName(uint8_t reg)
    {
      switch (reg)
      {
        case 0x00: return "SCI_MODE";
        case 0x01: return "SCI_STATUS";
        case 0x02: return "SCI_BASS";
        case 0x03: return "SCI_CLOCKF";
        case 0x04: return "SCI_DECODE_TIME";
        case 0x05: return "SCI_AUDATA";
        case 0x06: return "SCI_WRAM";
        case 0x07: return "SCI_WRAMADDR";
        case 0x08: return "SCI_HDAT0";
        case 0x09: return "SCI_HDAT1";
        case 0x0A: return "SCI_AIADDR";
        case 0x0B: return "SCI_MIXERVOL";
        case 0x0C: return "SCI_AICTRL0";
        case 0x0D: return "SCI_AICTRL1";
        case 0x0E: return "SCI_AICTRL2";
        case 0x0F: return "SCI_AICTRL3";
      }
    }

    void SaveUIState(void)
    {
    }

    void RestoreUIState(void)
    {
    }

    int GetUICommand(void)
    {
      while (Serial.available() > 0)
      {
        char c = Serial.read();
        if (c != 10 && c != 13)
          return c;
      }
      return -1;
    }

    void exit(int code)
    {
      if (code == EXIT_SUCCESS)
        Serial.println("Exited with no error.");
      else
        Serial.printf("Terminated with error: %d\n", code);
      while (true) { yield(); }  // yield() is needed for ESP8266 only
    }

    File fopen2(const char* fileName, const char* mode)
    {
      if (mode[0] == 'w')  // fast workaround!
      {
        Serial.printf("Opening for writing: %s\n", fileName);
        song = SD.open(fileName, O_WRONLY | O_TRUNC | O_CREAT);
      }
      else
      {
        Serial.printf("Opening for reading: %s\n", fileName);
        song = SD.open(fileName, O_RDONLY);
      }

      if (!(song))
      {
         Serial.printf("File not found: %s\n", fileName);
         return song;
      }
      Serial.printf("File opened: %s\n", fileName);
      return song;
    }

    size_t fread ( void * ptr, size_t size, size_t count, File stream )
    {
      yield();  // this is needed for ESP8266 only (otherwise reboots)
      return stream.read(ptr, size * count);
    }

    int fseek ( File stream, long int offset, int origin )
    {
      stream.seek(offset);
    }

    size_t fwrite ( const void * ptr, size_t size, size_t count, File stream )
    {
      return stream.write((uint8_t*)ptr, size * count);
    }

    int fflush ( File stream )
    {
      stream.flush();
      return 0;
    }

    #include "player1003.h"

(i had to manually clean this file out of my additional code, but I hope it will compile just fine).

**I have a request:**

If you run this example, please write me in comment whether the recording worked. I can't make my VS1003 module record sound. I have a suspicion that mic in my module is broken. That's why I was trying the official example (with the minimum changes as possible). It records only noise in my case, but plays mp3 perfectly. If you have a working example of recording, please share too.

And one more to the people with more rep (moderators): Please add a `VS1003` (and `VS1053` and `VS1063`) keywords and assign it to my questions about VS1003, because I'm unable to do it and it should be done. The chip deserves a keyword. (It's really good and not expensive.)


sender: user

sender: assistant

body:
This is best given with an example.

`foo.h` contains:

    #ifdef __cplusplus
    extern "C" {
    #endif
    extern int foo(const char* s);
    #ifdef __cplusplus
    }
    #endif

`foo.c` contains:

    #include "foo.h"
    #include <stdio.h>

    int foo(const char* s) {
      printf("foo: %s\n", s);
      return 42;
    }

So first, let's create a "library" from foo.c. Since we are compiling with a C, not a C++ compiler, the stuff in `#ifdef __cplusplus` is ignored.

    $ gcc -c foo.c

This creates a file called `foo.o`, which we can then use to link with.

`as24823.cpp` contains:

    #include "foo.h"
    #include <iostream>

    int main(int argc, char* argv[]) {
      int f = foo("called");
      std::cout << f << std::endl;
    }

Now I can compile the C++ program (as24823.cpp) and use a C library (foo.c):

    $ g++ -c ase24823.cpp
    $ g++ ase24823.o foo.o
    $ ./a.out
    foo: called
    42

*Why is this necessary?*, I hear you ask. Well, for reasons that are way beyond the scope of this posting, C++ mangles entry point names. Observe:

    $ nm as24823.o
    $ nm ase24823.o
    ...
                     U foo
    0000000000000000 T main
    ...

(I've removed most of the output). What this is telling me is that the .o file has an *entry point* called "main", and an *undefined external reference* (something that will be provided by a library) called "foo". Now, if I remove the ifdefs from the foo.h file and recompile, this is what I get:

    $ cat foo.h
    extern int foo(const char* s);
    $ g++ -c ase24823.cpp
    $ nm ase24823.o
    0000000000000000 T main
                     U _Z3fooPKc
    ....

What just happened? Because C++ no longer knows that it's supposed to call a *C* function, it has mangled the external so as to encode the types of its arguments (this is so that overloading can happen).

If you find this confusing, don't worry -- just edit the .h files that come with your C libraries and you'll be fine.


message:
Why can't my Arduino IDE recognize serial ports? (Mac El Cap, Ard. UNO)

My Arduino UNO I bought directly from Arduino.cc, so I'm pretty certain it's not a cheap clone. I have a MacBook Pro El Capitan 10.11.5. My Java is 1.8, but I'm pretty sure that doesn't matter. I have never used Arduino before, though I know a good bit of programming and some about computers. Whilst setting up Arduino, the only serial port my computer/Arduino recognizes is `/dev/cu.Bluetooth-Incoming-Port`. Please comment if there is more information I should provide.

My computer recognizes that I have a USB device as seen here:
[![enter image description here][1]][1]

Here is a screenshot of the Arduino IDE:

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/FSnuP.png
  [2]: https://i.stack.imgur.com/yuYa2.jpg

Finally, the command`ls /dev/tty.*` outputs only `/dev/tty.Bluetooth-Incoming-Port`. Is it possible no other serial ports exist for me?
Sorry for the barrage of pictures but I thought they'd help.

Things I have tried:

1. Installing CH34x driver

**I'm convinced it's not a driver issue though, as users and Arduino say that OS X does not need drivers installed to run Arduino**

2. Turning off System Integrity with `csrutil --disable` and also tried `csrutil --enable without kext`

3. Installing a FTDI USB Serial Driver

4. Bought a new USB A/B cable, as many reported the cable was faulty. I am getting a green light on my board

Does anyone know why my computer and/or Arduino does not list more serial ports that work? It's as if I don't have any besides the one Bluetooth port. I've been getting frustrated over this for several hours, so a solution would be **much** appreciated :)! I've tried all the solutions I've seen on SE thus far, but maybe I'm missing something

Thank you ahead of time!

body:
"ATmega16u2 DFU" indicates a USB interface micro that is in a state to have new firmware downloaded to it (DFU), *not* one which is ready for operational use as a USB interface to program the Uno's ATmega328p target MCU.  If this persists after power-cycling/re-plugging the board, it is probably faulty and at minimum needs firmware repair - though it might be worth trying on another computer (preferably with a different OS or version) just to be absolutely sure nothing in the host software is forcing it to this mode.

If this is a new board you have not modified in any way, you should probably return it as defective.

If you have modified it, or you want to try to fix things yourself, you would need to follow the [instructions][1] for reflashing the 16u2 via USB-DFU.  Beware that this is a non-trivial task that looks like it is going to require installing macports and running some terminal commands, and on older boards some soldering.

  [1]: https://www.arduino.cc/en/Hacking/DFUProgramming8U2


message:
Pro Micro - Measuring voltage between two pins, without using GND

Quite new to this but making pretty good ground. I have an issue I'm not sure how to solve. I want to add a Pro Micro to an RC Toy, I can easily power it from the toys GND and 5V power. But then I want to use the voltage going to an LED on the toy (uses a different ground) to trigger an event within the Pro Micro.

I can power the Pro Micro from USB and and accomplish what I need with AnalogRead(). But if I connect the GND from the toys main power input to the GND from the LED it no longer acts as it should. I'm thinking these GNDs are not common, or are a separate circuit.

What I'm wanting to know is.. I'm using PIN10 on the ProMicro for the AnalogRead(), can I make it so that maybe PIN11 is the GND for that reading?

Thanks.

body:
No, you cannot - the ATmega's ADC is referenced to its ground, and there are also some strict limits on providing inputs more than a little bit outside of the range between its power and ground.

You may be able to read two analog inputs and subtract them for a sort of "software differential" analog input, but the signal on an LED is unlikely to be meaningfully "analog" anyway - it might be pulsed with a duty cycle, but it will probably not have a steady reduced voltage.

It's actually quite likely that the anode of the LED is connected to the toy's positive supply, and it is the negative path to the cathode which is being switched - this is the most traditional way of doing things, because historically semiconductor switches suitable for "low side switching" have had better performance than those suited for "high side switching".  There will probably be a resistor on one side or the other of the LED.

With care and verification of suitable voltage ranges, you may be able to read the voltage on the LED cathode as a digital signal and invert it in software.


message:
7 segment with arduino

I am getting error with this. It is displaying those segments which are not to be displayed, i.e., 3.141 is dark and other segments are red. And I have checked that the seven segment module I am having is common anode type only.

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

    #include "SevSeg.h"

    SevSeg sevseg; //Initiate a seven segment controller object

    void setup() {
        byte numDigits = 4;
        byte digitPins[] = {2, 3, 4, 5};
        byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
        sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
        sevseg.setBrightness(1000);
    }

    void loop() {
        sevseg.setNumber(3141, 3);
        sevseg.refreshDisplay(); // Must run repeatedly
    }

body:
If you use [this library](https://github.com/DeanIsMe/SevSeg), then use

    sevseg.begin(P_TRANSISTORS, numDigits, digitPins, segmentPins);


message:
How to interpret analog values sent to Arduino from line scanner?

So I have a line scan camera attached to my Arduino Mega and I'm trying to send it a digital clock impulse and get an analog output back. The line scan camera is supposed to return 128 pixels.

So far I've been able to send the impulses and get analog values back which I am printing out. However, the values are different every time, which doesn't make sense because the camera didn't move so I assume that it should give back similar numbers.

Also, is there a way to determine what these numbers mean? Is there some way of turning analog signals into color pixels? My ultimate goals is to be able to determine if something has moved through the vision of the line scanner

Here is the datasheet for the line scanner: [http://www.farnell.com/datasheets/315815.pdf][1]

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

Here is my code:

    void loop() {

      int delayTime = 20;
      digitalWrite(syncPin, HIGH);
      delayMicroseconds(delayTime);
      digitalWrite(clockPin, HIGH);
      delayMicroseconds(delayTime);
      digitalWrite(syncPin, LOW);
      delayMicroseconds(delayTime);
      digitalWrite(clockPin, LOW);
      delayMicroseconds(delayTime);

      for (int i = 0; i < 128; i++)
      {
        digitalWrite(clockPin, HIGH);
        pixelValue[i] = analogRead(dataPin);
        delayMicroseconds(delayTime);
        digitalWrite(clockPin, LOW);
        delayMicroseconds(delayTime);
      }

      digitalWrite(clockPin, HIGH);
      delayMicroseconds(delayTime);
      digitalWrite(clockPin, LOW);
      delayMicroseconds(delayTime);

      for (int j = 0; j < 128; j++)
      {
        Serial.print("I received: ");
        Serial.println(pixelValue[j]);
      }

    }

body:
First, a preliminary note: according to the datasheet, the only time you
need a delay in your program is after reading the whole array and before
sending the next sync pulse. All the other timing requirements are
shorter than a single CPU cycle of your Mega, so no need to add extra
delays.

> the camera didn't move so I assume that it should give back similar
> numbers.

Similar: yes. Identical: no. You expect noise to make every reading
slightly different, and you also will have variations due to uneven
timing of your program (e.g. the timer interrupt kicking in from time to
time).

> is there a way to determine what these numbers mean?

They are proportional to the amount of light collected by each pixel.
That's about all you know about their meaning.

> Is there some way of turning analog signals into color pixels?

No. This is a B&W camera.


message:
Arduino Pi-3 Ubuntu MATE not compiling

When I try to upload a script to my Genuino Uno from the Linux ARM distro on genuino.cc/downloads it spits out this during compiling.
``
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device
``

Has anyone got any ideas?

Thanks,
Caleb

body:
After following the advice left by Majenko, I went to https://www.arduino.cc/en/Guide/Linux and followed the instuctions at the bottom of the page:

If you get an error Error opening serial port ... you need to set serial port permission.

Open Terminal and type:
```
ls -l /dev/ttyACM*
```
you will get something like:
```
crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0
```
The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is "dialout" (is the group owner of the file).

Now we just need to add our user to the group:
```
sudo usermod -a -G dialout <username>
```
where <username> is your linux user name. You will need to log out and log in again for this change to take effect.


message:
RFID/NFC Tag get data from wordpress MySQL

I have a local workshop for students to teach them 3D printing/woodworking
I want to know if its possible to create **RFID/NFC tags using wordpress data from MySQL or HTTP/HTTPS**.

***Web Scenario*** :

I have a wordpress website where I setup a gamefication plugin.
Each time a student takes a quiz/posts on forum he gets a "x" number of points that are accumulated on his profile.

I want to know if I can get a RFID/NFC tag to get that number of points.
Each member has a RFID/NFC tag card and with that card he can get access to different things around the workshop .

***Workshop Scenario :***

**For each tool there will be a lock , RFID/NFC reader and a LCD display screen.**

 **When a student want to access that tool he needs a number of points on the wordpress gamefication script that are transfered to the RFID/NFC card.**

If he has the needed points a text on the LCD screen will appear with something like " **You have access to this tool**" and the tool will be unlocked .

 Else if the user doesn't meet the needed points the LCD screen will show "**You don't have the needed points for this tool, please visit [URL] to get more info**" and the tool will stay locked.

***

> **I need only info if this is possible, not the way to do it.**
>
>***[ In case you are kind to hand me some guides on where to start to will be great! ]***

***
Thanks and waiting to see if this is possible!

body:
From what I can tell it's absolutely possible but will take some considerable development time and around $30-$70 of hardware per NFC terminal. Please note I would strongly not recommend this as a first project as it has a lot of individual components that all have to work together flawlessly and each is different. Properly done this will be complex software and hardware wise although more so from the hardware side of things.

Hardware wise you need/terminal:

 - **LCD display** (I would recommend segmented for simplicity and cost)
 - **Wifi or ethernet shield/breakout** and ethernet cable if the board is not wifi compatible
 - **Arduino** (MKR1000 has wifi built in), Feather (Adafruit's boards that are frequently Arduino software compatible and have many shields available and guides written on how to use them), or cheap Arduino knock off (preferably not this option as giving money to arduino.cc, Adafruit, or other designers is important if we want new boards regularly)
 - **NFC breakout** or shield (Google/DuckDuckGo/Bing RFID-RC52 for an economical option, they're ~$4 on Ebay)
 - **Power supply** corresponding to the requirements of the chosen board + shields + breakouts
 - **NFC tags**
 - **Lock** able to be unlocked by a servo. If you expect security in absence of supervising shop manager (aka just to be safe, assume dishonesty in people using the shop) from this system, the locks need to be better than a Masterlock as those are insecure to even simple soda can shims. The rotary masterlocks can also be reduced to 100 possible combinations and then the combo can be brute forced easily from there so if you get a rotary based lock system make sure the assembly covering the dial is not easily removed.
 - **Servo or stepper** powerful enough to actuate locks
 - **Servo or stepper driver breakout board**

Then you'd just want to have the public key (note I don't mean a "public key" in the general cryptography sense but on that subject, you do want the key encrypted) to the user stored on the NFC tag and then use the arduinos+electronics to read the tags and see point values. User data from wordpress could be downloaded periodically to the boards so the individual checks don't use network resources and the system works offline.


message:
MPU6050 acceleration values not 16-bit?

I'm looking at the little code snippet from [this](http://www.circuitmagic.com/arduino/control-dc-motor-cwccw-with-mpu-6050-gyroaccelerometer-arduino/) (many other projects also use similar code):

    void loop(){
     mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

     ax = map(ax, -17000, 17000, -1500, 1500);
     ...

If my reading is correct, it's assuming the value of `ax` to be between -17000 and 17000. But isn't the value supposed to be 16-bit? If so, shouldn't the range be wider than -17000, 17000? Is the value capped?

Any thought appreciated.

body:
The ADC for the accelerometer is 16 bit, yes. Also the data being sent out is in 16 bit format.

But what you are confusing is *resolution* and *range*.

The accelerometer can be programmed to have a sensitivity of 2g, 4g, 8g or 16g.  With it set to the least sensitive, that is 2g, the full range of -32768 to +32767 would equate to ±2g.

That's fine when you're measuring G-forces of up to 2g, but when all you are sensing is tilt then there is only 1g - the 1g the Earth exerts on it.

That 1g is half the 2g range, which is -16384 to +16363.  So round that up and give a little extra headroom to your calculations, and you get -17000 to +17000. It gives enough range in your calculations to give the full ±1g range "plus a little bit".


body:
No, the `map()` function does not cap it's input or output, you would
need `constrain()` for that. With `map()` alone, there is no assumption
about the range of the values, other than the calculation not
overflowing 32-bit integers. Thus,

    ax = map(ax, -17000, 17000, -1500, 1500);

simply multiplies x by the ratio 1500/17000. It is mathematically
equivalent to

    ax = map(ax, 0, 34, 0, 3);

or to

    ax = ax * 3L / 34;

C.f. the [documentation of `map()`](https://www.arduino.cc/en/Reference/Map).


message:
How do I read the fuse bits from within my sketch?

How can I read the fuse bits from within my sketch?

body:
You can use the [boot_lock_fuse_bits_get](http://www.nongnu.org/avr-libc/user-manual/group__avr__boot.html#ga37ce7078335dd85f04d150a52a01d6ad) function from [<avr/boot.h>](http://www.nongnu.org/avr-libc/user-manual/group__avr__boot.html).

    #include <avr/boot.h>;

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

        cli();
        uint8_t lowBits      = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
        uint8_t highBits     = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
        uint8_t extendedBits = boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS);
        uint8_t lockBits     = boot_lock_fuse_bits_get(GET_LOCK_BITS);
        sei();

        Serial.print("Low:  0x");
        Serial.println(lowBits, HEX);
        Serial.print("High: 0x");
        Serial.println(highBits, HEX);
        Serial.print("Ext:  0x");
        Serial.println(extendedBits, HEX);
        Serial.print("Lock: 0x");
        Serial.println(lockBits, HEX);
    }

    void loop()
    {
    }


message:
Code runs different on USB vs Battery

I have two Arduino, one is to handle the Bluetooth communication and send a signal to the other Arduino, and the other to interpret the signal and display or hide an image on the E-ink display.

It work just fine when they both are connected through the USB. But when I connect a 9V battery to the Arduino running the E-ink, instead of the USB, the image is displayed and cleared (looping), as if the IF ELSE conditions are not there.

I have tested if it actually runs the method by adding delay to the showImg()-method, and that seems to work.

I have also tested with connecting the USB cable to the E-ink Arduino to a 5V charger, and the case is the same.

Image:
[![Setup][1]][1]

Bluetooth code:

    int ledPin = 13;
    int state = 0;
    int flag = 0;

    void setup() {
     pinMode(ledPin, OUTPUT);
     digitalWrite(ledPin, LOW);

     Serial.begin(9600);
    }

    void loop() {

     if(Serial.available() > 0){
     state = Serial.read();
     flag=0;
     }

     if (state == '2') {
     digitalWrite(ledPin, LOW);
     if(flag == 0){
     Serial.println("Screen: off");
     flag = 1;
     }
     }

     else if (state == '1') {
     digitalWrite(ledPin, HIGH);
     if(flag == 0){
     Serial.println("Screen: on");
     flag = 1;
     }
     }
    }

E-ink code:

    #include <epd.h>

    int displayed = 0;
    int val = 0;

    void showImg(void)
    {
      Serial.print("showImg");
      displayed = 1;
      //epd_clear();
      epd_disp_bitmap("PIC9.bmp", 0, 100);

      epd_udpate();
      //delay(10000);
    }

    void clearImg(void){
      Serial.print("clearImg");
      displayed = 0;
      epd_clear();
      epd_udpate();

    }

    void setup(void)
    {
      //Serial.begin(9600);
      epd_init();
      epd_wakeup();
      epd_set_memory(MEM_TF);
      pinMode(7, INPUT);

    }

    void loop(void)
    {
      val = digitalRead(7);

      if(val == 1){

        if(displayed == 0){
          showImg();
        }

      }else {

        if(displayed == 1){
          clearImg();
        }
      }
      //Serial.println(val);
      //delay(3000);
    }

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

I am a beginner when it comes to Arduino, So I hope someone can give me some hints to what may be wrong.

Thanks!

body:
The USB provides the one thing that is missing from your diagram there: the **common ground**.

The GND pins of the two boards *must* be connected together. By using USB the USB becomes that connection. As soon as you use batteries there is no connection, so no communication happens.


message:
Arduino OBD library and software serial library

Can I use Arduino OBD library with "custom" software serial or it needs to be used with hardware UART only? For example if I have D5 and D6 pin as RX and TX in my code hooked on OBD board, how do I initialize OBD library from there?

This is the [OBD library][1] that I'm referring to.

And I'm using this [Allpro OBD][2] board.

**Update**
Actually I would be satisfied with a answer how to know when entire response from the board is received, because this way is way too messy:

    void getResponse(void){
     while(obdSerial.available()){
       Serial.write(obdSerial.read());
      }
    }
Here I don't know when the message is received. And if I try to use example from **Sparkfun** **obd-ii-uart-hookup-guide** (different board doe) I ended up in infinite-loop since the board never return `\r`, if I send ELM command to use `\n` as terminator, and if I disable ELM to echo the command so that I use just one `getResponse` call I get some readings, but not all the time, I ended up in infinite-loop again.

  [1]: https://github.com/stanleyhuangyc/ArduinoOBD
  [2]: http://www.obddiag.net/allpro.html

body:
That library is hard-coded to use the single Hardware Serial device on the Arduino Uno or the second Hardware Serial1 device on other boards.

    #ifndef OBDUART
    #if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168P__)
    #define OBDUART Serial
    #else
    #define OBDUART Serial1
    #endif
    #endif

You can edit the library's header file `OBD.h` to define your own serial port though:

    #include <SoftwareSerial.h>
    extern SoftwareSerial mySerialPort;
    #define OBDUART mySerialPort

And then in your sketch create the `mySerialPort` SoftwareSerial object.


message:
Does serial communication between PC and Arduino has to be in a loop?

I am trying to send a few variables from my python script to my Arduino. I am using pySerial. I am able to send the variables to the Arduino, but my Arduino sketch runs only for a second and then stops. But if I put the `ser.write()` command in a while loop (which I want to avoid) the sketch runs fine.

For example, I wrote this script on my PC -

    import serial
    ser = serial.Serial('COM3',9600)
    counter = 'Y'
    ser.write(counter)

This script should pass a "Y" to the Arduino and should stop executing.

My Arduino code-

    int flag = 0;
    void setup() {
       Serial.begin(9600); // set the baud rate
       Serial.println("Ready"); // print "Ready" once
       pinMode(13, OUTPUT);
    }

    void loop() {
       char inByte = ' ';
       if(Serial.available()){
          inByte = Serial.read(); // read the incoming data
          Serial.println(inByte);
          flag ++;
       }
       if(flag == 1){
          digtalWrite(13, HIGH);
       }
    }

Now according to me the Arduino should receive the data and increment the flag variable to 1. Next the program checks whether flag is one and if it is turns the onboard LED on. However when I run the python script, the onboard LED flashes for just a second and then goes blank. I again have to run the python script to make it light up or I have to put `ser.write` in a loop. I can't put `ser.write` in a loop as my script won't run further.

So how can a value be passed to an Arduino without having to put the `ser.write()` in a loop.

Thanks!

**EDIT :**

I wrote a new sketch, but it still doesn't work. Here's the sketch -

    int ledPin = 13;
    char data = ' ';

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

    void loop(){
       if (Serial.available()>0) {
          data = Serial.read();
       }
       if (data == 'Y'){
          digitalWrite(ledPin, HIGH);
       }
       delay(500);
    }

Here's an image of the wiring -
[![enter image description here][1]][1]

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

body: Just put a 10 µF capacitor between the 5v and RESET pins of your Arduino and do whatever you want, just make sure that the capacitor is connected after the board has been powered up, and also, remove the capacitor before uploading any code.


message:
What is the sampling-rate of the `analogRead()`?

I am about to Fourier analyse some data I've taken, but i need to know at which sampling rate the data was written to the serial monitor. I've found a lot of threads about how to increase it and such but not a single one that lays down some information about what the sampling-rate is.

My code is very simple, here it is:

          // the setup routine runs once when you press reset:
      void setup() {
        // initialize serial communication at 9600 bits per second:
        Serial.begin(9600);
      }

      // the loop routine runs over and over again forever:
      void loop() {
        // read the input on analog pin 0:
        int sensorValue = analogRead(A0);
        // print out the value you read:
        Serial.println(sensorValue);
      }

body:
The ADC in default configuration will take 104 µs to make a sample (which agrees with Edgar Bonet's comment of roughly 9600 per second).

You can speed that up somewhat by changing the ADC prescaler from the default of 128. See [ADC conversion on the Arduino (analogRead)](http://www.gammon.com.au/adc). A prescaler of 32 will reduce that to 26 µs and still give quite acceptable results.

You can also run the ADC asynchronously (in the background) so you can transmit the previous result while obtaining the next one. A higher baud rate than 9600 baud would be highly recommended in this case.

People have been doing FFT analysis using the Arduino Uno and similar. I suggest you Google for relevant posts about that.


body:
I loaded this program on an arduino uno and measured with oscilloscope the time from the rising edge to the falling edge of the signal on pin13.

 void setup() {

  Serial.begin(9600);
  pinMode(13,OUTPUT);
 }

 void loop() {
  PORTB = B00100000; //pin13 HIGH
  int sensorValue = analogRead(A0);
  PORTB = B00000000; //pin13 LOW
 }

results:
> time: 110.4 uS
> relevant freuency: 9.06 kHz

----------------
in case you are interested in fast analogRead with Due, I suggest you take a look at [this](http://frenki.net/2013/10/fast-analogread-with-arduino-due/).
The author stated that an analogRead with Due takes about 40uS and he also describes a couple of ways to make it much faster.


message:
Character array weirdness

I'm using Energia to program one of TI's MCU. Since Energia is based off the Arduino IDE, I'm hoping someone can help me here.

I'm building a simple UDP packet sender and receiver app. The MCU starts up and connects to the local Wifi network and waits for a packet from another device on the same network.

This packet is collected in a char array `char packetBuffer[16];`

I want to split this array into two separate arrays each of 8 elements. These are `char lampCmdRead[8];` and `char pwdReadBuffer[8];` Now the network bit works great. I can send the packet through my desktop and receive it on the MCU. However when I split this array I see that the `pwdReadBuffer` shows the same contents as `packetBuffer` even though they are of different sizes. How is this possible?

Here is the code:

    char packetBuffer[16];
    char lampCmdRead[8];
    char pwdReadBuffer[8];

    // This is code from the 'void loop()' section
    int packetSize = Udp.parsePacket();

    if(packetSize) {
     int len = Udp.read(packetBuffer, 16);
     if (len > 0) packetBuffer[len] = 0;
     Serial.println();

     Serial.println("packetBuffer:");
     Serial.println(packetBuffer);
     Serial.println();

     for(ctr = 0; ctr < 8; ctr++) {
       pwdReadBuffer[ctr] = packetBuffer[ctr];
     }
     if (len > 8) pwdReadBuffer[len] = 0;

     for(ctr = 0; ctr < 8; ctr++) {
       lampCmdRead[ctr] = packetBuffer[ctr+8];
     }
     if (len > 8) lampCmdRead[len] = 0;

     Serial.println("pwdReadBuffer:");
     Serial.println(pwdReadBuffer);
     Serial.println();

     Serial.println("lampCmdRead:");
     Serial.println(lampCmdRead);
     Serial.println();
    }

And here is the output:

    Received packet of size 16
    From 192.168.1.101, port 55056

    packetBuffer:
    2qZ@X51Rredledon

    pwdReadBuffer:
    2qZ@X51Rredledon

    lampCmdRead:
    redledon

body:
    if (len > 8) pwdReadBuffer[len] = 0;

This line is unsafe.  You declared pwdReadBuffer to be only 8 bytes in size, but this line of code will either do nothing, or write *outside* of the target buffer, with unpredictable results.

You make a related mistake here:

    if (len > 8) lampCmdRead[len] = 0;

First the test should be `>=` but again, such a value would be beyond the end of the target buffer.

Also consider that if you receive 8 or more characters, you will have no room for a terminating null in pwdReadBuffer, and so cannot pass it to anything that expects a null terminated string.

If you want to use null-terminate storage for a string of up to 8 bytes size, you need 9 bytes of storage.  And of course you need to only use in-range indices to access the elements.


body:
This behavior (where contents of `pwdReadBuffer` print out the same as those of `packetBuffer`) is occurring because you haven't properly null-terminated your strings.

After you copy the first 8 characters of `packetBuffer` to `pwdReadBuffer` the statement `if (len > 8) pwdReadBuffer[len] = 0;` gets executed.  It sets `pwdReadBuffer[16]` to 0, ie, references out of array bounds.

Apparently `lampCmdRead` is allocated directly after `pwdReadBuffer`, so when you copy the next 8  characters of `packetBuffer` to `lampCmdRead`, they are being copied, in effect, to `pwdReadBuffer[8] ... pwdReadBuffer[15]`, so that the `println` prints a 16-character string,
`2qZ@X51Rredledon`.

For each of your three arrays, allocate an extra byte for a null terminator.


message:
trying to use millis()

I'm learning how to use the millis() function. Instead of having it in the main body of the program I wanted to place it in a function so I can change the time interval with which an led will flash. I modified the code blinkWithoutDelay. My code is below. The output I get is an LED that is always on. I did print the output of the ledState to the serial monitor. Its changing from on to off repeatedly. So I think the led is really flickering too fast to see. I took a screenshot from the serial monitor. The output is below.

    const int LED2 = 2;
    int ledState2 = LOW;

    void timeCheck(int interval)
    {
     unsigned long cMillis = millis();
     unsigned long pMillis;

     if (cMillis - pMillis > interval)
     {
      pMillis = cMillis;

      if (ledState2 == LOW)
      {
       ledState2 = HIGH;
      }
      else
      {
       ledState2 = LOW;
      }
      digitalWrite(LED2, ledState2);
      Serial.println(ledState2);
     }
    }

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

    void loop()
    {
     unsigned long flashtime = 1000;
     timeCheck(flashtime);
    }

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

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

body:
The problem here is that the variables you declare in your function are not static. The rest of the code works as expected.

Where you declare the variables at the beginning of your function is correct. There is only one variable in question though as it is the cause of the error you are seeing.

What you need to do is change the variable

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

    unsigned long pMillis;

to

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

    static unsigned long pMillis = 0;

By not having the `pMillis` as a static variable, each time the function is called the value of `pMillis` is undefined, which means it is unpredictable whether ` (cMillis - pMillis > interval)` will be true or false. But with the `static` declaration the Arduino knows to keep the previous value for the next time you call the function.

An excerpt from [Wikipedia][1]:

> In computer programming, a static variable is a variable that has been allocated statically—whose lifetime or "extent" extends across the entire run of the program....
>
> A static local variable is different from a local variable. It is initialized only once no matter how many times that function in which it resides is called.

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


body:
Put it out, so it will be global. LedStaye should be bool:
<code>
const int LED2 = 2;
bool ledState2 = LOW;
unsigned long pMillis;

void timeCheck(int interval)
{
    if (millis() - pMillis > interval)
    {
        pMillis = millis();
...
</code>


body: You have used `pMillis` variable locally. Thats why when you call the function, `pMillis` initialized as 0. So set `pMillis` variable globally.


message:
Is there any reason not to solder power leads to the lugs for the power in socket on the reverse side of a mega 2560 rev 3 board?

I have a very tight space for a project that requires a mega board , the "power in" plug takes it over the space available. Are there safety or other concerns soldering to the lugs for the "power in" socket on the reverse of a mega 2560 rev 3 board board? the board is fitted with an elctrofreaks TFT LCD MEGA SHIELD v2.2 and a TFT_320QVT LCD screen. (the elctrofreaks mega shield uses vin pin)  1 other PWM  pin is used  and an esP8266 board on a uart channel The power  is from a regulated power supply. If  I do this, am I correct that the regulator and polyfuse will still be used?

body:
Soldering to the underside of the connector is exactly the same as plugging something in to the connector.

Yes the regulator will be used.

No the polyfuse will not be used - that is in the USB power circuit not the barrel jack power circuit.


message:
Unable to issue any AT commands to BT BLE Breakout Board

I'm a programmer, more from the software side but I do have hardware working knowledge too. I've completed the Arduino Starter Kit's 15 projects, Now trying to build some things with ESP8266 and HM-10 BLE.

I was able to connect ESP8266 to my network and start a TCP server too via AT commands(using  Arduino's Serial Monitor and FTDI 232RL USB to TTL converter)

I also have a HM-10 Bluetooth Breakout+connector board (Its based on CC2541 by TI (visible on the SMD chip)) brought from [here][1].

Using the same setup I was able to issue AT commands successfully for ESP8266. However I tried many things, different baud rates and \r\n combinations; I just couldnt get the HM-10 to acknowledge my AT commands.

Setup: [link][2]

Connections:

    Arduino +5V --> +ve input of LDO regulator --> 3.3v OUPUT to Vcc of HM-10
    Common GND for LDO regulator input and output pins, FTDI 232RL and HM10

    FTDI TX --> voltage divider (1k ohms --> connection output to HM 10 RX --> 1k ohms --> 1k ohms --> GND)

There is no code/sketch as of now. I'm just trying to hook up the HM-10 BLE chip. I can pair my Android phone to it but that's not the concern here.

The concern here is I cannot configure the HM-10 using AT commands.

The HM-10 does not reply an "OK" acknowledge for my "AT" command. Nothing happens in the serial monitor after hitting enter. Just a blank screen.

Is there a way by which I can determine what baud rate to use and what combination of \r and \n?

What am I missing here?

  [1]: http://www.amazon.in/ePro-Labs-Module-Connector-Board-Bluetooth/dp/B019WEUY6O
  [2]: https://i.stack.imgur.com/q90QO.jpg

body:
I found out that there is no need for a voltage divider to reduce the voltage being given to RX pin of BLE from FTDI's TX since both FTDI232RL and HM-10 are 3.3V devices (from [here][1])

I connected the TX from FTDI directly to the RX of BLE using female to female jumpers.

Used `No Line Ending` and 9600 as the baud rate.

Then it worked fine, I got an `OK` acknowledge for my `AT` command.

  [1]: http://arduino-er.blogspot.in/2015/12/test-hm-10-bluetooth-40-ble-module-with.html


message:
counting ADC samples ( using a light sensor)

i am new to micro controller programming and in need of help. i have managed to interface a light sensor to a micro controller (atmega 32a) and can read the value i.e. (1023) as per the set prescale. however i intended to achieve a single decimal value as the result. in this case (1) every time the sensor is exposed to light and successively perform an incremented tally as lights go on and off around the sensor ( i am using a LDR for this). i am currently having problem getting my micro controller to do this. i have searched all over the internet but no seems to assist me on this... please any insight on how to achieve this will be much appreciated. i know its a simple thing,HELP :(

 basically just a means of making my micro controller count the number of times light falls on the LDR

body:
There are 2 common light sensor types.  The [photo diode][1] and the [photo resistor][2].  The first produces small amounts of current and operates fast.  The second changes resistance and operates (very) slowly.

There is a good stack exchange response [here][3] for how to use a photo diode.  Often the photo diode output is small and additional hardware is used to amplify the signal.  As discussed in [this][4] stack exchange response.

The photo resistor or [cadmium sulphide][5] cell or Light Dependent Resistor is much easier to [interface with an Arduino][6].  However, the response time is very slow.  On the order of hundreds of milliseconds to seconds.  This is acceptable when controlling street lights.  But is not acceptable in applications requiring fast light detectors such as those used for communication.

Before going on, verify which device you are using in your design.

Generally, [Arduinos contain a 10 bit ADC.  This results in values from 0 to 210−1 or 0 to 1023][7].  Should you consistently get a reading at or near the limits of the ADC check your hardware.  Do this by measuring the voltage at the input of the ADC pin used.  Do this under varying conditions to verify the hardware is operating as expected.

A good software design uses [hysteresis][8] to convert an analog value to a logical 1 or 0.  [Here][9] is a stack exchange response about using hysteresis with Arduinos.

  [1]: https://en.wikipedia.org/wiki/Photodiode
  [2]: https://en.wikipedia.org/wiki/Photoresistor
  [3]: https://electronics.stackexchange.com/questions/33659/how-do-i-connect-a-photodiode
  [4]: https://electronics.stackexchange.com/questions/73732/how-to-use-sfh235-ir-photodiode-correctly
  [5]: https://en.wikipedia.org/wiki/Cadmium_sulfide
  [6]: http://playground.arduino.cc/Learning/PhotoResistor
  [7]: https://www.arduino.cc/en/Reference/AnalogRead
  [8]: https://en.wikipedia.org/wiki/Hysteresis
  [9]: https://arduino.stackexchange.com/a/9116


message:
MPU6050 code explanation

I'm new to arduino and electronics. I've been trying to use the MPU6050 with my arduino but I'm having difficulty understanding the code. I'm referring to the code put up on the arduino website (http://playground.arduino.cc/Main/MPU-6050#short). Is there any way I could get a line by line explanation of the code?

body:
I've added in a bunch of comments for you:

    // MPU-6050 Short Example Sketch
    // By Arduino User JohnChi
    // August 17, 2014
    // Public Domain
    #include<Wire.h>
    const int MPU_addr=0x68;  // I2C address of the MPU-6050
    int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; // declare accellerometer and gyro variables
    void setup(){
      Wire.begin(); // initiate i2c system
      Wire.beginTransmission(MPU_addr); // be sure we talk to our MPU vs some other device
      Wire.write(0x6B);  // PWR_MGMT_1 register
      Wire.write(0);     // set to zero (wakes up the MPU-6050)
      Wire.endTransmission(true); // done talking over to MPU device, for the moment
      Serial.begin(9600); // initialize serial port to 9600 bps so you can see your debug messages in Arduino IDE via debug channel
    }
    void loop(){ // main program loop
      Wire.beginTransmission(MPU_addr); // get ready to talk to MPU again
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false); // done talking to MPU for the time being
      Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
      // all the fancy <<8| stuff is to bit shift the first 8 bits to
      // the left & combine it with the next 8 bits to form 16 bits
      AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
      AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
      AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
      Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
      GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
      GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
      GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
      // the above lines have gathered Accellerometer values for X, Y, Z
      //  as well as Gyroscope values for X, Y, Z

      Serial.print("AcX = "); Serial.print(AcX); // share accellerometer values over debug channel
      Serial.print(" | AcY = "); Serial.print(AcY);
      Serial.print(" | AcZ = "); Serial.print(AcZ);
      Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
      Serial.print(" | GyX = "); Serial.print(GyX); // share gyroscope values over debug channel
      Serial.print(" | GyY = "); Serial.print(GyY);
      Serial.print(" | GyZ = "); Serial.println(GyZ);
      delay(333); // delay a bit to not overwhelm you the user/programmer as you view the results
    }


message:
ADC timer interrupt when ready

I have a microphone and I need as precise values as possible. I have been told by my teacher, that it is somehow possible to make a ADC timer interrupt, which would interrupt always when the value is ready, so that the reading itself would not slow the program down.
    I know, how to use timer interrupts to read the analog value every other ms or something and I even have a code that lets the ADC read automaticly and takes the value, but I need to make it take the value always when it's ready, so that I would have every value the ADC read. I tried to look into the datasheet, but it's too complicated for me.
   How can I achieve such thing? I am using arduino uno.

this is the code I have that sets up the ADC interrupt:

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

      ADCSRA = 0;
      ADCSRB = 0;
      ADMUX = 0;
      ADMUX |= (1 << REFS0) + (1 << REFS1);
      ADMUX |= (1 << ADLAR);

      ADCSRA |= (1 << ADATE); //enabble auto trigger
      ADCSRA |= (1 << ADIE); //enable interrupts when measurement complete
      ADCSRA |= (1 << ADEN); //enable ADC
      ADCSRA |= (1 << ADSC);
      ADCSRA |= 0b010;

    ISR(ADC_vect) {//when new ADC value ready
      af = af + ADCH;
      aaf++;
    }

I found this on the internet, but it didn't work as I expected.

body:
>  it is somehow possible to make a ADC timer interrupt

The ADC and the timers are two different things. If you mean a timer interrupt, I'm not sure why you would want that. If you mean an ADC interrupt, yes you can do do that.

Here is some example code from [my page about the ADC](http://www.gammon.com.au/adc) which shows using the interrupt (on a Uno):

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

    const byte adcPin = 0;
    volatile int adcReading;
    volatile boolean adcDone;
    boolean adcStarted;

    void setup ()
    {
      Serial.begin (115200);
      ADCSRA =  bit (ADEN);                      // turn ADC on
      ADCSRA |= bit (ADPS0) |  bit (ADPS1) | bit (ADPS2);  // Prescaler of 128
      ADMUX  =  bit (REFS0) | (adcPin & 0x07);    // AVcc and select input port

    }  // end of setup

    // ADC complete ISR
    ISR (ADC_vect)
      {
      adcReading = ADC;
      adcDone = true;
      }  // end of ADC_vect

    void loop ()
    {
      // if last reading finished, process it
      if (adcDone)
        {
        adcStarted = false;

        // do something with the reading, for example, print it
        Serial.println (adcReading);
        delay (500);

        adcDone = false;
        }

      // if we aren't taking a reading, start a new one
      if (!adcStarted)
        {
        adcStarted = true;
        // start the conversion
        ADCSRA |= bit (ADSC) | bit (ADIE);
        }

      // do other stuff here

    }  // end of loop

---

I should point out that if you do an `analogRead` it **blocks** until the read is done, so the very next line to be executed after `analogRead` will be when the data is ready.


body:
>  I have been told by my teacher that it is somehow possible to make a ADC timer interrupt.

You might have asked him or he could explain it ;)

Generally, if you want to do anything with an Arduino, which isn't implemented by the Arduino libraries, you're going to have to roll your own code (or copy it from the internet).

The answer from Nick will most certainly be enough to help you with the problem. However, it'd be way more cooler to find out how you can solve these problems yourself.

**Getting started**

I couldn't find a duplicate of this question, though it's a rather common question. You should've checked some of the [tutorials][1] on the web, it'll get you started a lot faster.

But don't forget the datasheet and manuals of the ATMega328(P). In case you can't really find something that fits your needs, or if you want to check some background information.

**Setting registers (ADC)**

This piece of code (from Nick Gammon), sets up the ADC.

      ADCSRA =  bit (ADEN);                      // turn ADC on
      ADCSRA |= bit (ADPS0) |  bit (ADPS1) | bit (ADPS2);  // Prescaler of 128
      ADMUX  =  bit (REFS0) | (adcPin & 0x07);    // AVcc and select input port

Fair enough, but if you wanted to change anything of it, you'll think: "How did he ever come up with this."

These are the registers of the microcontroller. By setting bits in the right pattern, you can enable/disable functions or change settings of the microcontroller.

You should download the [ATMega328(P)][2] datasheet. You can very easily navigate through it (if you've got a PDF reader that supports "bookmarks").

Check for "24. Analog to Digital converter" you should read through it, and go to "24.9 (Analog to Digital converter) - Register description.".

Here you can see, which bits of (in example) the `ADCSRA` register you have to set to enable the adc (`ADEN`), start the conversion (`ADSC`). And enable interrupts for it (`ADIE`).

[![enter image description here][3]][3]

**Interrupts**

Since you also want behavior that has to do with interrupts. You should also check out the interrupts bookmark (#12). 12.1 will show you an table with all interrupt vectors.

It's quite a shame that they don't have a nice C example code, they do have an [reference manual][4] though, but you'll implement an interrupt handler like this (from Nick Gammon).

    // ADC complete ISR
    ISR (ADC_vect)
      {
      adcReading = ADC;
      adcDone = true;
      }  // end of ADC_vect

If you now want to interrupt on SPI you can check the datasheet or reference manual for the vector name. (`SPI_STC_vect`)

  [1]: http://www.avr-tutorials.com/adc/utilizing-avr-adc-interrupt-feature
  [2]: http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet_complete.pdf
  [3]: https://i.stack.imgur.com/hqnzk.png
  [4]: http://www.atmel.com/webdoc/AVRLibcReferenceManual/group__avr__interrupts.html


message:
Can ESP8266 replace Arduino?

I’m a hobbyist and have used Arduino so far for simple projects. Now I want to build a project involving addressable LEDs, I want to write several programs on the Arduino for the LEDs and on my phone I select which ones to run.

I found ESP8266 as a good and cheap solution to talk to my Arduino. Searching on the web to learn getting it to work I found that It has its own mcu on it and I can write and upload my code in Arduino IDE! 20kB of RAM, 80MHz CPU and 4MB of flash for 3 USD (However I’m not sure of these numbers but even one fourth of it is great)!! If I just need a few GPIOs why should use an Arduino UNO? Is this module reliable?

body: If you can program it, then of course it is viable to directly control your lights.  It doesn't have a large number of I/O pins like the Arduino does, but as long as you have enough to do the job, it certainly drops the cost, the size, and the power requirements.


body:
Yes there are a few I/O pins, so in theory you could drive one or a few leds or use an I/O port expander (I2C) for example.

And yes you can develop software and download it into even the low cost modules.  The Arduino-like angle is just one way to do this.  It is not an ARM as one might be lead to believe.  But there is a gnu toolchain for the esp8266, etc.  Yes 80 or 160MHz, 32 bit RISC, some flash, some ram.


body:
The Arduino Uno board and the ESP module are not the same, but as long as the GPIO of the ESP8266 provides the hardware that you need for your application it will work.

One of my concerns is certification.  The product has received several certifications, you'ld need to check if your version is also certified.
You can lookup the manufacturer's certifications (and some documentation) from the [FCC Search Page][1] by entering 2AC7Z as the grantee code.
The board you use may depend on those or require their own certification.

As you noticed, it can be added as a board type to the Arduino tool which makes it a lot easier for hobiests to play with it.

I just checked the grants and all three of them require that the WiFi antenna is kept at least 20 cm of all persons.

  [1]: https://apps.fcc.gov/oetcf/eas/reports/GenericSearch.cfm


body:
Well, the answer of the question "Can it replace Arduino" - yes, in many cases it can.

Whether it would be "the Arduino killer" - I doubt it.

There are multiple arduinos and ESPs in my home and 1 ESP in my office running 24/7 as a part of my self-made (and constantly under development) smart home solution, together with 1-2 PCs. On top of that I have several experiments / unfinished projects involving the ESP.

So, from my not-so-limited experience, here are the pros and cons of ESP compared to Arduino:

++++ Internet connectivity built in!

++ Faster clock and more memory.

+ Runs on 3V3 (most, but not all Arduinos are 5V) so it can interface 3v3 devices (like most of the display modules) directly, without level shifters.

+ The "basic" ESP-12E costs about as much as an Arduino nano or pro micro.

- The "basic" ESP-12E is 2.0mm pitch, not 2.54mm, making it a pain in the ass to work with.

- There are breakouts that make it easier for prototyping, but they increase the cost and take too much space on a breadboard / protoboard.

- The most common breakout - NodeMCU - is more expensive and has pins remapped, major annoyance, unless you program it in Lua, which is only ok for very simple projects. IMO, it should be used for prototyping only.

- They run on 3v3, making it hard to interface 5V modules, fully turn on most MOSFETs, etc.

- They are extremely picky on their power supply.

- They draw significantly more power than the Arduino when not transmitting and much more when transmitting.

- They are almost always worse for battery operated projects - you need 3v3 regulator (which has quiescent current), you need to sleep a lot (and you need GPIO16 broken out for that) and at the end of the day an arduino + a low-power radio will do the same job while lasting significantly longer on battery.

- They have less GPIO pins and some of them must have set voltages at startup (GPIO0 - high, GPIO2 - high or floating, GPIO15 - low), also they "wiggle" some of their IO pins on startup, often making them unusable for many devices.

- They only have one ADC, and to my knowledge it is slower than the already slow Arduino ADCs, plus you can only use it with 0-1.1V (internal reference).

- Many of the Arduino libraries work out of the box or are already ported, but many don't. You either have to port them yourself or wait for someone to do it. In general, the Arduino community is much bigger and more mature, so most "noob-friendly" tutorials, libraries, etc. are provided for the Arduino.

Having that said, the ESP8266 is still great and extremely useful. Even Lua is useful for quick small projects. In most cases where internet connectivity is required, they seem to be the best solution. In many other cases, whether you will use ESP or Arduino actually doesn't matter. And sometimes the Arduino (or the little ATTiny85) is the better choice.

As always, "the right tool for the job" is the way to go.

Or combination of tools.


message:
Good Arduino motor drivers

I need some motor drivers that can control a DC motor with 10-15 A and 25 V. I can't find any shield that can do the job. I need to control 4 motors with these.

Can you suggest some models that are good with this?

And one more question: if a driver can control a DC motor in 2 directions, can it control 2 DC motors in one direction each?

body:
We don't really answer "shopping questions".
You could contact several suppliers like [Adafruit](https://www.adafruit.com/), [sparkfun](https://www.sparkfun.com/) or maybe even [Digikey](http://digikey.com), [Farnell](http://www.farnell.com/) etc ([ebay](http://ebay.com)?).

If you search for: "15A dual h-bridge" you will find some motor drivers which should work for you.

**If a driver can control a dc motor in 2 directions can it control 2 dc motors in one direction each?**

Where are you going to use them for?
If you're only going in one direction, you won't need a motor driver.

An [MOSFET][1] (per motor) is good enough if you only drive one direction.
If you want both motors to be able to turn each direction, a [dual h-bridge][2] will do.

  [1]: https://www.adafruit.com/product/1794
  [2]: http://www.ebay.com/itm/3-36V-Dual-15A-H-Bridge-DC-Motor-Driver-30A-for-Robot-Car-Arduino-Compatible-/171012036277


body:
I think that the current you need is high and you are not likely to get a shield that does that. Look at a H-bridge with the desired current and voltage rating, it will probable be largish with a heat sink. If the motors are going one way then you may just need a simple mosfet style driver. You should probably look for a module with the correct rating as it will have the correct heat sink, track sizes, connections for your motor power and will probably have a diode to protect stuff from the induction spikes.
The H bridge will probably be fine with the Arduino output and it may have a voltage reg for its logic that you could use to power the Arduino.


message:
Arduino's digitalWrite, precautions for direct port manipulation?

I stumbled upon this piece in `digitalWrite`.
I'm unsure why clearing interrupts and setting/resetting SREG is neccesary here.

Can anyone shed a light on this?

 uint8_t oldSREG = SREG;
 cli();

 if (val == LOW) {
  *out &= ~bit;
 } else {
  *out |= bit;
 }

 SREG = oldSREG;

I figure they don't want an interrupt to possibly change any of the bits in the output register while it executes `*out = *out & ~bit`?

And what would the SREG have to do with it? Could the code affect SREG and why would that matter?

When speed matters, I often use the direct port manipulation, I'd like to get an idea if it's neccesary for me to include these "precautions".

body:
> I figure they don't want an interrupt to possibly change any of the bits in the output register while it executes *out = *out & ~bit?

Correct. That is known as a *critical section*.

> And what would the SREG have to do with it? Could the code affect SREG and why would that matter?

SREG is where the flag that says if interrupts are enable or not is stored.  Basically that is storing the current state, disabling interrupts, then restoring the current state.

The upshot is:

* If interrupts are enabled to begin with, they are disabled, then re-enabled.
* If interrupts are disabled to begin with, they are again disabled, and they remain disabled.

It's a way of restoring the previous state without actually having to check what the state was and set or clear accordingly.


body:
Answering only the last question, as the rest has been addressed by
Majenko.

>  I often use the direct port manipulation, I'd like to get an idea if
>  it's neccesary for me to include these "precautions".

If you use _constant_ values, like `PORTB |= _BV(2);` or the like, there
is no need, since this compiles into a single CPU instruction. Even if
you write things that take multiple instructions,
like `PORTB |= _BV(2) | _BV(3);`, you probably know whether you are
modifying the same register inside an interrupt handler or not. If not,
no need for critical section either. The authors of the Arduino core
cannot make any assumptions.


message:
I just fried my Arduino on a breadboard. Can I still use the breadboard?

So, I just fried my arduino nano on a breadboard. Can I still use the breadboard and usb cable?

body: It really depends on the circumstances around its demise. If it went out in smoke and flames, maybe not. Assuming the chip quietly overheated and died, the breadboard and the cable are almost certainly ok. Either of them will stand more abuse than the chip will. What was the cause of failure?


body: you can test the breadboard if you have a multimeter. Even if you don't, you can place an LED, a resistor and a power source across the suspect portions of the breadboard. If you locate a trace or two that appear unreliable, you should be able to mark them appropriately and continue to use the board.


message:
How to connect Wi-Fi shield ESP-12E-ESP8266-UART-WIFI-Wireless-Shield with Arduino

I have bought this shield from ebay and now I don't know how to use it, [ESP 12E ESP8266 UART WIFI Wireless Shield for Arduino UNO R3 Bouclier Sans filfr](http://www.ebay.in/itm/ESP-12E-ESP8266-UART-WIFI-Wireless-Shield-for-Arduino-UNO-R3-Bouclier-Sans-filfr-/152048233906):

[![Photo of shield][1]][1]

There are no instructions in the box or anywhere on internet for this board. The only description I found everywhere is this:

> **Description:**
>
> 1. Standard pin interface to achieve full compatibility with the pitch Arduino Uno, Mega and so on. (Unless the standard size Arduino, such
> as Nano, Mini)
> 2. 3.3V power supply using advanced chip (with the official expansion board power chip CC3000 same), so 3.3V Arduino board provided more
> accurate, so ESP8266 as official CC3000 chip work as normal, there is
> no gap.
> 3. It leads to a WiFi module power supply / service interface to facilitate developers to extend the power supply and maintenance.
> 4. Onboard ESP8266-12 stable industrial grade serial WiFi module, using an enhanced PCB antenna, signal better.
> 5. You can quickly switch DIP switch ESP8266-12 industrial grade WiFi stable operation mode (such as operating mode and upgrade mode)
> module, integrated serial chip, quickly flashing the firmware.
> 6. Built-in 5V to 3.3V TTL level converter to prevent high-pressure Arduino TTL level of the WiFi module damage.
> 7. Onboard ESP8266-12 stable industrial grade WiFi module with a metal shield, immunity to interference.
> 8. Onboard ESP8266-12 standard pitch leads to a stable industrial grade WiFi module all interfaces, enabling developers to easily
> develop deep.
> 9. Use stackable design, it can continue to accumulate above the other modules, easy to use.
> 10. Onboard four LED displays the status of ESP8266, namely PWR, DFU, AP, STA

What should be the board settings for this?

I am new to electronics please help me how can I connect this with Arduino.

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

body:
A search on the designer's name turned up a few posts by people working with this board. [This post][1] was the most useful one I found. I don't have this shield and haven't tested this poster's instructions, but it seems worth trying:

> Hi! Finally back here, more enlightened! :D I have finally done some
> stuff with the 8266 shield. I just wanted to share it with you all.
> Since I know I wanted all this before I started. I write all this a
> little bit as a "for dummies" just to make sure every step is
> included. So to be more precise, I use a Arduino uno with a (se
> below).
>
> 1: (identifying) The shield is a "ESP8266 ESP-12E UART WIFI Wireless
> Shield for Arduino UNO R3" (from Ebay). Since there seems to be none
> documentation about this board, hopfully this will help you. I think
> there was some pictures before on this thread. On my board it states:
>
> "Arduino ESP8266 Wifi shield. Version 0.9 by WangTongze." (and 1.0..
> I've got two)
>
> Here is a good link to identify which ESP8266 module you got if you
> want to know exacly what you got (if it is a different wifi board) :
> wiki/doku.php?id=esp8266-module-family
>
> There a 4 DIP switches on this board are numbered from 1-4. To be
> honest I really don't know what 1 and 2 is. But my guess is that you
> can use TTL levels on TX & RX opposed to 3.3 which the 8266 module
> uses directly. These two are always set to DOWN for me. Second though,
> if so, I might set them to UP when using Arduino. I usually play
> around with the board with a USB to 232 converter when testing. The
> other two, 3-4, are connected to GPIO 0 and something else xD. I
> really doesn't matter really. All I know, that I set these to UP to
> start a firmware update. Here is a good link that might be somewhat
> equal to what the shield has implemented.
>
> http://blog.falafel.com/how-to-wire-the ... ogramming/
>
> 2: (using Arduino with the shield) So everywhere, including this
> thread states that Arduino UNO doesn't handle the software emulated
> serial very good at high speeds. That is true :D So I got it to work
> perfectly with a baud rate 9600. What I did was to find a firmware
> that has default baud rate 9600 from AI thinker. I never really got
> the baud change to work. AT+CIOBAUD=9600 never got stuck after a reset
> (rst button och a AT+RST). And the other AT+IPR=9600 broke the
> firmware. If someone got this to work, please write here in this
> thread!!
>
> Here is a link: http://wiki.aprbrother.com/wiki/Firmware_For_ESP8266
>
> The only wiring I did to make it work, is to connect the tx and rx to
> Arduino's pins. (rx->tx and tx->rx). According to this example:
> http://allaboutee.com/2014/12/27/esp826 ... d-circuit/ connect to pins
> 2 and 3. The tx and rx from the 8266 shield are located on the left
> down side. There are other pins you can use also.
>
> 3: (flashing a firwmware) To set the board on flash mode, put the DIP
> switches to 3-4 to UP, press the 'ESP-RST' button. When flashing is
> done, set these to DOWN and press the 'ESP-RST'. Maybe there is a way
> to flash a firmware with the Arduino, but I finally bought a "FT232RL
> 3.3V 5.5V FTDI USB to TTL Serial Adapter Module for Arduino Mini Port T". There is a picture here: http://blog.falafel.com/how-to-wire-the
> ... ogramming/. I use this flash software:
>
> https://github.com/Stadslab/ESP8266_exa ... te Ready
>
> Because you can't really do any setting with it and it has worked 100%
> of all time for me and my use.
>
> So to connect the FT232RL to the 8266 board:
>
> (pins down) from left to right you have: dtr, rx, tx, vcc,cts and gnd
> and on the wifi shield from left to right: txd, rxd, 5v, gnd, 3v3.
> rx->txd, tx->rxd, gnd->gnd, vcc-> 3v3. Remeber that the FT232RL board
> has a jumper to change the voltage. You should use 3.3v. But for me I
> had some problems flashing, so I actually the the voltage to 5v and
> then connect the vcc to 5v connector on the wifi board. Never had any
> problems after that.

  [1]: http://www.esp8266.com/viewtopic.php?f=8&t=7352&start=8


body:
I just managed to get mine working and wrote a [blog article][1] about it.
Long story short:

 - Set all DIP switches "off"
 - configure the ESP8266 to use 9600 baud using the AT command "AT+UART_DEF=9600,8,1,0,0"
 - connect debug ports RX/TX to Arduino pins of your choice (not being pin 0 and 1)
 - Use the [WiFiEsp Lib][2] and tell it to use "your" pins and 9600 baud

  [1]: https://claus.bloggt.es/2017/01/14/using-esp8266-shield-esp-12e-elecshop-ml-by-wangtongze-with-an-arduino-uno/
  [2]: https://github.com/bportaluri/WiFiEsp


body:
There are some fake Modules on eBay! Only after changing the wiring can you use them. The fake modules have the wrong text printed on it.

> Moer info $ tech

instead of

> More info & tech

[![Example Fake][1]][1]

But when you change the wiring you can use the shield!

The two transistors which are connected to Arduino board pin 0 and 1 have to disconnected. Also the connection to the switches 1 and 2 have to change. Then you can stack ESP-12 shield on the Arduino. You can now flash the Arduino Uno when you switch off (switch 1 and 2) With the old wiring you can't use it because the transistors are wrong connected.

The voltage divider is need for 3,3 V ESP-12 RX pin

[![Circuit][2]][2]

  [1]: https://i.stack.imgur.com/26uN6.jpg
  [2]: https://i.stack.imgur.com/hvdPS.png


body:
In addition to [Andreas' answer][1], I believe he is correct about the general wiring of the 2 pins #0, #1 for some cheap clones.

I got mine to talk to the serial monitor (Arduino) by jumpering over the shield pins directly to the header pins next to the ESP-12E module.

This is at 115200 baud and Both NL and CR on the serial monitor.

  [1]: https://arduino.stackexchange.com/a/33604/19409


body:
Just to add to Andreas' answer, this is what the shield's circuit looks like at the board level:

[![Layout of ESP8266 shield components][1]][1]

For connecting to a 3.3v Arduino I found the neatest solution was:

* Remove all the components from the area above
* add 2 small bits of wire to short the areas shown in green above
* Switch the DIP switch so 1&2 are towards 'ON' (to connect serial to D0/D1) and 3&4 are 'OFF' (to disable the bootloader)
* Use with your Arduino on D0/D1 at 115200 baud

(You *may* have to flash you own ESP8266 command firmware using the debug port and a USB-TTL converter, in which case setting 3&4 to 'ON' and resetting the ESP8266 will stick it into bootloader mode. If you're doing this you can also send `AT+UART_DEF=9600,8,1,0,0` to put the ESP8266 into 9600 baud mode permanently if you're using an Arduino that can't handle the higher baud rates)

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


body:
Same Shield here, the most useful guide I've found is https://www.espruino.com/arduino-esp8266

The DIP switches are:

    Switch Function
    SW1 Connect ESP8266 TX to pin D0
    SW2 Connect ESP8266 RX to pin D1
    SW3 Enable bootloader mode
    SW4 Use DFU LED to show serial activity (?)

For connection to the Arduino, just stack the shield over the Arduino board.
[![Shield Arduino connection][1]][1]
<sub>(source: [robotshop.com](https://www.robotshop.com/media/files/images/usb-host-shield-arduino-1-large.jpg))</sub>

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


message:
Safe changes in the Arduino Libraries and use them

I changed 2 Arduino Libraries because i have a 9 bit data protocol, now i want use the amended Libraries on my Arduino mega2560.

At first i have set a 9 bit data mode that can i do when i set the UCSZ12 bit on 1(original code under the following link: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.cpp#L103 ):

    void HardwareSerial::begin(unsigned long baud, byte config)
      ...
      sbi(*_ucsrb, RXCIE0);
      sbi(*_ucsrb, UCSZ12);  // chance: set 9-bit data mode on 1
      cbi(*_ucsrb, UDRIE0);
      ...

At second i want throw an interrupt when the 9th bit is an 1 that can i do when i change the code like the follow (original code under the following link : https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial_private.h#L101 ):

    void HardwareSerial::_rx_complete_irq(void)
      if (bit_is_clear(*_ucsra, UPE0)) {
        bool is_address = UCSR0B & _BV(RXB80);
        unsigned char c = *_udr;
        if (is_address) {
          do_something_with_address(c);
          return;
        }
      rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;
    ...

What must i do with the two file´s?

How can i use the changed Libraries?

body:
I found the path to the files i want change in the github link so i can change the files(C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino).

I enable the uart for 9 bit, i add sbi(*_ucsrb, UCSZ12);  in HardwareSerial::begin

I decided that i only send a Flag to my PC when the 9th bit is set. For that i change the _rx_buffer to a 2 byte matrix (short _rx_buffer). Now i send the databyte in the low-byte and flags for 9 bit, framing error and overrun error in the high-byte. That i can do that i change the void HardwareSerial::_rx_complete_irq(void) code like the follow:

    void HardwareSerial::_rx_complete_irq(void)
    {
      if (bit_is_clear(*_ucsra, UPE0))
      {
        bool is_address = UCSR0B & _BV(RXB80);
     bool is_framError = UCSR0A & _BV(FE0);
     bool is_overError = UCSR0A & _BV(DOR0);
     unsigned char c = *_udr;
        rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;

        if (i != _rx_buffer_tail)
        {
         _rx_buffer[_rx_buffer_head] = c;
      _rx_buffer[_rx_buffer_head] |= is_address << 8;
      _rx_buffer[_rx_buffer_head] |= is_framError << 9;
      _rx_buffer[_rx_buffer_head] |= is_overError << 10;
         _rx_buffer_head = i;
        }
      }
      else {    *_udr;  };
    }

I hope this will work and i can evaluate the data right at the PC.

Frindly wishes sniffi


message:
Storing integer into character buffer

I have my Arduino code as below.I am trying to send Serial request and get response for it. I can able to send request mentioned in Setup function and also able to switch cases. Problem i am facing Print character buffer after storing the  values. can someone suggest me how to store integer value into charcter buffer and print result later.

    #include "glob.h"
    const int BUFFER_SZ = 32;
    char sendBuffer[60]={'0'};

    void Take_Reading() {

      for (int row = 0; row < 8; row++)
      {
        //   // get rid of me:
        digitalWrite(SO_enable, array[row][0]);
        digitalWrite(S1_enable, array[row][1]);
        digitalWrite(S2_enable, array[row][2]);
        delay(50);
        analog_1_pv[row] = ANALOG_SCALING * analogRead(A0);
        analog_2_pv[row] = ANALOG_SCALING * analogRead(A1);
        analog_3_pv[row] = ANALOG_SCALING * analogRead(A2);
        if ( (analog_1_pv[row] <= MINV_RANGE || (analog_1_pv[row] >= MAXV_RANGE) ))
        {
          Current_Value1[row] =  0.0;
        }
        else
        {
          Current_Value1[row] =  (analog_1_pv[row] * 12.5) - 31.25;

        }

        if (  (analog_2_pv[row] <= MINV_RANGE || (analog_2_pv[row] >= MAXV_RANGE) ))
        {
          Current_Value2[row] =  0.0;
        }
        else
        {
          Current_Value2[row] =  (analog_2_pv[row] * 12.5) - 31.25;

        }

        if (  (analog_3_pv[row] <= MINV_RANGE || (analog_3_pv[row] >= MAXV_RANGE) ))
        {
          Current_Value3[row] =  0.0;
        }
        else
        {
          Current_Value3[row] =  (analog_3_pv[row] * 12.5) - 31.25;

        }

        Mod_current[row] = (uint16_t)(Mul_Factor * Current_Value1[row]);
        Mod_current[row + 8] = (uint16_t)(Mul_Factor * Current_Value2[row]);
        Mod_current[row + 16] = (uint16_t)(Mul_Factor * Current_Value3[row]);

      }

    }

    int ID_Check() {

      int ID_value;
      for (int row = 0; row < 8; row++)
      {
        digitalWrite(SO_enable, array[row][0]);
        digitalWrite(S1_enable, array[row][1]);
        digitalWrite(S2_enable, array[row][2]);
        Status_Out[row] = digitalRead(Output_Read);

      }

      ID_value = 1 * Status_Out[7] + 2 * Status_Out[6] + 4 * Status_Out[5] + 8 * Status_Out[4] + 16 * Status_Out[3] + 32 * Status_Out[2] + 64 * Status_Out[1] + 128 * Status_Out[0];
      return (ID_value);

    }

    int  Take_Temp_Reading()
    {

      Temp_Total = Temp_Total - Temp_readings[Temp_index];
      Temp_readings[Temp_index] = analogRead(A5);
      Temp_Total = Temp_Total + Temp_readings[Temp_index];
      Temp_index = Temp_index + 1;

      if (Temp_index >= numReadings)
      {
        Temp_index = 0;
        Temp_Average = Temp_Total / numReadings;
      }
      temp = (Temp_Average * 5.0) / 1023.0;

      //  temp = float(analogRead(A5)) * 5.0 / 1024.0;
      temp_int = (int)(temp * 100.0);
      return (temp_int);
      // Serial.print("Temp"); Serial.println(temp);
    }

    int SPD_Check()
    {

      SPD_STATUS = digitalRead(SPD_STATUS_PIN);
      return (SPD_STATUS);
    }

    int  DC_Status()
    {

      DC_STATUS = digitalRead(DC_STATUS_PIN);
      return (DC_STATUS);

    }

    int   Take_HV_Reading()
    {

      //int analog_int= analogRead(A4);

      total = total - readings[index];
      // read from the sensor:
      readings[index] = analogRead(A4);
      // add the reading to the total:
      total = total + readings[index];
      // advance to the next position in the array:
      index = index + 1;

      // if we're at the end of the array...
      if (index >= numReadings1)
      {
        index = 0;
        average = total / numReadings1;

      }
      else
      {

        HV_voltage = (average * 5.0) / 1023.0;
      }
      if (HV_voltage <= 0.25)
      {

        Conv_HV_voltage = 0.0;
      }
      else
      {
        Conv_HV_voltage = 197.837837838 * HV_voltage + 10.8108108108;
      }

      HV_Reading = (uint16_t)(Conv_HV_voltage * 10);

      //  HV_Reading = (uint16_t)(Conv_HV_voltage * 10);

      return(HV_Reading);
    }

    void  Serial_Command1()

    {
       Take_Reading();
      int Temp_read=Take_Temp_Reading();
      int HV_Read=Take_HV_Reading();
      SPD=SPD_Check();
      DISCONNECTOR=DC_Status();
      Serial.println("Command1 executed ");

      sendBuffer[1]=char(Mod_current[1]) ;
      sendBuffer[2]= ',';
      sendBuffer[2]= Mod_current[1];
      sendBuffer[3]= ',';

      sendBuffer[4]= Mod_current[2];
      sendBuffer[5]= ',';
      sendBuffer[6]= Mod_current[3];
      sendBuffer[7]= ',';

      sendBuffer[8]= Mod_current[4];
      sendBuffer[9]= ',';
      sendBuffer[10]= Mod_current[5];
      sendBuffer[11]= ',';

      sendBuffer[12]= Mod_current[6];
      sendBuffer[13]= ',';
      sendBuffer[14]= Mod_current[7];
      sendBuffer[15]= ',';

      sendBuffer[16]= Mod_current[8];
      sendBuffer[17]= ',';
      sendBuffer[18]= Mod_current[9];
      sendBuffer[19]= ',';

      sendBuffer[20]= Mod_current[10];
      sendBuffer[21]= ',';
      sendBuffer[22]= Mod_current[11];
      sendBuffer[23]= ',';

      sendBuffer[24]= Mod_current[12];
      sendBuffer[25]= ',';
      sendBuffer[26]= Mod_current[13];
      sendBuffer[27]= ',';

      sendBuffer[28]= Mod_current[23];
      sendBuffer[29]= ',';
      sendBuffer[30]= Mod_current[22];
      sendBuffer[31]= ',';

      sendBuffer[32]= Mod_current[21];
      sendBuffer[33]= ',';
      sendBuffer[34]= Mod_current[20];
      sendBuffer[35]= ',';

      sendBuffer[36]= Mod_current[19];
      sendBuffer[37]= ',';
      sendBuffer[38]= Mod_current[18];
      sendBuffer[39]= ',';

      sendBuffer[40]= Mod_current[17];
      sendBuffer[41]= ',';
      sendBuffer[42]= Mod_current[16];
      sendBuffer[43]= ',';

      sendBuffer[44]= Mod_current[15];
      sendBuffer[45]= ',';
      sendBuffer[46]= Mod_current[14];
      sendBuffer[47]= ',';
      sendBuffer[48]= Temp_read;
      sendBuffer[49]= ',';
      sendBuffer[50]= HV_Read;
      sendBuffer[51]= ',';
      sendBuffer[52]= SPD;
      sendBuffer[53]= ',';
      sendBuffer[54]= DISCONNECTOR;

      Serial.println(sendBuffer[1]);

    }

    void Serial_Command2(int a)
    {

      Serial.print("Command2 executed: ");
      Serial.println(a);
    }

    void setup()
    {
      Serial.begin(57600);
      Serial.println("Format 1: <SMCB1,1>");
      Serial.println("Format 2: <SMCB1,1,Length>");

    }

    // Parse the request, WITHOUT the '<' and '>' delimiters.
    void parseRequest(char *request)
    {
      // Check the request starts with the prefix "SMCB1,1".
      if (strncmp(request, "SMCB1,1", 7) != 0) {
        Serial.println(F("Error: bad request prefix"));
        return;
      }

      // Remove that known prefix.
      // Now we have either "", ",Length" or ",Timer,On_OFF"
      request += 7;

      // Format 1: ""
      if (request[0] == '\0') {
        //Serial.println(F("Received format 1"));
        Serial_Command1();
        return;
      }

      // Remove the leading comma.
      // Now we have either "Length" or "Timer,On_OFF"
      if (request[0] != ',') {
        Serial.println(F("Error: ',' expected"));
        return;
      }
      request++;

      // Format 2: "Length", no comma.
      char * comma = strchr(request, ',');
      if (!comma) {

        int length = atoi(request);
        Serial_Command2(length);
        //Serial.print(F("Received format 2, length = "));
        // Serial.println(length);
        return;
      }

    }

    void loop()
    {
      static char buffer[BUFFER_SZ];  // received chars
      static size_t pos;              // current position in buffer
      static bool insideRequest;      // are we between '<' and '>'?

      if (Serial.available()) {
        char c = Serial.read();
        if (insideRequest) {
          if (c == '>') {  // end of request received
            buffer[pos] = '\0';  // terminate the string
            parseRequest(buffer);
            pos = 0;             // get ready for the next request
            insideRequest = false;
          }
          else if (pos < BUFFER_SZ-1) {  // add char to buffer
            buffer[pos++] = c;
          }
        }
        else if (c == '<') {  // start of request
          insideRequest = true;
        }
      }
    }

Golb.h header file contains

    #ifndef GLOB_H
    #define GLOB_H
    int counter=0;
    int Mod_current[24];
    const int numReadings = 10;
    const int numReadings1 = 10;
    int Temp_Total = 0;
    int Temp_readings[numReadings];
    int Temp_index = 0;
    int Temp_Average = 0;
    float  reading[10];
    float Total = 0.0;
    static int i;

    int readings[numReadings];
    int index = 0;
    int total = 0;
    int average = 0;

    // These PinS are use to enable and disable analog MUX
    int SO_enable = 5;
    int S1_enable = 4;
    int S2_enable = 3;

    // temprature sensor permeter
    int TempPin = 5;
    float temp;
    static int temp_int;

    // digital mux setting
    int Output_Read = 2;

    float Vref = 2.5;
    // Used for sensor conversion
    float ANALOG_SCALING = 0.004887585532746823;
    //tempfloat ANALOG_SCALING=0.0049560117;

    int Sensor_Value0 = 0;
    int Sensor_Value1 = 0;
    int Sensor_Value2 = 0;
    float analog_1_pv[8];
    float analog_2_pv[8];
    float analog_3_pv[8];
    int Status_Out[8];

    //SPD & DC STATUS PIN
    static int SPD_STATUS_PIN = 6;
    static int DC_STATUS_PIN = 7;

    int row;

    int Mul_Factor = 10;

    float Current_Value1[8] = {
      0.0
    };
    float Current_Value2[8] = {
      0.0
    };
    float Current_Value3[8] = {
      0.0
    };

    //HV perameter setting are defined here
    int HV_SensorValue;
    int HV_Reading;
    float HV_voltage;
    float Conv_HV_voltage;
    unsigned  int DC_STATUS = 0;
    unsigned int SPD_STATUS = 0;
    float MINV_RANGE = 2.52;
    //float MIDV_RANGE1=1.875;
    float MAXV_RANGE = 4.5;

    int SPD;
    int DISCONNECTOR;

    int Serial_Status=0;

    int array[8][3] = {
      {
        0, 0, 0
      }
      , {
        0, 0, 1
      }
      , {
        0, 1, 0
      }
      , {
        0, 1, 1
      }
      , {
        1, 0, 0
      }
      , {
        1, 0, 1
      }
      , {
        1, 1, 0
      }
      , {
        1, 1, 1
      }
    };

    #endif

body:
The simple answer is: don't.

At the moment you are trying to assign integers to chars, and that just won't fit. It's like a round peg in a square hole. Or more like trying to force a bowling pin through a hose pipe. It just isn't going to fit.

So you either need to "print" the values into your final string (say with `sprintf()`) or just don't build up a string at all and print the values directly. And while you're at it, use some loops to make your code simpler:

    for (int i = 0; i < 14; i++) {
        Serial.print(Mod_current[i]);
        Serial.print(",");
    }

    for (int i = 23; i > 13; i--) {
        Serial.print(Mod_current[i]);
        Serial.print(",");
    }

    Serial.print(Temp_read);
    Serial.print(",");
    Serial.print(HV_Read);
    Serial.print(",");
    Serial.print(SPD);
    Serial.print(",");
    Serial.println(DISCONNECTOR);

If you really need to create a string the easiest way is probably with `sprintf` (or `snprintf` to prevent buffer overflows):

    char sendBuffer[200]; // Enough room for 28 integers of 1-5 characters, plus commas.

    snprintf(sendBuffer, 200, "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
        Mod_current[0], Mod_current[1], Mod_current[2], Mod_current[3],
        Mod_current[4], Mod_current[5], Mod_current[6], Mod_current[7],
        Mod_current[8], Mod_current[9], Mod_current[10], Mod_current[11],
        Mod_current[12], Mod_current[13], Mod_current[14], Mod_current[23],
        Mod_current[22], Mod_current[21], Mod_current[20], Mod_current[19],
        Mod_current[18], Mod_current[17], Mod_current[16], Mod_current[15],
        Mod_current[14], Temp_read, HV_Read, SPD, DISCONNECTOR);

    int len = strlen(sendBuffer);
    Serial.println(sendBuffer);
    Serial.print(len);
    Serial.println(" bytes");

(note: I think I got the right number of parameters there)


message:
Button Relay Control

How can I fix this sketch to make it so that once the button is pressed, it performs some action for a certain amount of time and then returns back to a low state until it is pressed again. For example, I need to run a pump for 5 seconds when the button is pressed and then turn off automatically. And then, when I press the button again it will repeat, etc. I am not trying to use a relay module if it is not necessary. Here is my current sketch and a Lab View of the components:

[![My Sketch][1]][1]

  [1]: https://i.stack.imgur.com/P3fk0.png
    #include <LiquidCrystal.h>
    #include <SoftwareSerial.h>

    int switchPin = 8;
    int ledPin = 13;
    int buttonPresses = 0;
    boolean lastButton = LOW;
    boolean currentButton = LOW;
    boolean ledOn = false;

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup()
    {
      Serial.begin(9600);
      pinMode(switchPin, INPUT);
      pinMode(ledPin, OUTPUT);
      lcd.begin(16, 2);
    }

    boolean debounce(boolean last) //just a debounce function
    {
      boolean current = digitalRead(switchPin);
      if (last != current)
      {
        delay(5);
        current = digitalRead(switchPin);
      }
      return current;
    }

    void loop()
    {
      {currentButton = debounce(lastButton);
      if (lastButton == LOW && currentButton == HIGH)
      {
        ledOn = !ledOn;

        buttonPresses++;
        lcd.clear();
        lcd.print("Number of Button ");
        lcd.setCursor(0,1);
        lcd.print("Presses = ");
        lcd.print(buttonPresses);
      }
       lastButton = currentButton;
       digitalWrite(ledPin, ledOn);
      }
    }

THANK YOU!

body:
This code should work. You will need to declare the following variables:

  * lastPress   // The last time the button was pressed
  * outputState  // The state of the timed output
  * outputPin  // The pin number for the timed output
  * PERIOD  // The amount of time that the outptu remains on

The code:

    void loop()
    {
        currentButton = debounce(lastButton);
        if (lastButton == LOW && currentButton == HIGH)
        {
            ledOn = !ledOn;

            buttonPresses++;
            lcd.clear();
            lcd.print("Number of Button ");
            lcd.setCursor(0,1);
            lcd.print("Presses = ");
            lcd.print(buttonPresses);

            outputState = HIGH;
            lastPress = millis();
        }

        if (outputState && ((millis() - lastPress) > PERIOD))
        {
            outputState = LOW;
        }

        digitalWrite(outputPin, outputState);

        lastButton = currentButton;
        digitalWrite(ledPin, ledOn);
    }

A relay should be used to drive a pump etc.. The Arduino Uno can only drive 5V at maximum 20mA.


message:
Can an ATtiny print results to a console?

I'm trying to port some Arduino code that I wrote for the Arduino Mega to an ATtiny and I'm having trouble figuring out how to do output. Here is what I have:

    char foo;
    #include <SoftwareSerial.h>
    const int rx=3;
    const int tx=4;

    SoftwareSerial mySerial(rx,tx);

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

    void loop() {
     if (mySerial.available()) {
       char data = mySerial.read();
       mySerial.write(data);
     }

     mySerial.println("hello");
    }

To my understanding this should print "hello" to the console over and over again but for some reason it uploads successfully but then it doesn't do anything.

Here is the programmer that I am using to connect my ATtiny to my computer: https://learn.sparkfun.com/tutorials/tiny-avr-programmer-hookup-guide/programming-in-arduino

body:
This is writing serial data to digital pin 4. If you have a serial to USB converter attached to pins 3,4 and you have a terminal attached to said serial to USB converter, it will print to that terminal.

Also, on an ATtiny, you have to check which pins are pins 3,4. They are probably not the physical pins 3,4, and it is dependent on which pin mappings you are using (dependent on ATtiny libraries).


body: You don't have any output because you don't have a serial adapter connected to the device. The programmer you have is only for programming and does not support a UART serial connection.


message:
Fan control circuit with Arduino

I have a fan control circuit with Arduino (PWM). I did all things and it worked. My question is why we did not directly connect the fan to Arduino. Why should we have a driver circuit?

![][1]

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

body:
This is an electronics question, and it should be forwarded to the electronics stackexchange.

The fan needs to have a proper amount of current to spin, and because the microcontroller that controls the fan draw very little current on its output pins (check the datasheet for the exact value, but it should be a few milliamps), unless you have a miniature fan, wiring it directly on the microcontroller will not be able to move the fan.

And this is by design that microcontrollers cannot provide much current. Because to provide larger amount of current than what they do, they'd need to have bigger copper tracks between the transistor to avoid having they internal circuits building too much heat, and they would be much much bigger.

So as a work around, we use an transistor, which receives on the "Base" pin a voltage, drawing almost no current, which will "connect" the collector and emitter pins where you can have a much bigger current flowing (though be careful to respect the datasheet's nominal values for current! Or use either a MOSFET, a Triac or a Relay for bigger currents).


body:
Arduino is a low voltage and low current device. Arduino max current output delivery capecity is 200ma, you can read about diffrent arduino's limitations here,
http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations

**Fan or anything that** has a coil inside it, needs a huge amount of current during their start up. The current draw decreases as it gains its motion to some limit. The initial huge current is called **surge current**. There is a high chance that it will blow you pins dead.

Let's say we are using really small fan. And it managed to start and rotating, that dosen't meant there is no problem at all. When a coil is rotated inside a magnetic field an opposite voltage is induced called **Back Emf** . This is **another** huge **potential concern**. This is why we are always suggested to use a **diode** which will **block** the opposite flow of **current**.

**Transistor**, being a low voltage device and as it can deliver tremendous large amount of output current, It is very widely used to drive high current devices


body:
The

    Vin pin = 5V or 3.3V

You cannot use the 5V from the USB to power up the FAN and the LOAD because the USB port usually delivers only 100mA, and this is not enough to switch the relay and the LOAD.
That is why you must use an external power supply (Vcc) that is between 7 to 12 volts to power up the Arduino board and the transistor + relay. The load uses its own power supply, for instance if you use a light bulb then you might connect it to the 110/220V mains or any other power source.

**or**

you can also use a fan that has one of the pins of the fan is a PWM input. The fan has an internal transistor to switch the 12V power when given a 0-5V input. That is the pin you want to connect to the actuator pin.

**please get back to me if it was helpful**


body:
Actually the Arduino Uno dc current per I/O pin is 40mA. When fan is connected directly to Arduino Uno, it cannot withstand, because the fan draws more-than `20mA` current.

The driver circuit provides sufficient current to rotate the fan. The `TIP 121` can withstand up to `3A` current.