text:
Generate single pulse from timer 1 in arduino nano
i have a code that shot a single pulse from pin D5 timer 0 (based on josh levine code), it works fine. the code is below
#define OSP_SET_WIDTH(cycles) (OCR0B = 0xff-(cycles-1))
void osp_setup(uint8_t cycles) {
    TCCR0B =  0;
    TCNT0 = 0x00;
    OCR0A = 0;
    OSP_SET_WIDTH(cycles);
    TCCR0A = _BV(COM0B0) | _BV(COM0B1) | _BV(WGM00) | _BV(WGM01);
    TCCR0B = _BV(WGM02) | _BV(CS00);
    DDRD |= _BV(5);
}

void osp_setup() {
    osp_setup(1);
}

#define OSP_FIRE() (TCNT0 = OCR0B - 1)
#define OSP_INPROGRESS() (TCNT0>0)
#define OSP_SET_AND_FIRE(cycles) {uint8_t m=0xff-(cycles-1); OCR0B=m;TCNT0 =m-1;}

void setup()
{
    osp_setup();
}

void loop()
{
    OSP_SET_AND_FIRE(4);
    delayMicroseconds(20);
}

however, i want to generate the same pulse in pin 10 or 9 which is timer 1, so a change the code a bit just like this
#define OSP_SET_WIDTH(cycles) (OCR1B = 0xff-(cycles-1))
void osp_setup(uint8_t cycles) {
    TCCR1B =  0;
    TCNT1 = 0x00;
    OCR1A = 0;
    OSP_SET_WIDTH(cycles);
    TCCR1A = _BV(COM1B0) | _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
    TCCR1B = _BV(WGM12) | _BV(CS10);
    DDRD |= _BV(10);
}

void osp_setup() {
    osp_setup(1);
}

#define OSP_FIRE() (TCNT1 = OCR1B - 1)
#define OSP_INPROGRESS() (TCNT1>0)
#define OSP_SET_AND_FIRE(cycles) {uint8_t m=0xff-(cycles-1); OCR1B=m;TCNT1 =m-1;}

void setup()
{
    osp_setup();
}

void loop()
{
    OSP_SET_AND_FIRE(4);
    delayMicroseconds(20);
}

but it doesn't work, and i am stuck, any help? i use arduino nano
Thank you

what does this mean? ... it doesn't work

Did you just change the 0s with 1s? You can’t do that as the registers for timer1 are a bit different from timer 0. Check the datasheet to see what the original code does. The look in the datasheet and see which bits need to be set in which registers to get the same functionality.

@jsotola it didn't generate the desired signal

@Gerben that is because when i change the 0s with 2 and use pin D3, it works fine

@ZahiAzmi, it didn't generate the desired signal that is almost the same as it doesn't work .... what did it generate?

@jsotola , it should generate a single pulse signal but nothing generated, just 0 volt all the time

Both timer0 and timer2 are 8-bit timers. Their registers are almost identical. Timer1 is a 16-bit timer and has some additional functions. So it's registers are a bit different.

Timer1 has a few extra features, so you need to set the registers slightly differently from timer0 (or timer2). You need to also set the WGM13 bit in the TCCR1B register.
Since timer1 is a 16 bit timer, you need to change OSP_SET_AND_FIRE to also use 16 bits.
Lastly; Arduino pin 10 is port B, not port D.
#define OSP_SET_WIDTH(cycles) (OCR1B = 0xff-(cycles-1))
void osp_setup(uint8_t cycles) {
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1 = 0x00;
    OCR1A = 0;
    OSP_SET_WIDTH(cycles);
    TCCR1A = _BV(COM1B0) | _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
    TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS10);
    DDRB |= _BV(DDB2);//pin 10; PB2
}

void osp_setup() {
    osp_setup(1);
}

#define OSP_FIRE() (TCNT1 = OCR1B - 1)
#define OSP_INPROGRESS() (TCNT1>0)
#define OSP_SET_AND_FIRE(cycles) {uint16_t m=0xffff-(cycles-1); OCR1B=m;TCNT1 =m-1;}

void setup()
{
    osp_setup();
}

void loop()
{
    OSP_SET_AND_FIRE(4);
    delayMicroseconds(20);
}


text:
How to connect an ESP8266 using an ESP-01 adapter to an Arduino Uno?
I am pretty new to Arduino programming and wanted to learn how to connect an ESP8266 generic WiFi module to an Arduino Uno using the ESP-01 Adapter shown in the image below.
I tried doing it on my own while connecting the Vcc, GND, Tx and Rx pins of the adapter to the 5V, GND, Tx and Rx of the Arduino Uno respectively but was getting the following error while trying to upload the sketch:

warning espcomm_sync failed
error espcomm_open failed
error espcomm_upload_mem failed

To the best of my knowledge there is no tutorial on the internet that explains about the above mentioned adapter and its interfacing with the wifi module in detail. It would be a great help if someone could please guide me through the process so as to convert my Arduino into a server.

io 0 most be LOW at startup to put esp8266 into flashing mode

@Juraj thanks for the reply, could you please help me with the exact steps that I need to follow or refer a tutorial where I can learn about the same including the adapter part.

I enhanced the answer

Recommended tutorial
you can't flash an esp-01 module with this adapter, unless you find a way to connect io 0 to ground in this setup

I have this type of adapter with esp8266 glued. I can't recommend this type of adapter boards. Easier is to use a development board like Wemos or NodeMCU with on-board USB adapter. And they are cheap.
The adapter has the esp-01 2x6 header J2 but the io 0 and io 2 pins were not connected on my version. I patched io 0 to JP2 header to be able to flash the module. On the picture you see a paperclip jumper connecting GPIO0 to ground.

I'm going to leave this here as well: Flashing the ESP8266 using an Arduino UNO

...connecting the Vcc, GND, Tx and Rx pins of the adapter to the 5V,
  GND, Tx and Rx of the Arduino Uno respectively...

At least one issue is the serial connections. Rx and Tx need to be cross-connected with whichever Arduino pins you are connecting to the ESP. Using the Arduino's built-in UART, Arduino pin #s 0 and 1, cannot work for uploading (to either board) since those pins are used to communicate with your PC.
If you are trying to upload to the Arduino, try removing the ESP adapter board during the upload. Even with that, communicating at run-time from the Arduino to the ESP (with it plugged back in, of course) may run into interference from the Arduino's 16U2 chip (serial <-> USB processor) which is hard-wired to those pins. And if it does work at run-time, you will have to forego serial communication to/from your PC, which uses those same pins.
The alternative is to use the SoftwareSerial library in your code, which will let you select two other Arduino pins as a second "software UART" to communicate to/from the ESP. This route come with it's own initial-setup complexities - you'll first have to change your ESP's default baud rate to 9600, about the maximum that SoftwareSerial can reliably receive. See my post about how to do this. To implement it, you'll need a short sketch that continuously tests Arduino's terminal for an available character and sends any to the ESP, and likewise tests the SoftwareSerial and sends to the Arduino's terminal.

did you read my answer? the part about io 0? and you can flash esp8266 over Uno. with RX to Rx and TX to TX and Armega in reset. (or with pass-through sketch. even over SoftwareSerial). but first the esp8266 must be in flash mode initiated by io 0 LOW

source: Stack Exchange

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

sort: votes


text:
Pulse counter to measure flow-rate: 0 Pulse issues
I am using a Netafim M-Series flow meter interfaced with a UC-32 Arduino. The goal of this is to create a pulse counter than in turn will allow us to determine flow rate in the meter. (1 US gallon per pulse for this model.)
I am using a relatively simple program to test my wiring and the flow meter's connection to the UC-32. I will include it here:
int pin = 30;
volatile unsigned int pulse;
const int pulses_per_litre = 450;

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

  pinMode(pin, INPUT);
  attachInterrupt(0, count_pulse, RISING);
}

void loop()
{
  pulse = 0;
  interrupts();
  delay(1000);
  noInterrupts();

  Serial.print("Pulses per second: ");
  Serial.println(pulse);
}

void count_pulse()
{
  pulse++;
}

Code was obtained by a source online, since I will make my own to match my specific needs later on. The problem is, no matter how much I modify this code, I receive 0 pulses (even when blowing air into the meter). I have therefore narrowed down the problem to wiring.
I am using a small breadboard with a 1 kOhm Resistor. The flow meter requires 12v input that is supplied by a barrel jack power supply into the UC-32. I will show an image of my circuit. From what I can see, this should be working, but I feel like I'm sort of going insane looking over and over this circuit so I wanted to get an outside opinion.

Sorry about the large sizes images, but to me, it is a simple circuit that should work. I could be very wrong. Does anyone with perhaps experience with this sort of flow meter see any problems with my code/circuit?

Fixed, wow. Sometimes typing out your problem helps answer the question. Resistor position was wrong, and adjusting the Vin wire.

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


text:
Coding multiple servos in Arduino
I'm a first year persuing Mechatronic engineering, and I'm having trouble with this code that I am using to control a biped robot for my project.
#include <servo.h>
Servo myservoa;
           myservob;
           myservoc;
           myservod;
int     myservoa=10;
          myservob=55;
          myservoc=25;
          myservod=125;

void setup() {
    myservoa.attach(2)
    myservob.attach(3)
    myservoc.attach(4)
    myservod.attach(5)
}

void loop() {
    for pos=10;pos<=75;pos+=1;
    {
        myservoa.write(pos);
        delay(1000);
    }
    for pos=55;pos<=100;pos+=1;
    {
        myservob.write(pos)
        delay (1800)
    }
    for pos=25;pos<=165;pos+=1;
    {
        myservoc.write(pos)
        delay (1000)
    }
    for pos=125;pos<=170;pos+=1;
    {
        myservod.write(pos)
        delay (1800)
    }
}

Could there be an error in the code?

Yeah, some syntax errors. For now I formatted your code correctly and changed the Void and Int to lower case. But you really have to describe, what your actual problem is. You should get error messages during compilation. It is mandatory to add those to your question (click at "edit" under your question do directly editing it)

@chrisl ... "some" syntax errors...? I think it's easier to list the bits that aren't a syntax error.

@user47756 You really need to go back to basics with your C++ syntax knowledge.  Learn the basic syntax before you try writing code.

Chrisl,what syntax errors did you get?

@user47756, are you not getting syntax errors?

what does this question mean? ...Could there be an error in the code?

I think in total there are maybe 5 lines there that don't have syntax errors (not counting brackets)...

Could there be an error in the code?

You could say that, yes.  Let's list all the syntax errors to start with:
#include <servo.h>
Servo myservoa;
           myservob; // This has no type. It's just a word by itself.
           myservoc; // This has no type. It's just a word by itself.
           myservod; // This has no type. It's just a word by itself.

int     myservoa=10; // You already defined myservoa as a Servo type.
          myservob=55; // This has no type. It's just a word by itself.
          myservoc=25; // This has no type. It's just a word by itself.
          myservod=125; // This has no type. It's just a word by itself.

void setup()
{
    myservoa.attach(2) // Semicolons must terminate all statements.
    myservob.attach(3) // Semicolons must terminate all statements.
    myservoc.attach(4) // Semicolons must terminate all statements.
    myservod.attach(5) // Semicolons must terminate all statements.
}

void loop()
{
    for pos=10;pos<=75;pos+=1; // Braces are missing, pos is not defined, and extra ;
    {
        myservoa.write(pos);
        delay(1000);
    }
    for pos=55;pos<=100;pos+=1; // Braces are missing, pos is not defined, and extra ;
    {
        myservob.write(pos)  // Semicolons must terminate all statements.
        delay (1800) // Semicolons must terminate all statements.
    }
    for pos=25;pos<=165;pos+=1; // Braces are missing, pos is not defined, and extra ;
    {
        myservoc.write(pos) // Semicolons must terminate all statements.
        delay (1000) // Semicolons must terminate all statements.
    }
    for pos=125;pos<=170;pos+=1; // Braces are missing, pos is not defined, and extra ;
    {
        myservod.write(pos) // Semicolons must terminate all statements.
        delay (1800) // Semicolons must terminate all statements.
    }
}

You really need to get to grips with the syntax of a language before you start programming in that language. I count just 6 lines (not including { and }) of valid C code there, and two of them are handed to you by the IDE.

I just pasted the code from a friend only that she used two servos. Majenko,could you kindly format my code and send it to me afresh?May be am getting trouble with many servos.

@user47756 This is no free coding service. Majenko pointed out the syntax errors in your code. Look at a basic C/C++ tutorial, learn and then rewrite the code yourself. You should not just copy from other people, because if you don't really understand the code, you will not be able to change it correctly to reach your goal. Show a bit effort here.

Ohh!I got it.My code is now OK and its running successfully upon uploading.Thanks guys.@majenko,@chrisl


text:
LCD prints weird characters when I place the print statement in setup after pinMode statements
#include "LiquidCrystal.h"

const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7)

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  pinMode(22, INPUT_PULLUP); // Reed switch - Row1
  pinMode(24, INPUT_PULLUP); // Reed switch - Row2
  pinMode(26, INPUT_PULLUP); // Reed switch - Row3
  pinMode(28, INPUT_PULLUP); // Reed switch - Row4
  pinMode(32, OUTPUT);
  digitalWrite(32, HIGH);
  lcd.setCursor(0, 0);
  lcd.print("hello");
}

When I run the above code I get weird characters in my LCD. I removed all the connections to the pins` defined in pinMode and left only the lcd connections but kept the pinMode and digitalWrite statements in the code, but am still getting weird characters. But when I remove the pinMode and digitalWrite statements from my code the lcd works fine. Can anyone help me out.
Edit:
Another weird thing happened, I removed all the pinMode and digitalWrite statements do my setup() had only Serial.begin() and lcd.begin() and I only had the lcd connections. Now I put this code to print into an function called lcdprintMove() and there were other functions too which were performing other tasks when I ran it as such I got weird characters in the LCD but when I removed all of the other functions,the lcd printed fine. From this I was able to conclude that this problem can't be because of the supply but has to be something else. But I still can't figure it out.
Problem Solved
Today I commented all the digitalWrite statements and uploaded the program and it worked! So,  I am going to connect the lcd onto a separate arduino and communicate serially. Someone suggested the solution of putting a cap to ground and buff the power of 5 v pin can you explain this in more detail.
Circuit diagram   Note: Rs is connected to pin 7 and E to 6

How is your LCD connected? Please show a schematic.

What is connected to pin 32?

all the pins defined in pinMode are connected to reed switches.

What are the reed switches connected to? Try disconnecting them, then run the program both ways again. If it works better this time, one or some of the reed switch circuits' current draw, combined with that of the LCD, may exceed the pin-drivers' capacity and drag down a voltage such that the LCD can't respond properly.

i actually just tried that,I removed everything and left only the lcd connections but kept the pinMode and digitalWrite statements there , but am still getting weird characters. but when i have only the lcd statements in setup() it works fine. I can't figure out what's happening.

I have noticed this type of behaviour when the LCD can't pull enough current.  Are you sure you power supply is adequate?  You can always add a cap to the ground and +5v pins as a buffer.  When I have noticed this in the past, it is usually when I am moving a servo at the same time as a LCD write.  LCDs seem to be quite sensitive in this regard.

What capacitor should I use?Also just to clarify by " +5v pins as buffer" did you mean that I should buffer the +5v pin for more power by using buffer chips like ULN2003A?

"I removed everything and left only the lcd connections but kept the pinMode and digitalWrite statements there , but am still getting weird characters." Edit your question to add that important information. The question should stand by itself without needing to read the comments. Without that information it seems like your circuit diagram is incomplete. With that information added I would willing to vote to reopen this

Is the LCD module's +5v supplied directly from the power supply, or off one of the Arduino's +5v pins? If the latter, try powering it directly.

it's from the arduino's 5v pins

The capacitor between 5V and GND effectively acts as a small battery. When a sudden demand in a current relatively large occurs, the system can get that extra small amount from the cap and not experience a voltage drop.


text:
Can't upload to arduino boards anymore
I have been working on several projects recently an made hundreds of uploads to several different boards.  I haven't had any issues to speak of.  Now I cannot upload. I have tried:

Disconnect all inputs and output from analog a digital ports - This is a board, nothing connected except USB.
Changing cables
Changing USB ports on my computer
Using a brand new out of the box Arduino Uno
Using example sketches, and even BareMinimum
Serial Loopback test - FAILED
Updating the driver with the one from the arduino folder
Using an unsigned driver
Manually setting the windows driver speed, parity, etc.
Uninstalling and re-installed Arduino IDE
Rolling back the board manager for AVR boards to 1.20 and 1.19
Change programmer to AVR ISP

Here is the output:
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

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

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

Here is the verbose output:
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\Users\kanan\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/bin/avrdude -CC:\Users\kanan\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\kanan\AppData\Local\Temp\arduino_build_835373/BareMinimum.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\kanan\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xd5
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xd5
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xd5
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xd5
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xd5
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xd5
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xd5
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xd5
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xd5
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd5

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

I am not attempting to install the beta version of the arduino ide, but I am not betting this will work.
I feel like I have tried everything that is reasonable, and more than most people would think to try, what am I missing?
-------------  UPDATES --------------
I have now moved away from the arduino IDE and am working directly with avrdude.  Still no luck.  Running:
avrdude.exe -p m328p -c arduino -P COM6

fails.
I also tried it on my Fedora 27 box.  Here is dmesg output:
[349004.632101] usb 2-1.5: new full-speed USB device number 5 using ehci-pci
[349004.711497] usb 2-1.5: New USB device found, idVendor=1a86, idProduct=7523
[349004.711503] usb 2-1.5: New USB device strings: Mfr=0, Product=2, SerialNumber=0
[349004.711507] usb 2-1.5: Product: USB2.0-Serial
[349004.713405] ch341 2-1.5:1.0: ch341-uart converter detected
[349004.714652] usb 2-1.5: ch341-uart converter now attached to ttyUSB0

then I ran this:
$ dmesg | grep tty

And got this:
[    0.000000] console [tty0] enabled
[    0.781927] 00:06: ttyS0 at I/O 0x3f8 (irq = 4, base_baud = 115200) is a 16550A
[   14.034377] usb 2-1.5: ch341-uart converter now attached to ttyUSB0

I then run this:
$ avrdude -p m328p -c arduino -P /dev/ttyS0

and get this:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

At this point I also tried
$ avrdude -p m328p -c arduino -P /dev/ttyUSB0

Same result.  At this point it seems to me I have a few fried arduinos.  They were fine yesterday, but today, they're toast.  Three computers, three cables, three arduinos, all the same result.
So, from here.  Has anyone heard of a bad cable frying an arduino?

You've tried swapping everything I can think of. Does "Using a brand new out of the box Arduino Uno" mean you've swapped that too? And if not, can you? When you swapped ports, did you correct the port-assignment in Tools | Port? "Change programmer to AVR ISP" - ? this is what it should be if you're trying to program via USB cable.

You can't upload the blink sketch too?

did you try a different computer?

Interestingly I did try a different computer, with a different cable and the new mega I had just opened.  Strangely, I got the same error.  I'm feeling a bit cursed at the moment.

test on the other computer with Arduino IDE. on Windows make sure that CH340 driver is installed (your linux outputs indicate CH340). on linux make sure you are in dialout group

I'm an idiot.
I should have looked more carefully.
Because I have used these boards so extensively, I figured that I knew the dip switches by heart.  Everything started to go wrong when I got confused switching from the Uno to the ESP.
Here is the reference from https://robotdyn.com/uno-wifi-r3-atmega328p-esp8266-32mb-flash-usb-ttl-ch340g-micro-usb.html:

Meaning this DIP switch pattern is for the ESP:
And This is for the UNO:

THANK YOU ALL FOR THE TIME AND EFFORT YOU PUT IN TRYING TO HELP ME!!!
tldr: Check your DIP switches.

add to tl;dr: mention DIP switches in OP...

Touché my friend

Since your USB ports likely work for other things (like your keyboard) and you have tried several arduinos, cables etc, now try Knoppix - it has both Arduino IDE (not the most recent version) and avrdude.
https://unetbootin.github.io or
https://www.pendrivelinux.com/install-knoppix-6-to-a-usb-flash-drive-in-windows
and
http://www.knopper.net/knoppix-mirrors/index-en.html
If it does not work, have a look through the boot log, or more quickly dmesg after plugging your arduino in and trying an upload.
Worth noting: the 328p target is not correct for mega, use e.g.: avrdude -vv -p atmega2560 -b115200 -c wiring -P COM3 or avrdude -vv -p atmega2560 -c wiring -P /dev/ttyUSB0. Omitting -b115200 should be no problem with the mega. Try this before torturing yourself further...
If you still get errors, and have not fiddled with clockspeed or anything else, it will be very strange indeed.

I actually have Fedora box here, let me try it on there.

@Beachhouse What if you connect using putty/minicom and punch in a string of characters? Does the RX led blink? Is it a different PC? Have you tried burning a fresh bootloader to the arduino? Have you played with the fuses? Have you tried manual reset of the board just before upload?

If you have an FTDI chip, try setting it to 5V (3V3 works for me on 5V boards, though), and connect RX to TX, TX to RX. Then press reset before upload.

@Beachhouse Don’t use 328p target with avrdude; use atmega2560. See my edited answer.

Scratch my last comment.  TX does blink when I send data from serial monitor. @user2497 I saw your comment, I had been adjusting the chip for the direct commands, but thank you.

@Beachhouse So you use a mega2560, and not a 328p target?

Correct.  Ran: avrdud -vv -p atmega2560 -b115200 -c arduino -P COM5 and got: avrdude.exe: stk500_getsync(): not in sync: resp=0x00

@Beachhouse That’s weird. Have no idea, then... apart from the clockspeed being off... try 12MHz in arduino-mk project Makefile, if it’s a clone. What is engraved on the crystal on the board? 16.000 or something else?

it is a clone.  https://robotdyn.com/uno-wifi-r3-atmega328p-esp8266-32mb-flash-usb-ttl-ch340g-micro-usb.html

@Beachhouse All bought at the same time? What is engraved on the crystal container?


text:
Why is my esp8266 still visible under "available connections" when connecting to WiFi?
I wrote a "Hello world" type of sketch using the Arduino IDE and uploaded it to an esp8266. I used no libraries, or any kind of WiFi commands. However, when I powered up the esp8266, it was visible under "available connections" when I connected to WiFi using a Windows laptop. I was told that the firmware on an esp8266 (which has the AT commands) is being flashed when the Arduino IDE uploads a sketch. Why do I still see the esp8266 when my laptop connects to WiFi?

It's because you don't actively program the WiFi - you just give instructions to configure it, and those instructions are stored elsewhere in flash, separate to a sketch.  The WiFi code is always included and always running regardless of what you include or don't include in your sketch.
Uploading a sketch doesn't replace those settings, and so they remain.
To change the settings you will need to write a sketch that specifically changes them - maybe set it to STA mode, for example.
If you want to completely blank the ESP8266, including the WiFi settings, there is an option in the Tools  menu in the IDE to Erase Flash.

I would add that, esp8266 basic libraries (SDK) are always part of the sketch and handle WiFi with setting remembered on flash. Erasing the flash or choosing "Sketch + WiFi settings" in IDE Tools menu "Erase flash" clears this settings

The  "TOOLS" menu in the Arduino IDE has grown since I last used it, I'm pretty sure that the "Erase Flash:" option is new. Either way (option is new or not), that makes my post a low quality question; and for that I apologize.  Nonetheless, I would like to see this menu option specifically mentioned as part of an answer. Just something mentioning navigation, like Tools>Erase Flash  I would then happily and thankfully accept the answer.


text:
Arduino Mega: Interrupt not working? Use any pin for interrupt?
I am using an arduino mega. I'm trying to use interrupts in one of my programs.
I have 8 pins that I will need to make separate interrupts for.
The pins are 40 - 47. These pins are attached to limit switches, so when the limit switch is pressed or not it'll indicate that via digitalRead().
#define switch_1 43     // Pin 43 is connected to Switch 1 (1: X+)
#define switch_2 42     // Pin 42 is connected to Switch 2 (1: X-)
#define switch_3 41     // Pin 41 is connected to Switch 3 (1: Y+)
#define switch_4 40     // Pin 40 is connected to Switch 4 (1: Y-)
#define switch_5 46     // Pin 46 is connected to Switch 5 (2: FR)
#define switch_6 47     // Pin 47 is connected to Switch 6 (2: BL)
#define switch_7 45     // Pin 45 is connected to Switch 7 (2: BR)
#define switch_8 44     // Pin 44 is connected to Switch 8 (2: FL)
int interruptVar = 5;

In my set up function I have:
attachInterrupt(digitalPinToInterrupt(switch_6), tightenStrings1, CHANGE);

Then I have:
void tightenStrings1()
{
  interruptVar = 9;

}

When I change the status of the limit switches, by pressing them or unpressing them, this function never activates. The variable interruptVar is still 5.
What am I doing wrong?
Also, Serial isn't the problem in this case. I understand now not to use it though, but still doesn't solve the problem. Additionally I tried instead of CHANGE using RISING or FALLING and still no changes.
I have a feeling it's because the pins I'm using aren't technically interrupt pins...is there a way to make them usable as interrupt pins? I'm not allowed to change the pins being used, and using an interrupt is the best solution for the coding portion I'm working on.

Never use Serial in an interrupt.

I changed it as you were commenting lol. But Serial isn't the issue..do you have any other suggestions why this doesn't work?

your programming style is inconsistent .... you declare #define switch_6 47 and then you use attachInterrupt(digitalPinToInterrupt(47), tightenStrings1, CHANGE); ...... you should be using  attachInterrupt(digitalPinToInterrupt(switch_6), tightenStrings1, CHANGE);  ...... the pin name should really be something like switch_BL

Ok....thank you. I'll fix that. But again, this doesn't point out a solution. Do you guys have any idea how to fix the actual problem?

You are right when you say "technically they aren't interrupt pins".
The only pins you can use as interrupts are 2, 3, 18, 19, 20 and 21. There is no way of changing that. You can't magic more interrupts out of thin air.
However there is a different interrupt system that may help you out - the pin change interrupts.  These are harder to work with since they are grouped into sets of pins that share the same interrupt, but there are far more pins with this kind of interrupt available. Note that you still have to be careful which pins you choose.
There are a couple of libraries available to help you configure the PCINT registers should you need it.

Limit switch implies some mechanical thing is closing the switches, which hardly needs an interrupt as that will be pretty slow electronically. Simple polling is probably more than sufficient at the top of loop() or similar.
You can declare all the pins as INPUT_PULLUP, wire the switches to connect the pins to Gnd when pressed, then do digitalRead of each to determine its state, or put all 8 on one port and do a PORTx read
for example, and if the result is other than 0xFF, then one has been closed and you can act on it, or read it directly and act on like here for example:
switches = PORTL;
if (switches != 0xff){
switch(switches){
case 0b01111111:
//code for switch 7
break;
case 0b10111111:
// code for switch 6
break;
etc for 0b11011111, 11101111, 11110111, 111111011, 11111101, 111111110
}
}


text:
How can I power a servo and Arduino from the same power supply?
I have an ESP8266 NodeMCU which I'm using for an automatic blinds project. The NodeMCU struggles to power the servo on its own, so at the moment I am using a 5 V supply for the servo and a USB cable for the NodeMCU (with a common ground).
The servo is an inexpensive MG996R which is rated up to 7.2 V I've read that NodeMCU can take 5-10 V on the VIN pin.
After I'm done prototyping, I want to only use one power supply. What could I use? Ideally it would be something with just a wall adapter and then I can cut the other and connect that to servo and MCU.

Wire the +5 and Ground from the supply to both the ESP's Vin & Ground and the servo's Vin & Ground. The only thing you have to avoid is trying to power the servo through the ESP.

You might be better off using an external supply with a voltage regulator like an LM7805. It would also be wise to add a protection diode to your servo motor if it does not already have one so that the microcontroller does not get damaged by any flyback voltages. The key thing to remember when running a supply from an Arduino is that it's on board supply current capabilities are very limited, especially in the case of a motor or servo. Good luck, I hope this helps, I recently replaced the blinds in my home and was thinking to build something similar myself!


text:
void loop is only run once why?it can recive only off signal?
    int L1=12;
void setup() {

  Serial.begin(9600);

  pinMode(L1,OUTPUT);

}

void loop() {

char receive=Serial.read();

if(Serial.available()>0){
    receive = Serial.read();
}

{

if(receive =='A') {
  digitalWrite(L1,HIGH);
}

if(receive =='a') {
  digitalWrite(L1,LOW);
}
}
}

int L1=12;

void setup() {

  Serial.begin(9600);

  pinMode(L1,OUTPUT);

}

void loop() {

//char receive=Serial.read(); //This is incorrect. because after u perform this serial.read(), the received data in serial's buffer is cleared. So ...

if(Serial.available()>0){
    receive = Serial.read(); //... at here, your 'receive' receives nothing
}

{

if(receive =='A') {
  digitalWrite(L1,HIGH);
}

if(receive =='a') {
  digitalWrite(L1,LOW);
}
}
}

Here's the correct codes.
int L1=12;

void setup()
{
  Serial.begin(9600);
  pinMode(L1,OUTPUT);
}

void loop()
{
  char receive;

  if(Serial.available()>0)
  {
    receive = Serial.read();

    if(receive =='A')
    {
      digitalWrite(L1,HIGH);
    }

    else if(receive =='a')
    {
      digitalWrite(L1,LOW);
    }
  }
}

nice, but not solving. if he sends only one character, this changes do not change the behavior of the sketch. read returns -1 if nothing is available. if the first read returns the character then next character is not available and the received character is compared to 'A' and 'a'.

so what should i do so that every time i send a character it receive and execute the conditions

@JhonRajbongshi, the problem is not in sketch


text:
Arduino reading string sent from Rpi multiple times
1.Reading strings sent from Arduino on RPI
Below you can see that I am communicating between a rpi and arduino serially. I am sending "start", then move_played to the rpi. The readline() reads until a newline so, first start gets read then the move_played string(it's like read the move played only after encountering the string start)
Python code on RPI
s1 = serial.Serial('/dev/ttyACM1', 9600)
stockfish = Stockfish('/usr/games/stockfish')
while 1 :
    if str(s1.readline(),'UTF-8').strip('\n\r') == 'start' :
           move_played = str(s1.readline(),'UTF-8').strip('\n\r')
           print(move_played)

Code on Arduino
void SendMove();
String movePlayed ="e2e4";
void setup()
{
  Serial.begin(9600);
}
void loop()
{
  SendMove();
  exit(0);
}
void SendMove()
{
  Serial.println("start");
  Serial.println(movePlayed);
}

2.Reading strings send from RPI on Arduino
The  goal for the arduino is to read the bestMove string after it reads "Rstart". But when I run the code on the rpi(sending the strings). The lcd prints "Rstart" and not the bestMove string. So from what I can see is that once the "Rstart" string is sent , the first readString() in the if condition , reads " Rstart" and the the second readString() in the print statement reads "Rstart".
Why is the string"Rstart" stll in the serial Buffer even after being read once?
Python Code on RPI
bestMove = "b3c7"
s1 = serial.Serial('/dev/ttyACM1', 9600)
s1.write(bytes("Rstart","ascii"))
s1.write(bytes(bestMove,"ascii"))

Code on Arduino
#include "LiquidCrystal.h"
const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; // 4 bit mode
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup()
{
  lcd.begin(16,2);
  Serial.begin(9600);
}
void loop()
{
  if (Serial.available()>0)
  {
    if(Serial.readString() == "Rstart")
    {
      lcd.setCursor(0,0);
      lcd.print(Serial.readString());
      delay(10000);
      exit(0);
    }
  }
}

it should not work at all. you send "Rstartb3c7" and readString should read it in one piece

so, how do I send it as 2 separate strings and read them separately,I've been trying but can't seem to find out.


text:
Problems with passing objects in tree structure
I'm new to C++ and arduino. I want to build an object Tree, but it did not behave like I expected. Here is the code:
TreeNode.h
class TreeNode {

  public:
    TreeNode(String inputNodeName);
    TreeNode *children[];
    TreeNode &getChild(int index);
    int getLength();
    String nodeName;
    void addChild(TreeNode &node);
    String getName();

  private:
    int childLength;
};

TreeNode.cpp
  TreeNode::TreeNode(String inputNodeName) {
    nodeName = inputNodeName;
    childLength = 0;
  }

  TreeNode &TreeNode::getChild(int index) {
    return *children[index];
  }

  int TreeNode::getLength() {
    return childLength;
  }

  String TreeNode::getName(){
    return nodeName.c_str();
  }

  void TreeNode::addChild(TreeNode &node) {
    children[childLength] = &node;
    childLength++;
  }

I'm initialising it in the setup function:
void setup() {
    Serial.begin(9600);

    TreeNode mainTree("main");
    TreeNode firstChild("first child");
    TreeNode secondChild("second child");
    TreeNode subChild("subschild");

    Serial.println(mainTree.getName()); //prints "main"
    Serial.println(firstChild.getName()); //prints "first child";
    Serial.println(secondChild.getName()); //prints second child";

    mainTree.addChild(firstChild);
    mainTree.addChild(secondChild);
    Serial.println(mainTree.getName()); // prints an empty string
    Serial.println(secondChild.getName()); //prints second child"

    secondChild.addChild(subChild);
    Serial.println(secondChild.getName()); //prints an empty string
}

So my problem is, when I'm adding a child to a node, the node name is empty, or strange characters will be displayed.
I think I misunderstood passing an object by reference. Can anybody explain what I did wrong?

Arrays do not expand like in Java or Basic. You need to allocate a specific number of entries, or use a linked list or C++ STL wrapper object like vector.

Here we go - I have just drafted a blog entry on C arrays: https://majenko.co.uk/blog/arrays-pointers-what-c

TreeNode *children[];

That declares an array of pointers however it also requires that you assign memory to it. I never see you allocate that memory.
If you only expect a small amount of children then you can use that upper bound as a static allocation:
#define MAX_CHILDREN 10

//...
TreeNode *children[MAX_CHILDREN];

Otherwise use a vector instead:
std::vector<TreeNode *> children;


text:
Arduino IDE Permision Denied For Upload, Ubuntu
I am having issues uploading to my Arduino from the IDE on Ubuntu 18.04. The error message I have received is:

Arduino: 1.6.10 (Linux), Board: "Arduino/Genuino Uno"
  avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied

I have checked other questions similiar to this one and have tried adding myself to the dialout group running:
sudo usermod -a -G dialout username

and added permission to write:
sudo chmod a+rw /dev/ttyUSB0

After, when I run:
ls -l /dev/ttyUSB0

I get:
crw-rw-rw- 1 username dialout 188, 0 jūl  2 16:09 /dev/ttyUSB0

However,I still get the same error message from the IDE.
Any help would be greatly appreciated!

Also have set the port in Tools to ttyUSB0

log-out and log-in https://www.arduino.cc/en/Guide/Linux#toc6

Are you sure it's /dev/ttyUSB0? A real Arduino will be /dev/ttyACM0. Maybe yours is a cheap chinese clone?

Yeah just discovered it is a CH340G chip. Any hope of still getting it to work? Have heard of people having success on Windows but haven't found any good troubleshooting for Linux.

Were you able to make it work?

No I ended up giving up and using another board I have. I have another project I am going to start in a month or so for which I am going to try to use that board so will post an update then if I figure it out.

Arduino has added a script to the install to fix this problem.  I found it after much annoyance trying to get it to work with all these suggestions.
In the arduino-1.8.8-linuxarm.tar.xz file that you download is a script called arduino-linux-setup.sh
run that from commandline with your user name ./arduino-linux-setup.sh <username>
It'll ask for the root password, and then ask you to reboot.  After that you won't have any more port trouble.

As mentioned on the official guide for Linux, you need to run
sudo usermod -a -G dialout <username>
with the <username> replaced with the username of your system.
After running this, log out and log in (or in some cases reboot the computer) and you should be good to go.

When you run

ls -l /dev/ttyUSB0

you have
crw-rw-rw- 1 username dialout 188, 0 jūl  2 16:09 /dev/ttyUSB0

The Problem is you have the dev as <username>, try to change to as root
sudo chown root:dialout -R /dev/

Note:
One thing after your plug your USB, check your port with follow
ll /dev/tty*

if you can see my port as ttyUSB0 or with difference name (i.g ttyUSBx / ttyACMx ).
and then try to compile your sketch with following,
cd /path/your/arduino/installation/
$ARDUINO-DIR(pwd)
cd /path/your/sketch/
$ARDUINO-INO/arduino --verify sketch.ino --board arduino:avr:uno --port /dev/ttyUSB0 --verbose //compile your sketch.ino with arduino uno board.

Hope this helps.

You definitely SHOULD NOT change the ownership of every file under /dev as chown -R will.


text:
Way(s) to store an integer from the serial output and sutract it from the next Serial output
This seems so simple but I can't solve it. (I'm new to Programming) I do not want to use EEPROM. Just store it and do the math. I strip the Azmuth and Elevation values from a satellite tracker program and need to calculate the difference the satellite has moved to turn the rotors. Here's my efforts so far as requested ...Thanks
/*  Sketch for WXtrack satellite tracking software
 *  VE3COJ Burlington, Ontario, Canada
 *  Requires COM port and Max 232 from PC
 *  to Serial in on Arduino (Rx)
 *
 *  Download URL:  http://www.satsignal.eu/software/wxtrack.htm
 *
 *  Setup in WXtrack: Go to <Tracker menu> <Options> <Select EGIS COM port> <check box XY mode>
 *  Select a Satellite using Manual in Timeframe box.
 *  Highlight Satellite icon, Use seconds box (third box from left side) to increment satellite.
 *  Use the Sketch Monitor to see Elevation and azimuth reading from Serial port.
 *  Alternatly, one can use an array to simulate Elevation and Azimuth increments in degrees.
 */

      #include <Stepper.h>
      #include <avr/pgmspace.h>
      #define STEP 50
      #define motorSteps 600      // Number of steps to turn the motor
      #define motorPin1 8
      #define motorPin2 9
      #define motorPin3 10
      #define motorPin4 11

      // 2 EasyDriver boards will be used in final project //

          String readString, read_az, read_el;

          int el_current_store_0;           // elevation ... global value ??
          int el_current_store_1;
          int el_position;                  // final value in degrees to move rotor

          int az_current_store_1;           // azimuth ..... global value ??

       void setup() {

          Serial.begin(9600);
          Serial.println("  AZ & EL "); // so I can keep track of elevation and Azimuth
          Serial.println (" =========");
          Serial.print("");
      }

      void loop() {

           while (Serial.available()) {
              delay(3);  //delay to allow buffer to fill
               if (Serial.available() >0) {
              char c = Serial.read();  //gets one byte from serial buffer
           readString += c; //makes the string readString
      }
    }

          if (readString.length() >0) {
          //Serial.println(readString); //see what was received from Serial input

          // pull out the number values required... parse the serial output
          // On WXtrack menu, select "Tracker" > "Options" > "EGIS COM" & "XY mode"
          read_az = readString.substring(3, 7);   //get the first 3 to the 6th integers (azmuth)
          read_el = readString.substring(10, 13); //get the next 10 to thee 13th integers (elevation)

         int el_current_store = read_el.toInt();  // Change String el to Integer
         int az_current_store = read_az.toInt();  // Change String Az to integer

        /* This is an attemp to calculate the difference in degrees the satellite moves. */

         int n1 = el_current_store_0;       // first elevation reading ... store it ... how?
         int n2 = el_current_store_1;       // second elevation reading ...
         int el_position = (n2 - n1);       // Subtract first from second ... equals how many degrees to turn the rotor

                                           // if result is negative, rotor changes direction

          /* Can't be done as is because the reading gets put in all variables

           * I cannot figure out how to store the number of degrees in memory (Not EEPROM)
           *  EEPROM will burn out eventually, FLASH cannot change values it appears... in docs.
           *
           * From here:
           * Store first reading from Serial port into memory.
           * Rotor moves to degrees probably 3 degrees ... read second position (if 4 degrees)
           * Subtract 3 degrees from 4 degrees equals 1 and multiply by variable STEP (200 STEP = 1 degree motor rotation)
           * Get next elevation reading and repeat subtraction...
           */

           // Print to serial monitor to see results of all values //

           Serial.print("  Elevation = ");
           Serial.println(read_el);

           Serial.print("  Azimuth = ");
           Serial.println(read_az);

           //Serial.println(el_position);
           Serial.println (" --------next-------");

           Serial.print("");

           readString="";
          }
         }

          /* 1. ========= Send Antenna to 0 degrees / Check for interrup at 0 degrees & Stop =========
                ========= Wait for Serial input then goto 2. =========

             2. ========= Get Az and El from Serial Port and Start Tracking ==========

             3. ========= Store (first, second, etc. ) El and AZ =========

             4. ========= Get Next El and Az / Subtract from one before El & Az =========

             5. ========= Move Antenna to Next Position =======

             6. ======== Goto 3. =========

             7. ======== If El Equals 0, Goto 1.

                       When El = 90 degrees, (Satellite overhead) Az rotates 180 degrees and

                       El decreases, coming down to the horizon.

                      When Satellite is off to E or W, elevation does not reach 90 degrees!
         */

When you say you want to "store" the values, but not use EEPROM, what is the time frame you are meaning? Do you want to store it so it is not lost when the microcontroller resets (power cycles)? Or do you just mean to store it within the program for use in subsequent statements?

You have the following global variables declared:
int el_current_store_0;           // elevation ... global value ??
int el_current_store_1;
int el_position;                  // final value in degrees to move rotor

int az_current_store_1;           // azimuth ..... global value ??

But you never put anything into these variables.
Here is your relevant code that attempts to work with these values:
// pull out the number values required... parse the serial output
// On WXtrack menu, select "Tracker" > "Options" > "EGIS COM" & "XY mode"
read_az = readString.substring(3, 7);   //get the first 3 to the 6th integers (azmuth)
read_el = readString.substring(10, 13); //get the next 10 to thee 13th integers (elevation)

int el_current_store = read_el.toInt();  // Change String el to Integer
int az_current_store = read_az.toInt();  // Change String Az to integer

Above, you are declaring new variables el_current_store and az_current_store and giving them integer values converted from your input string. When you prefix a variable name with int (or any other type) you are declaring a new variable within that scope. In this case, the scope is the if (readString.length() >0) {} block. Once that block ends, those variables don't exist anymore, and every time that block runs, new variables are created there, and destroyed at the end of the block.
/* This is an attemp to calculate the difference in degrees the satellite moves. */

int n1 = el_current_store_0;       // first elevation reading ... store it ... how?
int n2 = el_current_store_1;       // second elevation reading ...
int el_position = (n2 - n1);       // Subtract first from second ... equals how many degrees to turn the rotor

Above, you declare new variables n1, n2, and el_position. However, you give n1 and n2 whatever was in el_current_store_0 and el_current_store_1, but you have never put any value into those variables, and so they have nothing.
Once that is solved, you also need to take a look at declaring a new variable by the command:
int el_position = (n2 - n1);       // Subtract first from second ... equals how many degrees to turn the rotor

which, because it's in a nearer scope than the global variable of the same name, is used instead of the global. And when the scope block ends, it is destroyed.
You should instead assign the computed value to el_position without making a new variable:
el_position = (n2 - n1);       // Subtract first from second ... equals how many degrees to turn the rotor

(Note, no int in front...)
**EDIT: To actually keep the values for the next loop(), you do have to store them in global (or static) variables. Something like this appears to be what you were going for:
     int el_current_store = read_el.toInt();  // Change String el to Integer
     int az_current_store = read_az.toInt();  // Change String Az to integer

    /* This is an attemp to calculate the difference in degrees the satellite moves. */

     // Added code below keeps the older value in *_1
     // Puts the newer value in *_0
     el_current_store_1 = el_current_store_0;
     el_current_store_0 = el_current_store;

     az_current_store_1 = az_current_store_0;
     az_current_store_0 = az_current_store;

     int n1 = el_current_store_0;       // first elevation reading ... store it ... how?
     int n2 = el_current_store_1;       // second elevation reading ...
     int el_position = (n2 - n1);       // Subtract first from second ... equals how many degrees to turn the rotor

Hi Jose... Yes there re some variables not used yet...

It's not necessarily a problem to have unused variables. But what you have are uninitialized variables that you are trying to use.

Sorry... The program works... getting the AZ and EL I need. Once I get the two values, I need to stuff them somewhere so they do not get overwritten on the next loop around. When I have the next  Az and El I want to get the previous Az and El and subtract the difference. Then I know the satellite has moved x degrees. This will then turn the stepper motors. I can't figure out how to temporarily hold the Az & El values.

@jeff: You need two pairs of variables; one for the current values and one for the previous values. You have to declare the pair for the previous values "static", which means they get permanent memory assignments and will not be overwritten when your loop() function exits and gets called again. Those declaration would look like: "int az, el;" and "static int prevAz, prevEl". On each loop, once you've calculated the 'az' and 'el' differences and moved the rotors, copy 'az' and 'el' to 'prevAz' and 'prevEl', respectively.

@JRobert. Thank you for your suggestions. I will see what I can do to get this to work using static memory. It will be a new learning curve.

@jose can u c. Thanks for the feedback. I need to clean up some code and have noted your added code. Also, I see where I slipped up not putting info in the variables. I'll go at it again. Thanks

@jeff: A variable declared 'static; is just like one without the declaration; the difference is where it will be stored. Variables you declare within a function are local variables and are only "visible" to code within that function, regardless of the memory class. Without 'static', the variable is 'automatic': it "comes into being" when the function is called and "ceases to exist" when the function returns (which is why you can't use one to save a value between calls). With 'static', it exists for the entire duration of the program run. Besides that, you use them the same way.


text:
Writing Libraries that use libraries that are being used in the sketch
I know the title is a little obtuse, let me try to explain:
I am trying to create a library of simple functions for use with my TFT Panel.
The Panel has an include file (#include "SSD1306Wire.h")
I have a sketch and I have the above #include file referenced in the sketch
I also want to use my library tftHelper.h but that library needs to reference SSD1306Wire.h as well to get the helper functions to work.
Is there a way to reference SSD1306Wire.h one time and be able to use the reference in the functions in my helper library?
I guess, more importantly, what is the proper way to handle a situation like this?

The proper way to handle this is to have an #include guard in the header file to prevent the content from being included more than once.
In your header file filename.h you would add something like this:
#ifndef _FILENAME_H_
#define _FILENAME_H_

// Your header code here

#endif /* _FILENAME_H_ */

The #ifndef block will prevent the code from being included more than once. Best practice is to always put include guards in header files.

A library has no way of knowing what is in your sketch. The two things are completely separate and there is no way to bridge that gap.
You can't include library A into the sketch and expect library B to know about it. Library B has to explicitly have library A included in it for library B to even have a clue what library A is.
There are two important parts to including a library. Not only does it tell the translation unit that you include it in what the library has in it, but it also tells the IDE that you want to use that library and to compile the source code for it.
You see, a library usually contains two distinct things - a header file (or a number of header files) and source code files.  The header file describes the library - what classes it has, any exported functions or variables, etc.  The source code implements the library.  When you include a library it just inserts that definition of the library (the header file) into your source code at the point of the #include. Just like a copy-and-paste.
The IDE does a little extra magic and associates that header file with a directory which has other files in it. It then finds the source code files in that location and compiles them.
Every file that gets compiled gets compiled separately. This is called a translation unit (TU) and each one is completely separate from all the others. None can know what any other file has in it, unless you explicitly tell that file to find something from somewhere else (though you don't tell it where, only that it "exists somewhere else"). And that is what the header files do - they tell the translation units what things are available elsewhere.
So if TU A needs resource F it needs to be told. If TU B needs resource F it also needs to be told.
And because of the IDE's extra magic your main sketch has to also be told about every library in use - whether that library is directly used by the sketch or not - so that it knows to go and find and compile the source code for that library.


text:
getting started with programming Arduino board in C/embedded c
I want to move away from Arduino IDE and start directly working with avrdude. Can anyone tell me some resources and tips on starting and moving forward with using C/embedded C to access more functionality.Would appreciate some help.

The Atmel/Microchip web site may be a place to start for AVR development.

Read the chip datasheet. It has everything you need.

Check out Atmel Studio 7.

Not an exhaustive answer, but one step would be to realize what the Arduino IDE does behind the scenes before it gives your source code to avr-gcc.
From https://github.com/arduino/arduino/wiki/build-process#pre-processing

The Arduino environment performs a few transformations to your sketch
  before passing it to the avr-gcc compiler:

All .ino files in the sketch folder (shown in the IDE as tabs with no    extension) are concatenated together, starting with the
  file that    matches the folder name followed by the others in
  alphabetical order,    and the .cpp extension is added to the
  filename.
If not already    present, #include <Arduino.h> is added to the sketch. This header    file (found in the core folder for the
  currently selected board)    includes all the definitions needed for
  the standard Arduino core.
Prototypes are generated for all function definitions in .ino files    that don't already have prototypes. In some rare cases
  prototype    generation may fail for some functions. To work around
  this, you can    provide your own prototypes for these functions.
#line directives are added to make warning or error messages reflect the original sketch layout.

No pre-processing is done to files in a sketch with any extension
  other than .ino. Additionally, .h files in the sketch are not
  automatically #included from the main sketch file. Further, if you
  want to call functions defined in a .c file from a .cpp file (like
  one generated from your sketch), you'll need to wrap its declarations
  in an extern "C" {} block that is defined only inside of C++ files.

This is handy to know if you are trying to port Arduino sketches to pure avr-gcc.
You'll also want to have the header files that define all the various registers specific to the ATMega328p that is the heart of several of the Arduino boards. They can be downloaded as part of Atmel Studio 7, which also includes avr-gcc and the various other toolchain utilities and scripts necessary.
You'll also want the processor's reference manual or datasheet. At this time, the data sheet is available at https://www.microchip.com/wwwproducts/en/ATmega328P in the "Documents" tab. This will lay out everything you ever need to know about how to use the processor, set up peripherals, rules for the order of commands, names of all the registers, etc.


text:
Rectangular Input signal on digital pins
I have a silly question.
Today I saw a function for arduino, that is pulseIn(). So to test what it does I applied a rectangular wave at a pin same as the arduino reference page did and it worked fine. There was a line in the reference page which stated :-
Works on pulses from 10 microseconds to 3 minutes in length.
So as it seems it will work upto 100KHz signal. Is there any way to read signals of much higher frequency than this? like in the range of MHz or so?

It depends how you define "read"...  Google "Arduino Frequency Counting".

Reading high frequency signals can be done. It's possible to read signals up to about 6MHz or maybe even higher (depending on the system clock frequency).
That is, as long as all you want to know is the fundamental frequency of the signal.
Pin 5 of the Arduino Uno (PD5) is connected to Timer 1 and can be set to be the clock source for that timer.  By connecting that to your signal and allowing the timer to count up from zero using that signal as the clock source, and then waiting for a pre-defined time period, you can easily find how many clock pulses have arrived from your signal in that time. From that, you can calculate the frequency of the signal.

The Timer/Counter can be clocked by an internal or an external clock source. The clock source is
  selected by the Clock Select logic which is controlled by the Clock Select bits in the Timer/Counter control
  Register B (TCCR1B.CS[2:0]).

Since all you are working with us the number of pulses over a given period you lose any information such as the duty cycle of the signal.
You should read the datasheet section 20: "TC1 - 16-bit Timer/Counter1 with PWM" for more detail about how you can use the timer to count the frequency of a signal.

TC1 is a synchronous timer. Its T1 input is synchronized to the system clock before going to the edge detector. This means that each signal level must last more than one clock cycle in order to be reliably sampled, which puts an upper bound on the input frequency at F_CPU/2, assuming a 50% duty cycle.

@EdgarBonet indeed. Recommended is system clock / 2.5, so 6.4MHz on a 16MHz board.

It depends on the processor. Lets assume Uno/Atmega328p at 16MHz. You might get an order of magnitude faster by writing a pulsein() function in assembler. Finding out sounds like a fun project!
To go much beyond that, you'll probably need hardware support.


text:
compile error when using two typename in template class
I am using Arduino 1.8.5 ide. I am just creating a class with two typename which name is "Map". This class takes all int and String variations. Like;
class Map<int, int>;
class Map<int, String>;
class Map<String, int>;
class Map<String, String>;

Map<int, String> *list = new Map<int, String>();

If I create instance of this class like above in Main.ino file then everything is ok. But if I create it another file with .h extension which is "Test.h" then compilation fails. These are files;
    Main.ino
#include "Map.h"
#include "Test.h"

Test *test = new Test();
Map<int, String> *list = new Map<int, String>();

void setup() {

}

void loop() {

}

Map.cpp
#include "Arduino.h"
#include "Map.h"

template<typename E, typename T> Map<E, T>::Map()
{

}

template class Map<int, int>;
template class Map<int, String>;
template class Map<String, int>;
template class Map<String, String>;

Map.h
#ifndef Map_h
#define Map_h

#include "Arduino.h"

template<typename E, typename T> class Map {

public:
    Map();
    ~Map();
};

#endif

Test.h
#ifndef _Test_h
#define _Test_h

#include "Arduino.h"
#include "Map.h"

class Test
{
public :
    Test();
    ~Test();
    Map<int, String> *list = new Map<int, String>();
};

#endif

Error is;
In file included from C:\Users\zafer\Desktop\Main\Main.ino:3:0:
Test.h:14: error: expected ';' at end of member declaration
  Map<int, String> *list = new Map<int, String>();

                                        ^

Test.h:14: error: expected unqualified-id before '>' token
  Map<int, String> *list = new Map<int, String>();

                                              ^

Test.h:14: error: wrong number of template arguments (1, should be 2)
  Map<int, String> *list = new Map<int, String>();

                                   ^

In file included from C:\Users\zafer\Desktop\Main\Main.ino:2:0:
Map.h:6: error: provided for 'template<class E, class T> class Map'
 template<typename E, typename T> class Map {

                                        ^
exit status 1
expected ';' at end of member declaration

Sorry, If it's been already resolved and I couldn't find it.
Thank you.

What is the error?

I put the error in question.

What MCU/board are you using? AVR? ESP8266? Something else?

the errors indicate that it doesn't know what a 'String' is; 'string' is usually spelled in lowercase. n.b. not sure about string classes on arduino

Map.cpp has a ; missing at the end of the template.

I added ; to Main.cpp and I am still getting same error. I am using Arduino/Genuino Uno board. By the way, if I create instance like; Map<String, int> *list = new Map<String, int>(); then no compile error.

In this class declaration:
class Test
{
public :
    Test();
    ~Test();
    Map<int, String> *list = new Map<int, String>();
};

This line is wrong:
    Map<int, String> *list = new Map<int, String>();

You can't execute procedural code when declaring a class. That has to go into the constructor or some other function.
For example, this compiles without errors:
Test.h
#ifndef _Test_h
#define _Test_h

#include "Arduino.h"
#include "Map.h"

class Test
{
public :
    Test() { list = new Map<int, String>; } ;
    ~Test();
    Map<int, String> *list;
};

#endif


text:
Sensor TSL2591 with Arduino Mega
I have three light sensors  TSL2591, of signal I2C, that I need to connect (together) to an Arduino Mega. However, I'm not very sure of how share the SDA and SCL pins of the three sensors and I don't know how to change their address for the Arduino to read and show the data of each sensor.
I have already read sensor's datasheet but there is not much information about this.

 there is not much information ... what information is there? ... also, please add a link to the data sheet to your question (do not put the link into comments)

Looking at the datasheet, the TSL2591 does not appear to have a comfigurable address mechanism, therefore you are most likely obliged to use an I2C Multiplexer.
One example of such a device is the TCA9545A, Low Voltage 4-channel I2C and SMbus Switch With Interrupt Logic and Reset Functions, that can split one I2C line into 4 buses.

They are very easy to use and the pinout (and datasheet) are self explanatory.
Don't forget that you will need 3k3 Ω resistors on the INT, RESET, SDA and SCL lines from the Arduino and on each of the INTx, SDx, and SCx lines from the TCA9545A:

Adafruit has a module with the TCA9548A. The advantage is that these multiplexer chips will also do level shifting for sda and scl. That is needed because the arduino mega is a 5v board and the sensor is a 3.3v sensor. An arduino mega has 10k pullup resistors. Pullup resistors for all the sensors should still be added if they are not on the tsl2591 module.


text:
MFRC522: Firmware Unknown
Can someone help me what is the meaning of this sketch? It always outputs in the serial monitor:
Firmware Version: 0x1C = (unknown)
Scan PICC to see UID, SAK, type, and data blocks...

This is the code of the MFRC522 library I use:
#include <SPI.h>
#include <MFRC522.h>

constexpr uint8_t RST_PIN = 9;          // Configurable, see typical pin layout above
constexpr uint8_t SS_PIN = 10;         // Configurable, see typical pin layout above

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

void setup() {
   Serial.begin(9600);   // Initialize serial communications with the PC
   while (!Serial);    // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
   SPI.begin();      // Init SPI bus
   mfrc522.PCD_Init();   // Init MFRC522
   mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
   Serial.println(F("Scan PICC to see UID, SAK, 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));
}

The code is quite well commented, what don't you understand?  The outputFirmware Version: line is obviously output by PCD_DumpVersionToSerial(). Do you get any other output other than that? You should also see Scan PICC to see.... Are you not seeing that? Please be more explicit, and include a few more lines of output, to illustrate any repetition of output.

yes it also output but reader does not read the rfid card nor the rfid key , that is why I assumed that was the error

Try running the firmware_check example. In that sketch, it does say that only known versions are supported (Serial.println(F("Only known versions supported"));), so your first output line doesn't bode well

Please add a link to your post, to the library that you are using. Is it this one: https://github.com/miguelbalboa/rfid?

yes, thats the one I use.

The mention of unknown in the output line:
Firmware Version: 0x1C = (unknown)

isn't a good sign.
Run the firmware_check example to verify that first, before trying to run other code.
The unknown is output by line 1302 of MFRC522.cpp:
    default:   Serial.println(F(" = (unknown)"));

The firmware_check example states on line 49:
  Serial.println(F("Only known versions supported"));

So, your hardware (i.e. the reader) may not be supported.
The only thing I can suggest is try another reader. Also, read the README, there maybe some thing there, or contact the author and/or raise an issue to see if you can get support for your version of the firmware (0x1C) added.

Put a delay(5) after
mfrc522.PCD_Init();   // Init MFRC522

and it will show the correct firmware version.


text:
ATmega328P of Arduino Pro Mini not responding
While I was trying to change the fuse bits of ATmega328P of my Arduino pro mini using a USBasp device to operate it at 3.3 V/8 MHz, it failed due to the bad connection I guess. After that, the USBasp programmer can't detect the chip.
Does the MCU get bricked/locked?
How can I recover this?
Is there any way to solve this problem using an AVR Dragon board? If yes, please let me know the whole process.

Does the MCU get bricked/locked?

Yes, it's possible. The chip requires a valid clock to run, even when programming, so if the clock settings are corrupt or were set wrong it will no longer be programmable through ICSP.

How can I recover this?

Depending on what has actually happened you can either supply an external clock signal to the chip to get it working again, or you may need to reprogram the chip through the parallel programming interface, also known as HVP (High Voltage Programming).

Is there any way to solve this problem using AVR Dragon board?

Yes, the Dragon can do parallel programming. You can read more about how to fix fuses with it here.

Thank you very much for your answer.
I tried to set fuse bits such that it can run at 8MHz internal clock. Before that, it was running at 16MHz external clock. It the fuse bits are set correctly, it thas the internal clock, otherwise, it would be running on external 16MHz clock. May be for the loose connection while writing the fuse bits, the USBasp programmer writes something different in fuse bits. What do you think?

@MuhammadMonirHossain Perfectly possible, yes. Or you may have calculated the fuse bits wrong - it's easy enough to do (I have done it myself before now).

I tried with AVR Dragon. But the signature is read 0xDFDFDF that is not expected. What might be the problem?

@MuhammadMonirHossain Are you wiring it up for parallel HV programming?

yes, parallel HV programming according to this
Go to Device Connection Sheet from this link: https://www.microchip.com/webdoc/GUID-04E3421E-81C3-4E6C-BD29-9E1A7BAEBA7E/index.html?GUID-995553E0-AB09-4965-B761-FEE58C5FE5E1


text:
How to change the FFT function of the Arduino Uno for the Arduino Zero?
#define LIN_OUT 1   // Include the resources for the linear output function
#define Adafruit_ZeroFFT 256  // Sets the ZeroFFT length to 256 points
#define MERR 10     // Number of error values to store in elist[MERR]
#define PID_ON 1    // Use PID feedback or not
#define TRI_PERIOD 100 // Half-period of triangle wave in loops
#define F_BLACKMAN 0.02463994238109641755656975202572 // Osillation freq. for Blackman filter
#define ARM_MATH_CM0PLUS
#include <arm_common_tables.h>
#include <arm_math.h>
#include <Adafruit_ZeroFFT.h>
#include <SPI.h>

// Photodiode array variables

byte CLKpin = 4;    // Arduino pin delivering the clock pulses to pin 3 (CLK) of the TSL1402R
byte SIpin = 5;     // Arduino pin delivering the SI (serial-input) pulse to pin 2 of the TSL1402R
byte AOpin0 = A1;    // Arduino pin connected to pin 4 (analog output 1)of the TSL1402R
byte AOpin1 = A2;    // Arduino pin connected to pin 8 (analog output 2)of the TSL1402R

// Variables for determining the displacment from the ZeroFFT

int maxindex;       // Index of the maximum of the ZeroFFT
float maxvalue;     // For comparing the values of the ZeroFFT to find the global maximum
double kmax;        // Spatial wavenumber corresponding to the dominant fringe modulation Fourier component
float Am;           // Real part of Fourier coefficent corresponding to kmax
float Bm;           // Imag part of Fourier coefficent corresponding to kmax
float theta;        // Phase angle of Fourier transform at kmax
float preTheta = 0; // Storage for previous value of phase angle
int Nwrap = 0;      // Number of phase wraps
float displacement; // Displacement in nanometers
float predisplacement; // Storage for initial value of displacement
int w = 0;
int prevw = 0;
int wdiff = 0;

// PID Variables

unsigned long lastTime;
double Output=0;  // Output value for PID (voltage to the piezoelectric actuator (in millivolts))
double Setpoint;  // Desired value of displacement (in nm)
double kp = 0 / 1;    // 0 proportional gain for PID
double ki = 2/1;  // (1000 / (138.5)) integral gain for PID
//double ki = 2/ 1;  // (1000 / (138.5)) integral gain for PID
double kd = 0/ 100;    // 0 derivative gain for PID
double error;     // Error signal; difference between setpoint and displacement (in nm)
double preverror; // Stores previous value of error for derivative control
float esum;       // Integral of error signal over time
float D;          // Derivative of error signal
unsigned long time0 = 0; // Used in calculating the derivative term
float MSerror = 0;  // Mean squared error
float RMSerror = 0; // Root mean squared error
float elist[MERR];// Array of last MERR error values
int jerr = 0;        // index of integral error term
float runningRMSerror = 0; // RMS error calc'd from elist

float m = 0;      // extra variables for one time calculations
float pchange = 0;
float lastp = 0;
float k = 1;
int p = 1;
float M = 0;
//int switchtime = 1200; // Time (in ms) between Setpoint switches

void setup() {
  Serial.begin(9600); // Initialize serial interface to computer (i.e. serial monitor or plotter)
  INIT_PHOTO();       // Initialize the photodiode array
  READ_PHOTO();       // Read the photodiode array
  DO_ZeroFFT();           // Calculate the ZeroFFT of the photodiode array data
  FIND_PEAK_INDEX();  // Determine index of peak in ZeroFFT
  KMAX();             // Calculate spatial wavevector of the interferogram
  INIT_PHOTO();       // Maybe could be replaced by START_EXPOSURE()
  READ_PHOTO();       // Read photodiode again in preparation for next step
  PHASE_ANGLE();      // Calculate the complex phase angle of the ZeroFFT peak
  DISPLACEMENT();     // Calculate the displacement from the phase angle
  predisplacement = displacement; // Save the initial displacement corresponding to center of PZT range
  Setpoint = 0;       // Define the initial setpoint
  delay(100);         // Allow things to settle before beginning loop
  START_EXPOSURE();   // Turn on the photodiode array and begin integrating
}

void loop() {
  KMAX();                 // Calculate kmax from previous cycle's ZeroFFT
  READ_PHOTO();           // Read photodiode array
  PHASE_ANGLE();          // Calculate complex phase angle corresponding to kmax peak
  WRAPPING();            // Determine if a phase wrap occurred
  DISPLACEMENT();        // Calculate the displacement from the unwrapped phase
  DO_ZeroFFT();              // Calculate the ZeroFFT of the photodiode array data
  FIND_PEAK_INDEX();       // Determine index of peak in ZeroFFT
  //OSC_SET();             // Oscillate the setpoint up and down
  PID_LOOP();              // Perform feedback to follow the setpoint (if PID_ON is set to 1)
  //OSC_DAC();               // Send an oscillating voltage to the DAC
  //TRI_DAC();              // Send a triangular wave voltage to the DAC
  START_EXPOSURE();          // Turn on the photodiode array and begin integrating for next cycle
  SERIAL_PRINT();               // Print some outputs to the serial USB port
}

// Photodiode functions

void ClockPulse() { // For sending clock pulses during reading of photodiode
  delayMicroseconds(1);
  digitalWrite(CLKpin, HIGH);
  digitalWrite(CLKpin, LOW);
}

void INIT_PHOTO() { // Intialization of photodiode
  // Initialize two Arduino pins as digital output:
    pinMode(CLKpin, OUTPUT);
    pinMode(SIpin, OUTPUT);
  // To set up the ADC, first remove bits set by Arduino library, then choose

    for ( int i = 0; i < 14; i++ )
    {
      digitalWrite(i, LOW);
    }
  // Clock out any existing SI pulse through the ccd register:
    for (int i = 0; i < 260; i++)
    {
      ClockPulse();
    }
  // Create a new SI pulse and clock out that same SI pulse through the sensor register:
    digitalWrite(SIpin, HIGH);
    ClockPulse();
    digitalWrite(SIpin, LOW);
    for (int i = 0; i < 260; i++)
    {
      ClockPulse();
    }
}

void READ_PHOTO() { // Read the photodiode

  // Stop the ongoing integration of light quanta from each photodiode by clocking in a SI pulse
  // into the sensors register:
  digitalWrite(SIpin, HIGH);
  ClockPulse();
  digitalWrite(SIpin, LOW);

  // Next, read all 256 pixels in parallel. Store the result in the array. Each clock pulse
  // causes a new pixel to expose its value on the two outputs:
  for (int i = 0; i < 128; i++)
  {
    delayMicroseconds(20);  // We add a delay to stabilize the AO output from the sensor
    ZeroFFT_input[2 * i] = analogRead(AOpin0);        // Output of first half of photodiode array
    ZeroFFT_input[2 * i + 1] = 0;                     // Store zero in the "imaginary" part of the array
    ZeroFFT_input[2 * i + 256] = analogRead(AOpin1);  // Output of second half of photodiode array
    ZeroFFT_input[2 * i + 257] = 0;                   // Store zero in the "imaginary" part of the array
    ClockPulse();
  }

  // Next, AGAIN stop the ongoing integration of light quanta from each photodiode
  // by clocking in a SI pulse. This is necessary because during the readout operation,
  // the 18th clock pulse starts the integration of light intensity again.
  // This way we can turn on the integration when we want using the START_EXPOSURE() command.
  digitalWrite(SIpin, HIGH);
  ClockPulse();
  digitalWrite(SIpin, LOW);

  // The photodiode remains OFF after this function completes.
  // Call START_EXPOSURE() to turn on the photodiode array and begin integrating.
}

void START_EXPOSURE() {
  // The photodiode array starts integrating once 18 clock pulses have passed.
  // At that time, the photodiodes are once again active. We clock out the SI pulse through
  // the 256 bit register in order to be ready to halt the ongoing measurement at our will
  // (by clocking in a new SI pulse):
  // To be used after all calculations are finished, but
  // before the next photodiode read operation.
  for (int i = 0; i < 260; i++)
  {
    if (i == 18)
    {
      // Now the photodiodes goes active..
      // An external trigger can be placed here
    }
    ClockPulse();
  }
  // Uncomment the next line to increase the integration time.
  //delay(15);// <-- Add 15 ms integration time
}

//Calculation Functions

void DO_ZeroFFT() {  // Performs the ZeroFFT
  ZeroFFT_reorder();  // Reorders the ZeroFFT_input array to allow the ZeroFFT_run() command to be used
  ZeroFFT_run();      // This is the function that actually does the ZeroFFT
  ZeroFFT_mag_lin();  // Produces a variable ZeroFFT_lin_out that contains the absolute values of the ZeroFFT, 128 elements long.
}

void FIND_PEAK_INDEX() { // Finds the index of the major peak in the ZeroFFT
  maxvalue = 0;
  maxindex = 0;
  for (int i = 5; i < 128; i++) // Go through each element of the ZeroFFT (skip the DC peak)
  {
    if (ZeroFFT_lin_out[i] > maxvalue)
    // If the magnitude is larger than the previously seen maximum...
    {
      maxvalue = ZeroFFT_lin_out[i]; // ...store the new max...
      maxindex = i;              // ...and the index at which it occurs.
    }
  }
}

void KMAX() {
  // Calculates the spatial wavevector of the interferogram corresponding
  // to the peak in the ZeroFFT.
  kmax = 2 * PI / 256 * maxindex;
}

void PHASE_ANGLE() { // Calculates the complex phase angle of the ZeroFFT peak
  // NOTE: This function must be called BEFORE the ZeroFFT is calculated.
  Am = 0;
  Bm = 0;
  for (int i = 0; i < 256; i++) // Calculate the real and imag Fourier components
  {
    Am = Am + float ((ZeroFFT_input[2 * i]) * cos(kmax * i)); //magnitude of real part
    Bm = Bm + float ((ZeroFFT_input[2 * i]) * sin(kmax * i)); //magnitude of imaginary part
  }
  theta = atan2(Bm, Am); // Complext phase angle (in radians)
}

void WRAPPING() { // Determines if a phase wrap/unwrap occured and accounts for it
  if ((preTheta ) > (0.5 * PI) && (theta) < (-0.7 * PI)) {
    // Compare the previous theat to the current theta to see if a wrap occured.
    Nwrap = Nwrap + 1; // If so, add 1 to the number of wraps.
  }
  if ((preTheta) < (-0.7 * PI) && (theta) > (0.5 * PI)) {
    // If an unwrap occured (a phase wrap in the other direction)...
    Nwrap = Nwrap - 1; // ...then subtract 1 from the number of wraps.
  }
  preTheta = theta; // Store the current theta for the next cycle
}

void DISPLACEMENT() { // Calculate the displacement after the phase angle is determined
  m =   2 * PI * Nwrap;
  //M = theta + m;
  displacement = ((-(theta + m) * 632) * (1 / (4 * PI)) * (1 / sqrt(2))) - predisplacement;
  //displacement = ((-(theta + m) * 632) * (1 / (4 * PI)) * (0.80)) - predisplacement;
}

// Servo Functions

void PID_LOOP() { // Performs feedback signal for PID control
  error = Setpoint - displacement;

  // Store the current error signal; overwrite if necessary
  if( jerr >= MERR ){
    jerr = 0;
  }
  elist[jerr] = error;
  jerr++;

  // Calculate the running RMS error
  runningRMSerror = 0;
  for(int i=0; i<MERR; i++) {
    runningRMSerror += pow(elist[i],2);
  }
  runningRMSerror = sqrt(runningRMSerror/MERR);

  // Calculate the mean-squared and root-mean-square errors over all time
  MSerror = (k - 1) / k * MSerror + pow(error, 2) / k;
  RMSerror = sqrt(MSerror);
  k = k + 1;

  // Integral of error over all time
  esum = esum + error;

  // Derivative of error
  time0 = millis();
  D = (error - preverror) / (time0 - lastTime);

  // The feedback signal (in millivolts)
  // The minus signs are to make sure the piezo moves in the right direction
  Output = -(kp * error) -(ki * esum) -(kd * D);

  // Send the feedback to the DAC if PID_ON is 1
  /*if (PID_ON) {
    val = offset + Output;
    val = max(val, 0);    // Constrain the output voltage so that is stays in range
    val = min(val, 4096);
    DAC_TRANSFER();
  }

  // Save the current time and error for calc'ing the derivative next cycle
  lastTime = time0;
  preverror = error;*/
}

void SERIAL_PRINT(){

  Serial.print(displacement);
  Serial.print(" , ");
  Serial.println(millis());
  Serial.print(" ") ;
}

Hi every one. I tried to compile this code for the Arduino Zero which was originally written for the Arduino Uno. I got the following errors. What am I doing wrong?
Error:
/Users/RAJU/Documents/Documents/All Folders/Arduino 2017_v03_Maintable/Arduino-zero/DIS_SET_V04_Arduino-zero/DIS_SET_V04_Arduino-zero.ino: In function 'void READ_PHOTO()':
DIS_SET_V04_Arduino-zero:144: error: 'ZeroFFT_input' was not declared in this scope
     ZeroFFT_input[2 * i] = analogRead(AOpin0);        // Output of first half of photodiode array
     ^
/Users/RAJU/Documents/Documents/All Folders/Arduino 2017_v03_Maintable/Arduino-zero/DIS_SET_V04_Arduino-zero/DIS_SET_V04_Arduino-zero.ino: In function 'void DO_ZeroFFT()':
DIS_SET_V04_Arduino-zero:186: error: 'ZeroFFT_reorder' was not declared in this scope
   ZeroFFT_reorder();  // Reorders the ZeroFFT_input array to allow the ZeroFFT_run() command to be used
                   ^
DIS_SET_V04_Arduino-zero:187: error: 'ZeroFFT_run' was not declared in this scope
   ZeroFFT_run();      // This is the function that actually does the ZeroFFT
               ^
DIS_SET_V04_Arduino-zero:188: error: 'ZeroFFT_mag_lin' was not declared in this scope
   ZeroFFT_mag_lin();  // Produces a variable ZeroFFT_lin_out that contains the absolute values of the ZeroFFT, 128 elements long.
                   ^
/Users/RAJU/Documents/Documents/All Folders/Arduino 2017_v03_Maintable/Arduino-zero/DIS_SET_V04_Arduino-zero/DIS_SET_V04_Arduino-zero.ino: In function 'void FIND_PEAK_INDEX()':
DIS_SET_V04_Arduino-zero:196: error: 'ZeroFFT_lin_out' was not declared in this scope
     if (ZeroFFT_lin_out[i] > maxvalue)
         ^
/Users/RAJU/Documents/Documents/All Folders/Arduino 2017_v03_Maintable/Arduino-zero/DIS_SET_V04_Arduino-zero/DIS_SET_V04_Arduino-zero.ino: In function 'void PHASE_ANGLE()':
DIS_SET_V04_Arduino-zero:217: error: 'ZeroFFT_input' was not declared in this scope
     Am = Am + float ((ZeroFFT_input[2 * i]) * cos(kmax * i)); //magnitude of real part
                       ^
exit status 1
'ZeroFFT_input' was not declared in this scope
/Users/RAJU/Documents/Arduino/libraries/Adafruit_Zero_FFT_Library/examples/mic_tft/mic_tft.ino
/Users/RAJU/Documents/Arduino/libraries/Adafruit_Zero_FFT_Library/examples/normalized/normalized.ino

Are you sure, that this really compiled for an Arduino Uno? The used library already is for the Arduino Zero, which is totally different from the Uno. Where did you get this code from? The array ZeroFFT_input has to be defined somewhere, that the error.

That's true. Sorry for the confusion. This code compiles for the Arduino Uno if I replaced all Zero_FFT by FFT. Obviously I have to comment out the following lines of syntax to make it working for the Arduino Zero:  #define Adafruit_ZeroFFT 256
#define ARM_MATH_CM0PLUS
#include <arm_common_tables.h>
#include <arm_math.h>
#include <Adafruit_ZeroFFT.h> And I have to add one more library <FFT.h> to make it work for the Arduino Uno. If you want I will post the code which works for the Arduino Uno.

The Adafruit ZeroFFT library is not a drop in replacement for the FFT Library.
You can't easily use the same code for both.

Do you have any suggestions?

Hi Craig did you have any idea how does the FFT library work in the Arduino Zero?

No, I have never used it. I suggest reading the source code and the examples.


text:
Unable to send SMS from interrupt routine
I am trying to develop a burglar alert system. I am using PIR sensor, Arduino Mega and SIM800L. I have connected PIR sensor to interrupt pin. Whenever motion is dected, a function corresponding to the interrupt will be called. In that function I am sending a SMS to notify with an alert message. If motion is detected 2 times, I will call the emergency contact number.
This is the code I have written.
#include <SoftwareSerial.h>
#define PIR1 2
#define SIREN 13
#define statusLED 12

SoftwareSerial SMS(11, 10);// rx(11-arduino) connect to tx(gsm module)
                         // tx(10-arduino) connect to rx(gsm module)

String CONTACT1 = "xxxxxxxxxx";  //mobile number

boolean status;
byte motionCtr = 0;
unsigned long latestMovementTime = 0;

void setup() {
  pinMode(PIR1,INPUT);
  pinMode(SIREN,OUTPUT);
  pinMode(statusLED,OUTPUT);

  Serial.begin(9600);
  SMS.begin(9600);
  SMS.println("AT+CNMI=2,2,0,0,0");

  delay(5000);
  activateSystem(0);
}

void loop() {
  unsigned long currentTime = millis();
  //If motion is not dected for 5 minutes, turn off the siren.
  if(currentTime - latestMovementTime > 300000 && motionCtr>=1){
    stopSiren(0);
  }
  delay(500);
}

void activateSystem(byte manual){
  delay(60000); //warm up time for PIR sensor
  attachInterrupt(0,motionDetected,RISING);

  status = true;
  digitalWrite(statusLED,HIGH);

  if(manual){
    Serial.println("System ACTIVATED by SMS.");
    notifyBySMS("System ACTIVATED SMS.");
  }else{
    Serial.println("System ACTIVATED.");
    notifyBySMS("System ACTIVATED.");
  }
}

void deactivateSystem(byte manual){
  detachInterrupt(0);

  status = false;
  digitalWrite(statusLED,LOW);

  if(manual){
    Serial.println("System DEACTIVATED by SMS.");
    notifyBySMS("System DEACTIVATED SMS.");
  }else{
    Serial.println("System DEACTIVATED.");
    notifyBySMS("System DEACTIVATED.");
  }
}

void motionDetected(){
  startSiren("Motion at bedroom door.");
}

void startSiren(String msg){
  //Record the time of latest motion dected.
  latestMovementTime = millis();

  motionCtr++;
  Serial.print("Ctr="+motionCtr);
  Serial.println(msg);
  notifyBySMS(msg);

  //Start the siren only if motion is detected 2 times
  if(motionCtr==2){
    digitalWrite(SIREN,HIGH);
    Serial.println("Siren STARTED.");
    notifyBySMS("Siren STARTED.");
    call(CONTACT1);
//    call(CONTACT2);
//    call(CONTACT3);
  }
}

void stopSiren(byte manual){
  motionCtr = 0;
  Serial.println("Ctr="+motionCtr);
  digitalWrite(SIREN,LOW);
  if(manual){
    Serial.println("Siren STOPPED manually.");
    notifyBySMS("Siren STOPPED manually.");
  }else{
    Serial.println("Siren STOPPED");
    notifyBySMS("Siren STOPPED.");
  }
}

void sendSMS(String mobileNumber, String msg){
  Serial.println("Sending SMS to "+mobileNumber);
  //AT command for text mode of gsm module
  SMS.println("AT+CMGF=1");
  delay(100);
  SMS.println("AT+CMGS=\""+mobileNumber+"\"\r");
  delay(100);
  // the text you want to send
  SMS.println(msg);
  delay(100);
  // ASCII code of CTRL+Z
  SMS.println((char)26);
  delay(5000);
  Serial.println("SMS sent to "+mobileNumber);
}

void call(String mobileNumber){
  Serial.println("Calling..."+mobileNumber);
  SMS.println("AT+CMGF=0"); //AT command for PDU mode of gsm module
  SMS.println("ATD"+mobileNumber+";");
  delay(45000);
  SMS.println("ATH");
}

void notifyBySMS(String msg){
  sendSMS(CONTACT1,msg);
  delay(1000);
//  sendSMS(CONTACT2,msg);
//  delay(1000);
//  sendSMS(CONTACT3,msg);
//  delay(1000);
}

I am receiving the SMS from setup(). But I am not receiving the SMS that I have sent from interrupt routine. Also I am receiving the call only sometime, it is random. I guess this is because I am using delay() in interrupt routine.
How can I implement such logic without delay().

Never use Serial in an interrupt!

Serial and delay() both require interrupts in order to work right, but within an ISR, interrupts are already disabled.

Have the interrupt set a flag (boolean variable). Then in the loop, check that flag, do your actions and reset the flag. Using delay, serial, and softwareserial inside the ISR is not adviced.

As mentioned in the comments Serial won't work in an ISR. Generally, you should do as little as possible in an ISR. Often an ISR will just set a flag to be handled in loop()
You will then need to refactor loop() to handle the flag set in the ISR. A common method is to use a finite state machine.

don't forget to declare the flag volatile!


text:
MAX6675 gives a climbing reading
I am using a MAX6675 board and a k-type thermal couple to measure temp. The problem is even when running the example the temp value keeps climbing.
MAX6675 test
27.25
C = 27.25
F = 130.10
109.00
C = 218.00
F = 816.80
872.00
C = 1744.00
F = 2624.00
832.00
C = nan
F = nan
512.75
C = nan
F = nan

I am using the max6675.h library. Is there a way to fix this?
#include "max6675.h"

int thermoDO = 4;
int thermoCS = 5;
int thermoCLK = 6;

MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);
int vccPin = 3;
int gndPin = 2;

void setup() {
  Serial.begin(9600);
  // use Arduino pins
  pinMode(vccPin, OUTPUT); digitalWrite(vccPin, HIGH);
  pinMode(gndPin, OUTPUT); digitalWrite(gndPin, LOW);

  Serial.println("MAX6675 test");
  // wait for MAX chip to stabilize
  delay(500);
}

void loop() {
  // basic readout test, just print the current temp

   Serial.print("C = ");
   Serial.println(thermocouple.readCelsius());
   Serial.print("F = ");
   Serial.println(thermocouple.readFahrenheit());

   delay(1000);
}

edit: Added code (https://github.com/adafruit/MAX6675-library/blob/master/examples/serialthermocouple/serialthermocouple.pde)

Code? Wiring? ...?

I think your house is on fire. Or maybe your code is incorrect, but it's impossible to say when you haven't provided it to us.

The output does not look like it came from this sketch, quite apart from the values it prints. Your loop() function is coded to sample and print 2 lines every second: "C = .... \n" "F = .... \n", yet the output you showed has another line preceding each pair. Are you saying the sketch (or the library) is producing 3 lines where only 2 are coded?

I added a line that was just C= thermocouple.readCelsius() Serial.print (C)

Please provide a picture of your wiring, or at the very least confirm that the pins GND, VCC, DO, CS and CLK do indeed go to data pins 2, 3, 4, 5 and 6 respectively - as declared in your code. I assume this is AdaFruit's version of the library? If this all checks out, then it's almost certainly hardware: the thermocouple, the MAX6675, or the Arduino itself.

Check the sensor wiring. The return value NAN indicates that "no thermocouple attached". https://github.com/adafruit/MAX6675-library/blob/master/max6675.cpp#L38

I can confirm that the pins do match and I am using the AdaFruit library ( most current one I could download from using library manager)

After test some other K-type thermal couples on this I am now thinking I just got a bad board. Thanks for all the help

After test some other K-type thermal couples on this I am now thinking I just got a bad board. I was able to order a new one and it worked without issue