# Question
Title: Can't store RFID data in the next 5 bytes of array
I'm working on RFID project to handle multiple cards.

I did most of the things OK. But now I have one problem. Which is the following:

1. The RFID code is 5 bytes, so I need an array of 5 bytes. If more cards then the array size = number of card * 5.
2. For my example I'm working with 2 cards. So array size is 10 bytes.
3. I can store the first card in the first 5 bytes.

The problem: I can't store the 2nd card in the next 5 bytes in the array. I don't know why.

This is my only test code:

```
/****************************** LIBRARIES ******************************/
#include <SPI.h>
#include <RFID.h>

/****************************** DEFINITIONS ******************************/
// pins definitions
#define SS_PIN          10
#define RST_PIN         9

// setup definitions
#define CARDS           2
#define MXCD            CARDS*5

/****************************** VARIABLES ******************************/
// rfid variables:
byte crd_buf[MXCD],card_no;
byte register_lock,check_lock,print_lock;

/****************************** FUNCTIONES ******************************/
// rfid functions
void register_accepted_card(void);
void record_new_cards(void);
void check_card(void);
void print_registered_cards(void);

// objects
RFID rfid(SS_PIN, RST_PIN);

//////////////////////////////////////////////////////////////////////
void setup(){
  Serial.begin(9600);
  SPI.begin();
  rfid.init();
}

void loop(){
    register_accepted_card(); // apply only once
}

void register_accepted_card(void){
  if (!register_lock) {
    if (rfid.isCard()) {
      if(rfid.readCardSerial()){
        if(card_no>0){
          for(byte i = 0; i<card_no; i++){
            if(!memcmp((crd_buf+(i*5)),rfid.serNum,5)){

              Serial.println("already card is");
              for(byte p = i*5; p<(i*5)+5; p++){
                Serial.print(crd_buf[p],HEX);Serial.print(", ");}
                Serial.println();

              lcd_state = ALREADY_MSG;
              register_lock = 1;
            }
          }
        }

        //////////////////////////
        // problem is in this part
        //////////////////////////

        if(!register_lock){

          for(byte i=card_no*5;i<(card_no*5)+5;i++){
            crd_buf[i] = rfid.serNum[i];}

          Serial.print("loop#"); Serial.println(card_no);
          Serial.print("start index ");Serial.println(card_no*5);
          Serial.print("end index ");Serial.println((card_no*5)+5);
          Serial.println();

          Serial.print("card#"); Serial.println(card_no+1);
          for(byte i=card_no*5;i<(card_no*5)+5;i++){
            Serial.print(crd_buf[i],HEX);Serial.print(", ");}
          Serial.println();Serial.println("//////////////////////////");

          card_no++;
          if(card_no >= CARDS){lcd_state = FINISH_MSG;}
          else{lcd_state = REGISTER_MSG;}
          register_lock = 1;
        }
      }
    }
    rfid.halt();
  }
}

```

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

My second question, for the part of checking the cards after finishing registering the cards to be accepted.

I did a for loop for the number of cards to get the card that is registered in the array and send a message that the card is stored and accepted, otherwise, it returns a denied message that the card isn't stored in the array with alarm buzzer.

The problem that is the for loop checks the card for all the indexes in the array which is what I want but the result is mixed with accepted and denied.

The question is how to get out of the for loop?

```
void check_card(void){
  if (check_lock){
    if (rfid.isCard()){
      if (rfid.readCardSerial()){
        for(byte i=0;i<card_no;i++){

          // start of for loop
          Serial.print("check# ");Serial.println(i);
          if(!memcmp(crd_buf+(i*5),rfid.serNum,5)){
            Serial.println("card accepted");
            digitalWrite(ACCEPT_LED,HIGH);
            digitalWrite(DENIED_LED,LOW);
            digitalWrite(BUZZER,LOW);
            check_lock = 0;
            sys_state = 1;
            lcd_state = ACCEPTED_MSG;
          }
          else{
            Serial.println("card denied");
            digitalWrite(ACCEPT_LED,LOW);
            digitalWrite(DENIED_LED,HIGH);
            digitalWrite(BUZZER,HIGH);
            check_lock = 0;
            sys_state = 1;
            lcd_state = DENIED_MSG;
          }
        }
            // end of for loop

      }
      rfid.halt();
    }
  }
}

```

# Answer
> 1 votes
Your problem is this bit:

```
      for(byte i=card_no*5;i<(card_no*5)+5;i++){
        crd_buf[i] = rfid.serNum[i];}

```

For the first card you're copying bytes 0-4 of the serNum to bytes 0-4 of crd\_buf.

However for the second card you're copying bytes 5-9 of serNum to bytes 5-9 of crd\_buf. That's correct for crd\_buf but wrong for serNum.

The right way would be to add card\_no\*5 to i when creating the index:

```
      for(byte i=0; i<5; i++){
        crd_buf[(card_no*5) + i] = rfid.serNum[i];}

```

Or better to define your card buffer as a 2D array so you don't need to do that calculation:

```
byte crd_buf[CARDS][5];

for (i = 0; i < 5; i++) {
    crd_buf[card_no][i] = rfid.serNum[i];
}

```

Or simpler:

```
memcpy(crd_buf[card_no], rfid.serNum, 5);

```

---

For your second question, don't print your message at all in the loop.

Instead start out assuming that access is denied. Then if a card matches, grant access. The simplest way is with a flag.

```
if (rfid.readCardSerial()){

    bool accessGranted = false;  // A flag to store the state - start off denied.

    for(byte i=0;i<card_no;i++){
        if(!memcmp(crd_buf+(i*5),rfid.serNum,5)){
            accessGranted = true;
        }
    }

    // replace these with your own message routines.
    if (accessGranted) {
        Serial.println("Access Granted");
    } else {
        Serial.println("Access Denied");
    }
}

```

---
Tags: arduino-uno, array, rfid, datalogging
---


# Question
Title: Why is no PWM signal generated using Timer 2?
I managed to work with timer 0 and 1 but am unable to generate a PWM with timer 2 in my atmega328p.

This is the code:

```
#include <avr/io.h>

int main(void)
{
    /* PD6 output */
    DDRD |= (1 << DDD6);

    /* 50% duty cycle */
    OCR2A = 128;

    /* fast PWM  */
    TCCR2A |= (1 << WGM21) | (1 << WGM20);

    /* prescaler = 8 */
    TCCR2B |= (1 << CS21);

    while (1);

}

```

Could someone explain what the issue is and why I am not seeing a pwm signal on pin 6 of my arduino uno board?

Thanks

# Answer
> 5 votes
The output compare unit of timer 2 is connected to pins PB3 (OC2A) and PD3 (OC2B). So you have to configure those as outputs. Keep in mind that you can't choose any pin when using hardware pwm, this hardware feature is linked to specific pins.

You also have to set `COM2A1` in `TCCR2A`. Otherwise `OC2A` is disconnected from the output compare unit (ref: Table 17-3 in datasheet). The effect of `COM2A0/1` depends on the configuration in `WGM20`-`WGM22`. The same applies to `OC2B` respectively.

---
Tags: timers
---


# Question
Title: How to sample incoming 600khz pin and divide it by 4 and generate low frequency signal at output pin of arduino
I am trying to divide a incoming high frequency signal 600kHz by 4 and output wave at arduino MEGA2560 digital pin.

* The input to arduino comes from incremental Encoder which is connected to motor that runs at 9000 rpm and the generates 1024 pulses per rotation.
* I am trying to downsample the frequency I am getting from arduino to 250kHz or less.
* I tried following approaches :

a. I counted the rising edge of the incoming wave and a interrupt is triggered as number of rising edge reaches certain value and ISR toggle an output pin. b. I tried to get hardware counter work at T0 pin but I was not able to hit ISR when the count has reached specific value.

The problem with approach 1 is: As my frequency of incoming wave increases the output wave starts missing some pulses and generates one half cycle for 6/8/10 pulses of incoming wave. It should actually generate one half cycle for 4 pulses.

**Here is approach 2 code:**

```
#define outPin1 10
volatile short encoder = 4;

void setup ()
{
   pinMode (outPin1, OUTPUT);
   Serial.begin(9600);
   cli();
   // reset Timer 0
   TCCR0A = 0;
   TCCR0B = 0;

 }  // end of setup

 ISR(TIMER0_COMPA_vect)
 {
     digitalWrite(outPin1, !digitalRead(outPin1));

 }

 void loop ()
 {
    TCNT0 = 0;      //counter to zero

    // set compare match register to desired timer count:
   OCR0A = encoder;
    // turn on CTC mode:

   bitSet(TCCR0A, WGM01);
   // Timer 0 - counts events on pin D4

  bitSet(TIMSK0, OCIE0A);    // interrupt on Timer 0 CTC
   // start Timer 0
  // External clock source on T0 pin (D4). Clock on rising edge.

   bitSet(TCCR0B, CS02);
   bitSet(TCCR0B, CS01);
   bitSet(TCCR0B, CS00);
}

```

**Please someone help me out with this issue**

# Answer
> 3 votes
This is probably too fast to have have software involved in the loop. You should try to use a hardware-only solution. Note the Arduino timers should be usable as hardware frequency dividers:

* configure a timer to be clocked off the input signal, so that it behaves like a counter.
* configure it for delivering a PWM output with a period of 4 timer clock cycles and a duty cycle of 50%.

You may try this, but beware I have not tested it:

```
void setup()
{
    // Configure Timer 5 as a frequency divider:
    //   input: digital pin 47 = PL2 = T5
    //   ouput: digital pin 46 = PL3 = OC5A
    DDRL  |= _BV(PL3);    // set pin PL3 as output
    TCCR5A = 0;           // undo the Arduino core's configuration
    TCCR5B = 0;
    ICR5   = 4 - 1;       // period = 4 timer clock cycles
    OCR5A  = 2 - 1;       // output HIGH for 2 timer clock cycles
    TCCR5A = _BV(COM5A1)  // non-inverting PWM on pin OC5A
           | _BV(WGM51);  // mode 14: fast PWM, TOP = ICR5
    TCCR5B = _BV(WGM52)
           | _BV(WGM53)
           | _BV(CS50)    // clock on rising edges of T5
           | _BV(CS51)
           | _BV(CS52);
}

void loop(){}

```

# Answer
> 1 votes
I am writing another answer because what I propose here is radically different from the previous answer. In that answer I wrote that this is too fast for being done in software, and here I am going to contradict myself. :-/

At 600 kHz, the input stays low for roughly 13 CPU cycles, then high for another 13 cycles. You cannot do much in 13 cycles. Notably, the prologue of an ISR can quite often take more than this. Also, whenever the Timer 0 overflow ISR from the Arduino core fires, it can delay your own ISR for way more than 13 cycles. That's why it is usually illusory to expect any job to be reliably done in this time frame. Especially if interrupts are involved.

That being said, if the CPU has *absolutely nothing else* to do. And specifically if it is never interrupted, Then it can keep up with that pace. Here is a program that should do what you expect. I initially thought about writing it in assembly, but it can also be written in C, as the compiler translates it in a quite straightforward way. If in doubt, however, check the generated assembly:

```
/*
 * From one square wave generate two waves in quadrature at 1/4 of the
 * original frequency.
 *
 * https://arduino.stackexchange.com/questions/63202
 *                               _   _   _   _   _   _
 *  input:  digital 13 = PB7    / \_/ \_/ \_/ \_/ \_/ \_/
 *                               _______         _______
 *  output: digital 10 = PB4    /       \_______/       \
 *                                   _______         ____
 *  output: digital 11 = PB5    ____/       \_______/
 */

int main(void)
{
    DDRB = _BV(PB4) | _BV(PB5);  // PB4 and PB5 as outputs
    for (;;) {
        loop_until_bit_is_clear(PINB, PB7);  // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB |= _BV(PB4);                   // rise PB4
        loop_until_bit_is_clear(PINB, PB7);  // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB |= _BV(PB5);                   // rise PB5
        loop_until_bit_is_clear(PINB, PB7);  // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB &= ~_BV(PB4);                  // fall PB4
        loop_until_bit_is_clear(PINB, PB7);  // wait for rising input
        loop_until_bit_is_set(PINB, PB7);
        PORTB &= ~_BV(PB5);                  // fall PB5
    }
}

```

Note that, since this is not using the Arduino core, I wrote `main()` rather than `setup()` and `loop()`. This overrides the `main()` provided by the core, thus you don't have the initializations that come with it and, in particular, you don't have the Timer 0 interrupt.

---
Tags: arduino-uno, arduino-mega, rotary-encoder
---


title: Brushed ESC won't move slowly

text:
# Question
Title: Brushed ESC won't move slowly
I'm trying to control the brushed motor in a Traxxas Slash RC car with the built-in XL5 ESC using the Servo library on Arduino. I previously had success controlling this car with a Pololu Micro Maestro, but it died on me, and so, while waiting for a replacement to arrive, I thought I'd give a more manual approach a try.

The problem is, the motor moves *way* too fast. My understanding is that, for this ESC (which allows for reverse driving), 90 degrees / 1500 ms should be the neutral point, with anything above this leading to progressively faster forward speed; and, below, reverse. But, while it seems there is some speed modulation, the motor just abruptly begins with a very high speed at an angle (`Serial.write(95)`) of 95 or so, and then gets even faster from there.

A minimal version of my code is pasted below; my circuit has the signal pins of the steering and ESC servo connectors (white wires) attached to pins 2 and 9, respectively on a Pro Micro, their two 5V pins connected to each other (since the ESC supplies its own 5V), and their grounds connected to the Arduino's ground pins.

While it's possible that I need a special arming sequence to get this ESC to work properly (I do operate in the three-blink "training" mode, which is supposed to be slower), I would expect that problem to manifest as no motion at all, not too *much* motion.

I've tried powering the ESC with the original 9.1V battery (nominal 8.4V), and with a 8.4V regulated supply attached to a ~15V battery.

What could I be doing wrong here?

```
#include <Servo.h>

Servo throttle;

void setup(){

    Serial.begin(115200);

    throttle.attach(9);
    // throttle.write(91);
    // delay(300);

    int first = 90;
    for(int angle=first; angle < first+20; angle++) {
        Serial.println(angle);
        throttle.write(angle);
        delay(10);
    }

    // This doesn't work any better.
    // int first = 1500;
    // for(int us=first; us < first+10; us++) {
    //     Serial.println(us);
    //     throttle.writeMicroseconds(us);
    //     delay(50);
    // }

    throttle.write(90);
}

void loop() {
}

```

# Answer
> 1 votes
Per @jsotola 's suggestion, I looked more closely at the manual (see the section "XK-5 Setup Programming"):

> XL-5 Setup Programming (Calibrating your ESC and transmitter)
>
> Read through all of the programming steps before you begin. If you get lost during programming or receive unexpected results, simply unplug the battery, wait a few seconds, plug the battery pack in, and start over.
>
> 1. Disconnect one of the motor wires between the XL-5 and the motor. This is a precaution to prevent runaway when the speed control is turned on before it is programmed.
> 2. Connect a fully charged battery pack to the XL-5.
> 3. Turn on the transmitter (with the throttle at neutral).
> 4. Press and hold the EZ-Set button (A). The LED will first turn green and then red. Release the button.
> 5. When the LED blinks RED ONCE, pull the throttle trigger to the full throttle position and hold it there (B).
> 6. When the LED blinks RED TWICE, push the throttle trigger to the full reverse and hold it there (C).
> 7. When the LED blinks GREEN ONCE, programming is complete. The LED will then shine green or red (depending on LowVoltage Detection setting), indicating the XL-5 is on and at neutral (D).

I wrote a short program to send specified servo angles in \[0, 180\] interactively. The manual says to apply "full throttle" and "full reverse", but I wasn't exactly sure what these translated to in terms of servo angle/pulse width milliseconds. I gather that these are often given as 45° and 135° (1.25 ms and 1.75 ms), respectively, but that setting the limits to \[0, 180\] during this training period also worked. It's valuable to get the full range, so I can get finer gradations in speed. Since I don't expect to ever reach full speed in my application, and will only use the near-90 part of the range, this will be particularly helpful.

I'm still perplexed about what caused the original problem--the Pololu servo controller never needed this tuning process. Perhaps the limits were set to \[45, 135\], and I mistakenly sent 180, which put the ESC into some state not described in the manual. And I don't know whether I'll need to repeat this in the future, or whether my new \[0, 180\] limits will prevent the above mistake from being a problem. For that matter, I don't know how non-volatile the non-volatile memory is on the ESC in which these limits are stored. Does it require periodic battery power to refresh?

Finally, while it might be even more particular to the XL-5 ESC and my power supply setup, another useful note is that the low-voltage detection mode might prevent movement independent of the setup process.

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


# Question
Title: What Version of the Sketch did I leave on there?
Is there a way to "ask" the Arduino what sketch was compiled on it?

There are several versions of the sketch and I need to see which version the Arduino has been running.

# Answer
> 2 votes
First, you have to store the desired information in your sketch.

```
#define VERSION F("0.01 4-Apr-2019")

void setup() {
   Serial.begin(9600);
   Serial.print(F("Test Sketch V"));
   Serial.println(VERSION);
}

void loop() {
}

```

Of course any other way might work as well:

* Only print it, if at reset a test button is pressed
* Check for a Serial command and respond the version info.
* Don't print it, but use avrdude and a programmer to read the FLASH memory and search it for the version string. (Similar to jot's comment above)

# Answer
> 0 votes
If you have not set the flash protection bits you can read back the contents of the program memory. See https://www.evilmadscientist.com/2011/avr-basics-reading-and-writing-flash-contents/

By reading back the first pages you can then compare with the different versions of the sketch (hex file) and determine which version is on the device. The first pages are the different ISR vectors and should be unique for the sketches.

Cheers!

---
Tags: programming
---


title: Multiple void loops with ESP8266

text:
# Question
Title: Multiple void loops with ESP8266
I want to run multiple sketches on one sketch. I use the method of multiple void loops. It works but esp8266 take a lot of time to execute commands.

```
void Setup()
 {
  setup1();
  setup2();
 }
void loop()
 {
  loop1();
  loop2();
 }

```

Is there any method to avoid that ?

# Answer
If the `setup()` or `loop()` functions call `delay()` then of course that will delay getting to the next function and will slow down the whole process.

The only way to deal with that is to rewrite the code, combining what you're calling and fixing it so that it takes into account the other work it needs to do.

Same thing if you call any blocking functions, like reading from `Serial` until you get a newline.

If that's not the case... well, the ESP8266 is a small, not particularly fast processor. If there are no delays or blocking functions then your code is running as fast as your code might run and you'll just have to live with it.
> 1 votes

# Answer
As long as you're not using `delay()` or other blocking code, as John mentions in his answer, that approach will work fine. I have a fairly large project where I defined a class `ArduinoObject`. The `ArduinoObject` class has a setup method and a loop method, and the main sketch creates and manages an array of `ArduinoObject`s (and another stack of a subclass of `ArduinoObject` called a `MenuObject` that manages menus on the LCD screen the project uses.)

At times there are a dozen or more `ArduinoObjects` being called on each pass through the sketch's `loop()` function and it works just fine. The key thing is to write your sub-loops to be FAST. They should do a tiny amount of work on each pass, and then a little more on the next pass (if needed.) You never want one of your sub-loops to take enough time to make the other sub-loops "stutter".
> 0 votes

---
Tags: esp8266, arduino-ide, core-libraries
---


# Question
Title: Can someone check my code? My Arduino isn't doing a consistent count cycle
I'm wondering if someone could have a look at my code and let me know if there's something wrong with it. I had the code done for me a while back and did a quick test and it seemed to work. I have now built a pneumatic machine for it to work on, and it's doing some strange things.

The first relay turns on and off a pneumatic solenoid, this is connected to a small pneumatic cylinder, it moves in and out. This cylinder causes a pneumatic feeder to activate and move back and forth also.

The feeder has a proximity sensor attached which lights up when the feeder is in its resting position.

The solenoid turns on for approx half a second and then back off again, this pushes the small cylinder out then back in. This sends the feeder forward, it then turns around and comes back toward its resting position. The Arduino waits for the signal from the proximity sensor to tell it that the feeder is back in its resting position before doing it again.

It then repeats this sub cycle about 20 times.

After 20 sub cycles, the Arduino turns on the second relay for about a second, before turning it back off again.

It then does this whole complete cycle 20 times before stopping.

There's a momentary switch as well, which when pushed, is supposed to restart everything again.

It almost works, the closest i have had is where it was doing the cycles but counting them wrong. i changed the subcycle to 16 instead of 20 and it would count somewhere between 10 and 16. it seems to count different each time.

I just bought a new board and tried again, but now it counts to about five subcycles and then jumps the gun and doesn't wait for the signal from the proximity sensor before doing the next sub cycle. So once again the count ends up wrong.

Any ideas what I could try?

```
int Relay_1 = 10;           //first Relay
int Relay_2 = 11;           //second Relay
int Prox_Input = 12;        //input signal from proximity sensor
int Switch_Input = 13;      //the switch

int Cycle_Number = 20;      //number of repeating number of "complete" cycle
int Sub_Cycle_Number = 20;  //number of repeating number of "sub" cycle
int Delay_Cycle = 1000;     //delay of the "Complete" Cycle in milleseconds
int Delay_Sub_Cycle = 500;  //delay of the "Sub" Cycle  in milliseconds

bool Button_Pushed = true ; //the state required for the button
int i, j;

void setup() {
  /*configurate the output relays to be begin "low"*/
  pinMode(Relay_1 , OUTPUT);
  digitalWrite(Relay_1, LOW);

  pinMode(Relay_2 , OUTPUT);
  digitalWrite(Relay_2 , LOW);
  /*===========================================================*/
  /*configurate the input switch and sensor*/
  pinMode(Prox_Input , INPUT);
  pinMode(Switch_Input , INPUT_PULLUP);
  /*===========================================================*/
  /*configurate Serial port if you want it*/
  Serial.begin(9600);
  /*===========================================================*/
}

void loop() {
  if (Check_Button() == Button_Pushed) { //check the button
    for (i = 1 ; i <= Cycle_Number ; i++) { //the loop of the "complete" Cycle
      for (j = 1 ; j <= Sub_Cycle_Number ; j++) { //the loop of the "sub" Cycle
        digitalWrite(Relay_1 , HIGH);
        delay(Delay_Sub_Cycle);
        digitalWrite(Relay_1 , LOW);
        while (digitalRead(Prox_Input) == HIGH) {} // waiting the sensor signal
      }
      digitalWrite(Relay_2 , HIGH);
      delay(Delay_Sub_Cycle);
      digitalWrite(Relay_2 , LOW);
      delay(Delay_Cycle);
    }
  }
}

bool Check_Button()  {
  int Reading_1;
  int Reading_2;

  Reading_1 = digitalRead(Switch_Input);
  delay(20);
  Reading_2 = digitalRead(Switch_Input);
  if ((Reading_1 == 1) && (Reading_2 == 1))
    return true;
  else
    return false;
}

```

# Answer
> 0 votes
The only reason it might "jump the gun" would be this line:

> ```
>          while(digitalRead(Prox_Input) == HIGH){}          // waiting the sensor signal
>
> ```

I suggest you check for a *transition*, that is, make sure the proximity switch has become LOW, and then wait for it to become HIGH again. So for example, if sending HIGH to the relay should make the proximity sensor read LOW, then put a loop in to make sure it does that, before proceeding.

---
Tags: programming, code-review
---


# Question
Title: Wire with MCP23008 I/O expander with I2C
I'm trying to read from an MCP23008 I/O expander using the Wire library over I2C. The MCP23008 is wired to address 0x04, giving an effective device address of 0x24. Writing to the device GPIO seems to work fine, and I'm a bit confused on how to read from the GPIO.

So I set it up for read as follows:

```
#define MCP23008_DEVICE_I2C_ADDRESS 0x20
#define MCP23008_SLAVE_I2C_ADDRESS  0x04

#define MCP23008_REGISTER_IODIR     0x00
#define MCP23008_REGISTER_GPIO      0x09

#define IO_ALL_PINS_INPUT           0xFF

inline void eeprog::_read_enable()
{
    Wire.beginTransmission(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS);
    {
        Wire.write(MCP23008_REGISTER_IODIR); // Set I/O direction
        Wire.write(IO_ALL_PINS_INPUT);       // Set all pins as input
    }
    Wire.endTransmission();
}

```

after which I attempt to read from it, by first addressing the GPIO register and then requesting a byte to read:

```
inline uint8_t eeprog::_read()
{
    Wire.beginTransmission(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS);
    {
        Wire.write(MCP23008_REGISTER_GPIO); // Select the GPIO register
    }
    Wire.endTransmission();

    Wire.requestFrom(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS, (uint8_t)1);

    return Wire.read();
}

```

Looking at my logic analyzer this is what I get:

The NACK seems to indicate that the read went wrong.. actually a bit unsure what "Data read: 07" means in this context, did it read the value 7, or did it try read address 07?

Any ideas what I could be doing wrong? Am I missing something obvious from the documentation?

# Answer
Everything is fine and nothing is wrong.
You are reading the GPIO register and its contents is 0x07.

The NACK at the end is not an error, it is a way to communicate between the Master and Slave.

When the Master reads data, the Master gives an ACK after each databyte from the Slave. The Master is not trying to tell the Slave that it was received, but rather it tells the Slave that another byte is going to be read.
After the last databyte, the Master send a NACK and after that a STOP.

Since only one byte is read, the Master sends a NACK and a STOP. The Master is telling the Slave that no more data is needed.

The I2C bus is only two wires. There are START, STOP, ACK and NACK conditions and the clock pulse can be stretched by a Slave. The possibilities are limited. For example when the Master wants to read 6 bytes and the Slave has only 1 byte. The Slave has no way to tell the Master that it has only 1 byte, and the Master will read those 6 bytes, valid or not.
> 1 votes

---
Tags: arduino-uno, io-expander
---


title: How to calibrate the MQ7 sensor module?

text:
# Question
Title: How to calibrate the MQ7 sensor module?
I recently bought a **MQ7 sensor module** like the one in the attached picture. I have read several tutorials, and they're all different. Some of them says that i need to **connect the module directly to 5v** and wait 24 hours to made it work properly, others says that i need to program **different periods (5v and 1.4v) and wait the same time to make correct meditions.** I read this Datasheet, but i think that the information it has is not for the module.

If anyone knows how to setup this module i will aprecciate an answer (i want to read analog values).

Thanks in advance and sorry for my bad english.

# Answer
> 2 votes
first of all, you need to understand how these sensors work.

1. the sensor itself is just a resistor (like a normal resistor, with 2 legs) which is constructed from materials that are affected in presence of a specific gas. the gas changes its resistance. but as it's obvious, these type of materials are not calibrated.
2. in order to make that resistor sensitive enough, we have to warm it. so the manufacturer puts a simple coil element near the resistor in the capsule and you connect it to 5v. it warms up (it draws a lot of current) and thus, the effect of gas on the resistor becomes greater and we can measure it easily. when they say connect and let it be for 24 hours they mean warming up the resistor. I think it's a little high. I used them after a few minutes of warming up but it depends on situation and desired precision.
3. the resistor and element, have separate pins and are completely independent. you have to connect the coil to 5v (because manufacturer made it like that) and use the resistor anyway you like. even with a ohmmeter.
4. as we have to use Arduino, so we have to measure a resistor with the ADC of Arduino. the procedure is straightforward. you put a normal resistor in series with the sensor resistor and make a voltage divider (search that if you don't know about it. it's a fundamental thing to know in electronics).I think there should be a schematic in datasheet for it. and you measure the voltage with ADC.

and some notes :

* you have to use A0 pin of the module if you want reading the value like the procedure above. this pin is the output of voltage divider(the sensor + blue pot on the board) and should be connected to ADC.
* the D0 is just the output of another circuit present on board for another purpose. it's a comparator output. it's used for situations where you only need to do something (like turning emergency lights on and off) when the gas goes up from a level. you don't read anything with ADC. you just turn the pot to set a threshold (that's empirical) and digital pin get high and low according to that.
* the voltage divider's GND and VCC are connected to GND and VCC of heating element accordingly. so you have just one pair of GND/VCC

---
Tags: arduino-uno, sensors
---


title: Why is IF statement executing on itself

text:
# Question
Title: Why is IF statement executing on itself
```
x = 5;
Serial.println (x);

if (x == 0);
    {
      //stuff in this IF keeps happening why ?
      //Iam too stupid ?
    }

```

# Answer
You have a rogue semi-colon.

Splitting your code up on the end of statements you get:

```
1. x = 5;
2. Serial.println (x);
3. if (x == 0);
4. { // stuff }

```

With the semi-colon after the `if` it terminates the `if` before the opening block `{`, and that block becomes a completely separate statement detached from the `if`.
> 3 votes

---
Tags: arduino-uno, arduino-mega, arduino-nano
---


# Question
Title: How to start serial monitor on Windows startup
How can I get Windows to start the Serial Monitor window after a restart? Is there something I have to copy into the Windows startup folder for my account? Thanks

# Answer
You can't. You would need to have some way of telling the Arduino IDE to open the serial monitor and connect to a certain serial port. That can't be done.

Instead you would need to use some other third party serial communication program. How you would configure that depends on what the software is.

For Windows 10 you can make a program run at startup by following these instructions. You still need to configure the software to automatically connect to the right port at the right speed, of course.
> 0 votes

---
Tags: serial, windows, startup
---


# Question
Title: LED on same Pin as Toggle Switch, not illuminating
I am trying to do something I think should be relatively simple. I would like to read an input from a toggle switch, and have a red 5mm LED indicate the state of the switch. Rather, however, than have an input for the switch and an output for the LED (controlled by software), I'd like to put them in series on a single circuit. That is, flip the toggle and current flows from the 5v source on the Arduino Uno through an LED and to an input pin on the Arduino. (I would ultimately like to have eight such switches; I am trying to create a sort of **simulated byte**, with individually flippable bits controlled by toggles; this will be read by a GTK Python program, that can interpret that "byte" in different ways: as a decimal value, a hex value, an ASCII character, a color in 8-bit color space, etc).

So, I have an LED with a 200 Ohm current-limiting resistor. I also have a pull-down resistor (1k) to prevent the toggle from floating.

My results, however, have been inconsistent. Using a breadboard, I've gotten this working. But it seems very fragile, and sometimes when I rebuild the circuit on a breadboard, it doesn't work as expected. Right now, for instance, the switch seems to work, and I am reading the expected value from the Serial Monitor--but the LED is not illuminating.

I had been playing around with different values for the pull-down resistor and the current-limiting resistor. This pair (200-ohm current limiting; 1k pull down) *seemed* to work, but now isn't. (I have swapped out the LED; and current is passing through the LED, otherwise I wouldn't be able to read the correct pin value--I think.)

Is there something I'm not understanding? Does the position of the current limiting resistor (before/after the LED) make any difference (I assume not)? Does this seem like the correct setup for what I'm trying to achieve? More generally, should, in principle, this approach scale to 8 more toggle/LED pairs? Is there a better/smarter approach? Is there a reason why I see so few Arduino projects that put LEDs in series with an input toggle?

The breadboard looks like this:

# Answer
LEDs have a (fairly) fixed voltage drop across them. The red LED is about 2V.

You can use that to work out the voltage at the input. You basically have a voltage divider, with your 200Ω resistor as R1, and your 1kΩ resistor as R2. The voltage drop of the diode is subtracted from Vin.

So:

```
Vout = (Vin - Vled) * (R2 / (R1 + R2))

     = (5 - 2) * (1000 / (200 + 1000))

     = 3 * (1000 / 1200)

     = 3 * 0.833

     = 2.5V

```

The ATMega328P datasheet states that a HIGH input voltage must be over 0.6\*Vcc, and a LOW input voltage must be below 0.3\*Vcc. That means to register a HIGH you need more than 3V. To register a LOW you need less than 1.5V.

You're between those two voltages - in the "dead zone".

The simplest way to achieve what you want is to use a douple-pole switch and keep the LED completely separate from the Arduino.
> 4 votes

# Answer
This is your circuit that does not work:

simulate this circuit – Schematic created using CircuitLab

There are many ways to use a single pin. Some circuits are with a diode and some circuits need to turn off the led to read the switch. The most simple solution might be this:

simulate this circuit

When the switch is not closed, the LED is a weak pullup (perhaps too weak). By using INPUT\_PULLUP for D7, the pullup is stronger and D7 can read the switch.
As an extra it is possible to turn the LED on when the switch is open. But you have to be sure to switch between OUTPUT + LOW and INPUT\_PULLUP in the code or else there is a shortcut.
> 2 votes

---
Tags: arduino-uno, led, switch
---


# Question
Title: Store value in EEPROM to perform different actions on reset?
I want the same button to wake up (reset) and put it to sleep but this is hard if the button is tied directly to the rst pin. My thought was to read and store a value in EEPROM so tell the chip what mode we were in so it can perform the counter action. For example, on RST if the value is 0 the chip should wake up and do things. It would then set the value to 1. If the button is pressed again, the chip resets, reads there is a 1 and now just puts the chip into deep sleep after setting the value back to 0. Rinse, repeat.

Does this make sense? Will this work? Is there a better/easier way?

# Answer
> 4 votes
While it looks interesting as idea, IHMO you have keep in mind:

1. Include some code for button denouncing logic. Actually you will receive couple of “resets” during ~20ms during button press. Without denouncing you may end up with reset signal right at the moment you write to the EPROM. While EPROMs are pretty “solid” nowadays, it many not be good practice. One of potential solutions IMHO is to delay update EPROM with state switch for 20ms after boot, so it be done in stable state.
2. You may also consider to include electronic circuit to hold reset long enough to reboot the controller (it may also reduce bouncing).
3. EPROM has finite lifespan in terms of rewrite cycles, if your device turned on and off ~100 timers per day, it may die in a ~year.
4. Writing the EPROM usually consumes significant amount of energy, so it may reduce battery lifespan (if you use battery).

Probably more classic approach with sleep / wake up by button looks more reasonable, unless you have shortage of pins ;)

# Answer
> 1 votes
Totally agree with Serge.
To cover issues #3 and #4 of Serge's answer I recommend you to have a look at FRAM.
It has more durability with 10 trillions of write cycles.

---
Tags: eeprom, sleep, reset, deep
---


# Question
Title: Reading file from SPIFFS in nodemcu using ArduinoJson
```
#include <ArduinoJson.h>
#include <FS.h>

/* Set these to desired credentials in runtime */
struct Config {
  String ssid = "";
  String pass = "";
  bool hFlag = false;
};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("");
  delay(1000);

  //allows serving of files from SPIFFS
  Serial.println("Mounting FS...");
  if (!SPIFFS.begin()) {
    Serial.println("Failed to mount file system");
    return;
  }

  if (readConfigFile("/LaSt.json", false)) {
    Serial.println("Config read");
  } else {
    Serial.println("Failed to read config");
  }
}

bool readConfigFile(char* fileName, bool whichFile)
{
  File configFile = SPIFFS.open(fileName, "r");
  if (!configFile) {
    Serial.println("Failed to open config file");
    return false;
  }

  size_t size = configFile.size();
  if (size > 1024) {
    Serial.println("Config file size is too large");
    return false;
  }

  // Allocate the memory pool on the stack.
  // Use arduinojson.org/assistant to compute the capacity.
  StaticJsonBuffer<256> jsonBuffer;

  // Parse the root object
  JsonObject &root = jsonBuffer.parseObject(configFile);

  if (!root.success())
    Serial.println(F("Failed to read file, using default configuration"));

  // Copy values from the JsonObject to the Config
  Config.ssid = root["ssid"];
  Config.pass = root["pass"];
  if (whichFile)
  {
    Config.hFlag = root["hFlag"];
  }

  // We don't need the file anymore
  configFile.close();

  return true;
}

```

Compile gives error in `Copy values from the JsonObject to the Config` section. Error: `expected unqualified-id before '.' token`.

Want to read file from SPIFFS, and store in variable to use.

# Answer
> 2 votes
Your code at the top:

```
struct Config {
  String ssid = "";
  String pass = "";
  bool hFlag = false;
};

```

defines a variable "type". It's like making a new `int` or `bool`, but yours is called `struct Config`.

After making the type, you need to create declare an instance of it.

```
struct Config cfg;

```

Then, you refer to the one **you** created:

```
  // Copy values from the JsonObject to the Config struct named cfg
  cfg.ssid = root["ssid"];
  cfg.pass = root["pass"];
  if (whichFile)
  {
    cfg.hFlag = root["hFlag"];
  }

```

Note that a particular issue with ArduinoJSON and Strings is that you may get an error like:

```
error: ambiguous overload for 'operator=' (operand types are 'String' and 'ArduinoJson::JsonObjectSubscript<const char*>')

```

There is an ArduinoJSON FAQ entry that states

> Most of the time you can rely on implicit casts.
>
> But there is one notable exception: when you convert a JsonVariant to a String.
>
> For example:
>
> ```
> String ssid = network["ssid"];
> ssid = network["ssid"];
>
> ```
>
> The first line will compile but the second will fail with the following error:
>
> ```
> error: ambiguous overload for 'operator=' (operand types are 'String' and 'ArduinoJson::JsonObjectSubscript<const char*>')
>
> ```
>
> The solution is to remove the ambiguity with any of the following replacement:
>
> ```
> ssid = (const char*)network["ssid"];
> ssid = network["ssid"].as<const char*>();
> ssid = network["ssid"].as<String>();
>
> ```

# Answer
> 0 votes
```

#include FS.h
#include ESP8266WiFi.h
#include ArduinoJson.h

/* Set these to desired credentials in runtime */

  String ssid = "tttttttt";
  String pass = "ssssssss";

#define fileName "/LaSt.json"

DynamicJsonBuffer jsonBuffer;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("");
  delay(1000);

  //allows serving of files from SPIFFS
  Serial.println("Mounting FS...");
  if (SPIFFS.begin()) {

 if (SPIFFS.exists(fileName)) {

  File subscribedUsersFile = SPIFFS.open(fileName, "r");

  delay(10);

  String file_content = subscribedUsersFile.readString();

  JsonObject& users = jsonBuffer.parseObject(file_content);

           if(users.containsKey("ssid"))          {ssid=users["ssid"].as();}
           if(users.containsKey("pass"))          {pass=users["pass"].as();}

    subscribedUsersFile.close();

    users.prettyPrintTo(Serial);

  }
else  {

   // Create empty file (w+ not working as expect)

   File subscribedUsersFile = SPIFFS.open(fileName, "a+");

   JsonObject& users = jsonBuffer.createObject();

   users.set("ssid", ssid);

   users.set("pass", pass);

  users.printTo(subscribedUsersFile);

  users.printTo(Serial);

  subscribedUsersFile.close();

  Serial.println("New Config File Created...\n");

  users.prettyPrintTo(Serial);

    }

  }
}

```

---
Tags: esp8266, nodemcu, json
---


# Question
Title: What is the difference between the two sensors?
I am working on a project which requires the use of sensors and i don't know which one to use so i would like to know the difference between the two.

# Answer
Apart from the obvious construction and component differences the two sensors seem totally equivalent from their look. They seems to both be `FC-51` modules: those are “line followers” meaning one diode (the clear one) emits infrared light and the other (the dark one) measure the amount of IR light reflected by the surface in front of them. The potentiometer is there to determine the triggering level so that when powered you can have a `LOW` signal on the `OUT` pin when the threshold is reached.
> 3 votes

---
Tags: arduino-uno
---


# Question
Title: How do I redefine the overlfow of compare interrupts in Arduino programming?
If I'm programming a pin change interrupt I can call attachInterrupt at various points in my code and change what function is called when the interrupt occurs.

The overflow and compareA/B interrupt calls are defined by the ISR macro which is evaluated at compile time, which therefore can't be changed at run time. One solution would be to make that function consist of a single line, which invokes a function pointer. If I'm reading the code correctly, this is how attachInterrupt is implemented. Short of mucking with the interrupt vector table (which seems like a bad idea, or at least very hard to debug if you screw it up), is there another way to redefine the overflow or compare interrupt functions?

# Answer
> 1 votes
What about using a `switch` statement inside the ISR function and reroute the flow depending on the value of the global variable used in the switch?

```
uint8_t status = 0;

void myInterruptFn() {
  switch(status) {
    case 0:
      // do something
      status = 1;
      break;
    case 1:
       // do something else
       status = 0;
       break;
   }
}

```

---
Tags: arduino-ide, interrupt
---


title: Arduino WiFi Rev2 JSON String

text:
# Question
Title: Arduino WiFi Rev2 JSON String
I have been trying to use the WifiNINA library to access the JSON output from the following API using the WifiNINA library and the Arduino Wifi Rev2.

This is the code that I have been using (it is an **edited** example form the library):

```
/*
  Web client

 This sketch connects to a website (https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo)
 using the WiFi module.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 Circuit:
 * Board with NINA module (Arduino MKR WiFi 1010, MKR VIDOR 4000 and UNO WiFi Rev.2)

 created 13 July 2010
 by dlf (Metodo2 srl)
 modified 31 May 2012
 by Tom Igoe
 */

#include <SPI.h>
#include <WiFiNINA.h>

#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.alphavantage.co";    // name address for Google (using DNS)

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < "1.0.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();

  Serial.println("\nStarting connection to server...");
  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected to server");
    // Make a HTTP request:
    client.println("GET /query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo HTTP/1.1");
    client.println("Host: https://www.alphavantage.co");
    client.println("Connection: close");
    client.println();
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    client.stop();

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

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

```

However, when I run the library, all that the serial monitor returns is:

```
Attempting to connect to SSID: HIDDEN
Connected to wifi
SSID: HIDDEN
IP Address: HIDDEN
signal strength (RSSI):-40 dBm

Starting connection to server...
connected to server
HTTP/1.1 301 Moved Permanently
Connection: close
Server: gunicorn/19.7.0
Date: Sun, 07 Apr 2019 15:02:16 GMT
Transfer-Encoding: chunked
Location: https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&outputsize=full&datatype=json&apikey=8UV48KKJJM1JW700
Content-Type: text/html; charset=utf-8
Via: 1.1 vegur

0

disconnecting from server.

```

I would like the code to return the string from the link. The output should like this (instead of just the 0). I had to shorten the example output below because of size restraints, but it should be the full webpage.

```
{
    "Meta Data": {
        "1. Information": "Intraday (5min) open, high, low, close prices and volume",
        "2. Symbol": "MSFT",
        "3. Last Refreshed": "2019-04-05 16:00:00",
        "4. Interval": "5min",
        "5. Output Size": "Compact",
        "6. Time Zone": "US/Eastern"
    },
    "Time Series (5min)": {
        "2019-04-05 16:00:00": {
            "1. open": "119.8100",
            "2. high": "119.9100",
            "3. low": "119.7350",
            "4. close": "119.8800",
            "5. volume": "728814"
        },
        "2019-04-05 15:55:00": {
            "1. open": "119.9200",
            "2. high": "119.9200",
            "3. low": "119.7800",
            "4. close": "119.8000",
            "5. volume": "307126"
        },
        "2019-04-05 15:50:00": {
            "1. open": "119.9300",
            "2. high": "119.9300",
            "3. low": "119.8800",
            "4. close": "119.9200",
            "5. volume": "235238"
        }
    }
}

```

# Answer
> 0 votes
It's not that the API is incompatible with the Arduino, it's that the Arduino Firmware update tool used to add the required SSL certificate to the wifi module fails to do so because the SSL certificate for www.alphavantage.co does not exist at their domain.

This can be verified by:

openssl s\_client -showcerts -connect www.alphavantage.co:443

# Answer
> 0 votes
The target site uses HTTPS. If you connect to port 80, it redirects to HTTPS on port 443.

Use the `WiFiSSLClient` of the library. See the WiFiSSLClient example. Basically it is same as the example you used. There are two differences. It uses `WiFiSSLClient` instead of `WiFiClient` and connects to standard https port 443.

---
Tags: arduino-uno, wifi, json, arduino-uno-wifi
---


# Question
Title: How to communicate between a webcam and an Arduino UNO and get the live feed on mobile using ESP8266?
I am working on a project of making a Smart Robot Car using Arduino UNO, L298N Motor Driver Module, ESP8266 Esp-01 WiFi module and RemoteXY app for controlling via smartphone over WiFi.

My question is: ***If I want to get the live feed of the view that my robot is seeing, using a webcam (say Logitech HD Webcam C270) using a USB to serial converter module or whatsoever, how can I make it possible?*** *Please let me know if there is any special shield or any processing board needed.* ***Help with coding and the conversion of Video data into the transmittable Data for Arduino and help in making that kind of data which can be read by the Device (e.g. Smartphone) is also needed and will be appreciable.***

It may be mentioned here that I am a beginner and I am currently learning through YouTube and Blog Tutorials. I am totally dependent on StackExchange like forums for the help in my projects either whenever I am making a mistake or when I want to try and learn something new or both. Please Help me while keeping these things in your mind also.

Please *suggest me some good books* on this branch of the subject that could make me able to do these kinds of things on my own.

Thank You So Much in advance!

(P.S.: If you feel this question should be downvoted then, please firstly let me know in the comments section why do you feel like this before downvoting, I may delete my question earlier, cause I am concerned about my reputation here.)

# Answer
> 2 votes
The Uno is a very limited platform, perhaps surprisingly, given its wide range of abilities and built-in hardware features. The two most glaring limitations for you application are its 16MHz clock speed (relative to modern desktop processors) and thus its bandwidth, and it's non-expandable 2KBytes of RAM.

Image processing would be right out the window, and even merely transmitting a raw image would be pushing its bandwidth limits, for any reasonable frame-size with even a very modest frame-rate.

Example: For a 100x100 8-bit frame at 15 frames/sec, a 16MHz processor (16M instructions per sec) would have (16000000 / (100x100x15)) = ~107 clocks (instructions) available to process each byte. You'd need some of those to either poll for next-byte-ready or to enter and exit an Interrupt Service Routine to process the byte. You're probably up to around 20 clocks (at a wild guess), to do nothing more than a bit of wire can do! Maybe you could do some trivial manipulation of each byte on the way through (say, brightness manipulation) with a few more clocks and you're already using a significant fraction of the processor just for that. And there isn't enough memory to be able to process a region of the image. And if you could, you run out of processor time before you could do much .... The problem just cascades as you approach the limits of speed and memory-space.

# Answer
> 2 votes
As rightly pointed out by others and @JRobert, its very difficult or nearly impossible to live stream a video/audio through Arduino Uno which uses Atmega328 micro-controller which is mostly used for simple embedded processing such as sensor reading, serial tr/rx, i2c like operations.

But there are some workarounds which can make it possible by using some SPI camera and some Bluetooth shield or ESP8266 together.

Take a look at this project which can be helpful to you.

https://github.com/ArduCAM/Arduino

But remember, don't expect a very good quality or higher frame-rate video stream. Also it might only send video, i.e. picture frames and not audio.

Second solutions is:

If you just want your robot to get equipped with a camera which need to be live streamed back to your android/ios phone with good quality AV then the best way to do this is by a standard method used by most RC toys, UAV or robots.

What you need is:

1) 5.8Ghz AV transmitter

* A Mini FPV Camera NTSC/PAL with inbuilt transmitter or
* FPV camera and a 5.8G 600mW Wireless Audio/Video Transmitter for FPV

with above options you can get a possible range of 1 Km to 5Km or more.

2) second thing you need is receiver section

* OTG 5.8G 150CH Full Channel FPV Receiver For Android and iOS is best for this. This above module will help you to receive AV from FPV camera/module to your android.

I'll not give you direct link to the products as that wont be a good idea here on SE. instead you can search for them on google and choose as per your requirement. most of these modules will be less than 2000 INR or 30$

---
Tags: arduino-uno, esp8266, wifi, l298n, camera
---


# Question
Title: Calculating the time between the signal when its ON and when it gets OFF
```
class Channel
{
    private:
        uint8_t _pin;
        uint8_t _state;
        uint32_t _rise;
        uint32_t _fall;
        uint8_t _count;
        uint8_t _channel;

        static uint8_t channelCount;

        void display()
        {
            uint32_t diff = (_fall - _rise) / 1000;
            uint32_t secs = diff % 60;
            uint32_t mins = diff / 60;
          //  Serial.print(",");
            Serial.print(_channel);
            Serial.print(",");
            Serial.print(mins);
            Serial.print(",");
            Serial.print(secs-4);
            Serial.print(",");
            Serial.println(_count);
        }

    public:
        Channel(int pin) : _pin(pin), _count(0)
        {
            _pin = pin;
            _count = 0;
            _channel = channelCount;
            channelCount++;
        }
        void process()
          {
            int s = digitalRead(_pin);
            if (s != _state)
              {
                _state = s;
                if (s == LOW)  // Fell
                  {
                    _fall = millis();
                    _count++;
                    display();
                  }
                else
                  {
                    _rise = millis();
                  }
                }
            }
        void begin()
        {
            pinMode(_pin, INPUT);
        }
};

uint8_t Channel::channelCount = 0;

Channel channels[] = { 3,5 };
#define NUM_CHANNELS (sizeof(channels) / sizeof(channels[0]))

void setup()
{
    Serial.begin(115200);
    Serial.println("Channel,Minutes,Seconds,Count");
    for (unsigned int i = 0; i < NUM_CHANNELS; i++)
      {
        channels[i].begin();
      }
}

void loop()
{
    for (unsigned int i = 0; i < NUM_CHANNELS; i++)
      {
        channels[i].process();
      }
}

```

This code works normally in some cases, (i.e.) It provides the exact time between the signal when it's ON and when it gets OFF in seconds.

In some cases, it spits out a 10 digit number. The correct value follows the unknown number in the screenshot attached below

# Answer
> 4 votes
I suspect secs is 0 sometimes, because of \_rise being 0? In that case unsigned int subtraction causes this: secs(0) - 4 = -4 % 2^32, resulting in your 4294967292

---
Tags: arduino-uno
---


# Question
Title: Ensure board is always on the same port?
I want to make a VB.NET program to communicate over serial with the board, but I need to be sure it knows which port. Instead of programming in more advanced methods of verification, for this project I would simply prefer to keep the board on the same (internal) USB port. Will it always appear on the same serial port (COMx) and will VB always be able to find it there?

# Answer
My experience is that the Serial-to-USB converters (of which Arduino is one) have are assigned a COM port according to the USB port they are plugged into. So if you always to connect it to the same physical USB port it will have the same number. However this number will not be the same with a different Arduino or on a different computer.
> 1 votes

# Answer
*Normally*, the COM port number wont change, but you cannot simply rely on this.

Depends on various effects, especially if you have multiple USB-Serial devices, update the driver, etc. Also, there's the possibility to clean the COM port numbers in the operating system to get rid of unused legacy entries, which will restart counting them from fresh.

Most applications search for all existing ones, eventually display their names, and leave it to the user to choose the desired port.

And, btw. it's not related to VB.net
> 2 votes

---
Tags: serial, arduino-mega, usb, communication
---


# Question
Title: Wiring for Arduino Mega and multiple MPU 6050/Gy 521?
I have an Arduino Mega 2560 that I need to connect 4 MPU 6050/Gy 521's to.

I found some resources on the Mega and Uno, however I'm having trouble piecing them together.

This resource gives great detail for connecting a single MPU to a mega. http://dummyscodes.blogspot.com/2014/07/mpu6050-gy-521-breakout-arduino-mega.html

This resource gives a trick for connecting multiple to an UNO. https://playground.arduino.cc/Main/MPU-6050

My problem is that the wiring for the Uno and Mega are different. The resource I have for the UNO describes using the MPU AD0 (output) connecting it to different output pins for each MPU. The resource talking about the MEGA doesn't even use the AD0, and uses INT but I'm not sure if I can use the same concept.

Plus, I still don't actually understand how to connect/what other pins to use for the other 4.

I'm pretty new to Arduino, definitely new to anything with wiring.

Please help! I'm really confused about using multiple together, and about how to properly wire them.

# Answer
> 1 votes
MPU-6050 uses I2C for comm's, yes? Connect all the SCLs in parallel to the Mega with a 4.7K, or 3.3K, pullup resistor. Same for the SDAs. I2C is D20, D21 (or D21, D22) on the Mega.

The MPU-6050 has an A0 pin to select from one of two addresses, let's call them Add0 and Add1 for simplicilty. Connect each MPU-6050 A0 pin to a unique Mega pin. When none are being addressed, have each Mega output high. When one MPU-6050 is to be accessed, take that device's A0 pin low and communicate with it using Add0. The other's will be looking for communications at Add1 and thus will not respond.

If the MPU6050 is a 3.3V device, then you should also remove the pullup resistor network package on the Mega that pulls SCL/SDA to 5V. There are 2 pullups in a very little 8-pin package, the other 2 are not used. Connect the 3.3K or 4.7K pullup resistors discussed above to 3.3V.

---

This is the part, RN1, on the Mega R3 board. It may not be marked as such on the board. Remove it, or cut the traces next to the pad legs, one on the left side (connects to pin 3), one on the top (connects to pin 2).

# Answer
> 0 votes
CrossRoads' answer using the address selection pin on your MPU modules is excellent. It does tie up a GPIO line for each MPU you want to address however.

(If you are using a Mega 2560 this might not be an issue since they have tons of GPIO lines.)

You could also get a I2C addressing multiplexer. Adafruit and Sparkfun both offer them Example: https://www.adafruit.com/product/2717?gclid=EAIaIQobChMItYnah7zB4QIVAoTICh1JlAk3EAQYASABEgK7hvD\_BwE

That one will multiplex up to 8 I2C devices with the same address, and doesn't require any additional pins. You send a single I2C command to it to select one of your 8 devices.

I don't know if anybody makes an I2C multiplexer that also does voltage conversion. Seems like that would be handy.

---
Tags: arduino-mega, mpu6050
---


title: problem in uploading the code

text:
# Question
Title: problem in uploading the code
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"

```
Sketch uses 12452 bytes (38%) of program storage space. Maximum is 32256 bytes.
Global variables use 970 bytes (47%) of dynamic memory, leaving 1078 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

# Answer
> 1 votes
Try to upload your code without any device connected to Uno. Disconnect all IO pins. Upload the code via onboard USB port.

# Answer
> 0 votes
It means there is no proper communication between the IDE and your Arduino. The reason can be many things:

* RX/TX UART port used
* USB port broken
* USB cable broken
* Arduino broken
* USB port drivers not properly installed
* Problem inside IDE
* ...

To troubleshoot you could try:

* Disconnect RX/TX jumpers
* Try another USB port
* Remove other USB devices
* Try another USB cable
* Try another Arduino
* Try another PC/laptop
* Reinstall IDE
* Reinstall USB drivers

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


# Question
Title: Adafruit esp32 Feather Failing to compile
So yesterday, I was able to upload/compile given example code to the Esp32 Huzzah board. Today I couldn't even compile. Even carefully using the tutorial adafruit provides.

I was getting errors as given below. How do I fix this?

```
C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/lib\libesp32.a(cpu_start.o):(.literal.main_task+0x14): undefined reference to `app_main'

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1/tools/sdk/lib\libesp32.a(cpu_start.o): In function `main_task':

/Users/ficeto/Desktop/ESP32/ESP32/esp-idf-public/components/esp32/cpu_start.c:503: undefined reference to `app_main'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial9availableEv+0x0): undefined reference to `uartAvailable'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial4peekEv+0x0): undefined reference to `uartPeek'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial4readEv+0x0): undefined reference to `uartRead'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial5flushEv+0x0): undefined reference to `uartFlush'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial5writeEh+0x0): undefined reference to `uartWrite'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o):(.literal._ZN14HardwareSerial5writeEPKhj+0x0): undefined reference to `uartWriteBuf'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::available()':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartAvailable'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::peek()':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartPeek'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::read()':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartRead'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::flush()':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartFlush'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::write(unsigned char)':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartWrite'

C:\Users\YBSECO~1\AppData\Local\Temp\arduino_cache_436740\core\core_b15e1ec95534e29a355269b84b798354.a(HardwareSerial.cpp.o): In function `HardwareSerial::write(unsigned char const*, unsigned int)':

C:\Users\YbSeconds\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.1\cores\esp32/HardwareSerial.cpp:157: undefined reference to `uartWriteBuf'

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Adafruit ESP32 Feather.

```

# Answer
So it turns out the problem is that you're using the esp32 1.0.1 library provided by espressif. I'm assuming you're using the Arduino IDE board manager URL: https://dl.espressif.com/dl/package\_esp32\_index.json

To fix this, **don't** use 1.0.1. Use 1.0.0! Remove 1.0.1 and install 1.0.0. That should get it to compile properly without the uart, app\_main errors.
> 1 votes

---
Tags: esp8266, arduino-ide, adafruit, esp32, espressif
---


# Question
Title: how to write an int to RFID tag and when read then store that in an array
The writing code is from the MFRC522 Example below:

I have added an array to store the value but it does not store it as the same value written to it in the writing. instead it stores it as byte values. I am fairly new so would appreciate any help.

```
/*
 * Write personal data of a MIFARE RFID card using a RFID-RC522 reader
 * Uses MFRC522 - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 * Hardware required:
 * Arduino
 * PCD (Proximity Coupling Device): NXP MFRC522 Contactless Reader IC
 * PICC (Proximity Integrated Circuit Card): A card or tag using the ISO 14443A interface, eg Mifare or NTAG203.
 * The reader can be found on eBay for around 5 dollars. Search for "mf-rc522" on ebay.com.
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

void setup() {
  Serial.begin(9600);        // Initialize serial communications with the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card
  Serial.println(F("Write personal data on a MIFARE PICC "));
}

void loop() {

  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  byte buffer[34];
  byte block;
  MFRC522::StatusCode status;
  byte len;

  Serial.setTimeout(20000L) ;     // wait until 20 seconds for input from serial
  // Ask personal data: Family name
  Serial.println(F("Enter the weight, ending with#"));
  len = Serial.readBytesUntil('#', (char *) buffer, 30) ; // read family name from serial
  for (byte i = len; i < 30; i++) buffer[i] = ' ';     // pad with spaces

  block = 1;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("PCD_Authenticate() success: "));

  // Write block
  status = mfrc522.MIFARE_Write(block, buffer, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

}

```

and the reading code is :

/*
 * Initial Author: ryand1011 (https://github.com/ryand1011)
 *
 * Reads data written by a program such as "rfid_write_personal_data.ino"
 *
 * See: https://github.com/miguelbalboa/rfid/tree/master/examples/rfid_write_personal_data
 *
 * Uses MIFARE RFID card using RFID-RC522 reader
 * Uses MFRC522 - Library
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
*/

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

int weightArray[2];
int counter = 0;

//*****************************************************************************************//
void setup() {
  Serial.begin(9600);                                           // Initialize serial communications with the PC
  SPI.begin();                                                  // Init SPI bus
  mfrc522.PCD_Init();                                              // Init MFRC522 card
  Serial.println(F("Read personal data on a MIFARE PICC:"));    //shows in serial that it is ready to read

}

//*****************************************************************************************//
void loop() {

  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  //some variables we need
  byte block;
  byte len;
  MFRC522::StatusCode status;

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

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  Serial.println("Detected");

  byte buffer1[18];

  block = 4;
  len = 18;

  //------------------------------------------- GET FIRST NAME
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Authentication failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer1, &len);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Reading failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  //PRINT FIRST NAME
/*  for (uint8_t i = 0; i < 16; i++)
  {
    if (buffer1[i] != 32)
    {
      Serial.write(buffer1[i]);
    }
  }
  Serial.print(" ");
*/
  //---------------------------------------- GET LAST NAME

  byte buffer2[18];
  block = 1;

  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid)); //line 834
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Authentication failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer2, &len);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Reading failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  //PRINT LAST NAME
  for (uint8_t i = 0; i < 16; i++) {
    Serial.write(buffer2[i]);
    }

  for(int i = 0; i < sizeof(weightArray) / sizeof(weightArray[1]); i++) {
    Serial.print(weightArray[i]);
  }

  counter++;

  Serial.println(F("\n**End Reading**\n"));

  delay(1000); //change value if you want to read cards faster

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}
//*****************************************************************************************//
````````````````````````````````````

# Answer
First you are not writing `int` value during write as, buffer is defined as `byte` type. Your are just type casting it `char*` during serial read for storing data. And Your are writing just first 16 value in your CARD, so you might not get the expected results.

`byte` data type provides only `8 bit` or `1 byte` of memory location. `int` data type provides `2 bytes` or `4 bytes` of memory location.
> 1 votes

---
Tags: arduino-nano
---