body: I have recently brought an arduino nano. It has only two ground pins but I needed three for my project. Is there a way to use a digital or analog pin as ground pin? Please show me how to do it

title: How to use digital pin as ground?

Answers: 3

body: There is no need to separate grounds, you can connect all grounds together. In fact they are connected together on the board itself.

body:
If your project is on a breadboard, you can use one of the "rails", typically the blue longways row at either edge of the breadboard, to collect all of the necessary grounds, and wire that to one Ground pin on the Arduino.

If you're building a printed circuit board to connect to the Arduino, do the same thing - collect all of the PCB grounds together and wire that to one Arduino Ground pin.

If you're using a manufactured shield, you may have to get creative about collecting your grounds. A tiny breadboard is one way. Another is to solder a number of wires together in star-formation, insulate the solder joint with tape or shrink-tube, and connect one of the star's points to the Arduino ground.

*If* some of your devices needing grounds are low-current devices such as LEDs, you could set an unused pin to OUTPUT mode, and LOW, and use it as a ground, but the device must not be passing more current than an Arduino pin driver can sink. From Atmel's data sheet for the AtMega328p (used in the Uno):

> Although each I/O port can sink more than the test conditions (20mA at
>     VCC = 5V, 10mA at VCC = 3V) under steady state conditions
>     (non-transient), the following must be observed:

>    ATmega48A/PA/88A/PA/168A/PA/328/P: 1] The sum of all IOL, for ports C0 - C5, ADC7, ADC6 should not exceed 100mA.

> 2]     The sum of all IOL, for ports B0 - B5, D5 - D7, XTAL1, XTAL2 should not exceed 100mA.

> 3]     The sum of all IOL, for ports D0 - D4, RESET should not exceed 100mA.

> If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.

body:
You can just try converting two digital pins as 5V VCC and ground.
This will be useful when we use multiple sensors.

```c++
#define VCC2  5 // define pin 5 or any other digial pin here as VCC2
#define GND2  2 // define pin 2 or any other digital pin as Ground 2

void setup() {
  pinMode(VCC2,OUTPUT);//define a digital pin as output
  digitalWrite(VCC2, HIGH);// set the above pin as HIGH so it acts as 5V

  pinMode(GND2,OUTPUT);//define a digital pin as output
  digitalWrite(GND2, LOW);// set the above pin as LOW so it acts as Ground
}

void loop() {
}
```


body:
so a brief introduction about the project which I am working on before I go onto my issue.

I am working on a love-o-meter project (Not similar to the arduino example), whereby 2 people place 1 of their hands on a pad and with their other hand holding each other. Making use of a pulse sensor, I measure the BPM for 10s and then indicate the score on a LED strip.
Apart from indicating the compatibility score, I also plan to use the LED strip (cylon/fire effect) to indicate that the arduino is in the progress of calculating (when it is measuring the BPM for 10s) and also to indicate idling (rainbow cycle effect, when there is no one is using the love-o-meter).

However, here comes my issue: Performing the BPM measurement and displaying the cylon/fire effect function at the same time. I know that I cannot use the delay function and instead use millis(). However, the functions in the NeoPixel library already uses the delay effect and it seems like a tough job to edit the function to it using millis(). Is there another way to do so?

title: LED Strip Effect without delay

Answers: 1

body:
If you can find another way of calculating the BMP during displaying an effect on the strip depends highly on your BMP sensor. If you can do the measurement with interrupts, it should work. In this case you should make sure, that the interrupt cannot be fired during the execution of the `Adafruit_NeoPixel.show()` function, since it is quite timing sensitive.

But since I recently worked on a project with a NeoPixel LED strip, I have already edited functions from the `strandtest` example for use with the `millis()` function. So you will not have to reinvent the wheel again :D I will try to strip away my custom code, so that you can easily use it.

    float brightness = 1.0;
    uint32_t strip_state=0;

    uint32_t Wheel(Adafruit_NeoPixel *strip, byte WheelPos) {
      WheelPos = 255 - WheelPos;
      if(WheelPos < 85) {
        return strip->Color((255 - WheelPos * 3)*brightness, 0, WheelPos * 3*brightness);
      }
      if(WheelPos < 170) {
        WheelPos -= 85;
        return strip->Color(0, WheelPos * 3 * brightness, (255 - WheelPos * 3)*brightness);
      }
      WheelPos -= 170;
      return strip->Color(WheelPos * 3 * brightness, (255 - WheelPos * 3)*brightness, 0);
    }

    void fill_color(uint32_t color){
      byte r= ((color & 0xFF0000) >> 16) * brightness;
      byte g= ((color & 0xFF00) >> 8) *brightness;
      byte b= (color & 0xFF) * brightness;
      color = strip.Color(r,g,b);
      for(unsigned int i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, color);
      }
      strip.show();
    }

    void fade_color(){
      for(unsigned int i=0;i<strip.numPixels();i++){
        strip.setPixelColor(i,Wheel(&strip,strip_state));
      }
      strip.show();
      strip_state++;
      if(strip_state>255) strip_state = 0;
    }

    void moving_rainbow(){
      for(unsigned int i=0; i<strip.numPixels(); i++) {
        strip.setPixelColor(i, Wheel(&strip,((i * 256 / strip.numPixels()) + strip_state) & 255));
      }
      strip.show();
      strip_state++;
    }

    void colorWipe(uint32_t color) {
      byte r= ((color & 0xFF0000) >> 16) * brightness;
      byte g= ((color & 0xFF00) >> 8) *brightness;
      byte b= (color & 0xFF) * brightness;
      color = strip.Color(r,g,b);

      strip.setPixelColor(strip_state, color);
      strip.show();
      strip_state++;
    }

    //Theatre-style crawling lights.
    void theaterChase(uint32_t c) {
      byte r= ((c & 0xFF0000) >> 16) * brightness;
      byte g= ((c & 0xFF00) >> 8) *brightness;
      byte b= (c & 0xFF) * brightness;
      c = strip.Color(r,g,b);
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
     strip.setPixelColor(i + strip_state % 3, c);    //turn every third pixel on
     strip.setPixelColor(i + (strip_state +1) % 3, 0); // turn others off
     strip.setPixelColor(i + (strip_state +2) % 3, 0);
      }
      strip.show();
      strip_state++;
    }

    //Theatre-style crawling lights with rainbow effect
    void theaterChaseRainbow() {
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
     strip.setPixelColor(i + strip_state % 3, Wheel(&strip, (i+strip_state) % 255));    //turn every third pixel on
     strip.setPixelColor(i + (strip_state +1) % 3, 0); // turn others off
     strip.setPixelColor(i + (strip_state +2) % 3, 0);
      }
      strip.show();
      strip_state++;
    }

The functions use the float variable `brigthness` to modulate the overall brightness of all LEDs. You can set it to every value between `0.0` and `1.0`.

The variable `strip_state` holds the current state of the effect on the strip. It is incremented everytime one of the functions is executed. Reset it to `0` if you want to restart an effect.

You yourself have to declare the variable `strip` as from the type `Adafruit_NeoPixel`.

So now you only have to call these function from the typical `millis()` code (like from the `BlinkWithoutDelay` example) in an interval, that you chose.


body:
So I am writing code to control a servo with an RC radio. I am using an Arduino Mega.  I get this error whenever I compile.  I am not that experienced with Arduino so I am probably not doing something right. Thanks for the help!

> Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Mega or Mega
> 2560, ATmega2560 (Mega 2560)"
>
> C:\Users\ethan\Desktop\Periferals_control\Periferals_control.ino: In
> function 'void loop()':
>
> Periferals_control:46: error: expected ';' before '{' token
>
>    {
>
>    ^
>
> exit status 1 expected ';' before '{' token
>
> This report would have more information with "Show verbose output
> during compilation" option enabled in File -> Preferences.

    #include <Servo.h>
    Servo servo1;
    Servo servo2;
    //the following are all ~PWM capable ports
    int servoElevator_PwmIn = 6; //Elevator Servo
    int servoGrabber_PwmIn = 7; //Grabber Servo

    //Channels on AT9
    int leftStickVertical = 2; //Channel 3
    int rightStickVertical = 3; //Channel 7

    int elevatorServoStop = 50;

    void setup() {

      //pinMode(servoGrabber_PwmIn, OUTPUT);
      //pinMode(servoElevator_PwmIn, OUTPUT);
      pinMode(leftStickVertical, INPUT);
      pinMode(rightStickVertical, INPUT);
      Serial.begin(9600);

      servo1.attach(6);
      servo2.attach(servoGrabber_PwmIn);
    }

    void loop() {

      int leftStickVerticalPwm = pulseIn(leftStickVertical, HIGH, 25000);
      int rightStickVerticalPwm = pulseIn(rightStickVertical, HIGH, 25000);
      Serial.print(leftStickVerticalPwm);
      Serial.print("\t");
      Serial.print(rightStickVerticalPwm);
      Serial.print("\n");

      if (rightStickVerticalPwm == 0)
      {
        servo1.write(elevatorServoStop);
      }
      else if (rightStickVerticalPwm > 1500)
      {
        servo1.write(100);
      }
      else (rightStickVerticalPwm < 1400)
      {
        servo1.write(30);
      }
    }

title: What is wrong with this code?

Answers: 2

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

      if (rightStickVerticalPwm == 0)
      {
        servo1.write(elevatorServoStop);
      }
      else if (rightStickVerticalPwm > 1500)
      {
        servo1.write(100);
      }
      else (rightStickVerticalPwm < 1400)
      {
        servo1.write(30);
      }

You cannot have another comparison in an `else` statement. You might have meant `else if` in the last clause.

Clarification if you're not well familiar with C/C++: If you have an `if` statement, it can be followed by arbitrary many `else if` clauses and at maximum one `else` clause which will execute when all other conditions fail. For example:

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

     int a = 10;
     if( a == 9 ) {
           //Executed if a = 9
     } else if( a < 20 ) {
       //If above not executed, this will be executed if a < 20
     } else {
       //This is executed if none of the conditions above hold.
       //A pure "else" does not have a condition and only one may
       //exist in an `if` statement.
     }

body: you should not provide conditions for " else " statement because it focuses on what action should happen if all " if and else if " conditions are not fulfiiled.


body:
I'm new to using Arduino and I have managed a few changes to this sketch. But I want to check for a second tag if the first one is not correct. I just can't seem to get it to work. I think it would be good if the tag is not a match to ask it to check the next tag and carry on, but I'm not sure how to make this happen.

    //RFID Password Typer
    //If a matching tag is found, the keyboard types
    //CTRL-ALT-DEL, then types the password and presses enter
    //Which should log you on to a Windows computer
    //Or Lock the computer if you're already logged in

    #include <SPI.h>
    #include <MFRC522.h>
    #include "Keyboard.h"
    #include <Mouse.h>

    #define RST_PIN 9
    #define SS_PIN 10

    byte tag[10]={0x64,0xAE,0xDD,0xFC,};
    char pswd[]="********\n";      //password, end with just \n
    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

    void setup() {
      SPI.begin();              //start SPI
      mfrc522.PCD_Init();       //start RC522 module
      Keyboard.begin();         //start USB keyboard
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);     //LED off
    }

    void loop() {
      if (!mfrc522.PICC_IsNewCardPresent()){ return; }
      if (!mfrc522.PICC_ReadCardSerial()){ return; }
      for(byte i = 0; i < mfrc522.uid.size; i++) {
        if(mfrc522.uid.uidByte[i]!=tag[i]){ return; }
      }
      mfrc522.PICC_HaltA(); //stop tag so we don't get repeats
      digitalWrite(13, HIGH); //LED on so we know we've got tag match
      Mouse.click();
      delay(1000);
      Keyboard.press(KEY_LEFT_CTRL);
      delay(1000);
      Keyboard.releaseAll();
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_LEFT_ALT);
      Keyboard.press(KEY_DELETE);
      delay(100);
      Keyboard.releaseAll();
      delay(300);
      Keyboard.print(pswd);
      delay(100);
      digitalWrite(13, LOW); //LED off
    }

title: RFID reader code to identify more than one tag

Answers: 2

body:
Got it. Not sure if it's the best way but it works. Thanks for your help.

    //RFID Password Typer
    //If a matching tag is found, the keyboard types
    //CTRL-ALT-DEL, then types the password and presses enter
    //Which should log you on to a Windows computer
    //Or Lock the computer if you're already logged in

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

    #define RST_PIN 9
    #define SS_PIN 10

    byte tag[10]={****,****,****,****,};
    byte tag1[10]={****,****,****,***^,};
    byte tag2[10]={****,****,****,**^^,};
    byte tag3[10]={****,****,****,*^^^,};
    char pswd[]="*********\n";      //password, end with just \n
    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

    void setup() {
      SPI.begin();              //start SPI
      mfrc522.PCD_Init();       //start RC522 module
      Keyboard.begin();         //start USB keyboard
      pinMode(13,OUTPUT);
      digitalWrite(13,LOW);     //LED off
    }

    void loop() {
      if (!mfrc522.PICC_IsNewCardPresent()) { return; }
      if (!mfrc522.PICC_ReadCardSerial()) { return; }
      for(byte i = 0; i < mfrc522.uid.size; i++) {
        if(mfrc522.uid.uidByte[i]!=tag[i]) {
        } else if(mfrc522.uid.uidByte[i]!=tag1[i]) {
        } else if(mfrc522.uid.uidByte[i]!=tag2[i]) {
        } else if(mfrc522.uid.uidByte[i]!=tag3[i]) { return; }
      }
      mfrc522.PICC_HaltA(); //stop tag so we don't get repeats
      digitalWrite(13, HIGH); //LED on so we know we've got tag match
      Keyboard.press(KEY_LEFT_CTRL);
      Keyboard.press(KEY_LEFT_ALT);
      Keyboard.press(KEY_DELETE);
      delay(100);
      Keyboard.releaseAll();
      delay(300);
      Keyboard.print(pswd);
      delay(100);
      digitalWrite(13,LOW); //LED off
    }

body:
here's how I'd do it ... allowing for 4, 7 and 10 byte uid's (which are all possible apparently)

    struct tagInfo {
      byte len;
      byte uid[10];
    };
    struct tagInfo tag[] = { // add your tags here
      // the len is 1, 2 or 3, for lengths 4, 7, and 10
      // you could just use 4, 7, 10 here and not bother
      // with the len * 3 + 1 calculation later
      // the choice is yours, really
      {1, {0x01, 0x02, 0x03, 0x04}},
      {1, {0x02, 0x03, 0x04, 0x05}},
      {2, {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}},
      {1, {0x02, 0x02, 0x02, 0x02}}
    };
    const int numtags = sizeof(tag)/sizeof(struct tagInfo);

Then, your loop

    void loop() {
      if (!mfrc522.PICC_IsNewCardPresent()) { return; }
      if (!mfrc522.PICC_ReadCardSerial()) { return; }
      int i; // declare before the loop because we want to check the value after the loop ends
      for (i = 0; i < numtags; i++) {
        byte len = tag[i].len * 3 + 1;
        if(len == mfrc522.uid.size) { // 4, 7, 10?
          if(!memcmp(mfrc522.uid.uidByte, tag[i].uid, len)) {
            break; // found an exact match so stop the loop
          }
        }
      }
      if (i == NUMTAGS) { return; } // no matches
      // all good here - run the rest of your code
    }


body:
I'm confused about my esp8266-01 if they have SPIFFS or not. Is there a way to find it out? If they have, how to get their size?

I've got the following flash id: `0x1440e0`.

Example SPIFFS apps keep crashing with `wdt reset` and lots of dumped hexes.

title: How to determine the SPIFFS size on an esp8266-01?

Answers: 1

body:
First you need to know the size of the flash memory attached to esp8266 on your module. Common sizes are 512 kB (4Mbit), 1 MB (8Mbit) and 4 MB. Espressif [Flash Download Tool][1] (Windows) or [esptool][2] can determine it.

You can choose the size of the SPIFFS in your [flash 'layout'][3] by selecting the option in IDE Tools menu. Take one according to for you flash size and size of the files you want to put into SPIFFS.

If you have 1 MB flash on your module and you want to use OTA upload, let flash space for twice a space taken by the sketch.

  [1]: http://espressif.com/en/support/download/other-tools
  [2]: https://github.com/espressif/esptool
  [3]: http://esp8266.github.io/Arduino/versions/2.0.0/doc/filesystem.html


body:
I would like to make my own version of the Arduino Due.

What I can't find the answer to is;
Can I program a blank SAM3X8E using the native USB port from within the Arduino IDE, or do I first need to program some bootloader or similar?

My board will not have the Mega16U2 which is normally used for programming.

title: Using Due (SAM3X8E) native USB port for programming?

Answers: 2

body:
Microchips needs some kind of bootloader to be able programmed over USB. Arduino boards cames with default bootloader loaded (from Arduino company at least, net necesarry from Chine, probably without, if you byu just the chip from manufacturer), so on official boards it is all done for you to have aesy life.

Being able to properly communicate over USB is not exactly easy task and there are many different protocols for sending program to bootloader, which is then resposible to put the program at flash memory at proper place and give it controll later.

Also keep in mind, that there are other ways, how to put program in memory and that not all devices using some microcontroler are even meant to be programable by user over it. (For example they may idetyfy themself as keybords, mouses, joysticks and such to computer and be closed to reprogramming by manufactor of such device. Arduino community is only small part of industry, which uses the same chips for totally different tasks).

body:
The SAM3X8E comes with a bootloader in ROM.

* Memories
  * 256 to 512 Kbytes embedded Flash, 128-bit wide access, memory accelerator, dual bank
  * 32 to 100 Kbytes embedded SRAM with dual banks
  * **16 Kbytes ROM with embedded bootloader routines (UART, USB) and IAP routines**
  * Static Memory Controller (SMC): SRAM, NOR, NAND support. NFC with 4 Kbyte RAM buffer and ECC

Since this bootloader does all that the Arduino IDE asks of it, and has a freely available cross-platform command-line upload tool (`bossac`) the IDE just uses that. No need to invent the wheel when the wheel does everything you need and even comes with a tin of axel grease.

While technically it is possible to use your own bootloader in conjunction with the existing one (use the existing one to install yours, and then use yours to upload sketches) it requires in-depth knowledge of both the chip and GCC linker ("ld") scripts to set aside a block of memory for your bootloader to reside in and relocate the compiled code around it properly. Too much work when the bootloader that already exists does what you want.

However other chips either don't have a bootloader (like the M0 in the Feather) or don't have one that works as desired (like the DFU bootloader in the ATMega32U4) so a custom bootloader is used on those.

The IDE itself is pretty dumb. It just has a configuration file that says "Execute this command with these parameters to upload the HEX file". It neither knows, nor cares, what the bootloader at the other end of the connection is, nor how it works. As long as there is a command-line executable to do the work it just hands over to it.


body:
I would like to ask about a weirdness in my program. This is my program:

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

    void loop() {
       workout_Text();
    }

    void workout_Text() {
      int woT_x[] = {1, 4, 8, 12, 16};
      int woT_y[] = {1, 4, 8, 12, 16};
      int n = sizeof(woT_y);
      on_led(woT_x, woT_y, n);
    }

    void on_led(int a_mat[], int b_mat[], int m) {
      for (int i = 0; i < m; i++) {
        Serial.print(a_mat[i]);
        Serial.print(" : ");
        Serial.println(b_mat[i]);
        delay(100);
      }
    }

This is the part of my program for a LED matrix. The `on_led purpose` function is for printing the value of `a_mat` and `b_mat`. Instead of printing:

    1 : 1
    4 : 4
    8 : 8
    12 : 12
    16 : 16
    1 : 1
    4 : 4
    8 : 8
    16 : 16

It prints:

    1 : 1
    4 : 4
    8 : 8
    12 : 12
    16 : 16
    13312 : 1
    23296 : 4
    1 : 8
    4 : 12
    8 : 16
    1 : 1
    4 : 4
    8 : 8

Where does the big number come from? I am sure that my code is right to just print the `a_mat` and `b_mat`.

Thank you.

title: Error array value after passed to a function

Answers: 2

body: `sizeof` counts bytes. the type of your array is int. sizeof of the int array of length 5 is 10 bytes. your `for` loop goes to i < 10 and reads after the 5th item of the array.

body:
`sizeof()` returns the total number of bytes. If you have an array of 5 ints, where each int is 2 bytes long, sizeof will return 10.

If you want the number of elements in the array, you need to divide by the size of a single element:

    int n = sizeof(woT_y) / sizeof(woT_y[0]);


body:
it seems that I accidentally found a way to make my two Arduino nano clones run without resetting on serial connection close/reconnect. On one hand, this behavior is much closer to the desired behavior and on the other hand it feels hackish, because I don't know the cause yet.

The devices are still able to be flashed with new firmware

I assume that it has to do with the usage of `socat` as proxy for the devices in question. The described behavior was first observed after playing with `socat`. The command that finally worked for me:

    /usr/bin/socat -s -d /dev/ttyACM3,b115200,cs8,parenb=0,cstopb=0,clocal=0,raw,echo=0,setlk,flock-ex-nb,nonblock=1 PTY,link=~/.pyduin/ttyACM3.tty,b115200,cs8,parenb=0,cstopb=0,clocal=0,raw,echo=0,setlk,flock-ex-nb,nonblock=1

An Arduino Uno with the exact same firmware/treatment does not show the same bahavior.

Any ideas what had gone wrong? And how to restore the default FTDI behavior?

title: Arduino(s) not resetting on Serial connection lost / re-established - why?

Answers: 1

body:
What you have done is to disable the "HUPCL" signal that is sent when the port is opened/closed.

You can turn the signal back on with:

    $ stty -F /dev/ttyACM3 hupcl

And you can turn it off again with:

    $ stty -F /dev/ttyACM3 -hupcl

HUPCL means "HangUP on CLose".


body:
[![enter image description here][1]][1]I'm trying to connect 2 potentiometer (10k) and pass their value to Hairless Midi software (For Serial to Midi Bridge) the first pot is working fine but the second pot's value keep on changing and when i move around the knob of pot1 the value of pot 2 also changes.

I have tried reading the value twice but no luck....

My code:

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

    void loop()
    {
      analogRead(0);
       val = analogRead(0)/8;   // Divide by 8 to get range of 0-127 for midi
       if (val > lastVal+1 or val < lastVal+1 )
       {
       MIDImessage(176,1,val);}
       lastVal = val;

      analogRead(2);
       val2 = analogRead(2)/8;   // Divide by 8 to get range of 0-127 for midi
       if (val2 > lastVal2 + 1 or val2 < lastVal2 + 1 )
       {
       MIDImessage(176,2,val2);}         // 176 = CC command, 2 = Which Control, val = value read from Potentionmeter 2
       lastVal2 = val2;

       //val3 = analogRead(2)/8;   // Divide by 8 to get range of 0-127 for midi
       //if (val3 != lastVal3)
       //{
       //MIDImessage(176,3,val3);}         // 176 = CC command, 3 = Which Control, val = value read from Potentionmeter 3
       //lastVal3 = val3;

    delay(100);
    }

    void MIDImessage(byte command, byte data1, byte data2) //pass values out through standard Midi Command
    {
       Serial.write(command);
       Serial.write(data1);
       Serial.write(data2);
    }

[![Connected Second pot to A0 which was earlier for Pot 1 and removed pot 1][2]][2]

  [1]: https://i.stack.imgur.com/3tr0K.png
  [2]: https://i.stack.imgur.com/nLvM6.png

title: Unexpected value change of 2nd Potentiometer

Answers: 1

body:
As I was having chat with @Maxmilian Gerhardt he suggested to check the voltage of pot 2 so when I checked I was getting 0 volt So he Suggested me there may be a loose connection or something with the beadboard.

So This was a workaround :

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

Thnx for the help @Maxmilian Gerhardt

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


body:
I'd like to decode a PNG on an ESP8266 and access to some pixels of the result. Has anyone got experience with PNG on Arduino? Is it feasible at all? I've done some research on PNG decoding libraries, found [UPNG][1]. Will check if it can be used in Arduino/ESP.

  [1]: https://github.com/elanthis/upng

title: Decode PNG on an ESP8266

Answers: 0


body:
I have not used arduino until now. I thought of interfacing my 4x4 keypad. But when I press keys 1, 4, 7 and *, key values A, B, C and D are sent out to serial terminal respectively. All other keys are working fine. My HW is fine and tested keypad with Atmel Studio. Here is the arduino code. Also attached the schematic. I am using custom shield with arduino nano board on it and pins are marked in the schematic. Shorting links are placed on JP3 and JP2. What could be the reason?

    #include <Keypad.h>
    #include <util/delay.h>
    #include <Wire.h>

    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    char keys[ROWS][COLS] = {
      {'D', '#', '0', '*'},
      {'C', '9', '8', '7'},
      {'B', '6', '5', '4'},
      {'A', '3', '2', '1'}
    };
    byte rowPins[ROWS] = {A0, A1, A2, A3}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {12, 3, 2, 13}; //connect to the column pinouts of the keypad

    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
    }

    void loop() {

      char key = keypad.getKey();

      if (key != NO_KEY) {
        Serial.println(key);
      }
    }

Edit:
Below is the working code I wrote using avrgcc compiler. Note that pinMode is custom macro, works similar to arduino pinMode, but with small difference.

    #include "CL_keypad.h"
    #include <util/delay.h>

    #ifndef IOPORTB
    #define IOPORTB 0
    #endif
    #ifndef IOPORTC
    #define IOPORTC 1
    #endif
    #ifndef IOPORTD
    #define IOPORTD 2
    #endif

    #define IOPB0  0
    #define IOPB1  1
    #define IOPB2  2
    #define IOPB3  3
    #define IOPB4  4
    #define IOPB5  5
    #define IOPB6  6
    #define IOPB7  7
    #define IOPC0  8
    #define IOPC1  9
    #define IOPC2  10
    #define IOPC3  11
    #define IOPC4  12
    #define IOPC5  13
    #define IOPC6  14
    #define IOPC7  15
    #define IOPD0  16
    #define IOPD1  17
    #define IOPD2  18
    #define IOPD3  19
    #define IOPD4  20
    #define IOPD5  21
    #define IOPD6  22
    #define IOPD7  23

    #define IOBitSet(ioport, bit) (((ioport)==IOPORTD)?(PORTD|=1<<(bit)):((ioport)==IOPORTB)?(PORTB|=1<<(bit)):((ioport)==IOPORTC)?(PORTC|=1<<(bit)):0)
    #define IOBitClear(ioport, bit) (((ioport)==IOPORTD)?(PORTD&=~(1<<(bit))):((ioport)==IOPORTB)?(PORTB&=~(1<<(bit))):((ioport)==IOPORTC)?(PORTC&=~(1<<(bit))):0)
    #define IOBitDirOut(ioport, bit) (((ioport)==IOPORTD)?(DDRD|=1<<(bit)):((ioport)==IOPORTB)?(DDRB|=1<<(bit)):((ioport)==IOPORTC)?(DDRC|=1<<(bit)):0)
    #define IOBitDirIn(ioport, bit) (((ioport)==IOPORTD)?(DDRD&=~(1<<(bit))):((ioport)==IOPORTB)?(DDRB&=~(1<<(bit))):((ioport)==IOPORTC)?(DDRC&=~(1<<(bit))):0)
    #define IOBitInvert(ioport, bit) (((ioport)==IOPORTD)?(PORTD^=1<<(bit)):((ioport)==IOPORTB)?(PORTB^=1<<(bit)):((ioport)==IOPORTC)?(PORTC^=1<<(bit)):0)

    // Read the entire port and return the value read. Individual bits are not tested
    #define portRead(ioport) (((ioport)==IOPORTD)?(PIND):((ioport)==IOPORTB)?(PINB):((ioport)==IOPORTC)?(PINC):0)

    #define pinMode(pin,mode) (((mode)==OUTPUT)?IOBitDirOut(((pin)/8),((pin%8))):IOBitDirIn(((pin)/8),((pin)%8)))
    #define digitalWrite(pin,value) (((value)==LOW)?IOBitClear(((pin)/8),((pin)%8)):IOBitSet(((pin)/8),((pin)%8)))
    #define digitalRead(pin) ((portRead((pin)/8))&(1<<((pin)%8))?HIGH:LOW)
    #define digitalInvert(pin) (IOBitInvert(((pin)/8),((pin)%8)))

    #define NUM_ROWS 4   // Number of rows in the keypad
    #define NUM_COLS 4   // number of columns in the keypad
    #define NO_KEY_DETECTED '\0'   // When no key is detected, return '\0'
    #define SWITCHING_DELAY 1      // 2 msec delay between row switching.

    unsigned char readSwitch(unsigned char columnNum)
    {
     //check if key is pressed.
     if(!digitalRead(columnNum))
     {
      //Key De-bounce crude method. To be changed later
      _delay_ms(KEY_DEBOUNCE_TIME);
      if(!digitalRead(columnNum))
      {
       return(1);
      }
     }
     return(0);
    }

    // Assign port pin numbers  based on the hardware connectivity
    uint8_t rowBitNumbers[NUM_ROWS] = {IOPB4,IOPD3,IOPD2,IOPB5};
    uint8_t columnBitNumbers[NUM_COLS] = {IOPC0,IOPC1,IOPC2,IOPC3};

      unsigned char keyAssignments[4][4] = {
      {'D', 'C', 'B', 'A'},
      {'.', '9', '6', '3'},
      {'0', '8', '5', '2'},
      {'*', '7', '4', '1'},
     };

     // Initialize keypad need not be called if port pins are not shared
    // In case same pins are used as output in some cases, it could be re-initialized.
    void initializeKeyPad(void)
    {
     unsigned char loopCnt;

     for(loopCnt=0;loopCnt<NUM_ROWS;loopCnt++)
     {
      pinMode(rowBitNumbers[loopCnt],INPUT);
        }

     for(loopCnt=0; loopCnt<NUM_COLS; loopCnt++)
     {
      pinMode(columnBitNumbers[loopCnt],INPUT);
      // In case  of external Pull ups are used, no need to configure row Port pins.
      // Otherwise enable pull ups.

      // Enable pull up resistors if required
      digitalWrite(columnBitNumbers[loopCnt],HIGH);

     }
    }

    // Function to read the key that is being pressed.
    // Returns the value of the key pressed.
    // First one row will be set low and then all the columns are read.
    // Process is repeated for all the rows.

    //////////////////////////////// IMPORTANT   ///////////////////////////////////
    // Some delay needs to be given between row switching to avoid capacitance effect

    unsigned char getKeyStatus(void)
    {
     unsigned char rowLoopCount;
     unsigned char columnLoopCount;
     unsigned char retValue=NO_KEY_DETECTED;
     //Loop for maximum rows configured
     for(rowLoopCount=0;rowLoopCount<NUM_ROWS;rowLoopCount++)
     {
      // Make the Row as output port. So row will be low (No need to set low because default is low)
      pinMode(rowBitNumbers[rowLoopCount],OUTPUT);
      // Give small delay for settling
      _delay_ms(SWITCHING_DELAY);
      //  Read each column.
      for(columnLoopCount=0;columnLoopCount<NUM_COLS;columnLoopCount++)
      {
       //Read  the status of the switch
       if(readSwitch(columnBitNumbers[columnLoopCount]))
       {
        pinMode(rowBitNumbers[rowLoopCount],INPUT);
        return(keyAssignments[rowLoopCount][columnLoopCount]);
       }
       _delay_ms(SWITCHING_DELAY);
      }
      // At the end, change the direction as input so that port goes to high impedance
      pinMode(rowBitNumbers[rowLoopCount],INPUT);
      //CL_delay_mS(SWITCHING_DELAY);
     }
     return(retValue);
    }

Here is the Schematic [![Schematic][1]][1]

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

title: 4x4 Keypad Interface issues

Answers: 0


body:
I want to program an atmega328p-pu via my arduino uno as ISP in a circuit.

I omitted my connected sensors, LCD, etc in the schematic to keep it simple.

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

When I power the circuit via a 5V power supply (left) I get

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    An error occurred while uploading the sketch
    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
             Double check connections and try again, or use -F to override
             this check.

    avrdude done.  Thank you.

When powering off the circuit and connecting 5V and GND from the arduino to the power and gnd lines in my circuit everything works fine.

I connect 5V and GND from the arduino via pin headers I added to the 5V and GND rails in my circuit to power external sensors etc.

Is there a reason I apparently **have to** use power from the arduino?

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

title: Arduino ISP external power

Answers: 1

body:
Even with an external supply, you must still have a common ground reference between the ATmega being programmed, and the Arduino/ATmega doing the programming.  According to your comment this was the critical issue.

Also keep in mind that the specifications of most ICs including the ATmega prohibit applying signal voltages when the chip itself is unpowered.  To stay within that specification, you would need to turn on the external supply first, and insure that all of the pins were in their high impedance state and not driving the programmer's ATmega when it is unpowered.

Your pullup resistor on the target's reset would weakly drive pin 10 on the programmer, but a 10K resistor should limit the current to within what the protection diode on the corresponding ATmega pin can tolerate (even such a weak current can however cause problems with clean startup, though the ATmega is less sensitive than some other devices).

If you can't be sure power is going to be applied correctly, putting 1K (maybe even 2.2K) series resistors between the two chips can help a little, but there's a balance between keeping the signals strong enough to work well, and keeping illicit currents weak enough to avoid stress.


body:
    #include <GSM.h>

    // PIN Number
    #define PINNUMBER ""

    // initialize the library instance
    GSM gsmAccess;     // include a 'true' parameter to enable debugging
    GSMScanner scannerNetworks;
    GSMModem modemTest;

    // Save data variables
    String IMEI = "";

    // serial monitor result messages
    String errortext = "ERROR";

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

      Serial.println("GSM networks scanner");
      scannerNetworks.begin();

      // connection state
      boolean notConnected = true;

      // Start GSM shield
      // If your SIM has PIN, pass it as a parameter of begin() in quotes
      while (notConnected) {
        if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
          notConnected = false;
        } else {
          Serial.println("Not connected");
          delay(1000);
        }
      }

      // get modem parameters
      // IMEI, modem unique identifier
      Serial.print("Modem IMEI: ");
      IMEI = modemTest.getIMEI();
      IMEI.replace("\n", "");
      if (IMEI != NULL) {
        Serial.println(IMEI);
      }
    }

    void loop() {
      // scan for existing networks, displays a list of networks
      Serial.println("Scanning available networks. May take some seconds.");
      Serial.println(scannerNetworks.readNetworks());

      // currently connected carrier
      Serial.print("Current carrier: ");
      Serial.println(scannerNetworks.getCurrentCarrier());

      // returns strength and ber
      // signal strength in 0-31 scale. 31 means power > 51dBm
      // BER is the Bit Error Rate. 0-7 scale. 99=not detectable
      Serial.print("Signal Strength: ");
      Serial.print(scannerNetworks.getSignalStrength());
      Serial.println(" [0-31]");
    }

Results:
When I run the program, I can see the "GSM networks scanner" message appear on my serial monitor, but it does not display anything else after that. Also, the NET and STATUS LEDs turn off after some few seconds when the program starts running. I already made the minor adjustments necessary for the Arduino Mega, and the power supply is temporarily from the USB port of my laptop connected to the Arduino Mega. I am using a SIM card that has been activated.

I think my program stops at this stage:

      // connection state
      boolean notConnected = true;

      // Start GSM shield
      // If your SIM has PIN, pass it as a parameter of begin() in quotes
      while (notConnected) {
        if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
          notConnected = false;
        } else {
          Serial.println("Not connected");
          delay(1000);
        }
      }

P.S. when I run the program without inserting a SIM card, the NET and STATUS LEDs keep on working (NET is blinking, while STATUS remains ON)

I tried this program as well https://www.arduino.cc/en/Guide/ArduinoGSMShield#toc9
and it has the same problem (i.e. stops at the same stage as the previous program)

[![Serial Monitor result][1]][1]

[![GSM shield STATUS and NET (LEDs) turn off after some few seconds][2]][2]

  [1]: https://i.stack.imgur.com/lMbSY.png
  [2]: https://i.stack.imgur.com/WRcri.jpg

title: Arduino GSM Shield NET and STATUS led turn off after a few seconds

Answers: 1

body:
SOLUTION:
To solve my GSM shield issue, I connected a 9 V battery to my Arduino as a supply instead of using my Laptop's USB cable (and I also tried a 12 V supply as well). Thankfully, it did work. In the case that that it does not work (after uploading the program), click on the 'restart' button found on the GSM shield. You can find the type of sources that I used to supply my Arduino & GSM shield in the image posted below. IT IS IMPORTANT TO MENTION THAT THE FOLLOWING PROGRAM WAS IMPLEMENTED TO CHECK IF THE GSM SHIELD IS WORKING (I tried the "GSM Networks Scanner" program that I have mentioned in my question initially, but it did not work and it was not necessary anyways. So, I used the 'GSM SMS' code directly and it worked fine)

This is the code that worked out with me:

    #include <GSM.h>

    #define PINNUMBER ""

    // initialize the library instance
    GSM gsmAccess; // include a 'true' parameter for debug enabled
    GSM_SMS sms;

    // char array of the telephone number to send SMS
    // change the number 1-212-555-1212 to a number
    // you have access to
    char remoteNumber[20]= "Replace this text with a mobile number instead";

    // char array of the message
    char txtMsg[200]="Hello World";

    void setup()
    {
      // initialize serial communications
      Serial.begin(9600);

      Serial.println("SMS Messages Sender");

      // connection state
      boolean notConnected = true;

      // Start GSM shield
      // If your SIM has PIN, pass it as a parameter of begin() in quotes
      while(notConnected)
      {
        if(gsmAccess.begin(PINNUMBER)==GSM_READY)
          notConnected = false;
        else
        {
          Serial.println("Not connected");
          delay(1000);
        }
      }
      Serial.println("GSM initialized");
      sendSMS();
    }

    void loop()
    {
    // nothing to see here
    }

    void sendSMS(){

      Serial.print("Message to mobile number: ");
      Serial.println(remoteNumber);

      // sms text
      Serial.println("SENDING");
      Serial.println();
      Serial.println("Message:");
      Serial.println(txtMsg);

      // send the message
      sms.beginSMS(remoteNumber);
      sms.print(txtMsg);
      sms.endSMS();
      Serial.println("\nCOMPLETE!\n");
    }

[![These are the different supplies that I used][1]][1]

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


body:
I'm designing a frequency generator with [ICL8038][1], which would output sine, square and triangle waves, which would reach frequency such as 300kHz.

I've already designed a circuit around the ICL8038, but I'm unsure how to measure the frequency, to show on LCD display.

I'm leaving down a schematics I've drawn.
A.Duty is going to the analog input of arduino, which will show the duty cycle between 2% and 98%. This will be going to a voltage divider to make a proportional input for the arduino analog input.

The "frequency pin" would be connected directly from the BNC connector from the casing, which means, that the input can be triangular, sine or square.

Just to mension, in case it makes any kind of difference, I'm planning to use just Atmega328 with 16MHz quartz and 2 capacitors, not exactly as Arduino UNO or NANO.
But the Atmega will have a arduino bootloader on it.

 [![enter image description here][2]][2]
By the time asking about ICL8038, I've got also few questions about the IC:

1. You connect the FM Bias(pin 7) and SWEEP (pin 8) together to create sweep on the output of any kind of signal, whichever it is? This is fixed time constant or should I add some kinda coapacitor there?

2. What exactly does Tcap (pin 10) does? I've read through the datasheet but couldn't understand it's meaning.

3. How would I get proper voltage range every time, when I would change the input voltage of the ICL8038? (it has wide range of output signal, proportionall to the input; it goes from 36V to input, 28V max output)

4. For power supply would be proper LM317 as adjustable power supply (since it has low power consumption) and just use a potentiometer to adjust input of the ICL8038 and monitor the OUTPUT levels?

5. PIn 13 and PIn 14 are NC (not connected). Can I just connect them together and connect them to GND?

As if anybody knows for any "better" IC as this one is, please let me know.
I'm already going to have to buy it from China (this gives me doubts about the capabilities), I'd rather just order one from Europe or US.

  [1]: http://www.alldatasheet.com/datasheet-pdf/pdf/67443/INTERSIL/ICL8038.html
  [2]: https://i.stack.imgur.com/ZjTmd.png

title: Measuring high frequencies (300kHz) with arduino

Answers: 1

body:
To sample a 300kHz signal you need to sample at *at least* 600,000 samples per second (see [Nyquist-Shannon Theorem](https://en.wikipedia.org/wiki/Nyquist–Shannon_sampling_theorem)).

The Arduino can sample at an absolute maximum of 125,000 samples per second.

A normal Arduino will not be able to sample the analog input fast enough to even remotely have a clue what the frequency is - let alone what shape the signal is (for that you would have to be sampling in the millions of samples per second).

You will need a much more powerful board than an Arduino to do it.

The other option is to feed the signal through a comparator (an op-amp with infinite gain) to convert the signal into a square wave. You can then use simple frequency counting to get the frequency (count the pulses within a given time frame - maybe 1 second).

As for the rest of your questions, you would be better off asking those on [Electrical Engineering](https://electronics.stackexchange.com/).


body:
so I am testing out the PulseSensor code from here: https://github.com/WorldFamousElectronics/PulseSensorAmped_2_Sensors/tree/master/PulseSensorAmped_2_Sensors_1.5.0

In the interrupt.ino file, there is a function interruptSetup() which initializes the timer settings. However, I want to undo these settings first, as I have found out that this function is affecting my other readings. What is the default settings for the timer?

title: Timer Interrupt Default Settings

Answers: 0


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

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

    void loop()
    {
     time_Text(2);
    }

    void time_Text(int PastTo_val) {
      switch (PastTo_val) {
       case 1:
       {
        int tPTT_y[] = {11, 11, 11, 11};
        int tPTT_x[] = {6, 7, 8, 9};
      }
      break;
    case 2:
      {
        int tPTT_y[] = {11, 11};
        int tPTT_x[] = {10, 11};
      }
      break;
     }

     int n_tPTT = sizeof(tPTT_x) / sizeof(tPTT_x[0]);

     Serial.print(tPPT_y);
     Serial.print(" : ");
     Serial.print(tPPT_x);
     Serial.print(" : ");
     Serial.println(n_tPPT);

    }

I have a case that I need to assign different kind of array value (with different size per case), and then find the size of the array, and print it. The problem is that the `tPTT_y` and `tPTT_x` is a local variable which cannot be accessed outside of the case function. I have tried to declare it before the switch function but I cannot give a size number because the size is different per case, how could I solve this?

title: Crosses Initialization in switch case with different size of array per case

Answers: 2

body:
Create two global arrays that contain the maximum amount of number you ever need, e.g.

    int tPTT_x[4];
    int tPTT_y[4];

Than create one global int that contains how much x and y are filled, e.g.

    int filled;

Than you can change your cases to

    void time_Text(int PastTo_val) {
      switch (PastTo_val) {
       case 1:
       {
        tPTT_y[0] = 11;
        tPTT_y[1] = 11;
        tPTT_y[2] = 11;
        tPTT_y[3] = 11;
        tPTT_x[0] = 6;
        tPTT_x[1] = 7;
        tPTT_x[2] = 8;
        tPTT_x[3] = 9;
        filled = 4;
      }
      break;
    case 2:
      {
        tPTT_y[0] = 11;
        tPTT_y[1] = 11;
        tPTT_x[0] = 10;
        tPTT_x[1] = 11;
        filled = 2;
      }
      break;
     }

Than you can use the 'filled' variable to see how many items in the array are 'valid' (0 <= item < filled).

body:
Just create a buffer of a maximum value and copy in the value you want while remembering the length of the array.

    #define MAX_ARR_LENGTH (4)

    void time_Text(int PastTo_val) {
     int tPTT_x[MAX_ARR_LENGTH];
     int tPTT_y[MAX_ARR_LENGTH];

     const int tptt_y_case_1[] = {11, 11, 11, 11};
     const int tptt_x_case_1[] = {6, 7, 8, 9};
     const int tptt_y_case_2[] = {11, 11};
     const int tptt_x_case_2[] = {10, 11};

     int filled = 0;

     switch (PastTo_val) {
     case 1:
     {
      memcpy(tPTT_x, tptt_x_case_1, sizeof(tptt_x_case_1));
      memcpy(tPTT_y, tptt_y_case_1, sizeof(tptt_y_case_1));
      filled = 4;
     }
     break;
     case 2:
     {
      memcpy(tPTT_x, tptt_x_case_2, sizeof(tptt_x_case_2));
      memcpy(tPTT_y, tptt_y_case_2, sizeof(tptt_y_case_2));
      filled = 2;
     }
     break;
     }

     Serial.println("Printing array values");
     for(int i=0; i < filled; i++) {
      Serial.println("tPPT_x["+ String(i) +"] = " + String(tPTT_x[i]));
      Serial.println("tPPT_y["+ String(i) +"] = " + String(tPTT_y[i]));
     }
    }

Depending on whether you need to modify the memory you can also just point to constant memory and remember the length.

    void time_Text(int PastTo_val) {
     const int* tPTT_x; //Pointers to the values
     const int* tPTT_y;

        //You make also add "static" if you want to reference this
        //data beyond the scope of the function
     const int tptt_y_case_1[] = {11, 11, 11, 11};
     const int tptt_x_case_1[] = {6, 7, 8, 9};
     const int tptt_y_case_2[] = {11, 11};
     const int tptt_x_case_2[] = {10, 11};

     int filled = 0; //number of elements

     switch (PastTo_val) {
     case 1:
     {
      tPTT_x = (const int*) tptt_x_case_1;
      tPTT_y = (const int*) tptt_y_case_1;
      filled = 4;
     }
     break;
     case 2:
     {
      tPTT_x = (const int*) tptt_x_case_2;
      tPTT_y = (const int*) tptt_y_case_2;
      filled = 2;
     }
     break;
     }

     Serial.println("Printing array values");
     for(int i=0; i < filled; i++) {
      Serial.println("tPPT_x["+ String(i) +"] = " + String(tPTT_x[i]));
      Serial.println("tPPT_y["+ String(i) +"] = " + String(tPTT_y[i]));
     }
    }


body:
    void alarm() {
      char keypressed4;
      char keypressed5;
      char keypressed6;
      char keypressed7;
      char disarmcode1[5];
      Serial.println("hi2");
      Serial.println(disarmcode1);

The array gets declared here and I print the values in the empty array. In the serial monitor I read this:

    hi2
    "c

I don't know why or how these values get put into the array. I have code later on that puts values into the array, but from where that point in the code is, no values should be in the array

Also I have an LCD screen hooked up too, and it prints a value of 0 at (2, 0).

title: Why does this array have stored values in it even though I have not put any values in it?

Answers: 3

body:
local arrays are not initialized. Reading uninitialized values is Undefined Behavior.

Practically this means that when read they will interpret the bytes at their memory location as values which can result in anything.

body:
The values haven't been "put" in the array. The array has been located in memory where those values (left over from some earlier operation, possibly as part of a function's [stack frame](https://stackoverflow.com/questions/10057443/explain-the-concept-of-a-stack-frame-in-a-nutshell)) happen to be.

The simple fact that you *haven't* put anything in there means that what was there before hasn't been changed.

body:
Ad to existing answers, while the default behavior of reading unassigned non-instance and non-static memory (e.g. local array) is *undefined*, you can use slightly different C++ declaration which is *defined* as initialized to all zeroes:

    char disarmcode1[5] = {};
or in pure C

    char disarmcode1[5] = {0};


body:
I’m working on a project where I want to control a motorized fader with an arduino.  I have a dual H-Bridge board to control the motor, but the thing is that it is a 10V motor.  I’m thinking of using a secondary power supply on the H-Bridge to power the motor with a proper voltage.
So here is where my lack of electrical knowledge comes into play.  My H-Bridge has the following connections: a set of +/- poles to provide the power to the motors, 4 motor control pins (2 per motor to control their direction) and 4 motor power pins (2 per motor).

If I was using the Arduino as the power source for the DC motor, I would connect the +5v rail to the + terminal ot the H-Bridge and the Gnd rail to the - terminal, which would, in turn act as the ground return for the control pins.

If I am to use an external power supply, how do I wire it properly so I don’t blowup the arduino or the h-bridge?  I’m guessing that my secondary power supply will be connected to the +/- poles of the H-Bridge and the the - pole will also get connected to the Gnd rail of the arduino?

Is that correct?

title: Multiple power supply for arduino controlled dc motor

Answers: 1

body: According to the datasheet on the L298 IC the connections you described should be right. First I would recommend to connect 10v to the + and - rails and measure the voltage on the logical inputs if it is 0 or lower than 3v than that should be ok to connect an arduino. Also now you can connect an additional 5v power supply with an the -5v connected to the - rail on the board and try to connect the +5v volts to the inputs and measure the voltages on the output (or connect an motor) if everything is ok you can try to connect your Arduino.


body: I am trying to connect Bluetooth, GSM and GPS to the ATMega328P, but since it has only 1 RX and 1 TX, can I use the digital pins of ATMega328P as RX/TX pins.

title: ATMega328P receiver and transmitter pins

Answers: 3

body:
It sounds like you are after the [SoftwareSerial][1] library.

> The SoftwareSerial library has been developed to allow serial communication on other digital pins of the Arduino, using software to replicate the functionality (hence the name "SoftwareSerial"). It is possible to have multiple software serial ports with speeds up to 115200 bps. A parameter enables inverted signaling for devices which require that protocol.

Although, SoftwareSerial does come with limitations. The major one is that only one serial port can receive data at a time.

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

body: Sounds like you need something with 4 hardware serial ports. 2560 processor.

body:
You can use SoftwareSerial as mentioned above, and just wire the TX/RX to the desired digital pins. You will have to enable and disable the serial ports when you want to read/write to a specific port (Bluetooth/GSM), but that is not terribly difficult. I wrote a blog post on SoftwareSerial with an HM-10 Bluetooth module - there you can see how I wired and coded the SoftwareSerial via digital pins.

[Arduino IoT with Bluetooth][1]

  [1]: https://engineersportal.com/blog/2018/3/21/arduino-internet-of-things-part-2-lowering-the-power-consumption-of-the-atmega328p-breadboard-arduino-with-the-hm-10-bluetooth-module


body:
I tried using my Arduino Nano in a circuit, switched on power to the circuit and heard a crack and smelt a bit of burning - something shorted.

I have plugged my Arduino into my PC with a USB, the light comes on - it's detected by my PC, so it's not fried completely.

However, when I try powering the Arduino with a 12V 2A wall adaptor (it was working with that before) no lights. Is it possible I somehow fried the voltage input or ground pins - or the voltage regulator (if it has one)?

title: Have I fried the voltage input on my Arduino Nano?

Answers: 1

body:
12V, 2A through a shorted LDO? Yes. It's toast, or something else in the power path (diode?) is toast.

If you are good at soldering you could maybe replace the component, but probably easier to just use a 5v supply instead.


body:
I don't like how my servo quickly jumps to the default middle position, so I commented out the line where `DEFAULT_PULSE_WIDTH` is set in `Servo.cpp`:

    //servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH);

Unfortunately while this stopped the servo from moving on execution of `attach`, the position of the servo is now showing up as `-52`!

Just running the following in `setup()` is enough to generate the bug:

    int servo_pin = 53;
    servo.attach(servo_pin);
    Serial.print("Initial position: ");
    Serial.println(servo.read());  //returns -52

This last line returns `-52` no matter what position the servo is actually in, which has bad consequences (its initial movement is way off).

Note I get the same behavior when I set the `DEFAULT_PULSE_WIDTH` to `0` in `Servo.h`.

I am using a Mega -- an Elegoo clone -- on Windows 10.

Note I got the ideas for stopping the servo from moving on initialization from these threads:

 - https://stackoverflow.com/questions/40892922/how-to-stop-an-arduino-servo-from-moving-during-the-myservo-attach-command?noredirect=1&lq=1
 - https://stackoverflow.com/questions/26695670/attach-arduino-servo-without-moving

title: servo.read() starts at negative value, no matter where servo actually is

Answers: 1

body:
You seem to be starting from a fundamental misunderstanding of RC hobby type PWM servos.  To put it simply, they do not electronically output any position information.

Until you have commanded a position and the servo loop has had a fair chance to seek to that, the position of the servo is utterly and entirely unknowable.

This is stated in the documentation of the Arduino servo system:

    read()

    Description

    Read the current angle of the servo (the value passed to the last call to write()).

As this explains, the returned value is not the *physical* position, but rather the last *commanded* position.

Until you have commanded a position (something your code does not do) the return value of this call is physically meaningless.


body:
I have edited my Code and now the issue is both are working but not together

    #include <Key.h>
    #include <Keypad.h>
    #include <Adafruit_Fingerprint.h>
    #include <SD.h>
    #include <SPI.h>
    #include<SoftwareSerial.h>

    SoftwareSerial mySerial(0, 1);
    SoftwareSerial mySerials(2, 3);

    int read_count = 0, tag_count = 0;
    int j = 0, k = 0; // Variabvles to iterate in for loops
    char data_temp, RFID_data[12], data_store[12];
    boolean disp_control;
    char filename[4], fileText[30], names[10];
    int atm[5];
    uint8_t n, num, p;
    char key;
    int p1, p2, p3, p4, z;
    char fid;

    File myFile;
    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerials);

    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    char keys[ROWS][COLS] = {
      {'1', '2', '3', 'A'},
      {'4', '5', '6', 'B'},
      {'7', '8', '9', 'C'},
      {'*', '0', '#', 'D'}
    };

    byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad

    Keypad keypads = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

    void setup() {
      finger.begin(57600);
      mySerial.begin(9600);
      Serial.begin(9600);

      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.print("Initializing SD card...");

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        while (1);
      }
      Serial.println("initialization done.");

      Serial.println("Please Place Your Card");

    }

    void RecieveData()
    {

      if (mySerial.available() > 0)
      {
        data_temp = mySerial.read();
        RFID_data[read_count] = data_temp;
        read_count++;
      }
    }
    void ReadData()
    {
      if (read_count == 12) {
        disp_control = true;
        for (j = 0; j < 12; j++) {
          data_store[j] = RFID_data[j];
        }

        int x = 0;
        for (int i = 9; i < 12; i++) {
          filename[x] = data_store[i];
          x++;
        }
        filename[3] = '.';
        filename[4] = 't';
        filename[5] = 'x';
        filename[6] = 't';
        filename[7] = '\0';

        myFile = SD.open(filename, FILE_READ);
        if (myFile) {

          // read from the file until there's nothing else in it:
          while (myFile.available()) {

            for (int i = 0; i < 20; i++) {
              fileText[i] = myFile.read();
            }

            int a, n = 0;
            for (int i = 0; i < 4; i++) {
              atm[a] = fileText[i];
              a++;
            }
            for (int i = 5; fileText[i] != '\0'; i++) {
              names[n] = fileText[i];
              n++;
            }
            fid = fileText[4];

            validate();

            myFile.close();
          }
        } else {
          // if the file didn't open, print an error:
          Serial.println("error opening test.txt");
        }
        read_count = 0;
        tag_count++;

      }
    }
    void validate() {

      Serial.print("Hello ");
      Serial.print(names);
      Serial.println();
      Serial.println();
      Serial.println();

      pin();

    }

    void pin() {
      Serial.println("Please Enter Your ATM PIN");

      p1 = keypads.getKey();
      while (p1 == NO_KEY) {
        p1 = keypads.getKey(); //UPDATE VALUE

      }
      Serial.print(p1 - 48);

      p2 = keypads.getKey();
      while (p2 == NO_KEY) {
        p2 = keypads.getKey(); //UPDATE VALUE
      }
      Serial.print(p2 - 48);

      p3 = keypads.getKey(); //UPDATE VALUE
      while (p3 == NO_KEY) {
        p3 = keypads.getKey(); //UPDATE VALUE
      }
      Serial.print(p3 - 48);

      p4 = keypads.getKey(); //UPDATE VALUE
      while (p4 == NO_KEY) {
        p4 = keypads.getKey(); //UPDATE VALUE
      }
      Serial.print(p4 - 48);

      Serial.println();

      if ((p1 == fileText[0]) && (p2 == fileText[1]) && (p3 == fileText[2]) && (p4 == fileText[3])) {
        Serial.println("Please verify Fingerprint");
      }
      else {
        Serial.println("Invalid. Buzzer!!!!");
      }

    }
    uint8_t getFingerprintID() {
      uint8_t p = finger.getImage();
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.println("No finger detected");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK success!

      p = finger.image2Tz();
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK converted!
      p = finger.fingerFastSearch();
      if (p == FINGERPRINT_OK) {
        Serial.println("Found a print match!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_NOTFOUND) {
        Serial.println("Did not find a match");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }

      // found a match!
      Serial.print("Found ID #"); Serial.print(finger.fingerID);
      Serial.print(" with confidence of "); Serial.println(finger.confidence);

      return finger.fingerID;
    }

    int getFingerprintIDez() {

      uint8_t p = finger.getImage();
      if (p != FINGERPRINT_OK)  return -1;

      p = finger.image2Tz();
      if (p != FINGERPRINT_OK)  return -1;

      p = finger.fingerFastSearch();
      if (p != FINGERPRINT_OK)  return -1;

      Serial.print("Found ID #"); Serial.print(finger.fingerID);
      Serial.print(" with confidence of "); Serial.println(finger.confidence);
      return finger.fingerID;

      // found a match!

      /*z = finger.fingerID;
        if ((fid - 48) == z) {
        Serial.println("Success");
        }
        else {
        Serial.println("Fail");
        }*/

    }

    void loop() {

      RecieveData();
      ReadData();
      getFingerprintIDez();
      delay(50);
    }

If I initialize in this format, then fingerprint works:

    mySerial.begin(9600);
      finger.begin(57600);
      Serial.begin(9600);

And if i do it this way, then RFID works:

    finger.begin(57600);
      mySerial.begin(9600);
      Serial.begin(9600);

I want both of them to work i.e; I first Scan the Card, then verify pin and then it checks the validity of the fingerprint. But the issue is only one of them works at a time. If RFID works, then fingerprint doesn't even blink and if Fingerprint works, RFID doesn't read.

title: Rfid with Adafruit fingerprint together not working in Arduino Uno

Answers: 1

body:
No surprise there. Your function says:

    uint8_t p = finger.getImage();
    if (p == FINGERPRINT_OK)
      z = finger.fingerID;

So what happens if `p` isn't `FINGERPRINT_OK`? This runs:

      if ((fid - 48) == z) {
        Serial.println("Success");
      }
      else {
        Serial.println("Fail");
      }

So `z` is uninitialized and so probably 0, `fid` was assigned some value along the way (and it doesn't seem to be 48). So what you get is the expression in the IF condition evaluates to false, 'Fail' is printed and the function returns.

Neglecting the poor structure of your code, magic numbers and all, you've failed to account for the case where there's *no* finger on the module. Aside from that, you're not even performing a fingerprint search (as I assume you intend); even when someone places their finger, all you're doing is grabbing the image and then reading the default value of `fingerID` which I believe is `0xffff` -- no template conversion or database search. Bottom line, you need to go back and study the original example, which is well commented with self-explanatory method names, before making any changes and writing your own stuff.


body:
I was looking at [this link][1] on RFID I2C interface. I added the library to arduino, but in `main.cpp`, I see an error:

>In function 'void setup()':
>
>sketch_mar27a:16: error: no matching function for call to 'TwoWire::begin(int, int)'
>
>   Wire.begin(SDA_PIN, SCL_PIN); // Initialize I2C

I looked at `Wire.cpp` file and found that there is no such member function overloaded with two parameters.

How should I fix the problem? Even if I fix this one problem, I am not sure if this code is working code.

Where can I find working code with I2C interface? I have resource problem and SPI PORT cannot be used.

The code:

    #include <Wire.h>

    #include "MFRC522_I2C.h"

    #define SDA_PIN 5
    #define SCL_PIN 6
    #define RST_PIN 3

    MFRC522 mfrc522(0x28, RST_PIN);  // Create MFRC522 instance.

    void ShowReaderDetails();

    void setup() {
      Serial.begin(9600); // Initialize serial communications with the PC
      Wire.begin(SDA_PIN, SCL_PIN); // Initialize I2C
      mfrc522.PCD_Init();   // Init MFRC522
      ShowReaderDetails();  // Show details of PCD - MFRC522 Card Reader details
      Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
    }

    void loop() {
      // Look for new cards
      if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
      }

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

      // Dump debug info about the card; PICC_HaltA() is automatically called
      mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
    }

    void ShowReaderDetails() {
      // Get the MFRC522 software version
      byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
      Serial.print(F("MFRC522 Software Version: 0x"));
      Serial.print(v, HEX);
      if (v == 0x91)
        Serial.print(F(" = v1.0"));
      else if (v == 0x92)
        Serial.print(F(" = v2.0"));
      else
        Serial.print(F(" (unknown)"));
      Serial.println("");
      // When 0x00 or 0xFF is returned, communication probably failed
      if ((v == 0x00) || (v == 0xFF)) {
        Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
      }
    }

  [1]: https://github.com/arozcan/MFRC522-I2C-Library

title: MIFARE RC522 I2C Library

Answers: 1

body:
SPI is a multi-slave bus. Unless you've run out of free pins to use for CS, or you have slaves that don't play nice, you can connect your RFID module to the SPI bus as well. Also your sketch will most likely compile if you only correct the offending line to simply `Wire.begin()`. Your library uses the standard Wire library but assumes the target is an ESP8266, whose version of Wire has an extended `begin()` method.

But this may all be no use since the MFRC522 you have (assuming it's the cheap blue module) is hardwired to use only the SPI interface. Unless you're ready to modify the PCB (cut traces, etc) as others have done.


body:
Here is a code snipet for ultrasonic sensor

    digitalWrite(trigpin,HIGH);
    delayMicroseconds(10);
    digitalWrite(trigpin,LOW);

    duration=pulseIn(echopin,HIGH);

Assume `trigpin` and `echopin` pins are already defined.

Now according to [Arduino reference guide `pulseIn` funcion](https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/):

>Reads a pulse (either HIGH or LOW) on a pin. For example, if **value** is **HIGH**, `pulseIn()` waits for the pin to go **HIGH**, starts timing, then waits for the pin to go **LOW** and stops timing. Returns the length of the pulse in microseconds or 0 if no complete pulse was received within the time out.

So shouldn't I be getting 10 microseconds as my answer, since since initial state of echo pin is low, now when the reflected sound hits receiver, echo pin goes high, the timer gets started and when and when the pulse ends the echo pin goes low again and since pulse sent was of 10 microseconds of length, the ans should be 10, but any ultrasonic program I have seen uses this code to find the duration the ultrasonic wave takes since it gets emitted to the time it gets into the receiver.

title: Ultrasonic sensor confusion

Answers: 1

body:
What happens is:

- You send a pulse of 10 ms with TTL signal. This is the first line in the picture below.
- Than you call pulseIn. This waits for the echo pulse.
- The echo pulse will become high when reflected. This happens internally in the module. This is the second line.
- The echo pulse will stay high depending on the time it took to be echoed back and makes a pin high (echo pin). This is the third line.
- Than your pulseIn command returns with the time (of the echo pin length).

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

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


body:
I've been trying to make a weather station using a I2C LCD Display and a DHT11, I know, the DHT11 is a bit low res and all that, but it came with the kit I ordered, so it's okay.

However, I'm trying to have it display like a "title" screen, and after a 2sec delay it should proceed to say "Welcome!" and "Press to Start", and wait there until the button is pressed, and after the button is pressed it should proceed to show the temp and humidity.

However it doesn't seem to mind any of the functions added, unless I set the "if" statement at the beginning of the loop to "LOW", then for some reason, the program stops at "Welcome!" and "press to start".
If I change the "if" statement condition to "HIGH" it just proceeds straight through to the temp and humidity.

    #include <DHT.h>
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    //CONSTANTS
    #define DHTPIN 3
    #define DHTTYPE DHT11
    DHT dht(DHTPIN, DHTTYPE);

    LiquidCrystal_I2C lcd(0x27, 16, 2);

    //Variables
    int chk;
    float hum;  //Stores humidity value
    float temp; //Stores temperature value

    const int buttonPin = 6;

    int buttonState = 1;

    void setup()
    {
      pinMode(12, OUTPUT);
      pinMode(13, OUTPUT);
      pinMode(buttonPin, INPUT);
      Serial.begin(9600);
      dht.begin();
      lcd.begin();
      lcd.clear();
      delay(1000);
      lcd.setCursor(0, 0);
      lcd.print("WeatherMate");
      lcd.setCursor(0, 1);
      delay(250);
      lcd.print("Press 'Start'");
      delay(1000);;
      if (buttonState = 0)
      {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Welcome!");
        lcd.setCursor(0, 1);
        lcd.print("Press Start");
      }
    }

    void loop() {
      buttonState = digitalRead(buttonPin);
      if (buttonState = 1) {
      delay(500);

      hum = dht.readHumidity();
      temp = dht.readTemperature();
      if (temp <= 25) {
        digitalWrite(13, LOW);
        digitalWrite(12, HIGH);
      }
      if (temp >= 25) {
        digitalWrite(13, HIGH);
        digitalWrite(12, LOW);
      }
      Serial.print("Humidity: ");
      Serial.print(hum);
      Serial.print(" %, Temp: ");
      Serial.print(temp);
      Serial.println(" Celsius");

      lcd.setCursor(0,0);
      lcd.print("Temp: ");
      lcd.print(temp);
      lcd.print(" ");
      lcd.print("C");
      lcd.setCursor(0,1);
      lcd.print("Hum:  ");
      lcd.print(hum);
      lcd.print(" %");

      delay(500); //Delay 2 sec.

    }
    }

Anyone? I'm stuck on this one.

title: LCD Weather Station - "Press To Start" Function

Answers: 1

body:
As Majenko points out in his comment, a couple of your `if` statements have the [assignment operator][1] (ie. `=`) whereas you are actually after the [comparison operator][2] (ie. `==`).

    if (buttonState = 0)

should be:

    if (buttonState == 0)

And

    if (buttonState = 1) {

should be:

    if (buttonState == 1) {

When an assignment is used, the `if` statement will execute if the value being assigned is a non-zero. For more information see [Using assignment as a condition expression?][3] over on Stack Overflow.

  [1]: https://www.arduino.cc/reference/en/language/structure/arithmetic-operators/assignment/
  [2]: https://www.arduino.cc/reference/en/language/structure/comparison-operators/equalto/
  [3]: https://stackoverflow.com/a/6807398/6075112


body:
I am trying to input 11 numbers only by the use of keypad but the problem is whenever i use this code. It gave me this error.

Here's my code. Help please.

    #include <SoftwareSerial.h>
    #include <LiquidCrystal.h>
    SoftwareSerial mySerial(6, 5);
    int table[] = { 0, 0, 0 };
    #include <Keypad.h>
    #include <Wire.h>
    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
    const byte ROWS = 4; //four rows
    const byte COLS = 3; //three columns

    char keys[ROWS][COLS] = {
        { '1', '2', '3' },
        { '4', '5', '6' },
        { '7', '8', '9' },
        { '*', '0', '#' }
    };
    byte rowPins[ROWS] = { 2, 3, 17, 16 }; //connect to the row pinouts of the keypad
    byte colPins[COLS] = { 15, 14, 13 }; //connect to the column pinouts of the keypad
    int count = 0;
    Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
    char entryStr[13]; // This can hold up to 4 digits
    int i = 0;
    char n1, n2, n3;
    char buf[15]; // i put here***
    void setup()
    {
        Wire.begin();
        Serial.begin(9600);
        Serial.begin(9600);
        lcd.begin(20, 4);
        ask();
    }

    void loop()
    {
        Wire.requestFrom(2, 3); // request 6 bytes from slave device #2 for(int i=0;i<3;i++) {

        int c = Wire.read(); // receive a byte as character
        Serial.print(c);
        table[i] = c;
        Serial.print('\t');
        // print the character } Serial.print('\n'); Serial.print(table[0]); Serial.print('\t'); Serial.print(table1); Serial.print('\t'); Serial.print(table[2]); Serial.print('\n');

        //if(table[0]<=8) //{ //Serial.print("Flame Detected!"); //Serial.println("Level1");
    }
    void ask()
    {

        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Enter no1.:");
        lcd.setCursor(0, 1);
        lcd.print("(starts with 0)");
        lcd.setCursor(1, 2);
        n1 = GetNumber(buf, sizeof(buf) - 1);

        Serial.print(n1);

        delay(1);

        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Enter no2.:");
        lcd.setCursor(0, 1);
        lcd.print("(starts with 0)");
        lcd.setCursor(1, 2);
        n2 = GetNumber(buf, sizeof(buf) - 1);

        Serial.println(n2);
        delay(1);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Enter no3.:");
        lcd.setCursor(0, 1);
        lcd.print("(starts with 0)");
        lcd.setCursor(1, 2);
        n3 = GetNumber(buf, sizeof(buf) - 1);

        Serial.println(n3);
        delay(1);
        Serial.println(n1);
        Serial.println(n2);
        Serial.println(n3);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("list of numbers ");
        lcd.setCursor(0, 1);
        lcd.print("will be shown press");
        lcd.setCursor(1, 2);
        lcd.print("reset if wrong");

        delay(7000);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Numbers Stored:");
        lcd.setCursor(0, 1);
        lcd.print("no1.:0");
        lcd.print(n1);
        lcd.setCursor(1, 2);
        lcd.print("no2.:0");
        lcd.print(n2);
        lcd.setCursor(2, 3);
        lcd.print("no3.:0");
        lcd.print(n3);
    }
    void GetNumber(char* result, const int maxLength)
    {
        char key = kpd.getKey();
        int i = 0; // how far through buffer we are
        while (key != '#') {
            switch (key) {
            case NO_KEY:
                break;

            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':

                lcd.print(key);
                if (i < maxLength) {
                    result[i++] = key;
                    result[i] = 0; // terminating null
                }
                break;

            case '*': // backspace
                if (i > 0) {
                    i--;
                    result[i] = 0; // terminating null
                }

                break;
            }

            key = kpd.getKey();
        }

    } // end of GetNumber

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

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

title: keypad storing problem (void value not ignored as it ought to be)

Answers: 2

body:
Your `GetNumber` function is defined to return void (nothing) while you use it as if it returns the number typed.

change GetNumber to return a int and the end of it do a `atoi` using the buffer and return the result.

body:
The `GetNumber()` function is coded in such a way as to pass the collected value back through the `result` parameter.

>     void GetNumber(char* result, const int maxLength)

So, when you use the `GetNumber()` function, you pass it `buf`, and after the call returns, you will find the result in the `buf` char array.

However, you appear to be trying to store the result in `n1`, `n2`, and `n3`, which are `char` type variables, and can hold only one character, or a number between `0` and `255`, neither of which can hold an 11-digit string of numbers like you wish.

A `char` is an 8-bit variable. An `int` (on Arduino Uno) is a 16-bit value and can hold at most `32,768`. Even an `unsigned long`, a 32-bit variable of all positive numbers, can hold a maxiumum value of `4,294,967,295`, which gets at most all 9-digit numbers, and some 10-digit numbers.

You would probably be better off holding the numbers as character arrays just like `buf`, and passing those as the first parameter of `GetNumber()` instead of `buf`:

    char n1[15], n2[15], n3[15];
    ...
    GetNumber(n1, sizeof(n1) - 1);
    ...
    GetNumber(n2, sizeof(n2) - 1);
    ...
    GetNumber(n3, sizeof(n3) - 1);

If you do that, then you can get rid of `buf` entirely.

Alternatively, you can keep `buf` as the temporary holder of the incoming string and use `strncpy()` to copy the string from `buf` to `n1` (etc.):

    GetNumber(buf, sizeof(buf) - 1);
    strncopy(n1, buf, sizeof(n1));

This method uses more memory, as you have `buf` taking up space, but it has an advantage that you can later do validation or error checking on the user input before you overwrite `n1` or the others with the new value.


body:
I am using an SH1106 and am creating my own driver for it. Nearly everything is doing great with about 2/3ms send time using **transfer16**. I did notice however that I can use **transfer** with a buffer and length to give a 1ms display time; something that'd be extremely useful.

For reference before here is the datasheet:
http://support.technologicalarts.ca/docs/Components/OLED13-SPI/SH1106.pdf

So the working solution is this:

    SPI.beginTransaction(settings);
    //
    for (int page = 0; page < 8; page++)
    {
        digitalWrite(DC, LOW);
        SPI.transfer(0xB0 + page);
        SPI.transfer(0x02);
        SPI.transfer(0x10);
        digitalWrite(DC, HIGH);

        for (int column = 0; column < 128; column += 2)
            SPI.transfer16(buffer[(page * 128) + column]);
    }
    digitalWrite(DC, LOW);
    //
    SPI.endTransaction();

This for each of the 8 pages writes the 128 bytes 2 at a time. I want to write the 128 bytes in a single call. This would be something like this:

    SPI.transfer(buffer + (page * 128), 128);

This however sort of inverts the display. It literally turns every pixel on for some reason and I can't figure out why. I am just using a few bytes set to **255** for testing and with the original method this works perfect.

Am I using the call wrong? Is there a limit to the buffer size I could use, I haven't really seen anything about that at the moment. I tried changed the pointer arithmetic but wasn't successful. I tried moving the 128 bytes into a temporary location and use that but still nothing.

Obviously this isn't major and maybe I could somehow improve the transfer in other ways but if you have any advice I'd love to have it

**----- EDIT -----**

I have had some luck now with using the transfer with buffer method when I changed the page datatype to a uint8_t. It also caused a few more issues however and I am not sure what is causing them.

 - Firstly with a fast display rate the display inverts itself once again with all pixels on.
 - With a delay between display calls, it works! But after a few seconds those pixels slowly go away, something I have never experienced before.

Here is the edited code:

    SPI.beginTransaction(settings);
    //
    for (uint8_t page = 0; page < 8; page++)
    {
        SPI.transfer(0xB0 + page);
        SPI.transfer(0x02);
        SPI.transfer(0x10);

        digitalWrite(DC, HIGH);
        SPI.transfer(buffer + (page * 128), 128);
        digitalWrite(DC, LOW);
    }
    //
    SPI.endTransaction();

It's hard to explain whats actually happening. But without a large delay between the calls of the buffer transfer method the screen freaks out and will maybe invert completely if it's too often. Even with the large delay the pixels randomly vanish over time, something I have never actually seen.

The 2 byte send method doesn't have any of these problems. No delay will work fine.

title: SH1106 - Transferring long buffer via SPI

Answers: 1

body:
You seem to have understood the following but just for clarification:

`transfer16(uint16_t word)`, as the name implies, shifts 16bits/2bytes instead of just 8bits/1byte like `transfer(uint8_t byte)`.

`transfer(uint8_t* buffer, unsigned int size)` on the other hand takes a pointer and the amount of **bytes** to shift.

Now to pointer arithmetic. Operations on pointer variables are dependent on their explicit data type(as well as processor architecture!). Therefore, in our case, a `+1` on `uint8_t* val` will advance the pointer by 8bits.
`+1` on `uint32_t* val` will do so by 4bytes/32bits.

**Check `buffer`'s data type**

It should be any of `char, unsigned char, uint8_t, int8_t`


body:
I need to calculate resistor for a PNP transistor.

To do this I need to know the voltage and current.

I know voltage is 5 volts as it is easy to find in the internet,
but how about current? I mean people say the maximum current is 40 mA, but
will it be 40mA? Does the arduino supply 40mA as long as it is able to?
Or for example if i just connect a single diode it magically "calculates" the current it needs and supplies, let's say, 20mA?

title: Max current per pin is 40 mA. But it is always 40 mA?

Answers: 2

body:
It means that a pin can give (source) at max. 40 mA. However, if a components uses more, than the Arduino cannot give it and as a result the pin becomes unusable.

So you never should exceed 40 mA. And 20 mA is adviced.

+5V and GND pins can take more, however there is also a maximum on 'groups' of GPIO pins. See more information [here][1], below is an excerpt of the page.

However, I doubt that your transistor needs so much, most (if not all) are directly controllable from a GPIO pin and if you need to calculate a resistor value, just make sure you are safely above the minimum current needed to switch the transistor.

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

  [1]: http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations
  [2]: https://i.stack.imgur.com/yhL3z.png

body:
Figure on driving the PNP hard so it turns in into full saturation.
To do that, you want to pull as much current from the base as you can.
Treat the PNP like it is one diode drop of voltage away from 5V when on.
So 4.3V generally (maybe 4.5, check your part specs).
Then you want the Arduino to sink 20 mA.
4.3V/20mA = 215 ohm resistor.
Use a 200, 220, both are standard values and should well to protect the Arduino output transistors and drive the PNP into saturation.
Maybe go as low as 150 ohm to drive a little harder.
If the PNP needs less to turn on full, go a little higher resistance value.


body:
I have a HP Optical Incremental Encoder (256 CPR) in which

- Pin 1 = A,
- Pin 2 = VCC,
- Pin 3 = GND,
- Pin 8 = B.

I already read and see tutorials for rotary encoder such this one:
https://playground.arduino.cc/Main/RotaryEncoders

I have written a program that is supposed to print out the position of my encoder, however I am only getting zeros in my serial monitor. I want to be able to use interrupts. I would like to actually return the position in degrees of my encoder as we rotate it.

**I was able to get it to work. I wasn't connecting my pin properly to my Arduino.**

        #include <LiquidCrystal.h>

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

    #define encoderPinA 2
    #define encoderPinB 3
    #define CPR 256
    volatile int counter =0;
    volatile boolean flag;

    volatile int var_degrees =0;

    void setup() {

      pinMode(encoderPinA, INPUT);
      pinMode(encoderPinB, INPUT);
      Serial.begin (9600);
      attachInterrupt(digitalPinToInterrupt(encoderPinA), isr, RISING);
      lcd.clear();

    }

    void loop() {

       if(flag == true){
            var_degrees = ((360/256.0)*counter);
            Serial.println(var_degrees);
            lcd.setCursor(0, 1);
            lcd.print("Degrees: ");
            lcd.setCursor(9, 1);
            lcd.print(var_degrees);
            flag = false;
      }

    }
    //Interrupts

    void isr_2(){
    flag = true;
      if(digitalRead(encoderPinA) == HIGH){
        if(digitalRead(encoderPinB) == LOW){
          counter = counter -1; //COUNTER CLOCK WISE
        }
        else{
          counter = counter +1; //CW
        }
      }
      else{
        if(digitalRead(encoderPinB) == LOW){
          counter = counter + 1; //CW
        }
        else{
          counter = counter - 1 ; //CCW
        }
      }
    }

title: Optical Incremental Encoder Reading using Arduino UNO

Answers: 1

body:
You are attaching your interrupt incorrectly. You should not pass in the pin number, but the interrupt number. There is also a handy function that converts a pin to the right interrupt number:

    attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);

So, your code should be:

    attachInterrupt(digitalPinToInterrupt(encoderPinA), isr,CHANGE);

Also, you should declare your `counter` variable to be `volatile`, since it is modified within an ISR, and thus the compiler should not assume that it doesn't change even though the `loop()` never changes it:

    volatile int counter = 0;


body:
I am currently trying to write (obtain) a code for getting raw acceleration values and yaw, pitch and roll angles using [these][1] Jeff Rowberg's examples. I have used MPU6050_DMP example to get this code:

    // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
    // for both classes must be in the include path of your project
    #include "I2Cdev.h"

    #include "MPU6050_6Axis_MotionApps20.h"
    //#include "MPU6050.h" // not necessary if using MotionApps include file

    // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
    // is used in I2Cdev.h
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
    #endif

    // class default I2C address is 0x68
    // specific I2C addresses may be passed as a parameter here
    // AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
    // AD0 high = 0x69
    MPU6050 mpu;

    //MPU6050 mpu(0x69); // <-- use for AD0 high

    // uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
    // pitch/roll angles (in degrees) calculated from the quaternions coming
    // from the FIFO. Note this also requires gravity vector calculations.
    // Also note that yaw/pitch/roll angles suffer from gimbal lock (for
    // more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
    #define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
    #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
    bool blinkState = false;

    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 =     success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer

    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorInt16 aa;         // [x, y, z]            accel sensor measurements
    VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
    VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

    // packet structure for InvenSense teapot demo
    uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

    // ================================================================
    // ===               INTERRUPT DETECTION ROUTINE                ===
    // ================================================================

    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
    mpuInterrupt = true;
    }

    int16_t ax, ay, az, axd, ayd, azd, axo=0, ayo=0, azo=0;

    // ================================================================
    // ===                      INITIAL SETUP                       ===
    // ================================================================

    void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial.begin(38400);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately

    // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3V or Arduino
    // Pro Mini running at 3.3V, cannot handle this baud rate reliably due to
    // the baud timing being too misaligned with processor ticks. You must use
    // 38400 or slower in these cases, or use some kind of external separate
    // crystal solution for the UART timer.

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();
    pinMode(INTERRUPT_PIN, INPUT);

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
    }

    // ================================================================
    // ===                    MAIN PROGRAM LOOP                     ===
    // ================================================================
    uint16_t lv = 1;
    void loop() {
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {

    }

    mpu.getAcceleration(&ax, &ay, &az);

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize)
        {
          fifoCount = mpu.getFIFOCount();
        }

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[2] * 180/M_PI);
            Serial.print("\t");
            Serial.print("ax ");
            Serial.print(ax);
            Serial.print("\t");
            Serial.print("ay ");
            Serial.print(ay);
            Serial.print("\t");
            Serial.print("az ");
            Serial.println(az);

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
    if(lv < 501)
    ++lv;
    else
    {
      lv = 1;
      digitalWrite(13, !digitalRead(13));
    }
    }

However when this code, run at 38400 or 1920 baud rate, gives the least frequent FIFO overflow errors (sometimes at 38400, otherwise at 19200). If this code is run below this "optimal" baud rate, FIFO overflow frequency increases. If thic code is run at above "optimal" baud rate, the board freezes after about 10 seconds (always, in every case), the TX just stops binking. Any suggested solution? Board : Arduino Uno, being used with MPU6050

  [1]: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050/examples

title: Baud rate dependency

Answers: 0