# Question
Title: Capturing images from OV7670 (w/o FIFO) using Arduino Uno?
I want to capture images from my OV7670 (w/o FIFO) and send it to my PC via Wi-Fi (ESP8266) (which I know how to use) using an Arduino Uno. I have read so many blogs and threads on the internet but couldn't find a simple and exact solution for the problem. I am a newbie in this and all I want is the simple wiring schema, code that can be used with Arduino IDE and the direction on how to proceed.

I found this random code. Please see if I can use it.

```
    #include <Wire.h>
    #include <Ethernet.h>
    #include <SPI.h>
    uint8_t sensor_addr = 0x42;

    //************ REGISTRADORES **********************//

    #define REG_COM1    0x04    /* Control 1 */

    #define REG_COM7    0x12    /* Control 7 */

    #define   COM7_RESET      0x80    /* Register reset */

    #define   COM7_FMT_MASK   0x38

    #define   COM7_FMT_VGA    0x00

    #define   COM7_FMT_CIF    0x20    /* CIF format */

    #define   COM7_FMT_QVGA   0x10    /* QVGA format */

    #define   COM7_FMT_QCIF   0x08    /* QCIF format */

    #define   COM7_RGB    0x04    /* bits 0 and 2 - RGB format */

    #define   COM7_YUV    0x00    /* YUV */

    #define   COM7_BAYER      0x01    /* Bayer format */

    #define   COM7_PBAYER     0x05    /* "Processed bayer" */

    #define REG_RGB444  0x8c    /* RGB 444 control */

    #define   R444_ENABLE     0x02    /* Turn on RGB444, overrides 5x5 */

    #define   R444_RGBX   0x01    /* Empty nibble at end */

    #define REG_COM9    0x14    /* Control 9  - gain ceiling */

    #define REG_COM10   0x15    /* Control 10 */

    #define REG_COM13   0x3d    /* Control 13 */

    #define   COM13_GAMMA     0x80    /* Gamma enable */

    #define   COM13_UVSAT     0x40    /* UV saturation auto adjustment */

    #define   COM13_UVSWAP    0x01    /* V before U - w/TSLB */

    #define REG_COM15   0x40    /* Control 15 */

    #define   COM15_R10F0     0x00    /* Data range 10 to F0 */

    #define   COM15_R01FE     0x80    /*            01 to FE */

    #define   COM15_R00FF     0xc0    /*            00 to FF */

    #define   COM15_RGB565    0x10    /* RGB565 output */

    #define   COM15_RGB555    0x30    /* RGB555 output */

    #define REG_COM11   0x3b    /* Control 11 */

    #define   COM11_NIGHT     0x80    /* NIght mode enable */

    #define   COM11_NMFR      0x60    /* Two bit NM frame rate */

    #define   COM11_HZAUTO    0x10    /* Auto detect 50/60 Hz */

    #define   COM11_50HZ      0x08    /* Manual 50Hz select */

    #define   COM11_EXP   0x02

    #define REG_COM16   0x41    /* Control 16 */

    #define   COM16_AWBGAIN   0x08    /* AWB gain enable */

    #define REG_COM17       0x42    /* Control 17 */

    #define COM17_AECWIN    0xc0    /* AEC window - must match COM4 */

    #define COM17_CBAR      0x08    /* DSP Color bar */

    #define REG_TSLB    0x3a    /* lots of stuff */

    #define   TSLB_YLAST      0x04    /* UYVY or VYUY - see com13 */

    #define MTX1            0x4f    /* Matrix Coefficient 1 */

    #define MTX2            0x50    /* Matrix Coefficient 2 */

    #define MTX3            0x51    /* Matrix Coefficient 3 */

    #define MTX4            0x52    /* Matrix Coefficient 4 */

    #define MTX5            0x53    /* Matrix Coefficient 5 */

    #define MTX6            0x54    /* Matrix Coefficient 6 */

    #define REG_CONTRAS     0x56    /* Contrast control */

    #define MTXS            0x58    /* Matrix Coefficient Sign */

    #define AWBC7           0x59    /* AWB Control 7 */

    #define AWBC8           0x5a    /* AWB Control 8 */

    #define AWBC9           0x5b    /* AWB Control 9 */

    #define AWBC10          0x5c    /* AWB Control 10 */

    #define AWBC11          0x5d    /* AWB Control 11 */

    #define AWBC12          0x5e    /* AWB Control 12 */

    #define REG_GFIX        0x69    /* Fix gain control */

    #define GGAIN           0x6a    /* G Channel AWB Gain */

    #define DBLV            0x6b

    #define AWBCTR3         0x6c    /* AWB (Automatic White Balance) Control 3 */

    #define AWBCTR2         0x6d    /* AWB Control 2 */

    #define AWBCTR1         0x6e    /* AWB Control 1 */

    #define AWBCTR0         0x6f    /* AWB Control 0 */

    #define REG_COM8    0x13    /* Control 8 */

    #define   COM8_FASTAEC    0x80    /* Enable fast AGC/AEC (Automatic Gain Control - Automatic Exposure Control)*/

    #define   COM8_AECSTEP    0x40    /* Unlimited AEC step size */

    #define   COM8_BFILT      0x20    /* Band filter enable */

    #define   COM8_AGC    0x04    /* Auto gain enable */

    #define   COM8_AWB    0x02    /* White balance enable */

    #define   COM8_AEC    0x01    /* Auto exposure enable */

    #define REG_COM3        0x0c    /* Control 3 */

    #define COM3_SWAP       0x40    /* Byte swap */

    #define COM3_SCALEEN    0x08    /* Enable scaling */

    #define COM3_DCWEN      0x04    /* Enable downsamp/crop/window */

    #define REG_BRIGHT      0x55    /* Brightness */

    #define REG_COM14      0x3E

    //*************************************************************************//

    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // MAC do arduino
    IPAddress ip(192,168,0,120); // IP do arduino
    byte server[] = {
      192,168,0,105}; //Endereço do servidor

    void setup (){

      DDRC&=~15;//low d0-d3 camera  PORTC (pino A0 ao pino A5) (11110000) A0 a A3 como entrada e A4 (SDA) e A5 (SCL) como saídas - essa linha tem a mesma função de pinMode que declara quem
      //é pino de saída e de entrada. Se for 0 é entrada e se for 1 é saída. O valor é não 15 (acima).
      DDRD&=~255;//d7-d4 and interupt pins PORTD (pino 0 ao pino 7) (0000 d7 ao d4           0=d3=vsync 0=d2=pclock               0=d1=href   1=d0=button)

      DDRB&=~1;

      Serial.begin(57600);
      Wire.begin();

      UCSR0B = (1<<RXEN0)|(1<<TXEN0);//Enable receiver and transmitter (habilita bit 4 e bit 3)

      UCSR0C=6;// B (00000110) async (b7 e b6 = 00); (b3 = 0) 1 stop bit; (b2 e b1 = 1)  8bit char; no parity bits (b5 e b4 = 00); (b0 = 0)clock polaridade

      //set up twi for 100khz
      TWSR&=~3;//disable prescaler for TWI
      TWBR=72;//set to 100khz

      //SET UP CAMERA
      wrReg(0x15,32);//pclk does not toggle on HBLANK COM10 vsync falling
      //wrReg(0x15,0);//pclk does not toggle on HBLANK COM10 vsync falling
      wrReg(REG_RGB444, 0x00);             // Disable RGB444
      wrReg(REG_COM11,226);//enable nigh mode 1/8 frame rate COM11*/
      wrReg(REG_TSLB,0x04);                // 0D = UYVY  04 = YUYV
      wrReg(REG_COM13,0x88);               // connect to REG_TSLB
      //definição para o RGB 565
      wrReg(REG_COM7, 0x04);           // RGB + color bar disable
      wrReg(REG_COM15, 0xD0);          // Set rgb565 with Full range    0xD0

        wrReg(REG_COM3,0);    // REG_COM3

      wrReg(0x32,0xb6);        // HREF
      wrReg(0x17,0x13);        // HSTART
      wrReg(0x18,0x01);        // HSTOP
      wrReg(0x19,0x02);        // VSTART
      wrReg(0x1a,0x7a);        // VSTOP
      wrReg(0x03,0x0a);        // VREF

      wrReg(REG_COM1, 0x00);

      //COLOR SETTING
      wrReg(REG_COM8,0x8F);        // AGC AWB AEC Unlimited step size
      wrReg(0xAA,0x14);            // Average-based AEC algorithm
      wrReg(REG_BRIGHT,0x00);      // 0x00(Brightness 0) - 0x18(Brightness +1) - 0x98(Brightness -1)
      wrReg(REG_CONTRAS,0x40);     // 0x40(Contrast 0) - 0x50(Contrast +1) - 0x38(Contrast -1)
      // wrReg(0xB1,0xB1);            // Automatic Black level Calibration
      wrReg(0xB1,4);//really enable auto black level calibration
      wrReg(MTX1,0x80);
      wrReg(MTX2,0x80);
      wrReg(MTX3,0x00);
      wrReg(MTX4,0x22);
      wrReg(MTX5,0x5e);
      wrReg(MTX6,0x80);
      wrReg(MTXS,0x9e);
      wrReg(AWBC7,0x88);
      wrReg(AWBC8,0x88);
      wrReg(AWBC9,0x44);
      wrReg(AWBC10,0x67);
      wrReg(AWBC11,0x49);
      wrReg(AWBC12,0x0e);
      wrReg(REG_GFIX,0x00);
      //wrReg(GGAIN,0x40);
      wrReg(AWBCTR3,0x0a);
      wrReg(AWBCTR2,0x55);
      wrReg(AWBCTR1,0x11);
      wrReg(AWBCTR0,0x9f);

      wrReg(0xb0,0x84);//not sure what this does
      wrReg(REG_COM16,COM16_AWBGAIN);//disable auto denoise and edge enhancment
      //wrReg(REG_COM16,0);
      wrReg(0x4C,0);//disable denoise
      wrReg(0x76,0);//disable denoise
      wrReg(0x77,0);//disable denoise
      wrReg(0x7B,4);//brighten up shadows a bit end point 4
      wrReg(0x7C,8);//brighten up shadows a bit end point 8
      //wrReg(0x88,238);//darken highligts end point 176
      //wrReg(0x89,211);//try to get more highlight detail
      //wrReg(0x7A,60);//slope
      //wrReg(0x26,0xB4);//lower maxium stable operating range for AEC
      //hueSatMatrix(0,100);
      //ov7670_store_cmatrix();
      //wrReg(0x20,12);//set ADC range to 1.5x
      wrReg(REG_COM9,0x6A);//max gain to 128x
      wrReg(0x11,9);//using scaler for divider
      delay(100);//i2c uses interupts to write data wait for all bytes to be written

      //            #ifdef qqvga || ifdef qvga

      wrReg(REG_COM3,4);    // REG_COM3

      //    #ifdef qqvga

      wrReg(REG_COM14, 0x1a);          // divide by 4

      wrReg(0x72, 0x22);               // downsample by 4

      wrReg(0x73, 0xf2);               // divide by 4

      wrReg(0x17,0x16);

      wrReg(0x1A,0x04);

      wrReg(0x32,0xa4);

      wrReg(0x19,0x02);

      wrReg(0x18,0x7a);

      wrReg(0x03,0x0a);

      wrReg(REG_COM1, 0x00);

      // COLOR SETTING

      wrReg(REG_COM8,0x8F);        // AGC AWB AEC Unlimited step size

      wrReg(0xAA,0x14);            // Average-based AEC algorithm

      wrReg(REG_BRIGHT,0x00);      // 0x00(Brightness 0) - 0x18(Brightness +1) - 0x98(Brightness -1)

      wrReg(REG_CONTRAS,0x40);     // 0x40(Contrast 0) - 0x50(Contrast +1) - 0x38(Contrast -1)

      // wrReg(0xB1,0xB1);            // Automatic Black level Calibration

      wrReg(0xB1,4);//really enable auto black level calibration

      wrReg(MTX1,0x80);

      wrReg(MTX2,0x80);

      wrReg(MTX3,0x00);

      wrReg(MTX4,0x22);

      wrReg(MTX5,0x5e);

      wrReg(MTX6,0x80);

      wrReg(MTXS,0x9e);

      wrReg(AWBC7,0x88);

      wrReg(AWBC8,0x88);

      wrReg(AWBC9,0x44);

      wrReg(AWBC10,0x67);

      wrReg(AWBC11,0x49);

      wrReg(AWBC12,0x0e);

      wrReg(REG_GFIX,0x00);

      //wrReg(GGAIN,0x40);

      wrReg(AWBCTR3,0x0a);

      wrReg(AWBCTR2,0x55);

      wrReg(AWBCTR1,0x11);

      wrReg(AWBCTR0,0x9f);

      wrReg(0xb0,0x84);//not sure what this does

      wrReg(REG_COM16,COM16_AWBGAIN);//disable auto denoise and edge enhancment

      //wrReg(REG_COM16,0);

      wrReg(0x4C,0);//disable denoise

      wrReg(0x76,0);//disable denoise

      wrReg(0x77,0);//disable denoise

      wrReg(0x7B,4);//brighten up shadows a bit end point 4

        wrReg(0x7C,8);//brighten up shadows a bit end point 8

        //wrReg(0x88,238);//darken highligts end point 176

      //wrReg(0x89,211);//try to get more highlight detail

      //wrReg(0x7A,60);//slope

      //wrReg(0x26,0xB4);//lower maxium stable operating range for AEC

      //hueSatMatrix(0,100);

      //ov7670_store_cmatrix();

      //wrReg(0x20,12);//set ADC range to 1.5x

      wrReg(REG_COM9,0x6A);//max gain to 128x

      //    #ifdef qvga

      wrReg(0x11,4);//using scaler for divider

      pinMode(4,OUTPUT);
      digitalWrite(4,HIGH);
      Serial.println("Iniciando conexao");
      Ethernet.begin(mac, ip);
      Serial.println("Por favor, espere.");
      delay(1000);

    }

    EthernetClient client;
    void loop (){

    connectWeb(7000,server);
    foto(480,640);

    }

    byte wrReg(int regID, int regDat )

    {

      Wire.beginTransmission(sensor_addr >> 1);
      Wire.write(regID & 0x00FF);
      Wire.write(regDat & 0x00FF);
      if(Wire.endTransmission())
      {
        return 0;
        PORTB|=32;
        while (1) {
        }
      }
      delay(1);
      return(1);
    }

    uint16_t d;

    void foto(uint16_t linha, uint16_t coluna)
    {
      while (!(PIND&8)) {
      }//wait for high
      while ((PIND&8)) {
      }//wait for low
      //uint16_t a =millis(); //teste de tempo
      if (linha != 0)
      {
        //while (!(PINB&1)) {}//wait for high
        //while ((PINB&1)) {}//wait for low
        //while (!(PINB&1)) {}//wait for high

        while (linha--)
        {

          while (!(PIND&4)) {
          }//wait for high
          while ((PIND&4)) {
          }//wait for low
          //      int a = millis(); //teste de tempo

          uint16_t byte1, byte2;
          uint8_t buf[512];

          uint16_t  coluna_temp=coluna;
          while (coluna--){

            for(int i=0; i<2;i++){
              while (!(PIND&4)) {
              }//wait for high
              if(i==0){
                byte1= (uint8_t)(PINC&15)|(PIND&240); //B 00001111 (A0 a A3) ou 11110000 (d7 ao d4)
              }
              else{
                byte2= (uint8_t)(PINC&15)|(PIND&240);

                //((byte1<<8)|byte2);
               /* for(int x=0;x<512;x++){
                  buf[x]= (((byte1<<8)|byte2),BIN);
                  d+=buf[x];
                }*/
            sendMsg(client, ((byte1<<8)|byte2));
                //Serial.println(d);

                // Serial.println(((byte1<<8)|byte2),BIN); //B 00001111 (A0 a A3) ou 11110000 (d7 ao d4)
                //teste++;
              }
              while ((PIND&4)) {
              }//wait for low
            }

          }
          //                                        int b = millis(); //teste de tempo
          //  Serial.println((b-a)); //teste de tempo
          coluna=coluna_temp;
        }

        //while ((PIND&1)) {}//wait for low

      }
      //uint16_t b =millis(); //teste de tempo
      //Serial.println((b-a)); //teste de tempo
     // return teste;

    }

    void connectWeb(int port, byte ipServer[]){

      if (client.connect(ipServer,port)){
        Serial.println("Conectado");
        //essa e a parte que da erro. Perceba que estou enviando a mensagem
        //aqui, mas a intençao e enviar na funcao de tirar a foto.Aqui e teste
       // sendMsg(client, 800);

      }else{
        Serial.println("Conexao falhou");
      }

       if (!client.connected()) {
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();

        // do nothing forevermore:
        while(true);
      }

    }

    //void sendMsg(EthernetClient client, uint8_t msg){
    //      client.println("valor "+String(msg));
    //}

    void sendMsg(EthernetClient client, uint32_t msg){
          client.println(msg,DEC);
    }

```

# Answer
You should start from connecting Arduino UNO to PC. For this purpose use the following article: Arduino Uno и камера ov7670 — пример использования. You can disregard the longer text in Russian on top, it discusses why choose exactly this camera.

As listed in that source, the main problems you will find are:

1. The camera input current is not 100% compatible with the Arduino current. You will need to use resistors. The linked blog includes a schematic how to connect both.
2. You will need to write code for connecting both. There are examples on the Internet. You can also see the code used in the link. The main gotcha here is that the camera works in YUV mode. Each pixel in that format is coded with two bytes. The first byte codes the grey gradient, the second carries the chroma information. For a simple test, it is sufficient to get a greyscale image, so discard the second byte.

The oscillograms in the linked site show the signal we are expecting, followed by the code needed to read the image information.

3. The actual program for getting the image can be very simple. The author of the linked article wrote one. It reads from COM9, uses Java communication API and saves in bmp. You can download it here.

This simple test connection has following disadvantages:

* Without buffering, the picture smears
* There are synchronisation artefacts in the image
* You cannot change the focus, the subject has to be kept at the camera's focused distance.

---

Transferring data via Wi-Fi will be the next step. But it will be hard because Uno and Wi-Fi module are connected via UART interface and maximum speed is limited to 230.4Kbps.

Here is example how to transmit image via bluetooth, Передача картинки с OV7670 через Arduino Uno на Android телефон. It maybe useful to you.

It assumes that you have connected the Arduino and the camera as described above, as step 1.

In step 2, you have to solve the problem of speed mismatch. The HC-06 UART interface and the Arduino Uno have following speeds:

> HC-06: 1200 / 2400 / 4800 / 9600 / 19200 / 38400 / 57600 / 115200 / 230400 / 460800 / 921600 / 1382400
>
> Arduino Uno: 2400 / 4800 / 9600 / 14400 / 19200 / 28800 / 38400 / 57600 / 76800 / 115200 / 230400 / 250000 / 500000 / 1000000 / 2000000

The maximum speed common to both is 230400, so you have to use that. You then need to reduce the internal processing speed with `wrReg(0x11, 31);`. You still cannot send at 230400, because the picture is sent in two steps, first the even rows, then the odd ones. You have to write the Arduino application to capture the image.

Finally, you can write the phone software. It only has to read the picture and show it on the page, nothing more. On a Bluetooth 2.1, the blog author measured more than 1 minute per frame, and the result was highly distorted. On Bluetooth 4.0, the picture quality was acceptable, and sending took less than 15 sec per frame.
> 2 votes

# Answer
translation from page: http://privateblog.info/arduino-uno-i-kamera-ov7670-primer-ispolzovaniya/ (consult links in the original link as I couldn't post them because I need at least 10 reputation blah blah blah)

**Arduino Uno and camera ov7670 - an example of use (December 15, 2015)**

Currently, the ov7670 is the most affordable image acquisition module for Arduino fans. Once it cost about $ 12, now its price dropped to less than $ 5.

ov7670 ( datasheet ) has good opportunities for its price:

> 1. different resolution VGA (640 x 480); - QVGA (320 x 240); - CIF (352 x 240); - QCIF (176 × 144);
> 2. transmission speed up to 30 fps,
> 3. several ways to encode an image RAW RGB, RGB 565/555, YUV / YCbCr 4: 2: 2
> 4. interface interaction I2C.

It would be ideal if not for one problem - connecting and getting at least a test image, as in any more or less complex hardware. There are a lot of discussions on the Internet, articles, recommendations, but it's impossible to find clear steps: someone is lazy to write them, someone lays only a diagram or code, somebody does not spread anything at all, but reports only about successful connection. Especially it would be desirable to note ComputerNerd which has laid out fine example with the small description, but for the beginner it is not enough.

This article is intended to show how to connect, configure and get a test image using a small program on java, which will be an excellent starting point for further experiments.

I conducted my experiments on Arduino Uno, as it was best described - connection schemes and articles. There was an attempt to set up on Arduino Mega, but it ended badly. It turned out that on the scaffold A4 and A5 this board already has a reference voltage of 5v, which burned the camera.

In my example, the camera will be used

> * AtmelStudio + arduino plugin
> * ov7670 without buffer, operating mode qvga (320 × 240), encoding YUV
> * Arduino Uno
> * 2 resistors per 10kΩ
> * 2 resistors at 4.7 kΩ
> * a computer.

1. Connection scheme for ov7670 to Arduino Uno

Programming the camera needs to start with the correct connection. The voltage of the camera inputs differs from Arduino voltage in places, so resistors are needed.

Connection scheme ov7670 to Arduino Uno

2. The program for ov7670 and Arduino Uno

To compile the program, we used an example from ComputerNerd, which had to be cut off a bit and then replaced in places. The code can be downloaded from the link .

The basic steps in the code are as follows:

1. Setting the Arduino Uno PWM, so that it gives out 8mhz on the 11th leg.

> DDRB | = (1 \<\< 3); // pin 11
>
> ASSR & = ~ (\_BV (EXCLK) | \_BV (AS2));
>
> TCCR2A = (1 \<\< COM2A0) | (1 \<\< WGM21) | (1 \<\< WGM20);
>
> TCCR2B = (1 \<\< WGM22) | (1 \<\< CS20);
>
> OCR2A = 0; // (F\_CPU) / (2 * (X + 1))
>
> DDRC & = ~ 15; // low d0-d3 camera
>
> DDRD & = ~ 252; // d7-d4 and interrupt pins

2. Configuring the I2C Interface

> TWSR & = ~ 3; // disable prescaler for TWI
>
> TWBR = 72; // set to 100khz

3. Configuring RS232.

> UBRR0H = 0;
>
> UBRR0L = 1; // 0 = 2M baud rate. 1 = 1M baud. 3 = 0.5M. 7 = 250k 207 is 9600 baud rate.
>
> UCSR0A | = 2; // double speed aysnc
>
> UCSR0B = (1 \<\< RXEN0) | (1 \<\< TXEN0); // Enable receiver and transmitter
>
> UCSR0C = 6; // async 1 stop bit 8bit char no parity bits

4. Camera setup

> ....
>
> wrReg (0x12, 0x80);
>
> delay\_ms (100);
>
> wrSensorRegs8\_8 (ov7670\_default\_regs);
>
> wrReg (REG\_COM10, 32); // PCLK does not toggle on HBLANK.
>
> ...

5. Obtaining an Image

The operating mode of the image transmission camera was set to YUV. In this case, each pixel is encoded with two bytes. The first byte encodes the gradation of gray, the second - color-difference component.

The task for us is to get at least a black and white image, so the second byte can be discarded.

Next, we need to bring an oscillogram from which it becomes clear what signals we expect with high and low values.

oscillogram ov7670

```
StringPgm (PSTR ( "* RDY *" ));

// VSYNC
while  (! (PIND &  8 )); // wait for high
while  ((PIND &  8 )); // wait for low

y = hg;
while  (y -) {
   x = wg;
   while  (x -) {
      // PCLK
      while  ((PIND &  4 )); // wait for low
      UDR0 = (PINC &  15 ) | (PIND &  240 );
      while  (! (UCSR0A & ( 1  << UDRE0))); // wait for byte to transmit
      while  (! (PIND &  4 )); // wait for high
      while  ((PIND &  4 )); // wait for low
      while  (! (PIND &  4 )); // wait for high
   }
}
_delay_ms ( 100 );

```
3. The program on java to get the image from ov7670 via Arduino Uno

The program for obtaining images is extremely simple. It receives data from the COM9 port using the Java Communication API and saves it as bmp. All variables are set directly in the code, so you'll have to change it to your own.

grabber

4. Results

On the basis of the images you can immediately draw a conclusion about the shortcomings:

> 1. The lack of an internal buffer leads to the blurring of the picture, it is immediately transferred to the computer, and this takes time.
> 2. There are artifacts in the form of horizontal stripes - synchronization failure in obtaining a picture. Instead of the gradation of gray sent tsvetraznostnaya component.
> 3. The subject must be in the focus of the camera for a clear image

This article can be finished. Waiting for comments and suggestions.
> 1 votes

---
Tags: arduino-uno, esp8266
---


# Question
Title: How do I create boundaries for the possible values of an integer?
I want to create an integer whose total value cannot go beyond a range of numbers when added to and subtracted from. For example, if the "total\_value" started at 0 (of a total possible range between -5 and 5), and then, using a button that added 1 to the total value, I got to 5, if I was to press it again it would not go to six but either reset to 5 or block another input of +1.

How would I go about achieving something to this effect?

Liam

# Answer
You are probably looking for the constrain() macro (an existing implantation of clamp logic, credit goes to @Edgar Bonet)

```
value = constrain(value + input, -5, 5);

```

---

If you get tired of writing `constrain()` you can even wrap it in a new type (which might be over-engeneering), producing something like following(code not tested)

```
template<typename T>
struct BoundValue {
    T value;
    const T vmin, vmax;
    //similar for other operators +,/,-=,...
    decltype(*this)& operator+=(T operand) { value = constrain(value + operand, vmin, vmax); return *this; }
    operator T() const { return value; }
    BoundValue(const T& vmin, const T& vmax) : vmin(vmin), vmax(vmax) {}
    BoundValue& operator=(const T& other) { value = constrain(other, vmin, vmax); return *this; }
};

```

and use like variable of its argument type

```
BoundValue<int> val(-5, 5);
val += 6;//val = 5

```
> 2 votes

# Answer
For adding:

```
total_value = total_value + 1;
if (total_value > 5)
  total_value = 5;

```

And for subtracting:

```
total_value = total_value - 1;
if (total_value < -5)
  total_value = -5;

```

You may find a C or C++ tutorial very helpful.

---

Another method for adding:

```
if (total_value < 5)
  total_value++;

```

And for subtracting:

```
if (total_value > -5)
  total_value--;

```
> 1 votes

# Answer
You can not create a number with arbitrary upper and lower limits. It is common in the C language to create an integer comprised of 16 bits. Such an integer has a minimum of:

```
-(2^15) = -32768

```

...and maximum of:

```
(2^15) - 1 = +32767

```

Instead, after pressing the positive button, consider testing if "total\_value" is 5 and skipping adding 1 to "total\_value" if TRUE. Conversely, after pressing the negative button, consider testing if "total\_value" is -5 and skipping subtracting 1 from "total\_value" if TRUE.
> 0 votes

---
Tags: arduino-mega, programming, calculation
---


title: Very long delay() possible?

text:
# Question
Title: Very long delay() possible?
I'm trying to make an opening and closing little door that should open or close every 12 hours. I was wondering if I could just make a small looping script with a delay() for 12 hours, delay(43 200 000 000); I guess? However, I have no idea if that's possible and/or recommendable. Some feedback/alternatives(if needed) would be nice :)

# Answer
> 10 votes
The real time clock method is the most accurate way but otherwise use `millis`

```
unsigned long startMillis = millis();
while (millis() - startMillis < LONG_DELAY_MS);

```

This will delay up to approx. 4294967295ms (2^32-1) or 49 days, after which the timer will catch up to the value of `startMillis`

# Answer
> 7 votes
`delay()` has its uses, but for long delays it's no good. It simply tells the microcontroller to do nothing for `x` clock cycles. During that time, your Arduino can't do anything else.

Your best bet would be to use a thing called a Real Time Clock (RTC). These chips are specifically made to keep track of time, and you can connect them to your Arduino with ease. Here's an example of how you could do that.

# Answer
> 7 votes
You could use the watchdog interrupt and have your MCU sleep while waiting and save power.

But notice that you'll only save power if your board also saves it. That means you have to have a low quiescent voltage regulator instead of the usual regulators that equip the most common Arduino boards, such as the Uno. Otherwise, it doesn't matter whether your MCU saves energy if your board doesn't.

Here's the code (untested):

```
#include <avr/sleep.h>
// This variable is made volatile because it is changed inside an interrupt function
volatile int sleep_count = 0; // Keep track of how many sleep cycles have been completed.
const int interval = 720; // Interval in minutes between waking and doing tasks.
const int sleep_total = (interval*60)/8; // Approximate number of sleep cycles
// needed before the interval defined above elapses. Not that this does integer math.

void setup(void) {
    watchdogOn(); // Turn on the watch dog timer.
    // Disable the ADC by setting the ADEN bit (bit 7) to zero.
    ADCSRA = ADCSRA & B01111111;
    // Disable the analog comparator by setting the ACD bit (bit 7) to one.
    ACSR = B10000000;
    // Disable digital input buffers on all analog input pins by setting bits 0-5 to one.
    DIDR0 = DIDR0 | B00111111;
}

void loop(void) {
    goToSleep(); // ATmega328 goes to sleep for about 8 seconds
    // and continues to execute code when it wakes up
    if (sleep_count == sleep_total) {
        // CODE TO BE EXECUTED PERIODICALLY
    }
}

void goToSleep() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Set sleep mode.
    sleep_enable(); // Enable sleep mode.
    sleep_mode(); // Enter sleep mode.
    // After waking from watchdog interrupt the code continues
    // to execute from this point.
    sleep_disable(); // Disable sleep mode after waking.
}

void watchdogOn() {
    // Clear the reset flag, the WDRF bit (bit 3) of MCUSR.
    MCUSR = MCUSR & B11110111;
    // Set the WDCE bit (bit 4) and the WDE bit (bit 3) of WDTCSR.
    WDTCSR = WDTCSR | B00011000;
    // Set the watchdog timeout prescaler value to 1024 K
    // which will yeild a time-out interval of about 8.0 s.
    WDTCSR = B00100001;
    // Enable the watchdog timer interupt.
    WDTCSR = WDTCSR | B01000000;
    MCUSR = MCUSR & B11110111;
}

ISR(WDT_vect)
{
    sleep_count ++; // keep track of how many sleep cycles have been completed.
}

```

The code I copied is from this page: Low-Power Arduino Using the Watchdog Timer.

# Answer
> 1 votes
Do you have a sleep(unsigned int seconds) available?

If not, this would allow you to delay() a very long time:

```
for (unsigned int bigloop=0; bigloop<65535; bigloop++)
{
   for (unsigned int smallloop=0; smallloop<65535; smallloop++)
   {
      for (unsigned int tinyloop=0; tinyloop<65535; tinyloop++)
      {
         delay(65535);
      }
   }
}

```

# Answer
> 1 votes
This will work:

```
longDelayInSeconds = 120; //two minutes;
while (p < longDelayInSeconds) {

        delay(1000);
        p++;

}

```

# Answer
> 1 votes
I just use for loops when I don't want to do stuff in between:

```
for (int Hours = 0; Hours < 12; Hours++) {            //Creates 12 hours
  for (int Minutes = 0; Minutes < 60; Minutes++) {    //Creates 1 hour
    for (int Seconds = 0; Seconds < 60; Seconds++) {  //Creates 1 minute
      delay(1000);                                    //Creates 1 second
    }
  }
}

```

---
Tags: arduino-uno, timers
---


# Question
Title: Emergency Vehicle - Make two LEDs flash with buttons and a passive buzzer change sound
My Dad and I are just learning how to use my new UNO.

We have learned how to make leds flash at the touch of a button. We have also learned how to make a passive buzzer sound at the touch of a button and change tone to sound like a police car.

We have just learned that we cant run more than one loop so we have combined the buzzer code and the LED code twice (for blue and red LEDs) and it works... but the delay on the LEDs is ruining the buzzer sound. Is there anything we can do?

The code is below.

Thank you!

Code:

```
int buzzerPin = 9;    // the number of the buzzer pin
int BlueLEDpin = 5;   // the number of the blue LED pin
int RedLEDpin = 7;    // the number of the Red LED pin
float sinVal;         // Define a variable to save sine value for buzzer
int toneVal;          // Define a variable to save sound frequency for buzzer

void setup() {
  pinMode(buzzerPin, OUTPUT); // Set Buzzer pin to output mode
  pinMode(BlueLEDpin, OUTPUT); // Set Blue LED pin to output mode
  pinMode(RedLEDpin, OUTPUT); // Set Red LED pin to output mode
}

void loop() {
    Buzzer();
    BlueLED();
    RedLED();

}

void Buzzer() {
  for (int x = 0; x < 360; x++) {       // X from 0 degree->360 degree
    sinVal = sin(x * (PI / 180));       // Calculate the sine of x
    toneVal = 2000 + sinVal * 500;      // Calculate sound frequency according to the sine of x
    tone(buzzerPin, toneVal);           // Output sound frequency to buzzerPin
    delay(1);
  }

 }

  void BlueLED() {
  digitalWrite(5, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1);              // wait for a second
  digitalWrite(5, LOW);    // turn the LED off by making the voltage LOW
  delay(1);              // wait for a second
}

void RedLED() {
  digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1);              // wait for a second
  digitalWrite(7, LOW);    // turn the LED off by making the voltage LOW
  delay(1);              // wait for a second
}

```

# Answer
We made it better with Nathan's pointer.

We learned how to make a class but the LEDs flashed together so we learned how to make another class (with Public and Void Update in the class - caught us out at first that bit). One class starts with state HIGH and the other with state LOW so the LEDs alternate. When we press all three buttons we get the two tone buzzer, and the alternating LEDs.

Using this method we can add as many new LEDs as we like.

Here is the code we wrote:

```
/*
  Jacob & Dad’s Police Car light and sounds
*/

int buzzerPin = 9;
float sinVal;
int toneVal;

class FlashingLED_A
{
    int ledPin;
    long OnTime;
    long OffTime;
    int ledState;
    unsigned long previousMillis;
  public:
  FlashingLED_A(int pin, long on, long off)
  {
    ledPin = pin;
    pinMode(ledPin, OUTPUT);
    OnTime = on;
    OffTime = off;
    ledState = LOW;
    previousMillis = 0;
  }

 void Update()
  {
    // check to see if it's time to change the state of the LED
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
        ledState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(ledPin, ledState);  // Update the actual LED
    }
    else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      ledState = HIGH;  // turn it on
      previousMillis = currentMillis;
      digitalWrite(ledPin, ledState);
    }
  }

};

class FlashingLED_B
{
    int ledPin;
    long OnTime;
    long OffTime;
    int ledState;
    unsigned long previousMillis;
  public:
  FlashingLED_B(int pin, long on, long off)
  {
    ledPin = pin;
    pinMode(ledPin, OUTPUT);
    OnTime = on;
    OffTime = off;
    ledState = HIGH;
    previousMillis = 0;
  }

 void Update()
  {
    // check to see if it's time to change the state of the LED
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
        ledState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(ledPin, ledState);  // Update the actual LED
    }
    else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      ledState = HIGH;  // turn it on
      previousMillis = currentMillis;
      digitalWrite(ledPin, ledState);
    }
  }

};

FlashingLED_A led1(5, 100, 400);
FlashingLED_B led2(7, 100, 400);

void setup() {
  pinMode(buzzerPin, OUTPUT);
}

void loop() {
  Buzzer();
    led1.Update();
    led2.Update();
}

void Buzzer() {
  for (int x = 0; x < 360; x++) {
    sinVal = sin(x * (PI / 180));
    toneVal = 2000 + sinVal * 500;
    tone(buzzerPin, toneVal);
    delay(1);
  }
 }

```
> 0 votes

# Answer
Your problem is the delay() in your BlueLED() and RedLED() calls. To get more "simultaneous" activities, you'd need to use timer interrupts to implement those delays. It's a lot more complex conceptually, but the right way to do it.
> 2 votes

# Answer
We have done it. Thanks for the help Harper Shelby.

We combined the Blink Without Delay example with our original code:

```
int buzzerPin = 9;    // the number of the buzzer pin
const int BlueLEDpin = 5;
const int RedLEDpin = 7;
float sinVal;         // Define a variable to save sine value
int toneVal;          // Define a variable to save sound frequency
int BlueLEDState = LOW;
int RedLEDState = HIGH;
unsigned long previousMillisBlue= 0;
unsigned long previousMillisRed= 0;
const long interval = 200;

void setup() {
  pinMode(buzzerPin, OUTPUT); // Set Buzzer pin to output mode
  pinMode(BlueLEDpin, OUTPUT);
  pinMode(RedLEDpin, OUTPUT);
}

void loop() {
    Buzzer();
    BlueLED();
    RedLED();

}

void Buzzer() {
  for (int x = 0; x < 360; x++) {       // X from 0 degree->360 degree
    sinVal = sin(x * (PI / 180));       // Calculate the sine of x
    toneVal = 2000 + sinVal * 500;      // Calculate sound frequency according to the sine of x
    tone(buzzerPin, toneVal);           // Output sound frequency to buzzerPin
    delay(1);
  }

 }

  void BlueLED() {
  unsigned long currentMillisBlue = millis();

  if (currentMillisBlue - previousMillisBlue >= interval) {
    previousMillisBlue = currentMillisBlue;
    if (BlueLEDState == LOW) {
      BlueLEDState = HIGH;
    } else {
      BlueLEDState = LOW;
    }

    digitalWrite(BlueLEDpin, BlueLEDState);
  }

}

void RedLED() {
  unsigned long currentMillisRed = millis();

  if (currentMillisRed - previousMillisRed >= interval) {
    previousMillisRed = currentMillisRed;
    if (RedLEDState == LOW) {
      RedLEDState = HIGH;
    } else {
      RedLEDState = LOW;
    }

    digitalWrite(RedLEDpin, RedLEDState);
  }

}

```
> 2 votes

# Answer
Firstly, congratulations! you've taken your first step into the very rewarding world of micro-controllers. I teach robotics at a local university, so it's always nice to see when the light-bulb goes on and people start understanding.

As mentioned above, the blink without delay code is a good start. Good code should also be expandable in case later you want to add another light or 10, and this is where coding every line can get very large. There are many other methods for doing this sort of task, however you might want to have a look at this series of tutorials. Multitasking with the Arduino.

The benefit to the state machine approach used in that example is it becomes very easy later on to change your code; if you want to have more lights flashing in sequence (like the knight-rider lights) or more sirens, it becomes easier to include. In your second code, the void redLED() and void blueLED() codes contain mostly the same lines; you could make an object called 'LED' and then just make as many instances of this as you need, all working at different speeds and different pins (the example on the website should provide this much. The buzzer can probably reuse the servo sweep part of the code). You could also for example, program 4 different types of siren as a switch:case, and after the elapsed time, switch between them.

Another more advanced method would be to include a real-time operating system. An RTOS makes it very easy to have multiple independent tasks running. Each light could be on its own task and the siren on a third, and the system would keep each working, effectively simultaneously. This approach then has advantages if you want to change the timing of one light; it gets changed in one place without fear of needing to change the whole code. Information on FreeRTOS on the arduino can be found here. There is an example at the bottom of the page which includes both Blink and analog read examples.

These are fairly advanced topics, but I think you and your dad will get there. Once again, congratulations.
> 1 votes

# Answer
This is probably a bit advanced but...

You could use a base class and pointers to the derived LED and Buzzer classes to reduce you loop function to a loop. You won't gain much at this level, but as you add more objects, such as the flashing headlights and mirror lights, maybe even a rear facing message board you will make life easier for your self.

```
/*
Jacob & Dad’s Police Car light and sounds
*/

class BaseOutputObject
{
protected:
    int Pin;
public:
    BaseOutputObject(const int& pin)
        : Pin(pin)
    {
        pinMode(Pin, OUTPUT);
    }
    virtual void Update()
    {
    }
};

class FlashingLED : public BaseOutputObject
{
    long OnTime;
    long OffTime;
    int ledState;
    unsigned long previousMillis;
public:
    FlashingLED(const int& pin, const long& on, const long& off, const bool& startLow = true)
        : BaseOutputObject(pin)                     // Call base class constructor
        , OnTime(on)                            // Use initialisers rather than assignments
        , OffTime(off)
        , ledState(startLow ? LOW : HIGH)
        , previousMillis(0)
    {
    }

    void Update()
    {
        // check to see if it's time to change the state of the LED
        const unsigned long currentMillis = millis();           // Make it const because it won't change within this call of the function.

        if (currentMillis - previousMillis >= OnTime)
        {
            ledState = (ledState == LOW ? HIGH : LOW);  // Toggle the state.
            previousMillis = currentMillis;  // Remember the time
            digitalWrite(Pin, ledState);  // Update the actual LED
        }
    }
};

class Buzzer : public BaseOutputObject
{
    float SinValue;
    int ToneValue;
public:
    Buzzer(const int& pin)
        : BaseOutputObject(pin)
        , SinValue(0.0f)        // Always initialise variables, in case you change the code later.
        , ToneValue(0)
    {
    }

    void Update()
    {
        for (int x = 0; x < 360; x++)
        {
            SinValue = sin(x * (PI / 180));
            ToneValue = 2000 + SinValue * 500;
            tone(Pin, ToneValue);
            delay(1);
        }
    }

};

// The objects could be declared dynamically, but thats not a great idea on embedded systems.
FlashingLED ledOne(5, 100, 400);
FlashingLED ledTwo(7, 100, 400);
Buzzer buzzer(9);
enum { LED_ONE, LED_TWO, BUZZER, MaxObjects };
// Have to have pointers to the objects to allow you to cast them down to the base objects.
BaseOutputObject* objects[MaxObjects] = {  &ledOne, &ledTwo, &buzzer};

void setup()
{
}

void loop()
{
    for (int index = 0; index < MaxObjects; ++index)
    {
        objects[index]->Update();
    }
}

```
> 0 votes

---
Tags: led, buzzer
---


# Question
Title: When i press a button to subtract 1 from 5 it skips to 3
When i press a button to subtract 1 from 5 it skips to 3, it's the same when I add 1 to -5 it skips displaying - 4 and goes straight to -3.

This is the code that i am using:

```
//Testing the use of addition and subtraction with the menu options.

#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

int lcd_key     = 0;
int adc_key_in  = 0;
int calc_total;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

int read_LCD_buttons(){
    adc_key_in = analogRead(0);

    if (adc_key_in > 1000) return btnNONE;

    if (adc_key_in < 50)   return btnRIGHT;
    if (adc_key_in < 150)  return btnUP;
    if (adc_key_in < 300)  return btnDOWN;
    if (adc_key_in < 450)  return btnLEFT;
    if (adc_key_in < 700)  return btnSELECT;

    return btnNONE;

}

void setup(){
   lcd.begin(16, 2);
   lcd.setCursor(0,0);
   lcd.print (calc_total);

}

void loop(){

   lcd_key = read_LCD_buttons();
   calc_total = constrain(calc_total, -4, 4);

   switch (lcd_key){

       case btnRIGHT:{
            lcd.clear();
            calc_total = calc_total - 1;
            lcd.print (calc_total);
            delay(700);
            lcd.setCursor(0,0);
            break;
       }
       case btnLEFT:{
            lcd.clear();
            calc_total = calc_total + 1;
            lcd.print (calc_total);
            delay(700);
            lcd.setCursor(0,0);
            break;
       }
     }
}

```

# Answer
Your main problem is that you aren't looking for a *change* in buttons. You're only doing your adding or subtracting *while* a button is pressed.

That means, all the time you're holding `btnLEFT` in your total is incrementing until it hits your limit.

You need to remember the button state from the previous iteration of `loop()` and compare it to the current state - and only if they differ do you need to do anything.

Also you should perform your constrain immediately after your addition or subtraction. As it is, you add or subtract, display the new value (I assume you do - I don't see the code for that), and only afterwards do you then chop the value back down to +/-4 (assuming it's outside the range). So your 5 becomes 4, and your next subtraction takes you to 3.
> 1 votes

# Answer
The whole point of `constrain` function is to keep the values between `-4` and `4` (including). In your code you can go to the -5 and show it, but right after that it's adjusted to `-4` (and you are not displaying this value).

If you increment this value, you can get only result and this is `-4 + 1 = -3`.
> 0 votes

---
Tags: arduino-mega, programming, lcd, calculation
---


# Question
Title: Nano v3 dual power source use & detection
I would like to run a Nano 3.0 from both the VIN (mains power supply 7V) and USB power (backup). I understand it selects the highest voltage and switches to VIN at 6.6V. However I am unsure of the following:

1. How is it possible to detect which power source is being used?
2. How is it possible to detect if the source has been switched?
3. How is it possible to detect if the power source NOT in use has been disconnected.

# Answer
> 2 votes
To check, if VIN is connected, you can connect VIN through a voltage divider to a digital pin (as suggested in the comment of Code Gorilla). For checking the USB connection you would have to connect VUSB to another digital pin. Since VUSB is not exposed on a pin, this could be difficult to do, but it is possible.

But note, that this would also show a disconnect, when the voltage drops (e.g. empty battery). When you want to detect real mechanical disconnects, you need a power jack with an extra switch integrated.

Let's take a look at the schematics: Arduino Nano 3.0 Schematics  The selection of voltage supply is done by the diode D1. If the voltage resultung from the VIN regulator is higher than VUSB - diode\_voltage\_drop, the diode is closing and the power comes from VIN. If the voltage resulting from VIN is lesser, the current can flow from VUSB. How much power is really drawn from USB depends on the voltage difference.

So - to detect which source is actually used - you can measure the voltage on the diode with an analog measurement with the ADC or through connecting for example a comparator and using a digital pin.

Note that the voltage on the diode can be positive or negative, depending on which source is used.

---
Tags: arduino-nano
---


# Question
Title: How do I connect my Ublox neo 6M GPS Module with arduino mega 2560?
I tried connecting RX of GPS to Pin 18 and TX of GPS to Pin 19 but I get an error that No GPS is detected,check wiring.VCC of GPS to 5V.

I have set baudrate to 115200.I am trying DeviceExample code of TinyGPS++ library.

# Answer
The default baud rate for ublox NEO-6M GPS devices is 9600, **not** 115200.

And try NeoGPS. It's smaller, faster, more accurate, more reliable and it comes pre-configured to use `Serial1` on a Mega. Be sure to read the Installation instructions. If it doesn't work, follow the Troubleshooting pages and try NMEAdiagnostic.ino.

NeoGPS has an example sketch (ubloxRate.ino) that can configure the NEO-6M to other baud rates, once you get the basic programs working at 9600.
> 1 votes

---
Tags: arduino-mega
---


title: Light Powered Motor Troubles

text:
# Question
Title: Light Powered Motor Troubles
I'm working on a small car (\<1 kg) which will drive when there is light and stop when there isn't. Below is a plan with code drawn up (the only numbers I know for sure are the current gains for the TIP31C transistor and the rated load current of the 6 V motor I'm using). I'm going to map the analog voltages to a digital signal output.

I read that the maximum digital output was 40 mA and also that `analogWrite` gives a pulse width modulation (PWM) which can be set to 100% (255) \[the code: `outputval/1`\], 50% (127) \[the code: `outputval/2`\]. I'm concerned with the lack of control I have here over the current. Will Arduino by default draw 7.75 mA maximum if the input signal is high \[giving the output signal also as high\]? If not, can I control the current in this manner reliably? Also are there anything I should worry about if I added another 6 V motor in parallel? Coding and electrical suggestions greatly welcomed.

TIP31 transistor: http://www.hobbytronics.co.uk/datasheets/TIP31.pdf

6 V dc motor: http://www.kysanelectronics.com/graphics/RF-370CA-22170.pdf

maximum digital output: https://www.arduino.cc/en/Tutorial/DigitalPins

PWM: https://www.arduino.cc/en/Tutorial/PWM

The code:

```
const int transistorbase = 9;
void setup() {
  //set the base as digital output:
  pinMode(transistorbase, OUTPUT);
}
void loop() {
  //read voltage at divider:
  int inputval=analogRead(A0);
  //map voltage to digital
  int outputval=map(inputval,0,1023,0,255);
  //control transistor:
  analogWrite(transistorbase,outputval);
}

```

tl;dr Codewise, how do I control the digital output current to my needs? Am I seeing ghosts?

# Answer
I would take a simple n-channel MOSFET like this one. At 5V on the gate it can drive up to 8A (so you have plenty of space to connect other motors as long as your power source can handle this) and because it is a MOSFET you don't have to draw much current from the Arduino (only enough to load the gate of the MOSFET). You can also hold the current under the critical value for your motor with a simple resistor (fit for the resulting power dissipation) in series.

Yes, the output of the PWM is 5V - the operation voltage of the Arduino. The whole point in PWM is to use only the digital values (here 0V and 5V) and varying so fast, that slow systems as the motor cannot follow this motion, but summing over the impulses. So the motor gets only very fast kicks. And for a normal motor you don't need fast PWM. This only increases the frequency response from the MOSFET.

The code seems for to me.
> 0 votes

---
Tags: current, digital
---


# Question
Title: HC-05 bridge using Arduino Nano and GNU Screen
I connect an HC-05 module to an Arduino nano with CH341 serial chip (voltage divider on RX pin). I am trying to make a bridge for a test, i.e. serial in, echo local and echo to Bluetooth and vice versa. I modified the echo code from here.

```
int incomingByte = 0;    // for incoming serial data

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup() {
    BTSerial.begin(38400);    // opens serial port, sets data rate to 9600 bps
    Serial.begin(9600);    // opens serial port, sets data rate to 9600 bps
}

void loop() {
  // send data only when you receive data:
  if (Serial.available() > 0) {

    // read the incoming byte:
    incomingByte = Serial.read();

    // say what you got:
    Serial.print((char)incomingByte);
    BTSerial.print((char)incomingByte);
  }

  if (BTSerial.available() > 0) {

    // read the incoming byte:
    incomingByte = Serial.read();

    // say what you got:
    Serial.print((char)incomingByte);
    BTSerial.print((char)incomingByte);
  }

```

under OSX I open two terminals. In the first terminal using `screen /dev/cu.wchusbserial1410 9600` I see local echo as desired. But on the second terminal using `screen /dev/cu.HC-05-SPPDev 38400` I see nothing after pairing. The only effect is that by typing the latter command, the module stops blinking rapidly and blinks only two times with long pause in between. Exiting the `screen` environment, then again blinks rapidly.

Appreciate any hints what I am doing wrong...

=====

intermediate success but not quite there yet:

I simplified the code and corrected the wrong connection. Local echo on serial works as usual, even between the two, characters are being transferred, but they are black question marks instead of why I typed.

```
/*
 * echo script
 */

byte incomingByte;

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(3, 2); // RX | TX

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

void loop() {
  if (Serial.available()) {
    incomingByte = Serial.read();
    Serial.print((char)incomingByte);
    BTSerial.print((char)incomingByte);
  }

  if (BTSerial.available()) {
    incomingByte = BTSerial.read();
    Serial.print((char)incomingByte);
    BTSerial.print((char)incomingByte);
  }
}

```

Any ideas?

========

Edited the Buadrate to 9600. Now everything works.

# Answer
Based on the above comments I provide here the full answer in the hope it will be useful in the future.

HC-05 has two modes. The **Communication Mode** and **AT Command Mode**. In the latter mode, HC-05 responds in kind of "config" way and many default settings of the communication mode can be change here. While the baud rate of the communication mode, and many other settings can be changed, the baud rate of the AT command mode is always fixed 38400 to avoid any confusions and mistakes. On the other hand, the **default** factory baud rate of the communication mode, i.e. before any change, is set to 9600. So the solution to my problem was to set the baud-rate to 9600 on my newly purchased HC-05 and I was able to make an echo bridge between HC-05 Bluetooth and serial. Here is the code:

```
/*
 * echo script
 */

byte incomingByte;

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(3, 2); // RX | TX

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

void loop() {
  if (Serial.available()) {
    incomingByte = Serial.read();
    BTSerial.print((char)incomingByte);
  }

  if (BTSerial.available()) {
    incomingByte = BTSerial.read();
    Serial.print((char)incomingByte);
  }
}

```

After pairing HC-05 with OSX, I was able to open two OSX Terminals with one of these commands in the first terminal:

```
screen /dev/cu.wchusbserial1410 9600

```

and in the other:

```
screen /dev/cu.HC-05-SPPDev 9600

```

Everything worked properly, i.e. typing in one terminal produced characters in the other and vice versa. For changing the default baud-rate in the communication mode, I found a very good tutorial which can be found here.
> 1 votes

---
Tags: arduino-nano, bluetooth, osx
---


title: Assign string to an array value

text:
# Question
Title: Assign string to an array value
I need to assign a string to an array value:

`char mystr[3] = "Hello";`

But when I run this code on arduino simulator: tinkercad.com, I get this error:

`1:17: error: initializer-string for array of chars is too long [-fpermissive]`

Why I'm getting this error?

# Answer
You have asked the compiler to allocate 3 `char` of memory, and then you ask it to fill that memory with 6 `bytes` of data (5 characters, plus null-char for termination.)
> 2 votes

---
Tags: c++
---


title: Detect current in car handbrake circuit

text:
# Question
Title: Detect current in car handbrake circuit
Using Arduino, how can I detect that the switch is on? I have access to the wire within the red rectangle only. That's because the switch is closely connected to the car body (ground). When the handbrake is up, the switch is pushed by a coil to touch car body and close the circuit. And when the handbrake is down, the switch go away from the car body and the circuit is open.

# Answer
> 0 votes
After examining the answers provided by "Jose can u c", "Alberto Perro" and "VE7JRO", and the comments by "Mark Smith", It was clear to me that there are a lot of methods to use, but I found out that the simplest way is to just measure the voltage at any point within the red rectangle. While the circuit is close, it will read 0V, and while the circuit is open, it will read about 12V. And of course we will use voltage divider to reduce the voltage to about 4V, and 4.7 zener diode to protect Arduino's pin.

# Answer
> 2 votes
If you truly only have access to the red rectangle content, and not the Ground or +12V supply, you could use an opto-isolator, assuming you can use enough of the wire in the red rectangle to be able to form a voltage divider to get at least 1-2 mA through the input side of the opto.

# Answer
> 1 votes
Wrap the wire around a ferrite or some iron core and detect magnetic field.

# Answer
> 1 votes
If you can modify the cabling, you can add a shunt resistor in series and measure the voltage drop between the terminals. This way you can measure the current draw that would be 0 if the switch is open and something if the switch is closed. Other way you can use an ACS712 Current Sensor.

# Answer
> 1 votes
Based on your comments:

"It's the handbrake switch button..." and "..if the switch is closed, the voltage would be zero as the ground, and if the switch is open, it will read 12 V.",

you could splice into the wire and use it as an input for the Arduino. You can NOT connect it directly to an Arduino because 5V is the maximum voltage permitted on a digital input (assuming your Arduino is running at 5V).

There are several ways to connect it to the Arduino safely, such as an opto-isolator, a level-shifter or using passive components.

This circuit using 2 resistors and a zener diode may work for you:

Be sure to connect the vehicle ground to the Arduino GND.

---
Tags: arduino-mega
---


title: Do Arduino Megas Burn Out?

text:
# Question
Title: Do Arduino Megas Burn Out?
Im building a bedside alarm clock/home assistant. I have a few buttons that input, an LCD display and some RGB LEDs. The LCD and RGBs are only on when commanded to be on. I was wondering if I could leave the mega plugged in and constantly running or if that would burn it out. Im a bit new to this so sorry if this is dumb. If it would burn out, how long is its lifetime?

# Answer
> 3 votes
As long as you operate the electronics within specification they will run for years and years. The first thing to probably fail will be the electrolytic capacitors that will dry out after maybe 10 years.

When reading datasheets and specifications the metric you are interested in is the **MTBF** \- the Mean Time Between Failures.

---
Tags: arduino-mega
---


# Question
Title: Trouble with Arduino -> PSOC4 communications over I2C! (Multi master/ slave config)
Hello Stack Exchangers!

I am currently working on a project which requires me to use PSOC4 - 049's to scan a series of inputs, and feed this data back to an arduino over I2C.

The arduino, or in this case a teensy 3.5, is the main unit which hosts a UI and retains key system variables. I wish to have the teensy send a few unsigned bytes to the arduino, and when user input is detected have the PSOC act as the master and send relevant information back to the arduino.

Unfortunately I've been trying for about a week now to no avail.

Currently I have 2 Teensy 3.5s sitting on my I2C bus and 1 PSOC4. I send the first teensy a 'H' or 'L' character from a terminal over USB and it turns an LED high or low respectively,

This teensy then relays this character over the I2C Bus to the other teensy at address 0x10, which also toggles an LED.

The idea is that the first teensy then also forwards a value to the PSOC at address 0x11 but this simply isn't working for me!

I can't seem to get a single byte over to the PSOC let alone set up the full MMMS system I need!

Does anyone see what I'm doing wrong or have a good simple example of a PSOC project using Multi Master Multi Slave?

=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-= ARDUINO MASTER CODE (Might be doing something wrong) =-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-= (Note that this function is part of a much larger project and is just being called from main at this time, much of the project is removed here but should not effect this code in any way)

```
#include <Wire.h>
void setup()
{
     Wire.begin();
     Serial.begin(9600);
}

void loop()
{checkCommand();}

byte I2CTargetAddr[8] = {0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17}; //       Declares the addresses of the PSOCs

void checkCommand() // Reads Serial Commands H or L, sets an LED, then     relays the instruction (hopefully) to the PSOC to do the same thing.
{
  static int CCFR = 1;

  if (CCFR == 1)
  {
    pinMode(36, OUTPUT);  // Debug LED
    digitalWrite(36,HIGH);
    CCFR = 0;
  }

  char c;
  static char previousC = 'L';

  static byte low = 0;
  static byte high = 255;

  Wire.setClock(100000); // Set to 100kHz

  while(Serial.available())
  {
    c = Serial.read();

    if(c == 'H')
    {
      Wire.beginTransmission(I2CTargetAddr[0]);
      Wire.write('H');
      Wire.endTransmission();
      digitalWrite(36, HIGH);
    }

    else if(c == 'L')
    {
      Wire.beginTransmission(I2CTargetAddr[0]);
      Wire.write('L');
      Wire.endTransmission();
      digitalWrite(36, LOW);
    }
  }

if(c == 'H')
{
  Wire.beginTransmission(I2CTargetAddr[1]);
  Wire.write(high);
  Wire.endTransmission();
  //digitalWrite(high, HIGH);
}

else if(c == 'L')
{
  Wire.beginTransmission(I2CTargetAddr[1]);
  Wire.write(low);
  Wire.endTransmission();
  //digitalWrite(low, LOW);
}

  previousC = c;
}

```

=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=--=-= ARDUINO TEST SLAVE CODE (Seems to be totally fine) =-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=--=-=

```
#include <Wire.h>
#define LED_1 23  // PWM Capable LED Pin

void setup()
{
  Wire.begin(0x10);
  Wire.onReceive(receiveEvent); // Calls the receiveEvent function when     something happens to the I2C bus
  pinMode(LED_1,OUTPUT);
  digitalWrite(LED_1, HIGH);
}

void loop()
{
}

void receiveEvent(int howMany)
{
  while(Wire.available())
  {
    char c = Wire.read();

    if (c == 'H'){digitalWrite(LED_1, HIGH);}
    if (c == 'L'){digitalWrite(LED_1, LOW) ;}
  }
}

```

=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-= PSOC 4 Code =-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=-=-=-==-=--==-=-=-=-=-=-=

The topdesign includes a bootloadable component, a pin for LED Extern and LED Local, and an i2c block set as multi slave/ multi master at 100kb/s

-------------------------------MAIN.C---------------------------------

```
#include <project.h>
#include <main.h>

extern uint8 I2CSlaveIn[BUFFER_SIZE];
extern uint8 I2CSlaveOut[BUFFER_SIZE];
extern uint8 I2CMasterIn[BUFFER_SIZE];
extern uint8 I2CMasterOut[BUFFER_SIZE];

/* Fast BootLoad ISR */
CY_ISR_PROTO(bootloadISR_Handler);

CY_ISR(bootloadISR_Handler)
{
    Bootloadable_1_Load();   // Forces a restart of the bootloader,     triggered by the onboard button.
}

int main(void)
{
    BootLoadSys_Start(); // Initialise easy bootloader tool
    bootloadISR_ClearPending();
    bootloadISR_StartEx(bootloadISR_Handler);

    initI2C(); // Initialised i2c

    CyGlobalIntEnable; /* Enable global interrupts. */

    uint8 transferredIn[BUFFER_SIZE];
    uint8 byteCount;
    uint8 lastVal = 0;

    LED_Local_Write(0);
    int i;

    for(;;)
    {
        if (0u != (MYI2C_I2CSlaveStatus() & MYI2C_I2C_SSTAT_WR_CMPLT)) //     Wait for master to complete Write
        {
            byteCount = MYI2C_I2CSlaveGetWriteBufSize();
            MYI2C_I2CSlaveClearWriteStatus();             // Take a wild guess

            for (i =0; i<byteCount; i++)
            {transferredIn[i] = I2CSlaveIn[i];} // Copy data from the buffer

            MYI2C_I2CSlaveClearWriteBuf();
        }

        if (transferredIn[0] != lastVal)
        {
            if (transferredIn[0] == 255u){LED_Local_Write(1);}
            if (transferredIn[0] == 0u  ){LED_Local_Write(0);}
        }

        lastVal = transferredIn[0];

    }
}

```

----------------------------------I2C.C------------------------------------

```
#include "project.h"
#include "i2c.h"
#include "main.h"

uint8 I2CSlaveIn[BUFFER_SIZE];
uint8 I2CSlaveOut[BUFFER_SIZE];
uint8 I2CMasterIn[BUFFER_SIZE];
uint8 I2CMasterOut[BUFFER_SIZE];

void initI2C()
{
    MYI2C_I2CSlaveSetAddress(MY_SLAVE_ADDR);

    MYI2C_I2CSlaveInitReadBuf( (uint8 *)I2CSlaveOut  , BUFFER_SIZE);
    MYI2C_I2CSlaveInitWriteBuf((uint8 *)I2CSlaveIn  , BUFFER_SIZE);

    MYI2C_Start();  // Calle after buffer setup
}

```

----------------------------------I2C.h----------------------------------

```
#define BUFFER_SIZE 1u // Sets Buffers size
#define MY_SLAVE_ADDR 0x11u

void initI2C();

```

# Answer
So it turns out I'm an idiot. At some point in the last day or so I must have accidentally changed the pins that the I2C component is assigned to.

This code (or at least code very similar to this, after a couple of minor changes) works perfectly for the slave side.

Feel free to make use of it if you need it!
> 1 votes

---
Tags: c, i2c, communication
---


# Question
Title: Can't get call / message from A7 gsm+gprs+gps module
I am making a project using arduino uno & A7 gsm+gps+gprs module.my circuit connection is like this:

```
A7 UTXD -> arduino RX
A7 RTXD -> arduino TX
A7 GND -> arduino GND
A7 pwr_key -> A7 VCC5.0

```

When i make call from my mobile to A7,it's ok.But i cannot get call/msg from A7. Here is my code for making call:

```
char phone_no[]="phone_no";

void setup()
{
Serial.begin(9600);
delay(200);
Serial.println("AT");
delay(1000);
Serial.print("ATD");
Serial.println(phone_no);
//Serial.println(";");
delay(10000);
Serial.println("ATH");
}

void loop()
{
}

```

What can i do now??? Please help me to fix it.I apologize for my poor english.

# Answer
Increase your second delay to 2000 (ie. 2 seconds).

```
delay(2000);

```
> -1 votes

---
Tags: arduino-uno, gsm, gps, uart
---


# Question
Title: Not able to control digital pins using commands sent via HC-05 module
I am trying to control the LED on pin13 using the below code but it's not working. With this code I am able to print to the Serial Monitor but the code has no effect on the any of the digital pins. I am unable to control the LED and so I have gotten stuck and can't advance further. I can't understand why it is happening even if I have excluded the new line from the Bluetooth app that I am using to send the strings and same on the Serial Monitor.

```
#include<SoftwareSerial.h>          // import the serial library

SoftwareSerial bluetooth(6, 7);     // RX, TX

void setup(){
  Serial.begin(9600);               //set baud rate
  bluetooth.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop(){
  while (bluetooth.available()){
    char ch = bluetooth.read();
    message += ch;
  }

  if(!bluetooth.available()){
    if(message != ""){
      if(message.equalsIgnoreCase("on")){
        digitalWrite(13, HIGH);
      }else{
        digitalWrite(13, LOW);
      }
      Serial.println(message);
      message = "";
    }
  }
}

```

# Answer
Your logic is a complete mess. You have:

1. If a character is available, read it and add it to `message`.
2. If another character is available, compare what you have already stored with `on`.
    * If it's equal ('o' is not equal to 'on') turn on, otherwise turn off.
    * Print what you have stored.
3. Forget what you stored
4. Go to 1 (a character is still available since you never read it in stage 2).

Instead you need something more like:

1. If a character is available, read it into a variable.
2. If the character you read is a line ending character:
    * Compare your `message` with 'on' and take appropriate action
3. If the character you read is *not* a line ending character:
    * Add the character to `message`.
4. Go to 1.

Note how you only check once if there is a character available, and all your testing is done within that one `if` block.
> 0 votes

---
Tags: arduino-uno, softwareserial, hc-05
---


# Question
Title: Send an multidimensional array of values from one arduino to another through serial port
I have connected two arduinos using pins: RX and TX and managed to send a string as an array of values:

```
//sender

char mystr[6] = "hello";

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

void loop() {
  Serial.write(mystr);
  delay(1000);
}

```

And receive it:

```
//receiver

char mystr[6];

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

void loop() {
  Serial.readBytes(mystr,5);

  if(mystr[0] == 'h' && mystr[1] == 'e' && mystr[2] == 'l'){

    for(int i = 0;i < sizeof(mystr);i++){

      Serial.print(mystr[i]);

      if(i == sizeof(mystr) - 1){
        Serial.print("\r\n");
      }
    }
  }
  delay(1000);
}

```

That worked fine! But I need to send and receive something like this:

```
int a[3][4] = {
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

```

How can I do that?

# Answer
Use two for loops to send the multidimensional array, and two for loops to receive the multidimensional array.

Sending:

```
int a[3][4] = {
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

for (int x = 0; x < 3; x++)
{
   for (int y = 0; y < 4; y++)
   {
      Serial.print(a[x][y]);
   }
}

```

Receiving

```
for (int x = 0; x < 3; x++)
{
   for (int y = 0; y < 4; y++)
   {
      a[x][y] = Serial.read(); // Not sure about the exact prototype
   }
}

```

If the sizes are fixed (like in your case 3 and 4), than you don't have to send the dimensions, just sent the values in order: 0, 1, 2, 3, 4, ... like above.

And when receiving them you know the first four values belong to row 0, next four values to row 1 etc.

If you need dynamic sizes, first send the number of rows and columns and than the values.

In that case instead of 3 and 4 define two constants and use them:

```
#define NR_ROWS 3
#define NR_COLUMNS 4

int a[NR_ROWS][NR_COLUMNS] = {
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

for (int x = 0; x < NR_ROWS; x++)
{
   for (int y = 0; y < NR_COLUMNS; y++)
   {
      Serial.print(a[x][y]);
   }
}

```
> 2 votes

---
Tags: c++, communication, arduino-mini
---


title: How does Arduino IDE 'Get Board Info'?

text:
# Question
Title: How does Arduino IDE 'Get Board Info'?
I want my C# application to automatically select the correct COM port by way of a string equality check against a 'GetInfo'-type request to the Arduino board.

I know the Arduino IDE can get info from the board;

`Tools > GetBoardInfo`

But I don't know how to get it using a sketch or if it is even possible for that matter.

Is this something that can be read from the board, or is it a USB-thing. If it's a USB thing, I'd have to get the info from `GetUSBDevices.DeviceID` or whatever, then get the serial port used by the USB Device, which would probably work, but I'd rather do it all via a `serialPort`.

# Answer
Looking at the source code of the Arduino IDE on github, it looks like they call an executable (listComPorts.exe). So I would guess you can't get that info through serial.

Here's a C# app using WMI that can get port, vid, and pid:

```
namespace PortTest
{
    class Program
    {
        // Helper function to handle regex search
        static string regex(string pattern, string text)
        {
            Regex re = new Regex(pattern);
            Match m = re.Match(text);
            if (m.Success)
            {
                return m.Value;
            }
            else
            {
                return null;
            }
        }

        static void Main(string[] args)
        {
            // Use WMI to get info
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\"");

            // Search all serial ports
            foreach (ManagementObject queryObj in searcher.Get())
            {
                // Parse the data
                if (null != queryObj["Name"])
                {
                    Console.WriteLine("Port = " + regex(@"(\(COM\d+\))", queryObj["Name"].ToString()));
                }
                //PNPDeviceID = USB\VID_1A86&PID_7523\5&1A63D808&0&2
                if (null != queryObj["PNPDeviceID"])
                {
                    Console.WriteLine("VID = " + regex("VID_([0-9a-fA-F]+)", queryObj["PNPDeviceID"].ToString()));
                    Console.WriteLine("PID = " + regex("PID_([0-9a-fA-F]+)", queryObj["PNPDeviceID"].ToString()));
                }
            }
            Console.WriteLine("Done");
            int c = Console.Read();
        }
    }
}

```

From there, it looks like it searches an online database for more info. See: `getBoardWithMatchingVidPidFromCloud()` function.
> 5 votes

# Answer
Please look here https://todbot.com/blog/2012/03/02/listcomports-windows-command-line-tool-for-usb-to-serial/ The article is right about what you are seeking. Thanks to @Johnny Mopp, searching "listComPorts" keyword helped me.

Quote from that article:

> **How it works**
>
> The C and the VBS versions both utilize the WMI infrastructure that’s been around since Windows 2000 to query the machine about its configured PnP devices. The WMI is a huge data structure of just about any information in Windows. Except, it seems, good information about COM ports. While there is a “Win32\_SerialPort” table in WMI, that only contains information about hardware serial ports, not USB-to-serial adapters. Instead, these two tools look at the “Win32\_PnPEntity” table. While this table does list USB-to-serial adapters, it does not contain a proper mapping of the adapter’s USB or PnP ID to COM port. Instead, these tools do a string search on the “Caption” field for the string “(COMn)” where “n” is a number. It’s an incredible hack but seems to work.
> 1 votes

---
Tags: arduino-uno, serial, programming, arduino-ide, c#
---


# Question
Title: Arduino TimerOne breaks the program when calling "digitalRead"
I'm trying to make this project.

But i have a problem running this code. It appears to be `val = digitalRead(inPin);` breaks entire program. just because i call this from the `callback` function which attached as an interrupt function `Timer1.attachInterrupt(callback);`

Here is the more simplified problem simulation program,

```
#include "TimerOne.h"

int inPin = 7;   // sensing digital pin 7

int val;

void setup() {
  pinMode(inPin, INPUT);      // sets the digital pin 7 as input to sense receiver input signal

  Serial.begin(9600);
  Timer1.initialize(8);  // initialize timer1, and set the frequency; this drives both the LC tank as well as the pulse timing clock
  // note: modify this as needed to achieve resonance and good match with the desired tags
  // the argument value is in microseconds per RF cycle, so 8us will yield RF of 125kHz, 7us --> 143kHz, etc.

  Timer1.pwm(9, 512);

  Timer1.attachInterrupt(callback);
}

void callback()
{
  val = digitalRead(inPin);//once you comment this line, it works fine
}

void loop() {
  Serial.print("Program running \n");

}

```

Any help is much appreciated.

# Answer
The time between 2 interrupt triggers is only 8us. Also `digitalRead()` is a quite big function, that needs some time to execute (I don't know how much). That way it is to short for the Serial print command to execute in the leftover time. Make the following change and you will see, that it works.

```
void loop(){
  noInterrupts();
  Serial.print("Program running \n");
  interrupts();
  delay(1000);
}

```

Now the interrupts are disabled during the execution of the `Serial.print()`, so that it can finish. After this the interrupts are enabled again and we wait for 1 second to give the interrupts some time before we are disabling them again.

The speed of the Arduino is limited, so you cannot do much, when constantly triggering interrupts in the pace of 8us. If you only want to check this digital input you can get the value directly with using the PINB registers (refer to this side), which works much faster.

Also you should consider making the variable `val` volatile, since it will can change everytime through your interrupt service routine.
> 3 votes

---
Tags: arduino-uno, interrupt, rfid
---


# Question
Title: How do i run multiple functions simultaneously on a LCD screen?
I have little to no experience in programming and i'm very slowly and gradually getting the hang of it. My next project is that i'm making a clock, and wanted to use multiple functions for the hour:minute:seconds instead of just using one for everything. But after reading some i came to the conclusion that the arduino can only run one function at a time. So my question is how can i make the illusion of multiple functions running simultaneously on a LCD screen.

My code:

```
#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     144
#define btnDOWN   329
#define btnLEFT   504
#define btnSELECT 741
#define btnNONE   5

int read_LCD_buttons()
{
 adc_key_in = analogRead(0);

 if (adc_key_in > 1000) return btnNONE;
 if (adc_key_in < 50)   return btnRIGHT;
 if (adc_key_in < 195)  return btnUP;
 if (adc_key_in < 380)  return btnDOWN;
 if (adc_key_in < 555)  return btnLEFT;
 if (adc_key_in < 790)  return btnSELECT;
 return btnNONE;

}
unsigned long minInterval = 60000UL; // Interval for minutes in milliseconds
unsigned long secInterval = 1000UL;  // Interval for seconds in milliseconds
unsigned long prevMinMillis = 0UL;   // Holds the timestamp of the last time Minute() was called
unsigned long prevSecMillis = 0UL;   // Holds the timestamp of the last time Second() was called

void setup()
{
 lcd.begin(16, 2);
}

void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - prevMinMillis > minInterval)
  {
    prevMinMillis = currentMillis;
    Minute();
  }

  if (currentMillis - prevSecMillis > secInterval)
  {
    prevSecMillis = currentMillis;
    Second();
  }

}

void Second(){
  int First_Digit = 0;
  int Second_Digit = 0;

  for(Second_Digit; Second_Digit<10; Second_Digit++){
    if(Second_Digit==10){
      First_Digit = First_Digit + 1;
      }

    lcd.setCursor(0, 0);
    lcd.print(First_Digit);
    lcd.setCursor(1, 0);
    lcd.print(Second_Digit);
    lcd.clear();

    if(First_Digit==5 && Second_Digit==9){
      First_Digit = First_Digit - 5;
      Second_Digit = Second_Digit -10;

      }
    if(Second_Digit==9){
      First_Digit = First_Digit + 1;
      Second_Digit = Second_Digit - 10;
      }

  }
}
void Minute(){
  int First_Digit = 0;
  int Second_Digit = 0;
  for(Second_Digit; Second_Digit<10; Second_Digit++){
    if(Second_Digit==10){
      First_Digit = First_Digit + 1;
      lcd.print(First_Digit);
      }

    lcd.setCursor(3, 0);
    lcd.print(First_Digit);
    lcd.setCursor(4, 0);
    lcd.print(Second_Digit);
    lcd.clear();

    if(First_Digit==5 && Second_Digit==9){
      First_Digit = First_Digit - 5;
      Second_Digit = Second_Digit -10;
      lcd.print(First_Digit);

      }
    if(Second_Digit==9){
      First_Digit = First_Digit + 1;
      lcd.print(First_Digit);
      Second_Digit = Second_Digit - 10;
      }

  }
}

```

# Answer
> 0 votes
Use the state machine model shown in BlinkWithoutDelay

```
unsigned long minInterval = 60000UL; // Interval for minutes in milliseconds
unsigned long secInterval = 1000UL;  // Interval for seconds in milliseconds
unsigned long prevMinMillis = 0UL;   // Holds the timestamp of the last time Minute() was called
unsigned long prevSecMillis = 0UL;   // Holds the timestamp of the last time Second() was called

void setup()
{
 lcd.begin(16, 2);
}

void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - prevMinMillis > minInterval)
  {
    prevMinMillis = currentMillis;
    Minute();
  }

  if (currentMillis - prevSecMillis > secInterval)
  {
    prevSecMillis = currentMillis;
    Second();
  }

}

```

With this example, `Second()` is called only when the difference between "now" and the last time it was called is greater than `secInterval`. Likewise for `Minute()`.

\[Note, the code above will not run as-is, but I assume you have initialized the LiquidCrystal library and assigned the pins as per your schematic.\]

**EDIT BASED ON UPDATED CODE SAMPLE**

Issue 1:

In both your `Minute()` and `Second()` functions you have a sequence like:

```
lcd.setCursor(0, 0);
lcd.print(First_Digit);
lcd.setCursor(1, 0);
lcd.print(Second_Digit);
lcd.clear();

```

After writing the characters, you immediately clear the LCD screen. Don't do this, it erases all the output on your LCD.

Issue 2:

At the start of the `Minute()` function, you have the following:

int First\_Digit = 0; int Second\_Digit = 0;

This means the variables `First_Digit` and `Second_Digit` are initalized to zero every time the function is called. This means you won't get an increment of the value, it will start at zero every time you try to update the LCD. You can declare those variables as `static` so that the value remains the same between calls of the function. Static variables are automatically initialized to zero. Thus:

```
static int First_Digit;
static int Second_Digit;

```

and similarly in the `Second()` function.

You're correct that `digitalWrite()` is not needed in your function as it is described. `digitalWrite()` is for changing a physical pin on the Arduino to a `LOW` or `HIGH` value (that is, a 0V or 5V voltage.) In the Blink without Delay example, `ledPin` and `ledState` are just variables to hold the pin identifier for the blinking LED, and the current state (`LOW` or `HIGH`) of that pin. Again, not necessary for your code, as you have described it.

**SECOND UPDATE**

Having tackled the issue of how to run multiple functions "simultaneously", now move on to fixing the overly complicated code for writing the minute and second values to the LCD... I'm not sure why you put the `for` loop in the `Minute()` and `Second()` functions, but it's unnecessary.

You also are treating each digit way too complicated. If your value for the seconds counter is 0 to 59, why not keep track of it that way, and then display each digit as necessary:

```
void Second() {
  static int second;

  second++;
  if (second>59) {
    second = 0;
  }
  lcd.setCursor(0, 0);
  lcd.print(second/10);   // Prints the 10s digit
                          // Note, lcd.print automatically moves to the next column
  lcd.print(second % 10); // Prints the remainder after dividing by 10
}

void Minute() {
  static int minute;

  minute++;
  if (minute>59) {
    minute = 0;
    // Probably want to increment an Hour counter here?
  }
  lcd.setCursor(3, 0);
  lcd.print(minute/10);   // Prints the 10s digit
                          // Note, lcd.print automatically moves to the next column
  lcd.print(minute % 10); // Prints the remainder after dividing by 10
}

```

---
Tags: arduino-uno, arduino-ide, lcd
---


# Question
Title: arduino --verify / --upload not working (command line)
I installed Arduino IDE version 2.1 on Ubuntu via apt-get. Then I typed the following command in terminal to see if the Arduino IDE compiles my sketch.

```
 arduino --verify xx.ino

```

However, this command launches the GUI IDE. Is the CLI not supported anymore, or is the cause in apt-get the package?

# Answer
It's quite possible that this "version 2.1" doesn't support command line processes. I've never heard of an Arduino IDE version 2.1. My understanding is the version you get from `apt-get install arduino` is something like 2:1.0.5+dfsg2 so maybe you interpreted that as 2.1. That version is based on Arduino IDE 1.0.5, though apparently it has some non-standard modifications. Command line operation was first added in Arduino IDE 1.5.2, though some additional functionalities were added in newer versions.

You should always install the official Arduino IDE downloaded from: https://www.arduino.cc/en/Main/Software
> 2 votes

---
Tags: command-line
---


# Question
Title: How can Arduino's 8 bit Microcontrollers handle C++
I have just started getting into Arduino and c++ programming!

For all the talk on the internet about c++ being incompatible with 8-bit and even 16-bit microcontrollers, how is it that Arduino Microcontrollers can safely handle c++ code, in terms of the ram usage? Is it that Arduino's library does not contain or utilize features such as constructors or objects (of C++) that (I believe) are very ram-usage-intensive?

Cheers!

# Answer
It's a misconception that using constructors or C++ in general requires lots of RAM. Plus, to be clear, the AVR processors like the Micro and Uno have separate RAM and PROGMEM (program memory). So, code for functions does not, in itself, use RAM.

As an example, this small program for the Micro:

```
int main ()
  {
  }

```

That uses only 206 bytes of PROGMEM and 0 bytes of RAM (according to the IDE).

```
Sketch uses 206 bytes (0%) of program storage space. Maximum is 28,672 bytes.
Global variables use 0 bytes (0%) of dynamic memory, leaving 2,560 bytes for local variables. Maximum is 2,560 bytes.

```

---

Adding in a class, with a constructor, and using that class, increases the memory a bit:

```
class foo
  {
  public:
  int bar;  // some class variable

  foo ()  // constructor
    {
    bar = 1;
    }
  };  // end of foo

foo nick;  // a global variable
int main ()
  {
  PORTD = nick.bar;
  }

```

That uses 2 bytes of RAM, and 278 bytes of PROGMEM. Hardly a lot.

```
Sketch uses 278 bytes (0%) of program storage space. Maximum is 28,672 bytes.
Global variables use 2 bytes (0%) of dynamic memory, leaving 2,558 bytes for local variables. Maximum is 2,560 bytes.

```

---

Of course, the more things you do, the more RAM and PROGMEM it takes, however the compiler generates quite efficient code, and the linker strips out things that are not needed by your code.

---

> Is it that Arduino's library does not contain or utilize features such as constructors or objects (of C++) ...

A lot of libraries use classes and constructors (for example the Serial library, the Print class, and a lot of others). There is nothing inherently RAM-intensive about a constructor. It's just a function that does something, with an implied **this** pointer to the current instance of the class.

---

> do lambdas work? (from a comment)

Yes you can use lambdas:

```
// array of function pointers
void (*doActionsArray []) () =
 {
 [] { Serial.println (0); } ,
 [] { Serial.println (1); } ,
 [] { Serial.println (2); } ,
 [] { Serial.println (3); } ,
 [] { Serial.println (4); } ,
 };

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  doActionsArray [3] ();
  }  // end of setup

void loop () { }

```

---

> as long as you don't (extensively) use: the standard library, exceptions, templates ... (from a comment)

Templates can certainly simplify doing things like writing to, or reading from EEPROM and similar. For example:

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

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

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

```

---

The standard library? There are implementations for the Arduino. We have to bear in mind that RAM is limited, however if you are going to do something *anyway* that involves linked lists, etc. then the Standard Template Library will probably do what you want as efficiently as you could if you coded it "by hand".

---

The bottom line is you need to be aware of what you are coding on. I have seen examples like this:

```
float foo [1000];  // hold my readings

```

That blows the available RAM on a Uno straight away. Nothing to do with C++ per se.

---

The other thing to be aware of is some tricks you can usefully employ. One common one is to replace:

```
Serial.println ("Program starting.");

```

With:

```
Serial.println (F("Program starting."));

```

The first example causes the compiler to copy the string "Program starting." from PROGMEM into RAM, using some of your valuable RAM. The second example doesn't.
> 14 votes

# Answer
The talk about C++ being incompatible with small MCUs implies that developers would use features it provides. In a *good* C++ project you're expected to use vectors and iterators instead of C arrays, throw exceptions instead of returning error codes, use lambda-functions, templates etc.

As long as you don't use those features, C++ memory consumption is manageable. The reason for this is simple: such limited C++ is just a syntactic sugar around C structures and function pointers.

The problems usually start when you write a class which is complex enough that its constructor can fail. Then you have a tough choice to make: start using exceptions and drastically increase memory consumption, or write classes which *pretend* they never fail to construct (which often results in a program which *pretends* to work).
> 5 votes

# Answer
C++ is fine with Arduinos or other AVR based Systems. I've been use it for quite a while in a home automation project.

The avr runtime does not support exceptions nor dynamic memory allocation, as has been stated. you can provide an implementation though.

There is much of C++ left to make use of. here are some examples

**Templates**

They are very useful because, e.g. they allow to move work from runtime to compiletime. I use template for a replacement of the Arduino HAL functions DigitalWrite and others, without the runtime and code bloat.

compare this

```
int main(void)
{
        DDRB |= (1<<7);
        while(  (  ( PINB & (1<<6) ) !=(1<<6) ) )
                ;
        while(1)
        {
                _delay_ms(100);
                PORTB |= (1<<7);
                _delay_ms(100);
                PORTB &= ~(1<<7);
        }
}

```

to this

```
int main(void)
{
        IOPin<13> ledpin;
        IOPin<12> testpin;
        ledpin.SetDir(out);

        while(0 == testpin.State())
                ;
        while(1)
        {
                _delay_ms(100);
                ledpin.SetHigh();
                _delay_ms(100);
                ledpin.SetLow();
        }
}

```

The template based version is much more readable, and generates exactly the same assembler code. In the abovementioned linked article i explain the template and why this works.

**more on templates**

The following code uses the "curiously recurring template pattern" CRTP. It is used to create a job class, which i use for a primitive scheduling

This template builds a chain of registrable items.

```
template<class registered>
struct Registered {
    static registered *registry;
    registered *chain;
    Registered() : chain(registry) {registry=static_cast<registered*>(this);}
};

```

The job class applies the CRTP pattern. The constructor takes the actual callback where the work is done, and how often the job is done.

```
class Job : public Registered<Job>
{
    voidFuncPtr m_p;
    uint16_t m_periodic;
    uint32_t m_lastrun;
    uint16_t m_initialdelay;
    public:
    Job(voidFuncPtr p,uint16_t periode=0,uint16_t initialdelay=0):m_p(p),m_periodic(periode),m_lastrun(0),m_initialdelay(initialdelay)
    {

    }
    void run(uint32_t t_ms)
    {
        // tbd handle wraparound !!
        if(t_ms >= m_lastrun + m_periodic + m_initialdelay)
        {
            m_p();
            m_lastrun=t_ms;
            m_initialdelay=0;
        }
    }
};

```

to use the job class i just create the instances for the jobs and pass lambdas or regular function pointers

```
Job jserial([](){mqttrouteradapter.handleSerialMQTT();},10);
Job jupdate(updatemc,1);
Job jprint(printstate,500);

```

initialize the beginning of the chain of jobs

```
template<> Job *Registered< Job >::registry = 0;

```

and inside main, run an infinite loop which calls the jobs.

```
while (1)
    {
        for ( auto p = Job::registry; p; p=p->chain )
        p->run(millis());
    }

```

**Lambdas**

Nice to avoid a callback function

instead of

```
void handleserial(void)
{
    mqttrouteradapter.handleSerialMQTT();
}
Job jserial(handleserial,10);

```

i can write something like

```
Job jserial([](){mqttrouteradapter.handleSerialMQTT();},10);

```

**the new meaning of auto**

Allows to deduce the type automagically. This function iterates over "something" passed the second parameter. It compiles, if the passed type provides the operations/attributes used in the function. And yes, **this** works only since c++17

```
void runRx(const char* data, auto msg_registry) {
    for (auto p = msg_registry; p; p = p->chain) {
        p->rx(data);
    }
}

```

**using a recent compiler**

If you want to use a recent compiler (The Arduino IDE uses gcc4.9) you can build your own gcc avr toolchain rather easily. Then you have gcc 7.2 with c++17 support ! An other very good reason to use gcc 7.2 is, that they have improved the error messages by a great deal.

My conclusion is, there is no excuse using c, except you havn't yet learned c++. And use a new compiler !
> 5 votes

# Answer
To write effective code with limited resources (RAM, program space, processing), you need to know enough about the processor to avoid features which it can't do. In this case you're limited on all three counts, so you want to get away from anything complex and slow.

A good start is to avoid any features later than C++98, or at least C++03. These features generally come at a cost.

Beyond that, particular issues are:-

* Polymorphism. All classes using virtual members have a virtual method table, meaning every function call from that class needs to look up against a table. On a small processor, this does slow down your function calls. By all means use this where it's required, but if you have performance issues then you want your polymorphic classes to live at a higher level where the function calls happen less often. Don't do this for low-level functions which get called thousands of times in a loop.
* Exceptions. Already covered by other answers.
* Inline. This is a *good* thing. Where you can use this, it can claw back some processing cycles: not just from the function call itself; but also from further optimisation in the calling functions.

And of course general issues for embedded firmware on low-end micros:-

* Dynamic memory allocation (new and delete, or most STL containers). This is ***always*** an anti-pattern in embedded development. It requires a chunk of RAM to be set aside for heap, and you always need to consider the possibility of allocation failing. If you really need some kind of dynamic storage, consider whether a FIFO buffer or something better bounded would be appropriate.
* Longer integers.
* Integer multiply and divide.
* Anything floating-point.
* Anything using a lot of stack, whether this is lots of local variables, lots of function parameters, or over-enthusiastic function partitioning.
> 1 votes

---
Tags: c++, arduino-micro
---


title: Arduino Burn the code programmatically

text:
# Question
Title: Arduino Burn the code programmatically
Is it possible to burn arduino code programmatically?

I was thinking of one way and that is to download hex file from my online server. Store contents of the hex file in a string, and write that string to arduino flash, restart arduino and it should run new code in flash.

Can this be done? If not than please suggest me any other way to burn the code using C++ instructions.

# Answer
First, the Arduino Uno has 32 KB of flash, but only 1 KB of RAM. So, to be able to store the new program in a string means your new program can only be, at most, 1kb.

Secondly, only the bootloader can write to flash. So you could write a new bootloader that downloads the new program (in parts) and writes it to the flash. You would however need quite a big bootloader, leaving less space for actual code. Also the main program still needs to access the server to see if it needs to "reboot" so the bootloader can run the update process.

An example of an OTA bootloader can be found at https://www.rotwang.co.uk/projects/bootloader.html which might be a good starting point. Similar idea https://ncrmnt.org/2014/02/27/rf24boot-a-universal-over-the-air-bootloader-for-all-those-ucs/

Another option is to write the new firmware to an external EEPROM. Then your modified bootloader only has to read the new firmware from EEPROM, making it a lot simpler and smaller. There is some useful info in the question OTA updates for Arduino using nRF24L01+

MySensors.org already made such a bootloader: https://www.mysensors.org/about/bootloader

I know there exists another bootloader that does just that, but I can't seem to find it.
> 5 votes

---
Tags: arduino-uno, bootloader
---


# Question
Title: Arduino Uno R3 to Wemos D1 R2 project migration - Pinout problems
So i've chosen to purchase a Wemos D1 R2 board in order that my old Arduino Uno R3 projects can get some new IoT features. However, even if my code is working in Uno perfectly, i want to test it using D1 before adding features. My problem is that, even if i have found tables showing differences between the 2 boards' pinouts, i cannot understand the correspondence between the pinouts.

So i am giving you the table below. Let's say i want to define echo and trigger pins for a sensor in my code. For example:

```
#define TRIGGER_PIN 4
#define ECHO_PIN 3

```

That would be pins D3 and D4 at my Uno. But i cannot understand which those pins would be in Wemos D1 R2. Also, my two boards can be seen below for comparison

# Answer
> 6 votes
The tricky thing with the WeMos boards is the pin notation is different from other Arduino boards.

Sometimes you will see the digital pins on Arduino boards referenced with the D*n* notation. For example: "Connect the HC-SR04's Trig pin to D4 on the Uno". In fact some boards such as the Nano even use the D*n* pin notation on their silkscreen. This is just a way of further differentiating the pins from the A*n* pins. You will only refer to that pin by the number 4 in your code.

The WeMos boards are different. You actually need to use `D3` and `D4` in your code to control the pins marked D3 and D4 on the silkscreen:

```
#define TRIGGER_PIN D4
#define ECHO_PIN D3

```

We can take a peek at the source code of the ESP8266 core for Arduino to see why: https://github.com/esp8266/Arduino/blob/2.4.0/variants/d1\_mini/pins\_arduino.h#L40-L50

```
static const uint8_t D0   = 16;
static const uint8_t D1   = 5;
static const uint8_t D2   = 4;
static const uint8_t D3   = 0;
static const uint8_t D4   = 2;
static const uint8_t D5   = 14;
static const uint8_t D6   = 12;
static const uint8_t D7   = 13;
static const uint8_t D8   = 15;
static const uint8_t RX   = 3;
static const uint8_t TX = 1;

```

Now you can see that if you use your original code:

```
#define TRIGGER_PIN 4
#define ECHO_PIN 3

```

That would actually be referring to the pins marked D2 and RX on the WeMos D1 R2!

---
Tags: arduino-uno, arduino-ide, pins, port-mapping
---