message:
6 wire 3 digits 7 segment display and arduino question

Here's a brain teaser for you:

I have the following 3 digit 7 segment display that has only 6 wires

[![][1]][1]

Experimentally I found out how it works, even though I don't understand it, but anyways every segment is lit by a combination of HIGH and LOW of certain two pins, the combinations are below:

[![][2]][2]

So I tried to make it work, but encountered the following problem (as you can see in the first picture): if, for example, I want to activate the segment that requires pin 5 high and pin 6 low, it also activates the other segments that require 5 to high, because apparently if a digital output is not high, it's automatically pulled to ground, and that's a problem.
I tried by setting the other pins I don't use in a segment to high, but then the segments that require 6 low are being activated, so that didn't work.

Other option I have would be transistors or a tri-state buffer, but for that I need all 12 digital inputs of arduino for the two states of each pin of the display.

Hope you understand what my problem is and maybe you have some advice on how to solve it.

Thanks in advance!

Edit: I managed to drive every segment individually using a small delay, and it works if the sketch has only the code for the display, but as soon as I add more code (for the temperature sensor I want to use) it starts to malfunction. You can find the code below.

LE: I managed to make it work by leaving only the display function in the loop and calling every 5 seconds the function for the temperature sensor. It still refreshes the display when it is called, but that doesn't bother me.

Here's the code: http://www.mediafire.com/file/2bs5r8u5rkzpu8g/6w_3D_7S_display.rar

  [1]: https://i.stack.imgur.com/zBpSq.jpg
  [2]: https://i.stack.imgur.com/rs1ah.jpg

body:
What you have is a [Charlie-Plexed][1] display like the one in the [picture below][2].  You need one more wire than this example because your display also includes the decimal point.  If you go through the electrical paths where for each pair one line is driven high, the other is driven low and all other lines are set to input, only one LED at a time will be forward biased.

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

  [1]: https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0ahUKEwiJzsvFqY3aAhVJ5oMKHZ6oAl8QFgg0MAI&url=https://en.wikipedia.org/wiki/Charlieplexing&usg=AOvVaw1__7SkP63bNfaY5KlIjjTh
  [2]: https://www.edn.com/design/led/4368071/Arrange-LEDs-as-seven-segment-displays
  [3]: https://i.stack.imgur.com/aQOv1.jpg


sender: user

message:
Arduino Uno with Kubuntu 16.04: Unable to enumerate device

I try to connect my arduino uno R1 in order to program the atmega8u2 but I am not able to do so. When I run `sudo dfu-programmer atmega8u2 erase` I get the following results:

    dfu-programmer: no device present.

So in order to diagnose it i run `dmeesg` with the following results:

     [ 1395.921051] usb 2-3: new full-speed USB device number 30 using
     xhci_hcd [ 1396.041175] usb 2-3: device descriptor read/64, error -71
     [ 1396.269135] usb 2-3: device descriptor read/64, error -71 [
     1396.497109] usb 2-3: new full-speed USB device number 31 using xhci_hcd [ 1396.617169] usb 2-3: device descriptor read/64, error -71
     [ 1396.845177] usb 2-3: device descriptor read/64, error -71 [
     1397.073163] usb 2-3: new full-speed USB device number 32 using xhci_hcd [ 1397.073371] usb 2-3: Device not responding to setup
     address. [ 1397.281311] usb 2-3: Device not responding to setup
     address. [ 1397.489086] usb 2-3: device not accepting address 32,
     error -71 [ 1397.609173] usb 2-3: new full-speed USB device number 33
     using xhci_hcd [ 1397.609382] usb 2-3: Device not responding to setup
     address. [ 1397.817200] usb 2-3: Device not responding to setup
     address. [ 1398.025176] usb 2-3: device not accepting address 33,
     error -71 [ 1398.025235] usb usb2-port3: unable to enumerate USB
     device
 Do you know fellows how to make my arduino connect back into my computer?

Furthermore II forgot to mention my user is in `dialout` group as `groups` gnu/linux command mentions:

    pcmagas adm dialout cdrom sudo dip plugdev lpadmin sambashare libvirtd docker wireshark

PS: That thing happened after soldering the resistor into the board so it is a new problem.

sender: assistant

body:
You should solder the resistor (in case you do not have the skills I reccomend doing into a proffessional, a professional close to me managed to solder it with a cost about 5 euros) and then hardware reset the atmega8u2 the [documentation](https://www.arduino.cc/en/Hacking/DFUProgramming8U2) mentions. For quick reference just look over in this image:

[![Where to reset atmega8u2][1]][1]

In the `dmesg` you will see similar the same or message:

    [ 1544.679504] usb 1-6: new full-speed USB device number 42 using xhci_hcd
    [ 1544.808341] usb 1-6: New USB device found, idVendor=03eb, idProduct=2ff7
    [ 1544.808350] usb 1-6: New USB device strings: Mfr=0, Product=1, SerialNumber=0
    [ 1544.808356] usb 1-6: Product: Arduino Uno DFU

Then look on the similar [question](https://arduino.stackexchange.com/questions/52032/arduino-uno-r1-i-soldered-resistor-but-i-cannot-dfu-program-atmega8u2) for R1 boards or in case you have a newer board then follow the instructions mentiones to the [documentation](https://www.arduino.cc/en/Hacking/DFUProgramming8U2).

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


message:
How to use digital pin as ground?

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

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() {
}
```


message:
LED Strip Effect without delay

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?

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.


message:
What is wrong with this code?

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);
      }
    }

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.


message:
RFID reader code to identify more than one tag

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
    }

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
    }


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

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.

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


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

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.

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.


message:
Error array value after passed to a function

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.

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]);


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

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?

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".


message:
Unexpected value change of 2nd Potentiometer

[![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

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


message:
Arduino ISP external power

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

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.


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

#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

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


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

<!-- 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?

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]));
     }
    }


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

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).

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};


message:
Multiple power supply for arduino controlled dc motor

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?

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.


message:
ATMega328P receiver and transmitter pins

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.

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


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

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)?

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.


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

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

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.


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

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.

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.


message:
MIFARE RC522 I2C Library

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

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.


message:
Ultrasonic sensor confusion

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.

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


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

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.

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


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

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

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.


message:
SH1106 - Transferring long buffer via SPI

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.

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`


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

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?

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.


message:
Optical Incremental Encoder Reading using Arduino UNO

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
        }
      }
    }

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;


message:
What is the lowest resistance pot that is useful with an analog input?

Background
----------
I've dabbled in electronics since my parents gave me a 150-in-1 kit in the 1970's but never had formal training. My dad repaired Honeywell mainframes so taught me to solder when I was 8. I have a decent set of equipment like irons, parts, meters, etc. and realize I know enough to be dangerous, which is why I avoid mains-powered stuff.  I'm not a newbie but am all too aware of the many holes in my knowledge.  I'm doing this for fun and in a way that allows for failures to be expected, cheap, and educational.
Project
-------
I have a WS2812b LED strip connected to an Arduino Uno and am using various animation libraries to drive it. The goal is to move to a pro mini once the hardware is more settled and use it for creative lighting inside my house or garage.  I started with just the strip and let it display different animations in a sequence based on time but then wanted to attach a button which would advance to the next animation.  After implementing debouncing it worked fine and I moved on to adding a potentiometer to select the speed of the current animation; increasing or decreasing the delay between each 'frame'.  Of interest here is I was using old pots (panel mount not for typical board use - hence I had to solder wires to them just to use them in any configuration) and not doing any ohms law calculations, just hooking up the hardware and tuning the values for mapping the detected voltage to the desired delay by checking printed output from the serial monitor.

I'm happy with the general setup when using a breadboard but when I went to solder something more permanent on perfboard I ran into a problem; the speed control wouldn't work.  I'm sure the first pot I used was 10k but when I checked it with the meter it registered as completely open so I figured I had blown it. Thinking that I needed to control the current I read posts like [this one][1] and [this one about limiting current][2] I felt better and proceeded to replace the pot with a 25 ohm version thinking that the only difference would be in calibrating the values for mapping the detected voltage to the desired delay.  The behavior I got was randomly fluctuating values for the delay and when I hooked up the prototype using USB to my laptop I could see that the analogread() values were fluctuating wildly within a range even when I wasn't manipulating the pot yet nothing I did could get it to be consistent.  My first thought was that there was a problem with ground so I rechecked the connections but they all tested fine, including still reading 25 ohms along the outside terminals and varying values on the wiper consistent with rotating it along its path from end to end.  When I gave up on my protoboard and returned the circuit back to the breadboard I replaced the full size pot with a 10k small one meant for breadboards and the speed control works again.  This leads to my question.

Question
--------
Is there a minimum value for a potentiometer connected to an analog input of an arduino, or is it more likely that there was an issue with my soldering job on the protoboard?  I don't have a picture of the board because I've already desoldered components from it but I can tell you that it was my first attempt at perfboard soldering and it would not win any prizes, sort of the 'face only a mother could love' sort of thing. If it matters, I was using analog input A2.

  [1]: https://arduino.stackexchange.com/questions/5141/how-does-an-analog-input-pin-work
  [2]: https://arduino.stackexchange.com/questions/20167/arduino-potentiometer-example-what-limits-the-current

body:
Most potentiometers take the form of a 3-terminal device, where the two outside terminals are a fixed resistor and the middle terminal adjusts the tap from one extreme to the other.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/g4cvQ.png)

<!-- End schematic -->

In this configuration, you end up creating a simple voltage divider. You should pick the potentiometer's voltage such that the fixed portion does not draw more current than necessary, regardless of the tap position. (The arduino's analog input itself does not draw any significant current really.)

If you use a 1k pot, then the current always flowing from 5V to ground is 5mA, which should not tax the Arduino's voltage regulator too much. If you used a 100 ohm pot, then the current would be 50mA -- not likely to damage things, but certainly more than is necessary just to operate a voltage divider.

If you use a 1M-ohm pot, then you are working with 5 micro-Amps, and at that low current, noise from the power supply starts to interfere with your analog readings.

As for your actual setup, it really depends on how you had it wired, etc.


body:
The Analog Digital Converter (ADC aka analog input) has only a small capacitance, which has to be loaded to do a measurement. This is normally no problem, even with high resistance potentiometers. Also - if you are using the potentiometer correctly - it is very unlikely, that you have blown it (with 5V supply voltage there is only a current flow of 0.5mA through a 10k potentiometer). The current that flows in the ADC is also very small.

The point in using a potentiometer for providing analog input is, that the total resitance is always the same, regardless of the position. See this schematic:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/ARbr8.png)

<!-- End schematic -->

Both voltage dividers have the same total resistance (10kOhm). If you set the position of the potentiometer to the middle, they have exactly the same output: 2.5V. Moving the slider of the potentiometer is the same as taking some of the resistance from one of the resistors on the right and adding it to the other. So a potentiometer is a variable voltage divider. Normally you want the current, that flows through this voltage divider to be small, because it would be only wasted to heat the resistor strip. If you are using a potentiometer with 25 Ohm total resistance while having a 5V power supply, the current trough it would be 200mA, which is pretty much. And if your power supply cannot give you that much, your application will get really instable.

So I see 2 possible problems:

 1. You used the potentiometer the wrong way, or
 2. You made a soldering mistake

EDIT:

From your comment I read, that you are not familiar enough with the rules, how a voltage divider really works. So I will try to explain a bit more.

A potentiometer looks like [this][1] on the inside. It consists of one strip of a resistive material. Each side of the strip is connected to one of the outer pins. The full length of the strip has a constant resistance, say 10kOhm for now. The knob of the potentiometer is connected to a contact, that slides over this resistive strip, making electrical contact with it. When you measure the resistance between one of the outer pins and this middle contact, you get a resistance that is dependent on the position of the contact.

Let's say, we want to measure the resistance between the left contact and the middle contact (the slider). If the slider is very close to the left pin, the resistance we measure is very small, since there is only very few resistive material between the contacts. As we move farer away from the left side of the strip, the measured resistance gets bigger.

At the same time (when we are moving away from the left side of the strip) we are moving towards the right side of the strip, essentially decreasing the resistance between the middle contact and the right side of the strip.

Now we have to do some maths: Ohm's Law states that voltage is resistance multiplied by current

    U = R * I

We connect the outer pins of the potentiometer to our 5V power supply and to ground. So `U = 5V`. And we know the total resistance between these pins: `10 kOhm`. To get the current, that flows through our potentiometer, we reform the above formula to

    I = U / R

Using the above values we calculate the current through the potentiometer to be `0.5mA`. The current through the first part of the resistor strip (say from left to the middle contact) is the same as in the second part (from middle contact to right), as the current has nowhere else to go.

Now we position the middle contact exactly in the middle of the resistive strip. This means that you have half of the total resistance on each side: `5 kOhm`. In electrical circuits the voltage is always measured in reference to ground. So here only the ground side matters for the rest of the calculation. We again need Ohm's Law:

    U = R * I = 5kOhm * 0.5mA = 2.5V

As we want to read this with an Arduino (which uses a 10 bit ADC --> values in the range of 0 to 1023) we get about 512. (This may vary a bit because of fluctuations and distortion)

When we position the middle contact at the ground end of the resistive strip, we have a ground-side resistance of about `0 Ohm`. So we get `0V` at the middle pin and a ADC value of about 0.

When we position the middle contact at the 5V end of the resistive strip, we have a ground-side resistance of about `10 kOhm`. Using Ohm's Law we get `5V` at the middle pin, which translates to an ADC value of about `1023`.

Changing the position also changes the ratio of the resistance on ground-side and 5V-side of the strip. But when you (as said in your comment) just add big resistors to both sides of the 25 Ohm potentiometer, you will only we able to control this really small part of the total resistance. So this will not work.

Note: Not every potentiometer has a linear changing resistive strip. Some have a logarithmic or exponential changing strip.

  [1]: https://tetsuoelectronics.files.wordpress.com/2012/01/dsc00691.jpg


body:
There is no lower limit on the value of a potentiometer that you can use with the Arduino, however the lower the resistance the more current it will pull from the power supply and, if it's too low a resistance and isn't rated for a high enough power, could burn out and catch on fire.

There is, however, an upper limit on the resistance of a potentiometer that you can use.

As a general rule of thumb the *output impedance* of what you connect to an ADC should be no more than around a tenth of the *input impedance* of the ADC.  On the Arduino the ADC has around a 1MΩ input impedance, so you shouldn't connect anything with more than around 100kΩ output impedance.

For a potentiometer (well, for any voltage divider) the output impedance is the value of the two halves of the resistance in parallel.  For a 10K potentiometer with the wiper set right in the middle that's 5K for each half, so the formula is:

         R1 * R2   5000 * 5000
    Ro = ------- = ----------- = 2500Ω
         R1 + R2   5000 + 5000

As you can imagine that's the maximum output impedance at that point. For example, if you adjust it so it's 9000Ω and 1000Ω it works out as:

         R1 * R2   1000 * 9000
    Ro = ------- = ----------- = 900Ω
         R1 + R2   9000 + 9000

So from that you can interpolate that the maximum value potentiometer you can reliably use would have an output impedance of 100kΩ, which is (100000/2500) 40 times more than the 10kΩ one, so 400kΩ is really the maximum you can use.

The main reason for this limit is that the ADC's front-end is a capacitor, and that capacitor has to charge up to the voltage of the input. That charge time is limited by the current available to flow into the pin, and with too high an output impedance the current available is too low and the capacitor can't charge to the right voltage in the limited *acquisition time* of the ADC.

The datasheet itself speaks of the output impedance limit:

> The ADC is optimized for analog signals with an output impedance of approximately 10 kΩ or less. If such a source is used, the sampling time will be negligible.

So they don't recommend anything more than 10kΩ, which equates to a maximum of 40kΩ for the potentiometer's resistance.


body:
Assuming you wired it correctly (ie. you put the wiper to the analog input) your first setup looked like this:

[![25 ohm pot][1]][1]

Your big problem here is the current flow through the pot. Using Ohms Law the current would be:

    I = V / R
    I = 5 / 25
    I = 0.2A  (200 mA)

That is too much to be drawing from the 5V pin and it could easily drag down the voltage to the rest of the board. Also the power would be:

    W = I * V
    W = 0.2 * 5
    W = 1W

One watt is a lot to put through a pot, and you may well have burned the track inside it.

----

> So, if I included a 10k resistor on either side of the pot that should address the current issue but it leaves the question of whether the remaining 25-ohm range is too small for the ADC to register distinct values, ...

The 10k resistor will stop the current problem, but now the range in the voltage divider will be ridiculously small. The setup will now look like this:

[![Pot with resistors][2]][2]

Unfortunately the range you are going to read with the analog input is going to be (voltage divider formula):

    Vout = Vin * (R2 / (R1 + R2))

With the wiper at one end R1 will be 10000 and R2 will be 10025 and with the wiper at the other end it will be vice-versa. So the voltage you get will be:

    Vout = 5 * (10000 / (10025 + 10000))
    Vout = 5 * 0.499
    Vout = 2.497

Or:

    Vout = 5 * (10025 / (10025 + 10000))
    Vout = 5 * 0.501
    Vout = 2.503

In other words you will always be reading about 2.5V and therefore your analog read will always return around 512, which won't be much use to you.

---

> I'm going with a larger value pot (10k or 25k) ...

That sounds like a sensible value. A 10k pot will only draw:

    I = V / R
    I = 5 / 10000
    I = 0.5 mA

That is a reasonable current draw and the analog input will still read it fine.

---

As Majenko points out in his answer you don't want a whole lot more than that resistance because of the optimal input impedance of the ADC converter (10k). A very high resistance would mean only a small current would flow into the analog input pin.

---

## How to use your 25 ohm pots

If you want to use your existing 25 ohms pots because of their physical appearance, then a  **small** resistor in series could reduce the current to a reasonable amount and still give a good reading range. For example, 330 ohms on the "high" side (and nothing between the low side and ground).

    Vout = 5 * (330 / (355 + 330))
    Vout = 5 * 0.193
    Vout = 0.963

Or:

    Vout = 5 * (355 / (355 + 330))
    Vout = 5 * 0.581
    Vout = 2.591

That is now going to give you a reading between 0.96V and 2.59V which, whilst not the full range of 0V to 5V should give you reasonable differentiation as you turn the pot. And the current through it would be:

    I = V / R
    I = 5 / 355
    I = 0.014A (14 mA)

Thus the power would be:

    W = I * V
    W = 0.014 * 5
    W = 0.070 (70 mW)

---

## References

* [Voltage Dividers tutorial](https://learn.sparkfun.com/tutorials/voltage-dividers)
* [Ohms Law](https://en.wikipedia.org/wiki/Ohm's_law)

  [1]: https://i.stack.imgur.com/NzJW2.png
  [2]: https://i.stack.imgur.com/GsTD2.png


message:
Generating Sinusoid Signal of 40khz

I would like to generate a sinusoidal signal of 40kHz using Arduino Uno.
Maximum I could generate was 1kHz, using bit banging, fast PWM. Do you have ideas of how to boost it to 40kHz?

I used "Advanced Arduino Sound Synthesis" for inspiration. https://makezine.com/projects/make-35/advanced-arduino-sound-synthesis/

body:
Let's first do some maths.

* You want 40,000 cycles per second.
* Each cycle needs splitting up into samples. For example, let's use 128 samples.
* Assume you want an 8-bit amplitude resolution.

Each second of signal would need 40,000 cycles * 128 samples. That's 5120000 samples per second.

If using PWM to generate the audio that's 256 clock cycles (28) per sample. That means 5120000 * 256 = 1,310,720,000.

That means a "carrier frequency" of over 1.3GHz.  There's no way an Arduino can do that.

If instead you used a simple DAC (e.g., an R-2R ladder) connected to the 8 pins of port D (that's pins 0-7 on the Uno) you don't need the 256 clock cycles per sample. That means that you have to output a new sample to PORTD 5,120,000 times per second. That's outputting at over 5MHz.

With some well crafted assembly code that *might* be possible.  The Arduino certainly won't be able to do anything else at all at the same time.

You would be much better off using a chip that has audio capabilities and DMA. Maybe a Teensy 3.x would be a better choice for your project.