text:
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.

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

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.


text:
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?

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

Yes, that was the cause. Thanks. Btw, is it safe to use it as a proxish feature? I mean the arduino does not reset on reconnect and there are tons of guys in the internet asking for that feature.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Unexpected value change of 2nd Potentiometer
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);
}

What happens if you swap the two pot? That shield point to whether it’s a software or hardware problem.

I have tried swapping the pots,changing the input pin number but still the problem persist...

What is your circuit? Did you wire the pots in series maybe?

Give me 5 min i will upload my circuit...

You should have something like that, right? (http://i.stack.imgur.com/JrLxr.png)

This is my circuit

You must have an error in your circuit. It works on my Arduino Nano and 2 pots perfectly. See screenshot https://i.stack.imgur.com/ZVzLR.png and code https://pastebin.com/Ww7JcBp0 and circuit picture https://i.stack.imgur.com/5zpN0.jpg

I have connected the same way as my circuit image and your is also the same right...

Try to add more debugging. Instead of connecting the serial to a MIDI device, let it print out the raw Pot analog values and the "would be sent" MIDI bytes to your PC.

One More thing i tried out what i did was I removed the pot one connection from arduino and connected the pot 2 to arduino pin 0 which was earlier used for pot 1. So here the values are changing automatically...adding the circuit

Let us continue this discussion in chat.

Also posted on the Arduino Forum

@tttapa  that's me who had posted on the Arduino forum  i got a lot of help from there but got stuck at this point so posted it here also...

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 :

Thnx for the help @Maxmilian Gerhardt

Some of those protoboards have power rails split in the middle.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


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

Is it feasable depends on the the size of your picture, where it stored, and how you want to store the decompressed data. On an ESP8266 you have ~40kB of free RAM and a decoded picture with RGBA8888 format (2 bytes per pixel) and 128x128 px will take 32kB to store the decompressed image. Notice that the libray always decodes whole pictures, not blockwise -- you must be able to fit the complete decoded image into RAM.

Thanks. Image comes from network stream, base64 encoded (urlData), with a maximum of 128x128 pixels size. I feel this is on the limits.

If you also have the base64 string of the compressed PNG in RAM (how much % of the original image size is that?), plus network / TCP buffers, this will be quite the tough call. You might have to change your logic to transfer smaller images (either resolution or pixel depth), or directly decoded images so you don't have to decode them. You might want to look into an ESP32 (512K RAM) or the ESP-WROVER (ESP32 + 4 MegaByte PSRAM)

With those small images and decompression overhead for png, I got the feeling you might be better of sending uncompressed bitmap images instead. Also try avoiding base64, as that makes things 30% larger, or decode the base64 on the fly.

UPNG is simple to port to a microcontroller. I just did it in an afternoon to run on a 200MHz PIC32MZ with 512kB RAM. It wouldn't run on an 80MHz PIC32MX with 32kB RAM. That's with a 100x100 pixel RGBA8 image. I need to test it with intermediate chips to see what the minimum memory for that image size is.  Also that's with the image source held in flash.

Update: a 128kB PIC32 works, but not a 64kB - so I'd say you need a couple of hundred kB to work with small images. 128kB is OK for things like small icons held in flash.

@Majenko I'm now dealing with an ESP32 which I guess is able to decode small PNGs. Would you be so kind and share the version of UPNG you ported? Thanks!

It's ported to DisplayCore which is for the chipKIT environment. You are welcome to use my code as an example of how to call the UPNG code though.  https://github.com/DisplayCore/PNG


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

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

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

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

void loop() {

  char key = keypad.getKey();

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

Edit:
Below is the working code I wrote using avrgcc compiler. Note that pinMode is custom macro, works similar to arduino pinMode, but with small difference.
#include "CL_keypad.h"
#include <util/delay.h>

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

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

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

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

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

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

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

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

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

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

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

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

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

    }
}

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

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

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

Here is the Schematic

So you seem to print out the values from the wrong column (leftmost instead of rightmost)? Did you double check the column wiring?

possible bad keyboard .... connect only one column at a time and test ...... also, get rid of the external pullup resistors and enable the internal pullups

Code written using AVR GCC works fine with same hardware. Updated first post with same code.

@jsotola Internal pull ups on PC0 to PC3 not enough. I had faced spurious input problems many times without external pull ups.


text:
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.

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?

Even with an external supply, you must connect the ground.  If it still doesn't work, perhaps your external supply is not 5 volts DC, or is noisy.  Also keep in mind that the specifications prohibit applying signal voltages to unpowered ICs - so it's going to be a little tricky to startup an external supply at the same time as the internal one without violating that.  If you have to start the external supply first since most signals are outputs from the programmer, and the 10K reset resistor is large enough not to challenge the programmer ATmega's protection diodes.

https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/

@ChrisStratton The external supply was powered first. But both you and majenko correctly pointed out, that my mistake was not sharing grounds. Does anyone want to make an answer out of that? Otherwise I'll answer myself to not leave the question open although the issue is solved.

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.


text:
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)

It would be great if you could format you code properly and describing expected results.

@jsotola I edited the question to make things clearer

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


text:
Measuring high frequencies (300kHz) with arduino
I'm designing a frequency generator with ICL8038, which would output sine, square and triangle waves, which would reach frequency such as 300kHz.
I've already designed a circuit around the ICL8038, but I'm unsure how to measure the frequency, to show on LCD display.
I'm leaving down a schematics I've drawn.
A.Duty is going to the analog input of arduino, which will show the duty cycle between 2% and 98%. This will be going to a voltage divider to make a proportional input for the arduino analog input.
The "frequency pin" would be connected directly from the BNC connector from the casing, which means, that the input can be triangular, sine or square.
Just to mension, in case it makes any kind of difference, I'm planning to use just Atmega328 with 16MHz quartz and 2 capacitors, not exactly as Arduino UNO or NANO.
But the Atmega will have a arduino bootloader on it.

By the time asking about ICL8038, I've got also few questions about the IC:

You connect the FM Bias(pin 7) and SWEEP (pin 8) together to create sweep on the output of any kind of signal, whichever it is? This is fixed time constant or should I add some kinda coapacitor there?
What exactly does Tcap (pin 10) does? I've read through the datasheet but couldn't understand it's meaning.
How would I get proper voltage range every time, when I would change the input voltage of the ICL8038? (it has wide range of output signal, proportionall to the input; it goes from 36V to input, 28V max output)
For power supply would be proper LM317 as adjustable power supply (since it has low power consumption) and just use a potentiometer to adjust input of the ICL8038 and monitor the OUTPUT levels?
PIn 13 and PIn 14 are NC (not connected). Can I just connect them together and connect them to GND?

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

Why measure the sine output when you have a perfectly good square wave output needing at most voltage adjust that you can count??

Okay, I've never thought of that :D But thanks, sure will use this tip!

the 2nd 1/2 of your post is not Arduino related.

To sample a 300kHz signal you need to sample at at least 600,000 samples per second (see Nyquist-Shannon Theorem).
The Arduino can sample at an absolute maximum of 125,000 samples per second.
A normal Arduino will not be able to sample the analog input fast enough to even remotely have a clue what the frequency is - let alone what shape the signal is (for that you would have to be sampling in the millions of samples per second).
You will need a much more powerful board than an Arduino to do it.
The other option is to feed the signal through a comparator (an op-amp with infinite gain) to convert the signal into a square wave. You can then use simple frequency counting to get the frequency (count the pulses within a given time frame - maybe 1 second).
As for the rest of your questions, you would be better off asking those on Electrical Engineering.

Certanly I realize that, the arduino fails to read such frequencies. But I tend to use "additional" PCB only to measure frequency and convert it into proper signal for the arduino. It can be either analog either digial. But I'd prefer digital, since analog has only 1024 bites.

Of course you wouldn't sample this - you would count whole periods!

In counting you lose the waveform shape information. If you don't care, then yes frequency counting is definitely the way to go.

It doesn't matter the waveform information. This part will be solved otherwise (already got a solution).
And how am I supposed to do the counting part, while it's range will be between 0.1 Hz and 300 kHz?

That makes it simpler then. The comparator and counting is the way to go. The comparator is optional but will give more reliable results and is a jellybean part anyway.

Okay, so a comparator and an up/down counter, which resets every 0.5 seconds?
And how am I supposed to read it with Arduino?

The Arduino is the counter. Google for Arduino frequency counting.

Yes, but you've probably missed out the point, that I'm going up to 300kHz.

Yes? And? That's fine for digital - especially if you use Timer 1's T1 pin (PD5 on the 328P)...

Let us continue this discussion in chat.

Made a research, wrong informations.
A 6MHz frequency counter, made with arduinio.
https://www.hackster.io/moty/counter-92ec57

Frequency counting (what you point to) is what I talk about in the 5th paragraph of my answer. It is not getting the frequency of a sine wave, but the frequency of a square wave. To use it you should really first convert the sine wave into a square wave. Frequency counting is not for sine waves. Frequency counting is easy, and 6MHz I would count as inefficient - you could go much faster than that - but is not suitable for all signals.


text:
Timer Interrupt Default Settings
so I am testing out the PulseSensor code from here: https://github.com/WorldFamousElectronics/PulseSensorAmped_2_Sensors/tree/master/PulseSensorAmped_2_Sensors_1.5.0
In the interrupt.ino file, there is a function interruptSetup() which initializes the timer settings. However, I want to undo these settings first, as I have found out that this function is affecting my other readings. What is the default settings for the timer?

Unless you are using PWM, you can just set all these registers to zero. Otherwise, see Arduino's init() function.

Is the init() function the default settings for the timer?


text:
Crosses Initialization in switch case with different size of array per case
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?

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

@MaximilianGerhardt Thanks for the remark (don't have a compiler at hand). I fixed it in my answer.

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


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

That is why you usually initialize stuff with = 0 and = { 0 } for arrays respectively.

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) happen to be.
The simple fact that you haven't put anything in there means that what was there before hasn't been changed.

How would i clear a array of these values or make them equal NULL then. im aware of in java you can declare they array with its values and make it equal null but null works differently in the C language

while (keypressed4 == NO_KEY) {
keypressed4 = keypad1.getKey();
}
Serial.println("hi2");
if (keypressed4 != NO_KEY) {
disarmcode1[0] = keypressed4;
lcd.setCursor(0, 0);
lcd.print(keypressed4);
}                                                                                after the serial.println disarm code is this and i need a clean array for this portion of the code to work how would i achieve this?

You can use memset: memset(discarmode, 0, 5); which sets the 5 bytes of memory to 0, or you can use an initialisation list: char discarmode[5] = {0}; or explicitly for all values: char discarmode[5] = {0, 0, 0, 0, 0};

void alarm() {
char keypressed4;
char keypressed5;
char keypressed6;
char keypressed7;
char disarmcode1[5]={0};
Serial.println("hi2");
Serial.println(disarmcode1);
while (keypressed4 == NO_KEY) {
keypressed4 = keypad1.getKey();
}
Serial.println("hi2");
if (keypressed4 != NO_KEY) {
disarmcode1[0] = keypressed4;
lcd.setCursor(0, 0);
lcd.print(keypressed4);
}
okay so this portion from the while loop to the if statment happens 3 more times to record 4 values which will be compared to a code example 1234, == keypad recorded values of 1234.

i did this in a earlier function in the code and it worked prefect. by changing the  char disarmcode1[5]; to char disarmcode1[5]={0}; it now apperares as blanks which is good. but i no longer can record values for the input and it leads for the value of the array after recording to hi2
hi2
hi2
hi2
1!N *** this happens after the 4 keypad values should have been recorded it skips right by it and outputs this

You have a fresh array every time the function is called. Make the array static so it only gets made once.

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.

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

An obsolete syntax for GCC even allows define ranges and their values for array initialization.


text:
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?

Possibly, but it's ultimately not possible to say without the documentation of this motor shield.

@ChrisStratton It’s not an arduino shield, it’s a generic H-Bridge board.  I’ll try to find more documentation, but it’s relatively hard to find the paperwork for stuff bought on ebay ;)

To an extent, then it's not really an Arduino question.  The Arduino should have a common ground with the compatible-signal-voltage "digital" side of a motor driver it commands.  What happens on the power side is a question about the details of the motor driver circuit, not an Arduino question.  Without documentation you may need to do some visual/continuity reverse engineering from the data sheet of the driver IC or raw circuit topology if it is made of discrete FETs.

The board is based on a L298N chip...  ill dig further.

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.


text:
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.

Look up SoftwareSerial.

you have not done any research, have you?

a little bit but that time i was not able to come up with a solution.Now i have the solution

The ATmega328p is not a good match for projects needing this level of connectivity - it can be done, but only by a lot of software juggling.

It sounds like you are after the SoftwareSerial 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.

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

Or an ARM part compatible with Arduino usage...

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


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

the usb chip is different than the workhorse chip; you can fry one but not the other. usually, the uart survives (if anything does) in my experience.

Did you try uploading a simple sketch (e.g. blink) to check whether the microcontroller is still working?

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.


text:
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

you are using Windows 10 to control the servo somehow?

Yes, mentioned at the end of my question.

how are you using Windows to to control the servo?

I'm using the IDE in windows just using a standard sweep algorithm. You can see code here: https://onlinegdb.com/HJIKaZv9z  But really all you need to reproduce it is what I showed above in setup().

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.

For those curious, what you would need is a servo with feedback. Something like this: https://www.adafruit.com/product/1404  I thought I was accessing that information, but no.


text:
RFID with Adafruit fingerprint together not working in Arduino Uno
I have edited my Ccde 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 the 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.

Also asked on SO

Why are you using software serial on hardware serial pins?

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.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
MIFARE RC522 I2C Library
I was looking at this link 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?"));
  }
}

Please edit your answer and include the sketch "sketch_mar27a".

the example code in that link is for nodemcu (i.e. ESP8266) - the ESP8266 wire library DOES have a void begin(int sda, int scl); - so it seems the library you are using is targeted to ESP8266

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.

Thanks for the info,  I am not using any SPI devices and SP pins are used for other purpose and that is why I thought I will try I2C. I too have cheap china made blue module. So no meaning in trying I guess. But does UART interface works in this module?

@Rajesh No, UART doesn't work either, SPI is what it was made for. All the other NodeMCU pins are in use? If you really must use RFID, you're only concerned with each card's unique ID and you don't intend to store data on the card, you can try the cheap 125 kHz readers/cards like this: https://www.aliexpress.com/item/Free-shipping-10pcs-lot-UART-125Khz-EM4100-RFID-Card-Key-ID-Reader-Module-RDM6300-RDM630-For/32284373493.html. They use a UART interface and you only need an RX pin really since they're read-only.


text:
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:

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.

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


text:
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.

Assignment is =. Comparison is ==.

As Majenko points out in his comment, a couple of your if statements have the assignment operator (ie. =) whereas you are actually after the comparison operator (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? over on Stack Overflow.

Actually it's not an indication of assignment success, but the value assigned 'falling through' to the if which is why changing 0 to 1 makes it stick in the first if.

Thank you!
This worked a charm, but it doesn't go to the "Welcome" screen now, any ideas?

Where in setup are you reading the current state of the button?

@Majenko Quite right. A mistruth that I learnt early on that has been hard to shake.  I'll change it right away. I don't want to pass on this mistruth to others!


text:
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

Please describe in greater detail.

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.

I already change the code to char[15] n1, n2, n3; but this line give me error it says "expected unqualified-id before '[' token"

My typo. The declaration should have said char n1[15], n2[15], n3[15];

Thank you I already change it but it gives me another new error to this line  n1 = GetNumber(n1, sizeof(n1) - 1); the error is "incompatible types in assignment of 'void' to 'char[15]' " Thank you really.

Don't say n1=. Please re-read the answer. Take the time to understand what the code does instead of copying-and-pasting blindly, and you will do much better.

Really sorry and its okay now. Thank you for your help . Thanks a lot :)

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.

Thank you . Can you give me idea how to do it in my code?Please elaborate thanks a lot.


text:
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.

Check endianess. Swap the byte order for every 2-byte pair in the buffer for a test.  (for(int i=0; i < sizeof(buffer); i +=2) { byte tmp = buffer[i]; buffer[i] = buffer[i+1]; buffer[i+1] = tmp; }

No issues there, just this method on it's own

Where is buffer declared?

Within the class, as 'uint8_t buffer[1024] = {0}'

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

Ah I see, it's a uint8_t. So by using page as an integer I assume I am pushing it 4 bytes instead of 1. Seems I need to do a bit of revision!

I made some progress but am encountering more issues. I edited the post detailing these


text:
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?

voltage depends on source, current depends on load. too much current and the voltage goes down.

Electronics doesn't use magic.

Which resistor? Base or load?

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

That's a great diagram and captures 1/2 of the Notes under the table in section 30 well - there is another section on Sink currents.  To reach the full 300mA of sink  or source current, a Surface Mount 328P needs to be used; the 328P in DIP only provide One VCC and One Gnd pin, and the chips have a max limit of 200mA per per pin, which I have personally confirmed with Atmel Tech Support.  Datasheet can be downloaded here http://www.microchip.com/wwwproducts/en/atmega328p

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.


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

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;

Quick question for this great community. I was able to read the position of my encoder and converted that position to an angle. However when I rotate the encoder right it gives me a negative output and when I rotate it left it gives me a positive output. It is backwards, I checked my Code and I can't find the issue.
Output rotating right starting from zero:
-1
-2
-4
-5
-7
-8
-9
-11
Output rotating right starting from zero:
0
1
2
4
5
7
8
9
11

Switch the counter+1 and counter-1

what do you mean? could you more specific please?

I'm not sure I can be more specific. There are places where you add one to counter and places where you subtract one from counter. Switch the adds with the subtracts... Or just swap the two encoder phases physically, or define the pins swapped.


text:
Baud rate dependency
I am currently trying to write (obtain) a code for getting raw acceleration values and yaw, pitch and roll angles using these Jeff Rowberg's examples. I have used MPU6050_DMP example to get this code:
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}

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

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

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

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

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

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

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

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

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

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

Doing a lot of serial printing at a low baud rate will of course cause you to fall behind.  You should try to determine where your code gets stuck in the fast case.  It looks like you have a possible race condition with potentially clearing the interrupt flag before acting on it, also you do an exact equality comparison on a length that might be able (?) to exceed that.  Try putting a counter in your while() loop and printing some output if you are stuck there for a long time.  Make sure you aren't overflowing any 16 bit variables...

@ChrisStratton Well, the above code has been modified by me. I have used long instead of int, and I am quite sure that overflow shouldn't be occuring, and used serial printing for debugging. But none of these seemed to help since the board freezes randomly anywhere. There is no pattern. Also, pressing the reset button should restart the code (which happens for other simpler codes), but it's not happening. The board remains frozen.This is the code in case you wanna see it.

@ChrisStratton Also, it should not be a case of integer overflow, because I have tested overflow on other simpler programs. In case overflow occurs, the value simply rolls over, it does not freeze the program execution.

Again, your best route to a solution is probably going to be figuring out where in the program it does get stuck.