text:
SIM800L not registering to network
I am using SIM800L module. I am new to GSM modules. I have searched in many web sites about SIM800L, every where they mentioned baud rate 9600 for SoftwareSerial but it is not working at all in my case. So I started a trail and error method to match baud rate. Finally I found that its baud rate is 38400. With baud rate of 9600 for Arduino and 38400 I am able to communicate with SIM800L.
The problem is that I am unable to register to network. AT+COPS=? shows all available networks. Using AT+COPS="value" I am able to select network. But after that the SIM800L module still blinks every second.
In loop() I am continuously reading software serial and it's printing the following:
RDY
+CFUN: 1
+CPIN: READY
Call Ready
SMS Ready
RDY
+CFUN: 1
+CPIN: READY
Call Ready
SMS Ready

The above data is continuously printing on console.

Sounds like your power supply is browning out due to overloading. What are you powering it with?

i am using arduino 5v pin with IC lm317. Output around 4.14 Volts.

Tried with 3.7v and 2amps battery, facing same problem. Blinking light every second for four to five seconds after that gap of 3 seconds and again starting blinking.

Experiencing this problem, anyone who knows how it was resolved?

@Mwangi Gilbert it is because of low current problem, for me solved this problem by parallel connection of more than 2 batteries (it may be of 3.7 to 4.2). Please try this it works.

The minimum operating voltage 3.4 V, but usually this is not enough. I tried a 5 V power supply with two serial silicon diodes. (with a voltage drop of approximately 3.5 V), but either of them must remove. Start of calling gives a NO DIALTONE error message, and the SIM800 reboots.

Did any of the posted answers solve your issue? If so, please mark it as the accepted answer. If not, then either refine your question or please post your comment above (which appears to contain the solution) as an answer, and then mark it as accepted in 48 hours, in order to remove your question from the unanswered queue. Answers are not allowed in comments, and may be deleted. If your answer is posted as an answer then it becomes searchable and may help others with the same issue.

If it's still relevant, had the same problem, struggled for days, tried many power Adaptor even 3A/4A range, but finally, I was able to register when I used a 3.7V/1200mAh Li-Po battery with a good charging module.

I am 90% sure it's a power issue. Not sure on what board/module you're using but the SIM800L/SIM900 needs a burst of current of 2 A during 577 µS (See the manual).
Try using 4700 µF and a 10 µF capacitor in parallel with the module. Powering it with a proper power source instead of the Arduino wouldn't hurt too.

Might be some power issues, but I fixed mine by just trying some AT command
AT+CBAND?

Then, AT+CBAND="DCS_MODE"
That works for me. Give it a try man.


text:
Trying to power multiple servos at once using a Arduino Mega
Recently I have been trying to do a project for my end of year project, it involved making a humanoid arm.
I am still a newbie at these things, I usually have my friend do the wiring, but since he is away for the moment can anyone help me with it?
I am currently using 6X MG996R Servos for each finger and 1 for the wrist. I am also using a Arduino Mega with a Adafruit 16-Channel 12-bit PWM/Servo Shield - I2C interface.
I have already searched through the web for the best way to power it but I only found people trying to power it with a 5v adaptor, my problem is I'm trying to make the hand mobile so I need to use a battery. I have tried 2x UltraFire 18650 3000mAh 3.7V rechargeable battery in series (still doesn't work only 1 servo moved), also using a 9v battery (Only moved 2 servos).
So i have been wondering if I could utilise the Adafruit 16-Channel 12-bit PWM/Servo Shield - I2C interface..

Take a multimeter and test the voltages and amps while the servos are being used. If there is voltage drop you will need more batteries in parallel (equalize the voltages before connecting them).

Ok ratchet ill try that soon, oh and BTW do you think the Adafruit 16-Channel 12-bit PWM/Servo Shield - I2C interface will make a difference since as of now im suing a breadboard to control all the servos..

You do have the servo power lines connected in parallel, yes? All Power lines together at the battery, same with all Gnd lines, and the Gnd from the Mega as well.  Some folks have mistakenly connected the power lines in series, that will not work.

OK then i guess i will try to do both in series and parallel

read what @crossroads wrote .... do not do a series connection

Ok thx jsotola for your response ill try that

Here is a spec-sheet for the MG996R servos. Notice at the top of the 2d page, they require a supply of 4.8 - 7.2 volts, and can draw .5 - .9 Amps running and 2.5 Amps when stalled.
You'll need a supply of 6 volts (+/-) that can handle that current, times however many servos you need to operate simultaneously. The 3.7 volt batteries don't even meet the minimum voltage for the servos (unless you have two of them in series, but then they're slightly over the maximum).
You need to figure out your power budget first, then how your are going to meet it. You might be able to use a lighter supply than the worst case (6 stalled motors) would require or even than 6 motors at full operating torque (0.9 Amp each), if you monitor the current on each motor and shut down the or sequence the one(s) with the highest draw. You might even try monitoring just the battery-pack voltage, which won't tell you which motor(s) are stressing, but will let you know that you're unable to supply the total requirement for that present move.
If it were me, I'd use battery voltage sensing first (easier, simpler) to see if I have a problem that I can't solve by sequencing the motors. I might find I don't need to measure each motor's current.
Update:

So its either i use 3.7 bat or 9v. Or.can you suggest any other power
  source?

A single 3.7v battery won't work well) for a motor that needs 4.8v minimum. Two of them in series will be slightly over the max voltage spec (7.4v vs. 7.2v). Will that slight overage damage or overheat the motor? Will be OK for intermittent use? Maybe, if you're careful to shut down a stalled motor quickly. The alternative is to build a voltage regulator that will drop the 7.4 to around 6v, but the regulator must also be able to meet your power budget, too.
A 9v supply is definitely too high and will need to regulated to within the motors' spec. (I assume you're not considering the four or five cm high ones with snap-on connectors, usually used in smoke-detectors? They have very little capability to deliver current and will be totally unsuitable for your application.)
My first try would be to experiment with 1 motor at 7.4v with a typical (for your project) mechanical forces on it, and see if it overheats and how soon, with how much load. You'd be taking a bit of a risk with that motor but the potential advantage is you might save yourself having to build a high-current voltage regulator.
Update2:

NiMH AA cells are 1.2V

Good call. Just know that Nickle-based batteries have the twin disadvantages of long charge cycles (or degradation of capacity with faster charging) and higher self-discharge rate of about 1%/day. Their advantage to you is that it's easier to make a battery pack whose voltage falls within the motor spec. If this is a one-time project, this may well be more important to you than their disadvantages.

Ooo ill keep that in mind Jrobert, but my problem is in my country i cant seem to find any 5v NiMH battery which was my 2nd option if the 3.7 ultrafire bt wont work. So its either i use 3.7 bat or 9v. Or.can you suggest any other power source? And keep.i mind im trying to make the hand mobile

NiMH AA cells are 1.2V, use 4 of them in series to make 4.8V, 5 for 6V.

@CrossRoads ok i will try to find those in my country

source: Stack Exchange

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

sort: votes


text:
Can you save data to heap section in Arduino memory?
On normal computers, heap will be cleaned as you close the program, but can I save data to Arduino's heap with malloc function. And will it be cleaned after I power off the Arduino?

Yes, you can use malloc (though it's seldom a good idea on such a small memory system). Will it get "cleaned"? No. It will get lost. There is no such thing as "cleaned". You remove the power the memory is erased. With no power to maintain the memory state there is no memory to "clean". And nothing to do that "cleaning".

@Majenko So I will lose the data when Arduino is powered off right?

Yes. Like you lose your word document when you unplug the power from your computer.

@Majenko Thanks! It will be great if you can post that as answer.

Yes, you can use malloc() on the Arduino - however it is not something I would recommend you use since memory is at a premium and excessive use of malloc() and free() causes heap fragmentation which can eat your memory up and cause random crashes (String is the biggest culprit of this).
I am not sure what you mean by "clean" the memory.  When power is removed the content of the memory is lost. The whole of the SRAM forgets its contents if there is no power to maintain that state.  A bit like when you unplug your computer it "forgets" that Windows is loaded.
If you want to retain information with the power removed you need to use the EEPROM.

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


text:
Simple multiplication bug
Executing the following code always gives -511 as a result, I performed many tests, and it seems that results are correct from 0 * 0 to 181 * 181, beyond that, results are abnormal, I tried many types for the z variable (int, long, float) without success, any idea? I'm using the Arduino Uno.
long z = 0;

void setup() {

Serial.begin(9600);

}

void loop() {

  z = 255 * 255;
  Serial.println(z);
  delay(200);

}

Hint: Try "z = 255 * 255L;" or "z = 255 * (long) 255;"

I did.
@MikaelPatel I worked indeed, could you explain the reason behind this, and is there similar cases for other types?

This "bug" is as old as programming. When you write "255" compiler creates an "integer constant" with value of 255. When you multiply 255 by 255 you multiply two "integer constants" and by convention result of such multiplication is an "integer". Then you implicitly cast it to long when doing assignment. When you multiply "255" by "255L" you actually multiply "integer constant" by "long constant" and result of such multiplication is "long". You will see similar issue when you write float z = 1 / 5 result will be 0 because integer division results with integer that is later casted to float.

Ref: https://gcc.gnu.org/wiki/avr-gcc is all the information you need for the AVR GCC compiler. It all has to do with 1) number range of "int" for a given target, and 2) compiler evaluation of constant expressions.

@MikaelPatel You should answer the questions instead of writing snippets of them in the comment section.

No, this is not a bug. You are using a compile time constant expression which is signed int unless told otherwise. Therefore you can only represent numbers between -32768 and 32767. Your computation of 255 * 255 = 65025 exceeds the range. Thus you see an overflow. In the C/C++ standard the overflow of signed types is actually undefined behavior. That means that the compiler is allowed to do anything from showing the correct answer to halt and catch fire. Only unsigned types with a known size like uint16_t have a well-defined overflow behaviour. You should promote your right hand side computation to unsigned type like this:
z = 255U * 255U;

This way you tell the compiler your intention and don't land in "Undefined-Behaviour-Land".

@Juraj Right, I thought it was signed 16 bit just as int. But the latter is still true. Compile time constants are signed int, which is 16 bit. So the right side of the assignement is the problem.

wrap around doesn't sound right - but I know what you're saying

Assuming long is 4 bytes, it should work.
However, if somehow a long type is only 2 bytes, or (more likely) you used another type or there is some wrong define/typedef, and it is a signed long (default if you do not used the unsigned keyword), the value range is -32,768 to 32,767 and 255 * 255 = 65,025 which is out of range.
So you can first try to use unsigned long.

long is  -2,147,483,648 to 2,147,483,647

With unsigned long the result becomes :4294966785.

Kwasmich's answer is correct

@Juraj - one short there :p

@Juraj I me ant that long somehow is defined as 2 bytes.

it is not. Kwasmich explains


text:
How to use an Arduino as an emulator to filter signals?

What should be the Arduino code to emulate it as a 3rd order IIR filter?

the picture is the simulink model

Do I smell homework? What did you try? What problem you had?

The Arduino code would be whatever the C code would be. I'm sure you can find some C code examples online...

that is a badly drawn diagram ..... there is no reason why any of the lines should cross

The Wikipedia page Digital filter shows how to derive the difference equation from the transfer function H(z), and how to practically implement it.


text:
Counting number of people inside a room
I want to count the number of people in a room using a microcontroller (Arduino Uno).
I have 2 ultrasonic sensors at a doorway about a 1.5m apart from each other. I want to increment the number when someone walks into the room and decrement that number when someone walks out.
To do this:
If sensor 1 detects a disturbance and then sensor 2 detects a disturbance then increment the counter.
If sensor 2 detects a disturbance and then sensor 1 detects a disturbance then decrement the counter.
However, my code is not working
#include<Ultrasonic.h>

Ultrasonic ultrasonic(5,6);

Ultrasonic ultrasonic2(11,10);

unsigned long currentMillis =0,t1,t2;

int d1,d2,c;

boolean ex=0,en=0,in;

void setup()
{
  pinMode(4,OUTPUT);
  digitalWrite(4,HIGH);
  Serial.begin(9600);
  delay(5000);
  Serial.println("WELCOME TO AUTOMATION !!");
  Serial.println(ultrasonic.distanceRead());
  Serial.println(ultrasonic2.distanceRead());
}

void loop()
{
  currentMillis=(millis())%100;
  d1=ultrasonic.distanceRead();
  d2=ultrasonic2.distanceRead();

  if(currentMillis==0)
  {
    Serial.print("Count is :");
    Serial.println(c);
    Serial.println(d1);
    Serial.println(d2);
  }

  if(d1<=15 && d2<=15)
  {
    c=c;
  }
  else if(d1<=15)
  {
    if(en==1)
    {
      c++;
      en=0;
    }
    else ex=1;
  }

  else if(d2<=15)
  {
    if(ex==1)
    {
      c--;
      ex=0;
    }
    else en=0;
  }

}

Please explain what is happening, why is it not working ? You can not use millis like that, you have to use millis like the blink without delay example: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay Which Ultrasonic.h library is that ? The code "c=c;" does not really do something. Do you know the state change detection example: https://www.arduino.cc/en/Tutorial/StateChangeDetection Some variables are declared but not used. The code for counting  with d1 and d2 is not mirrored code, once says "else ex=1;" but the other one says: "else en=0;" ("=1" versus "=0").

Considering abandoning the ultra sonic sensors.  Instead use 2 light beams positioned so a moving person would block one beam then both as they passed.  This problem has been commercially solved for decades using this method.
The technique used for counting people is similar to the technique used in older mouse-pointing-devices to detect direction.  The technique is called quadrature decoding such as used by an incremental rotary encoders.
Specifically, you need to detect if someone is walking in or is walking out of a room.  But, to do this, you need to assure that first one then both beams will be block by the person.  It is likely this requirement will be easier to meet using light beams rather than ultrasonic sensors.
Consider looking here for example Arduino code and an explanation how to use an Arduino with a quadrature encoded knob.

I want to count the number of people in a room using a microcontroller (Arduino Uno).

a few ways:
1) have sensors on the entrance + exit;
2) require people in the room to push a button periodically;
3) embed sensors on the people. rfid would work for example;
4) have an image sensor and put a super-computer to analyze the picture;
5) weigh those people on a scale;
6) route those people through a single file gate and count pulses;
...
just for starters.

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


text:
Pointer to Hardware Differences Documentation For Arduino Boards?
I hope this question isn't overly broad although it is more of a search for consolidated information.
BACKGROUND:
I am new to the Arduino universe and am drawn in by the open hardware concept. After years of doing electronics projects with PICs, I have tired of iterative hardware prototyping and DIY printed circuit construction for small one-off projects. The lure of buying off-the-shelf hardware and doing minimal wiring on protoboards / shields is a powerful concept that I welcome.
The availability of the hardware from multiple sources (and it seems multiple designers) does present a small problem I have discovered. There appear to be small but important differences between Arduino boards from multiple sources.
As an example, I have found that the hardware PWM isn't always the same from one Arduino Board design to another. I find that the arduino.cc pages (including the Forums) appear to indicate that hardware PWM runs at about 487 Hz. However, my testing shows that on the Arduino 101, two of the four hardware PWM outputs run at 487 Hz while the other two run at 975 Hz. I did not find such details when researching board choices and comparisons. I am assuming that this difference may also exist on other board designs although I have only Uno, 101, and Mega2560 boards to play with at the moment.
A second example is that for at least the Arduino Uno and Arduino 101 board I have, the DC power input jack is 5.5mm/2.1mm, a very common size. However, the Arduino Mega2560 I have (third party) uses a 5.5mm/2.5mm DC input jack -- a standard albeit less common size.
Another difference is the well known differences in (TTL) RS232 port interface chips used. At least these are generally made known and documented so that you can plan in advance for differences that may or may not affect you.
Finally, I have found that on the Arduino 101, plugging in or unplugging (or turning on or off) DC power at the DC input jack (or Vin pin) forces a reboot of the Curie module on the board. I think this is caused by the use of the power management chip and power switching circuitry on the board. The Mega2560 does not show this reboot behavior whenever DC power is changed. (This reboot happens even if the USB source remains connected at all times.)
These sorts of minor differences can affect the choice of board one makes for a given project -- especially, if you develop an application on one board and plan to deploy it on another. (Example: develop on a Mega2560 yet intend on deploying on a Uno later to save cost.)
QUESTIONS:
1) Has anyone come across a Website / page that details many of the minor design differences between Arduino boards?
[Edit] I should have used the word designs rather than boards in this question. I realize each vendor may have tweaks to a board but was more interested in detailed differences in the "official" design. Things like above would be interesting to know -- does the board reboot on application of DC input power? Are all PWMs running at the same default frequency, etc?
2) Are there any Web resources that might at least list other "oddities" with the different board choices? (i.e. PWMs at frequencies other than 487 Hz)?
Any pointers would be much appreciated.

You won't find an exhaustive list of differences between all "Arduino" boards from every vendor ever. 2) If minor software differences exist (e.g. a different default PWM frequency on different pins) then either their core or their board description for the IDE has a bug and this should be reported to the appropriate organization.

Ignacio, I should clarify the intent of question 1. I did not mean to find documentation from all vendors in one place. That would indeed be unreasonable. The question was meant to attempt to find documentation for the the different board designs i.e. Uno, Mega256, 101, Pro, Pro Mini, Micro, etc. I will edit the question to make the intent more clear.

You may find this helpful: PTD0001 Arduino Comparison Rev 0 - PDF - 245 KB.
Screenshot of above:
Credit: Payne Technologies Limited
That compares some models in a way you might find useful.

I have found that the hardware PWM isn't always the same from one Arduino Board design to another

The PWM frequencies can be changed over quite a wide range. I have a page about timers which describes a lot of their features.
According to the Arduino reference page about analogWrite:

The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.

By changing the hardware register you can change those frequencies. The frequency of 980 Hz is because of the compromise needed to get an approximate 1 ms interrupt for use by the millis() function:
16e6 / 64 / 256 = 976.5625 Hz

In other words the clock speed of 16 MHz is prescaled by 64 and then counted to 256, giving that frequency.
Note that this is almost 1 ms. The code behind millis() and micros() functions compensates for that so that you get a reasonably accurate result.
By changing the prescaler, and "count to" point you can get lots of other frequencies. However if you do that to Timer 0 on the Uno (and similar boards) then you will throw out the calculations for the millis() and micros() functions (you can compensate for that, of course).

This only partly answers your question, but hopefully will provide a nudge in a useful direction.

Nick, thanks for the pointer to that chart. That is exactly the type of reference I was looking for. It would be nice if other differences were documented (as well as other Arduino designs like the 101), but I knew the chances of finding a comprehensive comparison all in one place was pretty low.

If others know of similar charts out there, please do post additional answers with pointers. I will be building my own similar chart incorporating what I have learned from direct experimentation as well as any other sites that are pointed out. I sort of suspect that many other really helpful charts or comparisons are scattered about the 'net -- many buried deeply on vendors' Websites like the one Nick linked.

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


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:
sending and recieving data from esp8266
We're trying to make an network of connected cars in which the status of one car is continuously updated to the nearby cars (for example, speed, gear, brakes, etc.).
Can I continuously send out sensor data via ESP8266 and and any nearby ESP8266 can pick it up? Is it possible? Or if there's any other method?

yes, that's completely possible. you can go ESPNOW or mesh or a pre-setup LAN.

Yes, you can - if all the "cars" are on the same WiFi network.
If that is the case, then I'd recommend using UDP as your transport layer, and either broadcast or multicast the packets.
I use UDP and Multicast to send sensor data from multiple sensors to multiple receivers on my network. All nodes subscribe to the same multicast address, and the sensors include their own ID in the packet to identify them. A sensor sends out one packet, and all the other nodes can receive it.
However, if there is no active WiFi network already established between the "cars" then no, there's not a lot you can do with an ESP8266. It communicates using IP, and that relies on there being an established layer 2 network (WiFi / Ethernet, etc) already in existence. You should instead investigate more peer-to-peer communication technologies, or communication technologies that don't rely on establishing a connection to a network of any form.  Maybe the nRF24L01+ would be a better fit?

ESP-NOW fits the problem better than wifi, which has to maintain a connection. ESPNOW also allows encryption (nrf doesn't) and has a nice built-in encoder, with error detection, sender ID, etc.


text:
ESP8266 Arduino and Rotary Encoder
I'm trying to use the sketch bellow to work with my WeMos D1 mini (ESP8266 Arduino platform) together with Rotary Encoder KY-040 or MJKDZ, and it's not working for some reason, but the same sketch is working great on the Arduino Uno (with different pin assignment - 2, 3, 4).
Can someone explain to me what is the issue with the sketch?
const int PinA = 14; // Used for generating interrupts using CLK signal
const int PinB = 12; // Used for reading DT signal
const int PinSW = 13; // Used for the push button switch

int lCnt = 0; // Keep track of last rotary value
volatile int vPos = 0; // Updated by the ISR (Interrupt Service Routine)

void isr_event ()  {
  static unsigned long lIsrTmr = 0; // Last Interrupt time
  unsigned long IsrTmr = millis(); // Interrupt time

  // If interrupts come faster than 5ms, assume it's a bounce and ignore
  if (IsrTmr - lIsrTmr > 5) {
    if (digitalRead(PinB) == LOW)
    {
      vPos++ ; // Could be +5 or +10
    }
    else {
      vPos-- ; // Could be -5 or -10
    }

    // Restrict value from 0 to +100
    vPos = min(10, max(0, vPos));

    // Keep track of when we were here last (no more than every 5ms)
    lIsrTmr = IsrTmr;
  }
}

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

  // Rotary pulses are INPUTs
  pinMode(PinA, INPUT);
  pinMode(PinB, INPUT);

  pinMode(PinSW, INPUT_PULLUP); // Switch is floating so use the in-built PULLUP so we don't need a resistor

  attachInterrupt(digitalPinToInterrupt(PinA), isr_event, LOW); // Attach the routine to service the interrupts

  Serial.println(F("Starting..."));  // Ready to go!
}

void loop()
{

  // Is someone pressing the rotary switch?
  if ((!digitalRead(PinSW))) {
    vPos = 0;
    while (!digitalRead(PinSW))
      delay(10);
  }

  // If the current rotary switch position has changed then update everything
  if (vPos != lCnt) {
    // Write out to serial monitor the value and direction
    Serial.println(vPos);
    // Keep track of this new value
    lCnt = vPos ;
  }
}

Define "not work"... That phrase can mean anything from "jittery movement" to "the whole thing exploded and burned off my eyebrows".

@Majenko No, didn't exploded just not getting any output to the Serial monitor.

Not even the initial "Starting" message?

Yes, I get the message "Starting..."

To be sure 100%, I recompiled for Arduino Uno as we speak and tested with both Rotary Encoder type ( KY-040 and MJKDZ) and it's working as expected. But as I said, it's not outputing nothing except "Starting..." on ESP8266 platform. @Majenko

The ESP8266 doesn't know what a "LOW" interrupt is.  You will have to change your code to use FALLING, RISING or CHANGE interrupts only.

Tried all of them, the FALLING gives me the best result, also I made pinMode(PinA, INPUT); and removed digitalPinToInterrupt(), and made PinB to be attachInterrupt, but the output is weird, there are duplicates and messed counts too. link

perhaps your debounce isn't - perhaps this code can help

@JaromandaX tried that to and it's working really bad, skipping and messing numbers up


text:
exit status 1 no matching function for call to 'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'
The code below
// include the library code:
#include "LiquidCrystal.h"
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(2,4,5,6,7);

void setup()
{
// set up the LCD’s number of columns and rows:
lcd.begin(16,2);
// Print a message to the LCD.
lcd.print("hello");
}
void loop()
{
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis()/1000);
}

Gives me the following error:
exit status 1 no matching function for call to 'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'

It seems as if you are missing a parameter in the lcd() call. It seem to take six arguments, not five.
From the Blink example in the LiquidCrystal library:
// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

Also, looking at the library definition, from LiquidCrystal.cpp:
class LiquidCrystal : public Print {
public:
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
...
}

The number of arguments accepted by the various overloaded constructors are (respectively):

10
11
7
6

So, your statement:
LiquidCrystal lcd(2,4,5,6,7);

is missing a parameter (or more) as it only has five.
This explains why the error that you are seeing has five ints listed in the parameter list:
'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'


text:
Arduino connected keypad printing wrong numbers
Going crazy here trying to connect a keypad to my Arduino. I followed this article KeypadTutorial, but my guess is something is wrong/different because my keypad only has 9 pins and the far left (pin 1) and far right (pin 9) pins have no traces back to the keypad. I bought it years ago and just got around to finding a use for it. It looks just like this one Arduino Keypad but different with white keys with black font.
The issue is the wrong key shows up (i.e. press 0 and get 9). I used a multi-meter to test for continuity between pins when pressing each key and got results that are kind of stumping me. I would think there would be some kind of pattern (like the first pin would always be a 1, 2, or a 3), but obviously not (or I just have a bad keypad).
KEY(pin1, pin2)
1(2,3)
2(1,2)
3(2,5)
4(3,7)
5(1,7)
6(5,7)
8(1,6)
9(5,6)
0(1,4)
#(4,5)
*(3,4)

in your list, transpose the pins for a couple of keys and a pattern will emerge .... 1(3,2) and 3(5,2) and #(5,4)

@jsotola - I can't believe I completely missed that. Soon as I transposed the keys you pointed out and wrote it out on paper in a square pattern it made perfect sense. Wired it up, correctly, and it worked perfectly. If you want to post it I'll mark it as answered.

Transpose the pins for some of the keys and a pattern will emerge.
KEY(pin1, pin2)      transposed pins
1(2,3)        x        1(3,2)
2(1,2)                 2(1,2)
3(2,5)        x        3(5,2)
4(3,7)                 4(3,7)
5(1,7)                 5(1,7)
6(5,7)                 6(5,7)
8(1,6)                 8(1,6)
9(5,6)                 9(5,6)
0(1,4)                 0(1,4)
#(4,5)        x        #(5,4)
*(3,4)                 *(3,4)


text:
Is my Arduino dead?
I connected my Arduino Uno to an external power supply, but did not noticed the power supply was on 30 V, I saw the part in the picture smoking and immediately pulled the cable out of the Arduino.
now, each time I connect it to some source of power his "ON and "L" light up ("TX" and "RX" are dark) and the ATmega heats up, and it can't receive sketches from my PC. It says just

Problem uploading to board.

Is my board completely dead or I can somehow save it?

Have you tried powering it via USB?

If the '328P gets hot, it is dead. But, it's replaceable, you can even buy one with a bootloader loaded in already.
The part you circles is a 100nF capacitor, a 10 cents part.
If the PC is not recognizing it when you plug in USB, then the Atmega16U2 that does the USB interfacing is dead. That one is a very small surface mount part that you cannot replace without a hot air rework station, and then you will need a Programmer to reload it with its USB interface program.
And if you killed the 2 regulators, those need replacing too.
Get another board, be more careful next time.
I'd get a 7.5V or 9V wallwart for power. I think you can get the wallwart and a bootloaded '328P from www.dipmicro.com, www.sparkfruit.com, www.adafruit.com, etc.

You could try to replace the SMD part, probably a capacitor (I may be wrong), if you can identify which part it is from the schematic (or any marking on the board).  However, you may have damaged something else as well. You will only know if and once you have replaced the smoking part.
You may be lucky and only that part has been damaged.
The ATmega appears to be socketed so you could try removing it and putting it in another undamaged board to see if it works still.
It looks like the smoking part is next to a regulator, IC2 (I am not 100% sure about that), but that would make sense, seeing as it was a power supply issue that caused the smoking in the first place.  Maybe just the power supply part of the board is damaged (D1, PC1, PC2, C2, IC1 or IC2 - the two big black and white capacitors, with 47 25V written on them in your photo are PC1 and PC2), and you could slowly work your way through it, checking and replacing the sequential parts (again with the use of the schematic).
I wouldn't throw the board away, I have some partially damaged boards that only half function, but the part that still functions will probably suitable for some project or other in the future... or maybe not, depending on the damage.
It is hard to tell from just a photo which being able to check the parts using a multimeter.
Given that the power LED and L LED still work, there is some hope. Try using the USB input for power and see if that helps as the circuit is different from that of the power jack (no regulator). See VIN AND PWRIN versus USBVCC, on the schematic.
Here is the power jack circuit:

Here is the USB input:

However, if, as you say, the PC can not see the Arduino to communicate with it, it will make programming it difficult.
If you do have another UNO board, with a removable ATmega IC, program Blink.ino on to the ATmega and place it in the damaged board to see if the L LED blinks. If it does then at least some of the board still works.
However, to sum up, your Arduino is probably not going to be as useful as it was prior to the over voltage having been applied - unless you are both lucky and replace a few SMD parts.
On the positive side, look at it as a learning experience on how to track down and repair faults on a PCB - a very useful skill to have.


text:
Powering my Arduino Mega project
What power source should I use for my Arduino Mega project (involves 2 steppers, 2 servos and 2 dc motors)?
I tried to run two stepper motors with 9V battery. But the battery dried out. I am thinking of 8 AAA batteries. Is there a better option? How about powering through Arduino with the help of a DC adapter?

What is the voltage of the DC motors ? Do the stepper motors work at 5V ?

3.5v. yes,it works at 5v.

Low voltage steppers are usually very high current, and usually used with much higher voltage chopping drivers.  Your question is not presently answerable.  In general terms, AA's are a better choice than AAA's, but steppers are not efficient and are rarely used in battery powered gear.  Selecting DC power drives for steppers can itself involve complicated engineering, especially when you get beyond the re-purposed PC power supplies used in desktop 3d printers, "heavy iron" linear supplies are traditionally preferred.

To properly answer this, you first have to determine how long you want your application to be able to run on a full charge. Clearly, it'll run on a 9V battery, but not for very long.
To determine the appropriate power supply, you need to calculate the overall voltage and current requirements for the various components.
The Mega needs a pretty minimal power supply, just 5V @ 200mA.
You don't specify the ratings for your motors. Servos are typically 5-6V @ 500mA, but I'm only guessing. Steppers and DC motors vary quite a lot.
The first step would be to find the specifications for all your motors, and find the maximum values, specifically the operating voltage and stall current. Hypothetically, say the maximum voltage for all the motors is 5V, and the stall currents for the steppers, servos and DC motors are 1A, 1A, 500mA, 500mA, 3A, and 3A respectfully. (Again, this is just an example. Find the true values yourself). That means you'll need a supply that can safely deliver 1+1+0.5+0.5+3+3+0.1 = 9.1A @ 5V or 45.5 watts.
If you want to use a battery (instead of a stationary supply like a DC adapter), you'll need to chose a battery with adequate mAh rating, which is the total number of amps it can deliver in 1 hour.
Perfectly predicting battery life greatly depends on the battery chemistry and your application's average current draw, both of which great very complicated, so I won't go into that here. A battery is considered effectively "dead" when it's depleted to around 80% of it's fully charged voltage. You can lookup the formulas and do the math yourself, or you can use some online calculators to help you estimate discharge times for different battery and load configurations.
However, as a general rule of thumb, you want to select a battery with a voltage greater than the minimum voltage required by any of your components. For your application to run for 1 hour, it's mAh rating should also be greater than your application's total current consumption. To run longer, you'll need to find a battery with a higher mAh rating, or higher voltage that a switching regulator can use to convert that extra voltage into current.
The other important factor, which complicates these calculations, is the type of voltage regulators you use. If you want to power everything from a single battery, you'll definitely need some voltage regulators. Preferably, you should use high-efficiency switching regulators. For this purpose, you can find cheap UBECs used for RC applications on Amazon or Ebay. You should have one for the Arduino and each motor (or pair of motors if you want to save on cost or complexity). Just make sure the regulator's voltage and current requirements are greater than what's consumed by your components.
I find using 2 or 3 Lipo batteries in series, especially 18650 cells, are the cheapest and easiest way to provide power for mobile applications that have high spikes due to motors. For stationary applications, a 12V DC wall adapter with a high current rating would be simpler.
If you want to use akalines, I'd recommend using separate batteries for the Arduino and motors. Akalines aren't well known for being able to deliver high current. Motors can demand a lot of current, and if the battery can't deliver enough, it'll cause the voltage to drop, resulting in the Arduino browning-out. However, lipo batteries, or non-rechargeable lithium batteries are better suited for this.


text:
It is possible to program Linino to send HTTP requests and then use the returned values in sketch?
I am new to using Arduino Yun and I would like to know if it is possible to run a command from the Arduino sketch in order to make (probably, through the Bridge Library) Linino to execute a HTTP Request to a remote server. Then I would like to know if it is possible to use the returned values in that Arduino sketch.
In other words, I would like to delegate the task of retrieving values from the web to the Linux side and the usage of the retrieved data to the sketch.
If it is possible, how to do that?

Take a look at Bridge example or TemperatureWebPanel example: you see you can receive kind of "commands" and react "doing things".
Then take a look at HTTP Client example, where you delegate an HTTP call to the linux side.
Now mix the two: you can make HTTP calls after receiving a command from outside your Yun.
A short test can be done by cutting and pasting the examples above.


text:
Can I use relays with 10A125V~ for my 220V~ applications, safely?
I am using the TinkerKit Relay Module and recently they changed the relay mounted on the board from a white one with 10A250V~ to a black one with 10A125V~.
In my country the voltage is 220V~. Can I use the black relay in my application, safely? May be there problems that I have to be careful?

Definitely no!!!

Though it will most likely work, safely is wrong. If it is rated at 125V, it will work safely up to 125V only :)

In fact the answer is maybe. It all depends on the detailed relay specifications. Many relays have a current rating at one voltage, and a lower rating at a higher voltage. There is, of course, a maximum voltage, independent of current and vice versa.

The part is obsolete now according to Mouser.  The simple answer is no, you cannot use a 120 volt part at 220 volts.  The higher voltage can breakdown the lower voltage rated parts.  It really has nothing to do with the "power" rating as there will be very little power actually dissipated in the relay.  The current handling of the contacts is one issue and that seemingly didn't change but the voltage rating change is basically saying that this part cannot work at 220volts.


text:
Why does my wired button always read HIGH?
I have made a simple Arduino program that uses a potentiometer to dim a LED.
This program also makes a second LED blink.
Finally, I have added a button that controls a third LED; this part of my program does not work: the 3rd LED is always lit as the button always reads HIGH.
Here is the code:
//sensePin is wired up to the FSR
int sensePin = 2;

//this is wired up to an LED
int ledPin = 9;

//Wired up to a button
int inputPin = 1;

int val = 0;

//I was broed so added the default Blink
int ledPinX = 13;

//Wired up to a second LED
int ledPinY = 7;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(inputPin, INPUT);
  pinMode(ledPinX, OUTPUT);
  pinMode(ledPinY, OUTPUT);
  val = digitalRead(inputPin);
}

void loop() {
  if (val == HIGH){
    //This should ask "If your button is pressed, then do the code below
    digitalWrite(ledPinY, HIGH);
    //but for some reason the light is always on. I've tried it with more than one button
  }
  else if(val == LOW){
    digitalWrite(ledPinY, LOW);
  }
  int value;

  /*
 The rest of this stuff works. Well, it did before adding in the button. Now the FSR acts as a digital input. Please help.
   */
  value = analogRead(sensePin) / 4;
  analogWrite(ledPin, value);
  digitalWrite(ledPinX, HIGH);
  delay(500);
  digitalWrite(ledPinX, LOW);
  delay(500);
}

What did I do wrong in this code?
EDIT:: diagram and pic at: instagram.com/p/m3AmHWmp4e

Could you the part of your circuit showing how the button is wired to the Arduino?

You read the button once, in setup(). The function is not called every time the variable's value is read, only when the line is executed and the variable assigned to. Move the digitalRead() call and assignment into loop(), before you check the variable's value.

ok that helps a bit but when I run it the ledPinY stays on the entire time instead of responding to the button

http://pastebin.com/tBiHX7Zw
Ok the button still wont read input and I just revamped the code from scratch just to get the button working then I'll implement sensePin. It compiles fine but always digitalWrites HIGH to ledPinX

EDIT:: Taking a look at the button example i figured out whree I went wrong. I may just use that and integrate the FSR code
EDIT:: It doesnt work either

ummm.. even witht the button gone and input jumper cables pulled that output is screwed up

The main problem with your code is that you read the button state only once at the beginning of your program in setup(), so it keeps the initial value forever.
You should modify loop() as follows:
void loop() {
  digitalWrite(ledPinY, digitalRead(inputPin));
  ...
}

You can also remove the val variable, it is totally useless here; then you must also simplify setup():
void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(inputPin, INPUT);
  pinMode(ledPinX, OUTPUT);
  pinMode(ledPinY, OUTPUT);
  // val = digitalRead(inputPin);
}

I added the diagram to the original quesiton

Pin 1 is used for the serial output and can't be used if you enable serial using serial.begin(9600).
Change button to pin 2.


text:
Arduino time(milli) and pressure sensor
I've succeeded to get an Arduino to work with a pressure sensor.
What I want to do is

when I put pressure on the sensor, after 5 minutes the led lights on.
it starts over again if there's no pressure on the sensor.

Here's the program:
// FSR is verbonden met analoog 0
int fsrAnalogePin = 0;
// De LED is verbonden met pin 11 (pmw pin)
int LEDpin = 11;
// De analoge waarde van de fsr spanningdeler
int fsrWaarde;
// De helderheid van de led tussen 0 en 255
int LEDhelderheid;

void setup() {
    // start de serial monitor
    Serial.begin(9600);
    pinMode(LEDpin, OUTPUT);
}

void loop() {
    fsrWaarde = analogRead(fsrAnalogePin);
    // print ‘Analoge waarde’
    Serial.print(“Analoge waarde = “);
    // print de fsrwaarde op de monitor
    Serial.println(fsrWaarde);

    // maak van getallen tussen 0 en 1023 getallen tussen 0 en 255
    LEDhelderheid = map(fsrWaarde, 0, 50, 0, 255);
    analogWrite(LEDpin, LEDhelderheid);
    delay(100);
}

I've got this for the pressure sensor... now I need to combine it with 5 minutes and the led lights on when it's reached that 5 min of pressure.
i managed to do this but it aint enough...
unsigned long currentTime;
unsigned long startTime;

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

    void loop() {
  currentTime = millis();
  // put your main code here, to run repeatedly:
  Serial.println(currentTime);
  delay(1000);

  if(currentTime-startTime > 6000) {
Serial.println("1 minuut voorbij");
startTime = currentTime;
  }
}

Try this:
unsigned long pressureOnTime; //millis() time when pressure switch is first turned on

const unsigned long ledOnAfterTimeThreshold = 300000; //5 minutes * 60 sec * 1000 mSec
int pressureThreshold = 1; //minimum analog reading from pressure sensor considered to be "on"

const int fsrAnalogePin = 0;
const int ledPin = 11;

int ledState = LOW;
int pressureState = LOW;

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

void loop() {
    checkPressureSwitch();

    //do other stuff here
}

void checkPressureSwitch() {
    if( analogRead(fsrAnalogePin) >=  pressureThreshold )
    {
        handlePressureOn();
    }
    else
    {
        handlePressureOff();
    }

    digitalWrite(ledPin, ledState);
}

void handlePressureOn() {
    if ( pressureState == LOW )
    {
        //pressure switch was off, but is now on
        pressureOnTime = millis();
        pressureState = HIGH;
    }

    else if ( millis() - pressureOnTime >= ledOnAfterTimeThreshold )
    {
        ledState = HIGH;
    }
}

void handlePressureOff() {
    ledState = LOW;
    pressureState = LOW;
}

thanks but im getting a void error(void handlePressureOn) on the line; else if ( millis() - pressureOnTime >= ledOnAfterTimeTheshold ) and it says that (ledOnAfterTimeTheshold) was not declared

There was a typo: change ledOnAfterTimeTheshold to ledOnAfterTimeThreshold. I edited the answer as well.

thank you again but when i do the SerialMonitor i dont see anything doing...maybe its how i put my board check this link is how i put my board; http://www.thuisexperimenteren.nl/science/Arduino/Arduino_FSR/FSRsensor_bb2.jpg

Hi, please read and try to understand the code.  Notice that I didn't put any Serial.print() statements, so of course there is nothing happening in the serial monitor.  Your questions states that you want the LED to be the indicator and this code should do that.  If you want something output in the serial console, add some print statements.

sorry im a rookie...but im going to try to do it on my board see if it works and understand

The very simplest way - not necessarily the best way - is something like:

Keep re-reading the pressure sensor until it senses pressure;
Read millis(), add 300000 (# of msec in 5 min) to it's value, and store that;
Keep re-read millis() until it returns a number >= to that stored value;
Read the pressure sensor;
If it senses pressure,
  turn on the alarm;
  do nothing, forever;
Otherwise, start over again;

It isn't the best way, because the Arduino does nothing else for the 5 minutes until the final sensor check. But as you're learning, you probably don't need it to do anything else - for now. When that time comes, there are better ways than dedicating your processor to watching the clock. But this will get you started, and you may figure out some of those ways on your own, by then. Good luck!
Update: I realized my answer does not account for the possibility that pressure is released from the sensor and reapplied some time later, if both occur within the 5 minute wait. How you treat that situation will depend on the needs of your application (which I'm guessing is for you to learn to work with time and physical data). I'll leave that as a further exercise for you.


text:
loop once per startup for stepper motor
First of all sorry that i dont know much about programming, most of my codes are just copy paste. And of course, i know this question has been asked before, but while using this code:
#include <AccelStepper.h>

AccelStepper stepper (1,7,6);

void setup() {
  // put your setup code here, to run once:

 stepper.setMaxSpeed(100);

 stepper.setAcceleration(20);

  stepper.runToNewPosition(100);

 delay (1000);

stepper.runToNewPosition(0);

delay(1000);

}

void loop() {
  // put your main code here, to run repeatedly:

}

The code worked perfectly once but after resetting the power the code doesnt work in a way that my stepper motor just idles.  Obviously what I want is for the stepper motor to execute the code once per power on. Is there something that i miss? many thanks!

I have never used a stepper motor but check the wiring again and insted of using arduino for programing use platform.io it will help you to understand and complete the code faster it at least helped me a lot

run an example code from the arduino IDE just to verify hardware

don't forget that there is no feedback from the motor .... maybe the driver chip is unpowered or it is incorrectly connected or it is defective

For setup() there's no difference between power on and reset.
Eventually there are subtle ones (hardware dependent -> reason of reset), but not on the Arduino layer.


text:
if(val == 0) being ignored when it contains another nested if() statement
The issue: In the following example even though complexManoeuvre == 3, Serial.print(CTA5: "); ... is executed.
void loop()  {
  if(complexManoeuvre == 0) {
    if(timeisup == true && goingForwards == 1)  {   // If time is up while going forward, assume it's stuck
      goingForwards = 0;
      Serial.print("CTA4: "); stuck(stk);
    }
    if(timeisup == true && goingForwards != 1)  {
      Serial.print("CTA5: "); Serial.print(complexManoeuvre); forward(fwd);
    }
  }
}

However, if I include the first condition within the other if() statments two then it works:
if(complexManoeuvre == 0 && (deltaBegan >= manoeuvreFor) && goingForwards == 1) {
  goingForwards = 0;
  Serial.print("CTA4: "); Serial.print(complexManoeuvre); stuck(stk);
}
if(complexManoeuvre == 0 && (deltaBegan >= manoeuvreFor) && goingForwards != 1) {
  //Serial.print("complexManoeuvre == "); Serial.println(complexManoeuvre);
  Serial.print("CTA5: "); Serial.print(complexManoeuvre); forward(fwd);
}

Being completely stumped, I suspected compiler issue so I reinstalled Arduino to clear Meguno-link avrdude wrapper but the problem remains.
The full code (for a robot hoover) is as follows, slimmed down as much as possible to simplify reading:
const int fwd = 12000;            // ms duration
const int stk = 1600;
unsigned long beganManoeuvre;     // millis time when manoeuvre began
int manoeuvreFor;                 // Duration
unsigned long lastStuck;
byte goingForwards;               // Yes or no
byte complexManoeuvre;            // 0 = none, 1 = center, 2 = stuck, 3 = doubleStuck
byte progress;                    // complexManoeuvre progress

void setup() {
  Serial.begin(9600);
  Serial.print(F("CTA0: ")); spinR(4800);     // Spin through 360 degrees
}

void loop() {
  bool timeisup = false;
  if((millis() - beganManoeuvre) >= manoeuvreFor) {
    timeisup = true;
  }

  if(complexManoeuvre != 0 && timeisup == true)  {          // If part way through a in a complex
    switch(complexManoeuvre)  {                             // ..manoeuvre (eg; stuck)
    case 1:
      // do other()
      break;
    case 2:
      Serial.print(F("CTA2: ")); stuck(manoeuvreFor);       // return to the complex manoeuvre
      break;
    }
  }

//  if(complexManoeuvre == 0 && timeisup == true && goingForwards == 1) {
//    goingForwards = 0;
//    Serial.print("CTA4: "); Serial.print(complexManoeuvre); stuck(stk);
//  }
//  if(complexManoeuvre == 0 && timeisup == true && goingForwards != 1) {
//    //Serial.print("complexManoeuvre == "); Serial.println(complexManoeuvre);
//    Serial.print("CTA5: "); Serial.print(complexManoeuvre); forward(fwd);
//  }
  if(complexManoeuvre == 0) {
    if(timeisup == true && goingForwards == 1)  {   // If timeisup while going forward, assume stuck
      goingForwards = 0;
      Serial.print("CTA4: "); stuck(stk);
    }
    if(timeisup == true && goingForwards != 1)  {   // If finished another manoeuvre, go forwards
      if(complexManoeuvre != 0) Serial.println("What the?!");
      Serial.print("CTA5: "); Serial.print(complexManoeuvre); forward(fwd);
    }
  }
}

void stuck(int dur)  {
  Serial.print(F("void stuck(int dur == "));  Serial.println(dur);
  switch(progress) {
  case 0:
    Serial.print(F("CTA26: "));
    complexManoeuvre = 2;
    reverse(dur);
    progress = 1;
    break;
  case 1:
    Serial.print(F("CTA27: "));
    spinR(dur);
    progress = 2;
    break;
  case 2:                     // Reset
    progress = 0;
    complexManoeuvre = 0;
    lastStuck = millis();
    break;
  }
}

void forward(int dur)  {
  Serial.print(F("void forward(int ")); Serial.print(dur);
  if(goingForwards != 1) {
      Serial.print(F(") >> if(goingForwards != 1) then do"));
      goingForwards = 1;
      beganManoeuvre = millis();
      manoeuvreFor = dur;
      digitalWrite(9, HIGH);
      digitalWrite(10, LOW);
      digitalWrite(11, HIGH);
      digitalWrite(12, LOW);
  }
  Serial.println();
}

void reverse(int dur)  {
  Serial.print(F("void reverse(int dur == "));  Serial.println(dur);
  beganManoeuvre = millis();
  manoeuvreFor = dur;
  digitalWrite(9, LOW);
  digitalWrite(10, HIGH);
  digitalWrite(11, LOW);
  digitalWrite(12, HIGH);
}

void spinR(int dur) {
  Serial.print(F("void spinR(int dur == "));  Serial.println(dur);
  beganManoeuvre = millis();
  manoeuvreFor = dur;
  digitalWrite(9, LOW);
  digitalWrite(10, HIGH);
  digitalWrite(11, HIGH);
  digitalWrite(12, LOW);
}

The questionable Serial output is:
1) 19:59:31.964 -> CTA0: void spinR(int dur == 4800
2) 19:59:36.765 -> CTA5: 0void forward(int 12000) >> if(goingForwards != 1) then do
3) 19:59:48.771 -> CTA4: void stuck(int dur == 1600
4) 19:59:48.811 -> CTA26: void reverse(int dur == 1600
5) 20:11:12.695 -> What the?!
6) 19:59:48.851 -> CTA5: 2void forward(int 12000) >> if(goingForwards != 1) then do
7) 20:00:00.854 -> CTA2: void stuck(int dur == 12000
8) 20:00:00.894 -> CTA27: void spinR(int dur == 12000
9) 20:00:12.860 -> CTA2: void stuck(int dur == 12000
10) 20:00:12.900 -> CTA4: void stuck(int dur == 1600
...

Edit to add: Arduino version 1.8.13, Win7, tested on Nano Atmega168PA and Mega2560

if(timeisup == true) is equivalent to if(true == true) which is redundant ... if(timeisup) is the same

Your void Stuck() { ... }, which is called inside the first if (timeisup == true && goingForwards == 1) { ... } can set complexManoeuvre  to a non-zero value, before reaching the second if (timeisup == true && goingForwards != 1) { ... } (the one with "What the?!").

exactly Serial.print(F("CTA26: "));    complexManoeuvre = 2; recerse(dur);

But, if I'm not mistaken, it needs to do that in order for the process to return to stuck() to continue through the switch(progress).

It's not exactly "can set", it will set it to 2

Change the if() statements to the second version and everything works as it should. But... that's what I don't understand.

@lsbyte Maybe it needs to do that, but after the struck call ends, it'll continue processing commands after that call. That means it goes out of the first nested if block {} and guess what, another nested if is right after that first one.

But shouldn't the progress only increment once each time the process visits stuck()? I don't understand how changing the if() statements in loop could effect the behaviour of the switch(progress)

@lsbyte You are doing pretty much this int a = 0; if (a == 0) { a = 2; }  if (a != 0) { Serial.println("but why?"); } and you are asking why is the a not zero, after you changed it to 2. The stuck has "side effects" and one of them is changing complexManeuvre.

Let us continue this discussion in chat.


text:
ESP8266 Nodemcu create custom PWM with 1.25us resolution
I am trying to control some SMD LEDs WS2812B with the ESP8266-Nodemcu. I am using Arduino environment for coding. Actually I am trying to accomplish a PWM  that is precisely able to:

Go High for 850ns and then
Go Low for 400ns

According to the Spec this, this High Low change is considered as a bit with value 1.
I have tried to delay between the lows and highs, without an effort (delays only work for microseconds and above i suggest).
Do you have any idea how to accomplish that?

I believe you're using WS2812? Then you can use the NeoPixel library. You probably should not bother to try it yourself.

You could have better picked up an SPI based led strip. Since the ESP8266 has to do stuff in the background, it could affect the timing afaik. And the SPI ledstrips are easier to drive.

@Paul yes the libary could indeed be useful. I will try it later. Could you propose me a special model of SPI led stripes?

This could be relevant also: https://github.com/cnlohr/esp8266ws2812i2s, it 'hacks' the I2S bus for accurate timing.

For Arduino, the same I2S bus trick is used here: https://github.com/Makuna/NeoPixelBus/wiki/NeoPixelBus-object#neoesp8266dma800kbpsmethod

It would be really helpful if you could mention in your question what exactly the 'SMD LEDs' are, and what/why the timing requirement is for though. Are you doing actual PWM, or is this a protocol? If it's PWM, why so exact?

I've had luck with the APA120C led strips. There is an extensive review of them: https://cpldcpu.com/2014/08/27/apa102/ search the page for: "WS2812" to see the writeup on the difference between the LED strip types (and why it's so useful)

@Paul thanks sir, i will have a look at this later :)

According to §1.7 (Pulse-Width Modulation) of espressif.com's ESP8266 technical reference document, “PWM frequency range is adjustable from 1000 μs to 10000 μs, i.e., between 100Hz and 1 kHz.”  That range is shown in other sections of that reference, and in other ESP8266 documents as well.  I don't know whether that range reflects any hardware limitations, or whether the PWM APIs enforce such limits or can be operated outside them.
Depending on what your intent is, you might instead consider use of UART capabilities.  For example, if you set the UART data rate to 2.5 MHz and transmit a 110110110... binary pattern synchronously, you will have 800 ns high alternating with 400 ns low.  [I've seen references to use of USARTs on ESP8266's but don't know with certainty whether synchronous protocol actually is supported.]
The I2S subsystem mentioned in §1.5 and described in §10 of the technical reference document also may be able to generate a bit stream as desired.  As noted in §10.2.1.5 one six-bit field selects an input clock prescale factor, and another six-bit field is used as the frequency divider of the communication clock signal.
Edit 1: As noted in cranphin's comments, cnlohr's esp8266ws2812i2s github page provides code that uses the I²S subsystem and DMA to drive WS2812 LED units.  Using DMA (direct memory access, ie transfer of memory data under control of a subsystem other than the CPU) means that once the CPU has set up a data buffer for a new display, it can turn actual transmission of the buffered data over to I²S / DMA and then go on with unrelated tasks while transmission occurs.  Note, cnlohr's page links to a youtube video that illustrates and briefly explains the process.

Thanks for the broad information, this was very useful for me. The UART and I²C thing could be an interesting solution, i will try it at the weekend :)

I ahve tried the I2S thing and it worked! thx

authors: Георгий Змазнев


text:
Can i power Esp8266-Nodemcu with a solarpanel + usb-powerbank?
I was asking myself wether it's possible to power my nodemcu board (version 3) with a usb powerbank, like a smartphone, but the powerbank should then be recharged by a solar panel. So this is basically like it could look like:

I know, there should be some charge regulation, but i would just like to know, if that circuit would be able to charge the powerbank?
According to the Hardware Layout, it could be possible, but i am not definetly sure about that. Maybe you can give me some input about that.

You can not connect a solar panel just like that. There is a voltage regulator at the output of the power bank to get 5V out of the some number of Li-Ion cells and you can not charge the power bank backwards through the output. You must charge Li-Ion cells directly, that is why there is a separate input used for charging the battery pack. If you want to have a battery backup for NodeMCU you have to use a charging board and a MOSFET to switch off the battery output whenever the battery is being charged. The charger must supply enough power for both charging the battery and supplying NodeMCU.
When there isn't voltage at the charger (and NodeMCU) input, MOSFET should switch on the output from the battery and you have to use a diode (in a similar way you used it in your schematics) to prevent beckfeeding when working on battery. It should be Schottky diode with low forward voltage.

Thanks for the info :) Well i am sad about that, but it sounds plausible indeed.

You're welcome :-) You can search for Microchip's document an1149 (Designing A Li-Ion Battery Charger and Load Sharing System) to get an idea how to use the p-MOSFET and Schottky diode to make battery backup with one 18650. Just replace the MCP chip with cheap 1A Li-Ion charging board and put 5V step-up (boost) board from eBay between that circuit and NodeMCU and that's it. Both boards are very small and you can buy them for about $1 each.

Sounds great. Thanks for your help!

The internal wiring varies from case to case. Most power banks have a separate connector for input and output as in this picture. If you can use the same input/output to charge/use the power bank then it already has some internal circuitry similar to the circuit desciribed in an1149. If you can use the same connector for charging and powering some other device, then your connection will work - as that is NodeMCU in parallel with the power bank. But not many power banks are made that way.

Yes i guess your approach is the simplest one :) Thanks you helped me a lot!

And a question is if such power bank will, upon losing the input, switch to output mode fast enough to avoid reset of NodeMCU. Depending of the internal circuits you might need to add a capacitor. However, better way of powering NodeMCU is to bypass the 5V USB input and to connect 3.3V directly to one of the 3.3V pins. That way the battery will last much longer. You can use serial connection of two 18650s + step-down (buck) converter to get 3.3V.

Yes i guess it's more reliable then. I just didn't use that before, but i am excited to try it ;) And like you said, it doesn't seem to be that complicated. thx


text:
SPI conflict with two shields - IOREF?
Update:
I've refactored the code to be very resilient to boards missing or not being able to talk to them. Then I tinkered with a bunch of pins and learned that it all comes down to the IOREF pin being connected to the USB Host shield or not. If it's connected, the USB shield "takes over", allows communication with it, but the CAN shield does not work. If the USB shield IOREF pin is not connected, but the rest of the shield's pins are, CAN works. If I disable the IOREF pin going into the CAN shield (and thus the USB shield also since it's on top), the CAN shield works fine still, but the USB shield does not.
Something happens when the IOREF is powered into the USB board and if it's not powered, you can't talk to it.
Original post:
I have the following setup:

Yourduino RoboRED board
Seeed CAN Bus Shield v1.2 http://wiki.seeed.cc/CAN-BUS_Shield_V1.2/
USB Host Shield https://www.arduino.cc/en/Main/ArduinoUSBHostShield

My issue is that if I connect only the CAN bus shield, I can initialize it without any problem, but when I connect the USB host shield on top of the CAN, the CAN shield becomes unresponsive.
I looked into the wiring and per the specs, the following is how the hardware is set up:

SPI bus runs on ICSP header for both shield, not on D11, D12 & D13. I could switch it for the CAN bus shield if I wanted/needed to, but I don't believe I shoudl be.
The trigger pin for the USB host is D10
The trigger pin for the CAN bus is D9 (since it's v1.2 of the board)
Both boards have power. USB board is on top since it does not have an ICSP male connector on the top side, only female on bottom.

I started to debug the code and traced down to this CAN bus function in mcp_can.cpp, which I've instrumented with debug:
INT8U MCP_CAN::mcp2515_setCANCTRL_Mode(const INT8U newmode)
{
    Serial.print("mcp2515_setCANCTRL_Mode with newmode = ");
    Serial.println(newmode);
    INT8U i;

    mcp2515_modifyRegister(MCP_CANCTRL, MODE_MASK, newmode);

    i = mcp2515_readRegister(MCP_CANCTRL);
    i &= MODE_MASK;
    Serial.println("i & MODE_MASK");
    Serial.println(i);
    Serial.println(MODE_MASK);

    if ( i == newmode )
    {
        return MCP2515_OK;
    }

    return MCP2515_FAIL;
}

The output when it fails is:
USB started ok
past SPI begin
mcp2515_init called
mcp2515_setCANCTRL_Mode with newmode = 128
i & MODE_MASK
0
224
Enter setting mode fall
res = 1

For reference, this is the mcp2515_modifyRegister function:
void MCP_CAN::mcp2515_modifyRegister(const INT8U address, const INT8U mask, const INT8U data)
{
    #ifdef SPI_HAS_TRANSACTION
        SPI_BEGIN();
    #endif
    MCP2515_SELECT();
    spi_readwrite(MCP_BITMOD);
    spi_readwrite(address);
    spi_readwrite(mask);
    spi_readwrite(data);
    MCP2515_UNSELECT();
    #ifdef SPI_HAS_TRANSACTION
        SPI_END();
    #endif
}

The whole file is here: https://github.com/Seeed-Studio/CAN_BUS_Shield/blob/master/mcp_can.cpp. I've tried setting SPI_HAS_TRANSACTION to true with no change in the outcome, though I also don't know exactly what this does.
This is my init:
void setup (void)
{
    Serial.begin(115200);

    // init can bus : baudrate = 500k

    if (Usb.Init() == -1)
        Serial.println("OSC did not start.");
    else
        Serial.println("USB started ok");

    delay( 200 );

    while (CAN_OK != CAN.begin(CAN_500KBPS)) {
        Serial.println("CAN BUS Shield init fail");
        Serial.println(" Init CAN BUS Shield again");
        delay(10000);
    }

    Serial.println("CANbus ready");
}

It seems to have something to do with the registers available for write by the CAN bus library whenever the USB board is or isn't present. The write fails when the USB board is there. Any thoughts as to why or other things to try would be greatly appreciated.

There's a hardware conflict between these two boards which seems to not be resolvable. The solution was to buy the Keyes USB shield, make sure only it has access to pins 9 and 10 from the Arduino and then wire pin 7 (or 8) into pin 9 of the CAN shield, while also properly initializing the CAN shield with that new pin.
Lastly, the Keyes USB shield's ICSP header isn't long enough, so you need to cut 2 mm off the male non-ICSP pins in order to seat it properly on the CAN shield.


text:
Problem with uploading LUFA MassStorage .hex file to Leonardo
I have been trying to make my Leonardo board to work as a USB device. So I started with compiling the open source LUFA USB library demo "MassStorage" for the Leonardo board settings. Since I'm using Mac OS, I downloaded the "AVR Tools" software to upload the hex file to the board(I didn't want to use the ISP protocol to flash. Because it is not possible to remove the chip from the board to make the correct ISP circuit connection). Anyway I was managed to flash the board. But afterwards it is not detectable by the computer. The serial port is not detectable. This proves it flashed something. Afterwards I flashed it again with the original bootloader file and it was identified as before. I'm a beginner to Arduino programming and forgive me if I'm asking elementary question. What am I doing wrong?

Cannot say for sure, but if you was able to flash something, then loose functionality, but was still able to flash it back, then there is possibility, that you flashed the application part (with would-be-bootloder code), not the bootloader part (and the old bootloder in bootloader part then enabled you to flash back something sensibe).
bootloader is resposible for saving application in memory in process of flashing and running the application after that, or in case you just connect the board and do not start flashing it just after (maybe software/transmit) reset.
if you save bootloader to application part of memory, it is highly possible, that it would not do anything good, as the original bootloader would still run first and setup your board and the application (with new bootloader code) would try something futile (and maybe have bad addresses already, as it is suppose to be runned in bootloader place, not in application).
There are two parts of flash memory in arduino - one for application, other for bootloader and they have different use, even if they are just different parts of one big flash area. So make sure, what you actually updated and how was the hex compiled (for which address)

Thanks for your answer. This was my actual problem and I solved it before you posted this. But it explains well, what took me some research to understand. I solved the problem by using an external programmer to flash the uc. And also I was not using the latest lufa library for compiling the hex file. This was also part of the problem. Just mentioned it to complete your answer :)


text:
Integrating an analog signal using Arduino Mega 2560
The sample code is this:
Sample code for Edgar Bonet
I have questions. I need to integrate the analog sine wave of 60 Hz, this signal described in the next picture, adding an offset near 2.5 V, because I can damage the Arduino board with the negative signal cycle. Internally on the Arduino board, I remove this offset, multiplying by 2, and subtracting 1.
V1=analogRead(A0)*2/1023.0-1.0;

The sampling period must be at least fs=300 Hz, T=1/fs and V1 is the signal I need integrate.
What modifications can I make to Edgar Bonet's code?

You are new, so consider the critique as constructive in intention. The title is not descriptive. The edit changed the circuit AND the nature of the question AFTER three people answered. One thorough response to the wrong question was deleted by its author. There is a conversion formula with the wrong denominator adjacent to text stating the translation to voltage is not needed. The purpose of integration is unclear without reading an IEEE document. Code indentation does not aid readability. Multiplication by 2 is unexplained. The correspondence between the block and the schematic is unclear.

you probably want to understand the essence of your goal vs. your approach. cosine modulation is a fancy way of saying that you control the firing angle non-linearly so the (power) output is linear - as linear control of phase angle will yield a non-linear output.

once you understand that you will come to a couple points: 1) you don't need to adc to get it to work; 2) you don't need to integrate to get it to work;

if you really want to go down this path, consider the use of of a hardware integrator;

if you have to do it with software, consider the use of a differential adc. that can be done via a mcu with a different adc, a hardware solution, or use two single-ended adc channels and calculate the difference. For example consider adc the opamp's output as well.

V1=analogRead(A0)*2/1023.0-1.0;

This will give you the voltage across R1 in units of 2.5 V. I do
not know whether you care or not about the units but, if you want the
voltage in volts, then:

the voltage at the Arduino input is analogRead(A0) * (5.0/1024)
to get the voltage across R1, you have to subtract 2.5 V
to get the voltage at the output of the transformer, you have to
multiply by 11.

This could be written as
float V = (analogRead(A0) * (5.0/1024) - 2.5) * 11;

but, in order to minimize the number of floating point operations, you
can simplify it to
float V = analogRead(A0) * (55.0/1024) - 27.5;

You could then integrate the voltage by running it through a function
like this:
static float integral(float x)
{
    static float y;                         // last filter output
    static uint32_t last_sample;            // last time sampled
    uint32_t now = micros();
    float dt = (now - last_sample) * 1e-6;  // step time in seconds
    last_sample = now;
    y += x * dt;
    return y;
}

Now, there is an issue with this approach: the average voltage at the
input of the Arduino is not going to be exactly 2.5 V, because
your resistors R3 and R4 will not have identical resistance. Then the
output of the integral will slowly drift and eventually become
unreasonably large.
One way to mitigate this drift problem is to measure this average using
the same Arduino running the same program: disconnect the mains, see how
the output of the program drifts, and measure the drift rate. Then you
subtract the drift rate from the 27.5 in the code, and fine tune until
there is no drift at all. There is, however, the risk that some time
later it will drift again, due to components changing behavior as the
temperature changes.
A better option would probably be to not integrate, but instead use a
first-order low-pass filter. Such a filter behaves like an integrator
for any signal faster than its cutoff frequency but, unlike a simple
integrator, it has a finite gain at zero frequency. You can turn the
integrator into a low-pass filter simply by changing the line
y += x * dt; into
y += (x - y/tau) * dt;

where tau is the time constant of the filter.

Now I understand why SE experts overlook opportunities to gain a few rep points by gathering more requirements in the question's comments section. I wasted quite a bit of time answering a question that has completely changed, and I'm shell shocked now. Thanks for the discussion however. That was the only thing of interest that came out of my answering in this case. :)

Thanks Edgar Bonet, the low pass filter worked very well.
I could already integrate the signal. Happy week.

Brief Electrical Comment First
The circuit as depicted seems sound, but it may be wise to measure the max and min peaks with an oscilloscope or multi-meter to ensure you are within the voltage range of the Atmel chip on the Mega 2560, which is zero Volts to Vcc [1] per Atmel processor's spec sheet [1].
Since Vcc is 5V per the Mega's schematic [2], the safe range you depicted is correct, however you cannot trust the voltage on the mains to stay within IEEE specifications, the p-p secondary Voltage of the adapter to be dead on in proportional relation to the primary, or the resistors to be in the center of their 5% or 10% range of precision.  You may wish to add some potentiometers to your circuit to make adjustments.
Now the Math and Software Implementation
Continue to take the i,t (integer, time) sample vector as in the example you referenced.  I changed the variable names to be more descriptive from a systems engineering point of view.
int s_in = analogRead(input_pin);
unsigned long microsecs = micros();

The algebraic (not code) relation of the sample to the instantaneous voltage is as follows.

v_in = 5V X s_in / 1024
v_no_offset = v_in - v_offsreallyreallyet
v_offset = 2.5
v_secondary = v_no_offset X (110 KOhms / 10KOhms)

Keep in mind here that the sample is not a p-p measurement.  It is an integer representing a Voltage measurement over a very small time range relative to the period of an approximate [3] 60 Hertz sine wave.  There is no reason to multiply samples or corresponding Voltages by two for this circuit.
The period of a 60 Hertz sine wave is 16,667 usec, so the difference between your max value and min value for any given 16,667 usec period's worth of samples is your p-p Voltage for that period.  You can average those over time to get a less instantaneous p-p Voltage.  Before considering p-p or RMS calculations, you must first computing the secondary Voltage corresponding to the integer sample acquired in the analogRead.
Substitution and calculation in mV instead of Volts yields this.
mv_secondary = (5000 X s_in / 1024 - 2500) X (110000 / 10000)

Translating into C, which will be interpreted correctly within an Ino sketch, and using a simplified expression and long integers to achieve reasonable computational speed and accuracy [4] you get this.
int s_in = analogRead(input_pin);
unsigned long microsecs = micros();
unsigned long mv_secondary = 53711L * s_in / 1000 - 27500;

The v,t (secondary Voltage, time) vector is now in the variables mv_secondary and microsecs respectively.  Then calculate the delta time and find the product to sum.
unsigned long nano_volt_second = mv_secondary * u_sec_delta;

System Design Considerations
In designing the system, it is often better to delegate the conversion to physical units and the Gaussian approximation of an integral to another part of the system (as in the case of when the embedded program is doing data acquisition but not control) or not do it at all (as in the case when control is in the same board as the data acquisition and the PID parameters superseded the need to translate the integers from readAnalog to physical units altogether).
To achieve the higher loop speed when using USB transfer of the values, one can USB transfer the return values of the analogRead more directly as two byte pairs and perform calculations on the USB peer computer (workstation or other computing hardware).  Conversion of integers of any type to strings slows a data acquisition loop down considerably, and should be avoided.
Hardware triggering of the ADC subsystem of the Atmel chip can also increase speed, especially if the analogRead function is bypassed by a lower level implementation of the register reading.  At sampling speeds above 200KHz, completely within the capability of the Arduino Due, every usec counts.
Ambiguous Intent Reference to Integration
The summing of products isn't actually integration, which is a symbolic operation, not a calculation.  The example reference given does a Gaussian discrete approximation of an integral.  The reason for seeking that approximation is not given.
The result of such a calculation would be the product of the time over which the approximation is made and the offset, which would naturally be zero except for any calibration error and low frequency noise in the secondary winding's circuit.
If the intention is to calculate Voltage RMS, there is another real time methodology for that.  If you want the average p-p Voltage, there's another (partly described above) for that.  If you want to track spikes on the line, then you probably want a circuit with over-Voltage protection and a different algorithm.
Usefulness of Optimized Math
The use of unsigned long for optimization may not be necessary for low frequency applications [5], but any system that needs to meet the Nyquist criterion for audio will require a sample rate where the fixed point simulation may cause a statistically significant number of delays over the time of sampling.
Even if the speed is not needed, exceeding the Niquest criteria permits gaining extra bits of accuracy if windowing is used during data reduction.
References
[1] Atmel 2560 cpu spec sheet @ http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf
[2] Mega 2560 schematic @ https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf
[3] A Voltage waveform from a power grid is rarely if ever a perfect sine wave.
[4] Arduino use of long integer constants as in C/C++ discussion @ https://www.arduino.cc/en/Reference/IntegerConstants
[5] The maximum Δt before the unsigned long product overflows is given by `floor ((2^32 - 1) / (53,711 x 1023 / 1000 - 27,500)) = 156,485 usec, corresponding to a 6.39 Hz sample rate.

I timed yous computation of the integral at 49 µs, v.s. 50 µs for my floating point version. Worth the trouble? Your avoidance of floats looks to me like premature optimization. If you do have a performance issue, then fixed-point is definitively a worthwhile optimization technique, but doing it right is trickier than you may think. I would not recommend fixed-point to a newbie, unless it is a requirement or clearly worthwhile for his project.

@EdgarBonet, more than worth the trouble ... necessary in many if not most cases. The sample rate of 20KHz is far below the Due's capability. Perhaps the test code is string USB transfers instead of packed byte arrays. Optimization to avoid delays in faster loops is require to meet the Nyquist criterion for full spectrum audio & faster control apps. ... Reducing s/n ratios for weak signals requires multiples of the Nyquist. ... In sampling 60 Hertz, the code above does not require floats, fixed point libraries, or testing overflow . See [5] and the other material added to the answer.

The signal will saturate.
You should increase the attenuation if you want to be able to add the full cycle.  Or add half cycle and make assumptions about the other half.
As to the code you simply needs to convert the ADC readings to a DC reading and subtract the center offset from it  . Much better to do that in the ADC reading domain. Like this
Y = analogread(AIN) - 2.5 * 1023 / Vref;

Why would it saturate? The attenuation appears to be excessive, leading to unnecessarily loss of bits of accuracy. ... Also, your formula is incorrect in that you are missing the parentheses around the subtraction.


text:
Where should a modified "pins_arduino.h" be stored for Arduino IDE compile?
Our PCB uses an ATmega2560 chip and uses most of the pins, including some that are not defined in the standard pins_arduino.h module, since that module only provides for the pins that are brought out to headers on the Arduino Mega2560 PCB.
We have a modified pins_arduino.h module that has all pins defined, but it doesn't get included in the Arduino IDE compile.  It was cataloged in the same directory as the standard module (that we renamed original).  The path where the modified module is stored is C:/Arduino/hardware/arduino/avr/variants/mega, where the original was also located.
In the sketch, we added #include "pins_arduino.h" as well as #include <pins_arduino.h>, but neither seemed to have included the modified module, so the extra pins are not accessible.  Putting the module in the same library as the sketch didn't help either.
Any suggestions?

Did you try a folder within C:\Users\Username\Documents\Arduino\libraries?

Thanks for suggestion, however it still doesn't give access to the extra pins.

I'd vote for another board variant. Or you can use MegaCore

Now have 2560 “full pin definition” working.  This is what I think I did:
1) Download IDE with "Windows ZIP file for non admin install " from https://www.arduino.cc/en/Main/Software
2) Download pins.arduino.h from https://forum.arduino.cc/index.php?action=dlattach;topic=200887.0;attach=60348
3) Open the IDE distribution zip file and extract all files into the location where you want the IDE files and your sketches to reside.  Could be anywhere.
4) Before starting arduino.exe from the extracted files, replace the pins.arduino.h file that came with the IDE, with the "all pins defined" version.  It is replaced in folder path: .../arduino-1.8.5/hardware/arduino/avr/variants/mega/pins.arduino.h
5) Place sketch within the same path as everything else (e.g. create a folder like “12.My_Sketches” inside “examples”). For example, I put my test sketch Blinky-2560 in folder path: .../arduino-1.8.5/examples/12.My_Sketches/Blinky-2560/Blinky-2560.ino
Why it worked this time?  The only difference I can see is I got the new pins file inserted in the right place before running the IDE.  It is also possible the sketch has to be in the same path as the rest of the IDE (saw that somewhere!?!?).  Otherwise I don’t think there was anything else different from what I was doing with the previously installed IDE.
Since the “all pins defined” file is a superset of the standard mega pins.arduino.h file, there is full compatibility with the Arduino ATmega2560 PCB.  It would be great if Arduino would make this fully defined pins file the standard that comes with the IDE.
Never did get MegaCore to upload the sketch after the compile.

Add another folder in the /variant folder, and put your modified pins_arduino.h in there.
Then in boards.txt, create another section of lines like the exsting Mega section, use a new board name, and add the path to your new folder.
Adding Megacore to the IDE in a similar manner pretty much does all that for you.

Added folder Mega2560DJC in /variants with new pins.ardruino,h module. Duplicated "Genuino Mega or Mega 2560" with name "Mega2560DJC".  Not sure how to add the path to the new folder.  New board doesn't show up in IDE Board list.

Look at how board types are shown in boards.txt.  Make a section like that with  your new info.  I can't look it up further until I get home.  Which Arduino revision are you using? 1.8.5?

Yes, using IDE "Arduino 1.8.5 (Windows Store 1.8.10.0)" reinstalled but no change.

@KIIV  I have added a new board type "allmega" that points to the new “pins.arduino.h” file in C:/arduino/hardware/arduino/avr/variants/allmega with all 2560 pins defined, however, the new board does not show up in the IDE Tools-Board drop-down menu.  Is there something you have to do to make the new board type active in the IDE?


text:
How to make my servo slow down in it´s movement
I want to make my servo react on the data that my light sensor tells him by the amount of light that it is catching. I want the servo to go fast to the left when there is shadow/darkness and then I want it to go slowly back to the right when the light is back.
This is the code I´m now using for my 180 degrees servo.
I also want this to work on my 360 degrees servo but because I am a beginner, I can´t figure it out...
#include <Servo.h>

Servo s;

void setup() {
  // put your setup code here, to run once:
  //pinMode(9,OUTPUT);
  pinMode(A0, INPUT);
  Serial.begin(9600);
  s.attach(9);
}

void loop() {
   float l = analogRead(A0);
   Serial.print(l);
   Serial.print(" ");
   int v = map(l,0,1024,0,179);
   s.write(v);
   Serial.println(v);

}

Don't post code as a picture. Copy and paste it into your question and use correct formatting there (mark the code and press Control + K to format it as block code). 2. Don't post just images of your circuit. We are not really able to see much on these. Instead draw a schematic. You can use the internal schematics editor of this site, when you edit your question. Or, if you don't understand schematics at this point in your learning, use something easier like Fritzing. 3. Describe better, why you are not able to use a 360° servo with your code. What is happening, if you try it?

I don't really understand, what your exact target is, but you have to watch out when using a 360° servo. Some of them are actually continuous rotation servos, where you don't set the angle with the Servo.write() function, but the rotation speed (so a value of 90 would mean no movement)

your problem has nothing to do with the light sensor .... you can remove all the code that has anything to do with the sensor ...... develop the code to control the motor first ..... if you cannot get the motor to run slowly, then it is pointless to go on without changing your goal

I added the code, pictures from my circuit in the right way now.
Hope that it's better to understand and help from now.

The servo's rotation speed is controlled by its internal circuitry. Once you send it a new target position, it drives at it's maximum speed toward that position and decelerates as it approaches.
The best you can do to slow it down is to change its target stepwise, until you reach the target position, instead of setting the final target all at once. If you move it in several large steps, the motion will be jerky; if you send smaller steps at shorter intervals (so the total travel time will be same), the motion will get smoother.
If your application needs the smoothest motion possible, send it many tiny steps rapidly, again, observing your required total travel time. You should be able keep the servo constantly at (or closer to) it's approach speed.