text:
Making two Arduinos/MKR1000s communicate
I am trying to create a project in my free time just for a bit of fun. It consists of two MKR1000s (one acting as a web server connected to one laptop, and the other acting as a web client connected to a different laptop - so I can view the Serial Monitor).
One MKR1000 has a potentiometer attached to it (therefore I can change the value of it), and sends the potentiometer value to the serial monitor every 4 seconds.
THE AIM: Once the web server sets up the w
WifFi network, and the web client connects to that WiFi network, I want to send the potentiometer value across to the web client every time it gets updated. However, I am clueless on how to achieve this.
This is my web server void loop code (the rest is similar to the https://www.arduino.cc/en/Tutorial/Wifi101WiFiWebServer):
void loop() {
  WiFiClient client = server.available();
  // listen for incoming clients
  if (client) {
    // if you get a client,
    Serial.println("new client");
    // print a message out the serial port
    String currentLine = "";
    // make a String to hold incoming data from the client
    while (client.connected()) {
      // loop while the client's connected
      if (client.available()) {
        // if there's bytes to read from the client,
        char c = client.read();
        // read a byte, then
        Serial.write(c);
        // print it out the serial monitor
        if (c == '\n') {
          if (currentLine.length() == 0) {
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();
            // the content of the HTTP response follows the header:
            client.print("Click here showValue of the potentiometer
");
            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          } else {
            // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        } else if (c != '\r') {
          currentLine += c;
          // add it to the end of the currentLine
        }
        if (currentLine.endsWith("GET /showValue")) {
          Serial.println(sensorValue);
          delay(2000);
        }
      }
    }
    client.stop();
  }
}

And this is my web client code I use this https://www.arduino.cc/en/Tutorial/Wifi101WiFiWebClient  - I am not sure how I should modify this in order to receive the potentiometer value across from the web server MKR1000. Any tips or hints would be hugely appreciated!
I am sorry if this is a simple question, however I am just starting with the Arduino idea, and I'm new to coding!

At the bottom of the page for the client code link you provided, there's a link to a Chat Server example. If you study the code I think you'll see how to send and receive the potentiometer reading. Hint: Look in the code where it echoes what it receives.
mkr1000 WiFi Chat Server

You don't have to use a webserver/webclient for this; a raw socket would also work. If you do want to use "web technology":
You can either have the webclient poll the webserver periodically for a new value (ask for a new value every few seconds, and interpret the response), or have the webserver initiate the communication every time a new value is available.
For the latter, you could use Server-Sent Events (SSE) or a Websocket, both of which are very google-able.
I have made examples for both, but these examples are fairly large and have extra functionality. Still, they may give you some pointers and/or code to reuse.
These examples are here:
https://github.com/ocrdu/arduino-webinterface-sse
and here:
https://github.com/ocrdu/arduino-webinterface-websocket-ap
Note that the client side in the examples is a webpage in a webbrowser, but the principle is the same.


text:
What connects to Arduino Solar Shield?
I see there is an Arduino EnergyShield available, and am wondering what (specific) solar shield/panels/attachments can be used to power it. Thoughts?
Bonus points if someone can explain how long the solar unit would take to charge the Energy Shield if the Arduino was on but idling (low-to-nonexistent power output).

First, panels that you can use...
There are a few at Adafruit (here, here or here)
You just want to check that the barrel jack and plug are the same size.  I couldn't find dimensions in the documentation for the energy shield so you may need to dig a little deeper or just swap it for one that you know will work.
Also, the question about how long it will take also depends.  First, if we assume that the arduino is not running we can get ~500mA from the second solar panel listed.  If we can get all of that into the battery, it would take (1200mAH/500mA) about 2.4 hours to fully charge the battery.  It looks like you have to make some adjustments on the shield to get the most out of your solar panel.  And of course, you'll want to adjust those calculations based on the panel that you end up getting.
Now, if we assume the Arduino is running and consuming about 25mA you will have to subtract that 25mA from the 500mA that the solar panel is providing.  So, in general...
**

(Battery Capacity)/(Solar Panel Current - Arduino Current) = Charge
  Time.

**
And you have a lot of control over the solar panel current and the arduino current based on the exact arduino that you use, etc, etc.
There is also probably some loss regulating the solar panel voltage from 5-6V down to charge the battery (which is probably at 3.7V). I also don't know if the charging circuitry will limit the amount of current going to the battery.
Take Away: There's a lot of stuff to consider when trying to answer this question.  I think your best bet would be to get a panel that fits and dump the fuel gauge values out to the console every few minutes.

source: Stack Exchange

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

sort: votes


text:
How to tell what components are compatible with Arduino Due?
I am interested in using the Arduino Due in an upcoming project, however I am worried that the other shields/components that I need will not be compatible with it, because, according to that link:

The Due is compatible with all Arduino shields that work at 3.3V and are compliant with the 1.0 Arduino pinout.

The components I need to use are:

NightShade Electronics energyShield
Solar Panel
Servo Motors

Essentially a solar panel will power the energyShield (rechargeable battery), which in turn will power multiple servo motors.
I cannot tell if the energyShield uses the 1.0 pinout or not. I am also worried that since the the solar power generates 6V it will overload the energyShield which is rated at 3.3V. At the same time, I am worried that the servo motors, which seem to require 4.8V, will not be capable of being powered by the energyShield which outputs 3.3V. Thoughts?
Bonus Points if someone can explain to me what the "1.0 Pinout" is, and whether it is the latest/most modern pinout available for Arduinos.

As far as I understood this energyShiled accepts any input between 5-24V and output 5 - 3.3V. This specs are compatible with arduino Due. And with the solar panel.
You can always power servos from seperate source or from the same battery but with seperate direct line.

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


text:
How do I use two I2C LCDs with 4 pins?
I have two I2C LCD screens:

one with 2 lines
one with 4 lines.

Both have 4 pins each: GND, VCC, SDA, SDL. I connect SDA and SDL to A4 and A5 respectively, and I display text on each one of them with:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,4);

But how can I use both of them at the same time?
I connected the second one's SDA and SDL to A2 and A3, but apparently I have to provide the right address for them (like 0x27), right?
However, while both are connected, using I2C_Scanner only shows one device:
Scanning...
I2C device found at address 0x27  !
done

What am I missing?

With the I2C backpack there are three pairs of landings, A0, A1, A2, which determine the 3 LSB of the device's address, using inverted binary.
Left alone, they generate part of the F or 7 part of the address.  0x3F is common, as is 0x27.
To use more than one device it is necessary to jumper them all uniquely.
The upper bits that generate the 0x3 are hard-wired.  So is the highest bit of the lower byte.  Only the three lowest-order bits can be changed.
Since these address bits are inverted, jumpering the A0 will subtract 1 from the address.  0x3F will become 0x3E, 7 will become 6.
You have control enough to make up to 7 LCD modules on the same I2C bus.
The only caveat is that if you have more than one device writing to the various LCDs you might get collisions, which can mess up the display pretty good.
There are questions on I2C collision avoidance and detection on http://RaspberryPi.StackExchange.com if that is your situation.
Jumpering one or more of them is pretty easy - just pre-tin some wire and solder it quickly then cut off the excess.
Wire the SDA and SCL wires of the LCDs in parallel and to the SDA and SCL pins on the Arduino, usually A4 and A5.  (I always begin with a breadboard for this).  Make sure you have discrete pull-up resistors (10K is common) on each, in only one place on the bus.
If you have a DS3231 RTC module in the system, you do not need to add pull-ups because it has them internally.
If one LCD is already working then you know you have proper pull-up voltage on the bus.  (The signals are switched to the ground state to send data on the I2C bus)
So, to Summarize:
If you have two LCDs in your system you can use LCD modules that already come with different addresses, like
LiquidCrystal_I2C lcd1(0x27,....);

for the first one, then
LiquidCrystal_I2C lcd2(0x3F,.....);

for the second one.
Note that the parameters for these definitions are
LiquidCrystal_I2C lcdname(addr,en,rw,rs,d4,d5,d6,d7,bl,blpol);

0x27 and 0x3F are the most common stock addresses and 0x27 modules are getting harder to find.
If you have a 0x27 then it is very likely that if you buy a newer one it will be 0x3f. Problem solved.
The d4 and d5 in the definition specifies the pins to use for I2C.
You can run the i2cscanner program to see what it finds, once they are wired together.  If you see two different addresses, say 0x27 and 0x3F, then you are good to go.
If only 2F shows, then you want to consider soldering A0 together on one module then run the scanner again to make sure it worked.
Here is how I usually do it when both come set as 0x3f:
I have a Yellow one which is a stock 0x3F and a Blue one where I jumpered A0 to make it 0x3E.  They both are 20 x 4 displays.
Here are my definitions:  (remember, the 4,5 define SDA, SCL pins)
LiquidCrystal lcdblue  (0x3e,2,1,0,4,5,6,7,3,POSITIVE);
LiquidCrystal lcdyellow(0x3f,2,1,0,4,5,6,7,3,POSITIVE);

Then in setup() I use this:
lcdblue.begin(20,4);
lcdblue.backlight();
delay(250);
lcdblue.nobacklight();
delay(250);
lcdblue.backlight();

lcdyellow.begin(20,4);
lcdyellow.backlight();
delay(250);
lcdyellow.nobacklight();
delay(250);
lcdyellow.backlight();

And it's good to go, using pin A4 as SDA and A5 as SCL.
You know they are working as they wink their backlights at you.
If one of yours is 20 x 2 then use lcd2.begin(20,2); of course.
If you REALLY want to use other pins for your I2C bus then just change the 4,5 in the LiquidCrystal_I2C definition to the pins you want to use.  I never have met anyone who would want to do this.
Hope this helps.

You can't hook up I2C devices to arbitrary pins; they must either be connected to SDA and SCL and given different addresses, or you must use software I2C. Figure out how to give the second device a different address, and then instantiate another LiquidCrystal_I2C with the new address in order to be able to use it.

I found out that I can connect to A4, A5 up to 121 I2C devices. There aren't other ports for SDA, SCL. There must be a way to change the address, but I can't find it. Some other LCD displays have A0, A1, A2 pins: jumpering them changes their address. However, both of my display do not have them. (info at http://forum.arduino.cc/index.php?topic=158312.0 ) Will keep searching...

Do you have a link to a product page?

Yes it's this: http://www.ebay.co.uk/itm/181722213160?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT The other is from a Sunfounder kit and I can't find a specific link, only that it is a "I2C LCD 1602".

Don't waste your time on that though, I'll figure something out and let you know. :)

Can you see any jumpers or resistors on the underside of the board?

You mean like C1, C2 on the right or C3-4, R6-8 on the lower left? http://s4.postimg.org/6h8ajc21p/lcd.jpg

On the adapter board, not the display itself.

By adapter board you mean the other side of the small red board? Well I can't remove it to have a closer look, but it seems that there is nothing underneath it.

Pins 1, 2, and 3 select the I2C address of the device. If you lift one of them off the board and solder a wire to ground then you can change the address.

Ok, I'll get a soldering iron and will do it. So I will disconnect one of them and ground it. Then use I2C Scanner to find the new address. By the way, how did you know that?

A page on the web said that most of these modules use a PCF8574 (which your photo confirmed), and from there it's just a matter of reading the datasheet.

In the LiquidCrystal definition you can specify the pins to use for SDA and SCL.  Take a look at my answer about changing addresses on the I2C backpack.  A0, A1, A2 can be shorted together to change the least-significant-bits of the I2C address

Specifying the pins as something other than SDA and SCL only makes sense if you actually have I2C running on those other pins. Very few Arduinos have hardware I2C on more than one pair of pins.

You may be able to wire them in parallel, if you can hold the clock (SCL) high (for one at a time).
Put a diode in to stop the other one going high as well.
Pick a spare pin on your arduino (I will use digital pin 7 for device A, 8 for device B, but it doesn't matter which). When you want to talk to device A, make sure pin 7 is in high impedance mode, and 8 is high. Talk to device A. Stop talking to device A. Put pin 8 in high impedance mode, and pin 7 to high. Talk to device B. Wash, rinse, repeat. So long as a device sees it's clock as high, it won't listen or talk.


text:
Function generator with Arduino Nano
I'm trying to convert the project here to an Arduino Nano.
I scaled the waveforms from 12 bit to 8 bit values. I replaced the analogReadResolution and analogWriteResolution calls with pinMode(10, OUTPUT) and pinMode(11, OUTPUT) and changed the two analogWrite calls to write to pins 10 and 11. Otherwise the program is unchanged.
My thinking (and this is where my poor electronics skills come into play) is that I just need a simple low pass filter to convert the PWM into the appropriate waveform (which, at startup, ought to be a sine wave on both pins). According to the article, the frequency generator tops out at 170Hz. I figure the PWM signal is going to be significantly higher than that, so I use R=3.3K and C = .1uF for my RC filter which ought to give me a -3dB at about 480Hz, but what I'm seeing on my scope is a mess. Not a stable signal at all.
This is the waveform I'm seeing on my scope:

Can someone educate me?
Update: BTW, this is the initial waveform which ought to be a sine wave.

What you're proposing can work, but the PWM frequency needs to be much higher than the frequency you're trying to generate. If you look at the PCMAudio sample you'll see that it tunes the PCM frequency almost as high as it will go.

Can you elaborate on "much higher"? PWM on pins 5 and 6 is 980Hz. What sort of maximum frequency can I expect from the signal generator based on that? And how would I want to set up the low pass filter to clean up the signal?
I've read that DDS article, but I have no inductors in my collection of components, so I was trying to make an RC filter instead.

At a PWM frequency of 980Hz I wouldn't expect anything above 5Hz with any sort of fidelity.

Oh, that's far too low for my needs. I was aiming for simplicity, but a better approach may be to use the digital outputs and create a DAC with a resistor ladder.
Thanks for the education, I guess I'll have to start over.

You can tune the PWM as high as F_CPU/256, i.e. 62.5 kHz with a 16 MHz clock.

The PWMs on pins 10 and 11 of the Arduino Nano run at 488 Hz. That's what you are seeing on the scope. The code you are using was meant for an Arduino Due, which has real digital-to-analog converters.
Edit: You can tune the PWM to run as high as F_CPU/256 by
reconfiguring the timers 1 and 2 to “fast PWM” mode, instead of phase
correct PWM, and setting their prescalers to 1 instead of 64. This
should raise the PWM frequency to 62.5 kHz, given that the Nano has
a 16 MHz clock.
The following code should do exactly this. You can put it somewhere
inside your setup(). Warning: I have not tested this code. This
will change the PWM frequency on pins 10 and 11, but also on pins 3 and
9, which share the same timers. It will probably break the tone()
Arduino function.
// Set PWM frequency to 62.5 kHz on pins 3, 9, 10 and 11.
TCCR1A = 1<<WGM10;
TCCR1B = 1<<WGM12 | 1<<CS10;
TCCR2A = 1<<WGM21 | 1<<WGM20;
TCCR2B = 1<<CS20;


text:
Blink LED 5 times with for loop
Is it possible to let a LED blink, for example 5 times, with an Arduino? Should I use a for loop?
Something like this works in setup, but it will run continuously in the void loop, so my LED keeps blinking.
for (int i = 0; i <= 5; i++) {
  led HIGH
  delay(500);
  led LOW
  delay(500);
}

Also, the blink sequence has to be triggered, and have a reset after it is done.
The complete code is too big to share, but it runs a bit like the following:
There is a "bankValue", it is filled by a user, and counts back to zero.
If it's zero, then blink 5 times.
After the blink, the LEDs are off.
The sketch is waiting for a new user, who will fill the bankValue again and the LED blink should again be initiated.

In your for-loop, which is not recommended btw, you'd need a second delay to see anything blinking. The miracle however is your new user, who will fill the bankValue. please elaborate...

@jsotola, to refrase the question: How can I let a led Blink five times?
In my defense, I added the code snippet to show what I have tried.

@DataFiddler, I know the delay is not recommended, better to use millis. It was just an example of what I have tried.
To elaborate, the program is for some kind of CarWash. The program waits for some Coins/Tokens/eMoney, which is stored in the bankValue.
When the bank is filled, the user can choose different WashPrograms. Relays will activate corrosponding the program. bankValue will decrease when using the WashProgram, until it is zero. All relays will deactviate. On this point I want a flashing LED as a sign that the bank is empty. Washing is done, and now waiting for new money input

@Niles the code, as you presented it, blinks 5 times, but it gets executed repeatedly because loop() repeats tens of thousands of times per second (if there are no delays, of course) .... to run the code only once, use a flag such as setup () {bool xyz = true;} ... then you check the state of the flag loop () { if (xyz) { blink leds; do other stuff;   xyz = false; } }  ... this will run only once, unless there is some code in loop() that sets the flag again

Its really heavy to give a correct answer, if you don't show us the context where the for loop is used. But I'll try:
There should be a part in the void loop method where you detect that the "bankValue" is down to zero. Like:
if (bankValue == 0)
{

}

First you must be sure that, the for loop is called within this block.
if (bankValue == 0)
{
  // I corrected the loop to run exact 5 times (<= -> <)
  for (int i = 0; i < 5; i++)
  {
    led HIGH
    delay(500);
    led LOW
    delay(500);
  }
}

Then you need a flag int blinkingDone = 0;  to indicate that the for loop has executed. This flag must be initialize with a falsy value, set to trueish after the loop is done and reset if the user "fills" the bankValue again.
Then you could use it as a guard to enter the for loop. Like:
int blinkingDone = 0;
int bankValue = 0;

..... somewhere else

if ( coin inserted or so )
{
  // fill bankValue
  blinkingDone = 0;
}

..... somewhere else

if (bankValue == 0 && ! blinkingDone)
{
  // I corrected the loop to run exact 5 times (<= -> <)
  for (int i = 0; i < 5; i++)
  {
    // led HIGH
    delay(500);
    // led LOW
    delay(500);
  }
  blinkingDone = 1;
}

There are potential better ways to do it. But I don't know your code. So this is the simplest way I can imagine.

This is really helpfull. I didn't expect a perfectly ready answer.
Now I know I have to work with a Flag for blinkingDone.
The code itself is on several tabs in Arduino and in total a few 100 lines. I imagine it is to much to add here. I don't know if I used the tabs correctly, but that is something for another thread
Again, this is really helpfull

in the line
if (bankValue == zero && ! blinkingDone)
what is the meaning of the !

It's the not operator. It means "blinking is not done". Ahh and the line contains a typo zero must be 0. I should really think before writing ;-)

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


text:
High-frequency PWM on an Adafruit Feather M0
I'm trying to get a Bluefruit Feather M0, which has a SAMD21G on it, to do high-frequency  PWM by accessing timer registers directly, rather than using the Arduino API to do PWM at ~1 kHz or ~500 Hz. Actual frequency isn't important at this stage, I just want a lot more than 1 kHz.
I found an example for an MKR1000, based on a similar processor. I've adapted it as shown below. Comparing the Adafruit pinout with the original code and with the datasheet, it's apparent that the pin numberings are different and that pin 11, which is the only one of the two example pins that is accessible, is on TCC0 here and not TCC1.
The only change I see that I needed to make is to duplicate all the TCC1 setup in setupTimers() and the TCC1 duty cycle control in loop() for TCC0. Yet on the scope, I see no PWM output. I then tried setting pin 13 to PWM as well, so I'd see it on the on board LED. Still nothing. I'm somewhat stuck now.
Does anyone have any ideas?
void setup() {
    // put your setup code here, to run once:
    setupTimers();
    Serial.begin(9600);
}

void loop() {
    // put your main code here, to run repeatedly:
    int t = 0;
    Serial.println("\nRunning PWM 0 to 100%");
    for (t = 0; t < 1000; t = t + 1) {
        REG_TCC1_CC1 = t;                              // TCC1 CC1 - on D3  - PWM signalling
        while (TCC1->SYNCBUSY.bit.CC1);                // Wait for synchronization
        REG_TCC0_CC1 = t;                              // TCC1 CC1 - on D3  - PWM signalling
        while (TCC0->SYNCBUSY.bit.CC1);                // Wait for synchronization
        delay(1);
        Serial.print(".");
    }

    delay(2000);
}

// Output PWM 24Khz on digital pin D3  and D11 using timer TCC1 (10-bit resolution)
void setupTimers() {
    REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor N=1: 48MHz/1=48MHz
        GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
    while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

    REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
        GCLK_GENCTRL_GENEN |         // Enable GCLK4
        GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
        GCLK_GENCTRL_ID(4);          // Select GCLK4
    while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

    // Enable the port multiplexer for the digital pin D3 and D11  **** g_APinDescription() converts Arduino Pin to SAMD21 pin
    PORT->Group[g_APinDescription[3].ulPort].PINCFG[g_APinDescription[3].ulPin].bit.PMUXEN = 1;
    PORT->Group[g_APinDescription[11].ulPort].PINCFG[g_APinDescription[11].ulPin].bit.PMUXEN = 1;
    PORT->Group[g_APinDescription[13].ulPort].PINCFG[g_APinDescription[13].ulPin].bit.PMUXEN = 1;

    // Connect the TCC1 timer to digital output D3 and D11 - port pins are paired odd PMUO and even PMUXE
    // F & E specify the timers: TCC0, TCC1 and TCC2
    PORT->Group[g_APinDescription[2].ulPort].PMUX[g_APinDescription[2].ulPin >> 1].reg = PORT_PMUX_PMUXO_E;  // D3 is on PA11 = odd, use Device E on TCC1/WO[1]
    PORT->Group[g_APinDescription[11].ulPort].PMUX[g_APinDescription[11].ulPin >> 1].reg = PORT_PMUX_PMUXE_F; // D11 is on PA08 = even, use device F on TCC1/WO[0]
    PORT->Group[g_APinDescription[13].ulPort].PMUX[g_APinDescription[13].ulPin >> 1].reg = PORT_PMUX_PMUXE_E; // Try the LED.. doesn't work with E or F

    //Actually, pin 11 on the Feather is on PA16. Still even, not sure of the significance, but it's now TCC0/WO[6] and still port F.
    //All the stuff further down is about TCC1!

    // Feed GCLK4 to TCC0 and TCC1
    REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TCC0 and TCC1
        GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
        GCLK_CLKCTRL_ID_TCC0_TCC1;   // Feed GCLK4 to TCC0 and TCC1
    while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

    // Dual slope PWM operation: timers countinuously count up to PER register value then down 0
    REG_TCC1_WAVE |= TCC_WAVE_POL(0xF) |           // Reverse the output polarity on all TCC0 outputs
        TCC_WAVE_WAVEGEN_DSBOTH;     // Setup dual slope PWM on TCC0
    while (TCC1->SYNCBUSY.bit.WAVE);               // Wait for synchronization

    // Each timer counts up to a maximum or TOP value set by the PER register,
    // this determines the frequency of the PWM operation: Freq = 48Mhz/(2*N*PER)
    REG_TCC1_PER = 1000;                           // Set the FreqTcc of the PWM on TCC1 to 24Khz
    while (TCC1->SYNCBUSY.bit.PER);                // Wait for synchronization

    // Set the PWM signal to output , PWM ds = 2*N(TOP-CCx)/Freqtcc => PWM=0 => CCx=PER, PWM=50% => CCx = PER/2
    REG_TCC1_CC1 = 500;                             // TCC1 CC1 - on D3  50%
    while (TCC1->SYNCBUSY.bit.CC1);                   // Wait for synchronization
    REG_TCC1_CC0 = 500;                             // TCC1 CC0 - on D11 50%
    while (TCC1->SYNCBUSY.bit.CC0);                   // Wait for synchronization

    // Divide the GCLOCK signal by 1 giving  in this case 48MHz (20.83ns) TCC1 timer tick and enable the outputs
    REG_TCC1_CTRLA |= TCC_CTRLA_PRESCALER_DIV1 |    // Divide GCLK4 by 1
        TCC_CTRLA_ENABLE;             // Enable the TCC0 output
    while (TCC1->SYNCBUSY.bit.ENABLE);              // Wait for synchronization

    //Do everything again for TCC0

    // Dual slope PWM operation: timers countinuously count up to PER register value then down 0
    REG_TCC0_WAVE |= TCC_WAVE_POL(0xF) |           // Reverse the output polarity on all TCC0 outputs
        TCC_WAVE_WAVEGEN_DSBOTH;     // Setup dual slope PWM on TCC0
    while (TCC0->SYNCBUSY.bit.WAVE);               // Wait for synchronization

    // Each timer counts up to a maximum or TOP value set by the PER register,
    // this determines the frequency of the PWM operation: Freq = 48Mhz/(2*N*PER)
    REG_TCC0_PER = 1000;                           // Set the FreqTcc of the PWM on TCC1 to 24Khz
    while (TCC0->SYNCBUSY.bit.PER);                // Wait for synchronization

    // Set the PWM signal to output , PWM ds = 2*N(TOP-CCx)/Freqtcc => PWM=0 => CCx=PER, PWM=50% => CCx = PER/2
    REG_TCC0_CC1 = 500;                             // TCC1 CC1 - on D3  50%
    while (TCC0->SYNCBUSY.bit.CC1);                   // Wait for synchronization
    REG_TCC0_CC0 = 500;                             // TCC1 CC0 - on D11 50%
    while (TCC0->SYNCBUSY.bit.CC0);                   // Wait for synchronization

    // Divide the GCLOCK signal by 1 giving  in this case 48MHz (20.83ns) TCC1 timer tick and enable the outputs
    REG_TCC0_CTRLA |= TCC_CTRLA_PRESCALER_DIV1 |    // Divide GCLK4 by 1
        TCC_CTRLA_ENABLE;             // Enable the TCC0 output
    while (TCC0->SYNCBUSY.bit.ENABLE);              // Wait for synchronization
}

If you only want a PWM signal on D11 (PA16 on your MCU) then do not configure other pins from which you you know they are not supported. Perhaps your program crashes. Do you see the "." on the serial monitor? BTW: the example does configure D2 instead of D3 by accident.  But now you need only D11 ;-). Then do not configure both TCC, just the one you need.

For your specific problem: the Feather's D11 is the SAMD's PA16 and on TCC0/WO[6] (use REG_TCC0_CCB2 and PORT_PMUX_PMUXE_F), and also on TCC2/WO[0] (use REG_TCC2_CCB0 and PORT_PMUX_PMUXE_E).
An easier way: I have made a high-frequency-PWM library for this (called Arduino_SAMD21_turbo_PWM), and I have implemented the pin table for the Adafruit Feather M0.
I haven't tested it though, mainly because I don't have an Adafruit Feather M0. Still, feel free to have a try.
The pin mapping table itself for the Adafruit Feather M0, which AFAIK has the same pin mappings as the Arduino Zero, is here on Github; maybe it can help as well.

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


text:
Reading a string from Firebase and storing it as a CString
I have a mobile app (done using MIT App Inventor) storing some values to a Firebase database. App inventor stores all the values as strings (i.e. with quotes, and strings have quotes enclosed within quotes eg. "\"hello\"").
I'm using this library to fetch data from Firebase to ESP8266. I'm using String var to store the value retrieved and then change it to a CString (trying to store it directly doesn't work) as below:
This doesn't work:
Firebase.get(firebaseData, "/SCHEDULE DETAILS/SCHEDULE1/FREQ FR");
Serial.print("node -- schedule1 /FREQ FR -- type: ");
Serial.println(firebaseData.dataType());
char * cstr1 = new char [33];
cstr1 = firebaseData.stringData();
Serial.print(" -- data: ");
Serial.println(cstr1);

This works:
Firebase.get(firebaseData, "/SCHEDULE DETAILS/SCHEDULE1/WEIGHT");
Serial.print("node -- schedule1/WEIGHT -- type: ");
Serial.println(firebaseData.dataType() ) ;
String dummy = firebaseData.stringData();
Serial.print(" -- data: ");
Serial.print(dummy);
char * cstr = new char [dummy.length()+1];
strcpy (cstr, dummy.c_str());
Serial.print(" -- data int type: ");
Serial.println(atoi(cstr)) ;

I have some more nodes to get data from and I've read that lots of Strings are a bad practice. While trying to find out more, I saw the source code and stringData function itself returns a CString:

I feel like I'm doing one step more than what is required! Any suggestions on how to go about this would be very useful!
Try1 Based on the answer from @Majenko, I tried this before adding to the library:
const char* get_cstring() {
  String str = "will it work" ;
  return str.c_str();
}

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

void loop() {
  const char *new_c = get_cstring();
  int len = strlen(new_c);

  for (int i = 0; i < len; i++) {
    Serial.println(new_c[i]);
    delay(1000);
  }
  Serial.println("----------");
}

But how do I access the contents, because it just prints garbage values; strlen(new_c) gives 2 (I'm guessing that's the amount of storage needed in bytes!?)
Thanks!

Could you please post the solution so others can benefit.

In returning a String object the Firebase first generates that String object and copies the C string data into it.
If you want to get at the raw C string data you will have to look at adding a new "getter" to the library to return the pointer to that C string data:
I'd write it for you, but since you posted a screenshot of the Firebase function, and the change from that code to the new code is very minor (just change the function name and the return type), I can't copy-and-paste it. And I'm not going to peer at that little image and type it all in again.
Incidentally, internally the Firebase library actually uses std::string, which is a better implementation of the same thing that String does. String was created because the Arduino compiler has no STL, and hence no std::string. Either way they both use dynamic allocation.

The problem you have is that your str variable is local to the function. It, and the memory allocated within it, gets destroyed when the function returns. So what you have in new_c is a pointer to nothing much. That shouldn't be the case with Firebase, since _data is a std::string that is a member variable, not a local variable.

I tried with a global String var ; it works! But when I try to use new_c.atoi() with an integer value as input, it fails; so how should the return type be declared!? or where should the change be made to perform those type conversions !?

@SomasundharamSampath Use atoi(new_c)

that was very stupid from me!!! Thanks a lot! Looks like I need another primer on C.


text:
How to achieve smooth motion with a servo motor?
I'm trying to control the MG995 servo motor with an Arduino Uno, but the motion achieved by the motor is kind of erratic. The servo motor is externally powered from a 2200mAh 7.4V 30C LiPo battery with a 7806 voltage regulator which provides a voltage of 6.1V.
The circuit I'm using is as shown below:

When I load the sweep example, the servo rotates until a certain angle where it appears to be obstructed and is trying to overcome the obstacle before turning and rotating in the other direction. Here is a video of the motion I'm trying to describe: https://streamable.com/dcr2i
If I connect the motor directly to the battery without the regulator, the motion is smoother than that. I want to use the regulator to protect both my circuit and the motor. How do I achieve the same smooth motion?

According to Jameco:

Servos are controlled by sending an electrical pulse of variable
  width, or pulse width modulation (PWM), through the control wire.
  There is a minimum pulse, a maximum pulse, and a repetition rate.

I'm ignorant of the effect of a voltage regulator on pulse width modulation, but based on your experience, I suggest that it is detrimental.
You can confirm this if you have access to an oscilloscope with which to view the pulses directly from the circuit and then again from the output of the regulator. Correction, view the input to the servo without the regulator and then with the regulator.
According to Roger's Hobby Center, a 2S lipo battery, nominally 7.4v will reach voltages as high as 8.4 volts. This moves the concern of 6v deeper into the question.
Another website, pololu.com references "old style" servos as being designed for 6 volts in the form of 4 batteries at 1.5v, while manufacturers are embracing the newer battery chemistry and producing servos which will operate at levels as high as 9 volts.
Additional research (the data sheets for this model servo) show that it is designed to take 4.8 to 7.2 volts. The full charge voltage of 8.4 will cause the servo to run a bit faster, but I don't believe there will be long term effects, as the voltage will drop into the nominal range in short order.
Another piece of information I gathered somewhat indicates that a regulator will (or should) work, but it has to have the current capacity to handle the servo. I missed that figure in my research. This led to me discovering a caution that your circuits should have a common ground. If you don't have a common ground, your answer may lie there.

The datasheet says that the motor is rated for 6V, hence the regulator. I actually need to run three of those motors in the end. Each motor was to have its own regulator circuit as above. Would it be safe to run all three directly from the battery without the regulators?

added edits to answer.

Thank you for the incredibly detailed answer!
All the components do share a common ground, but still experience the same issue. The 7806 is rated for an output current in the range of 1A - 1.8A according to here or here which the stall torque of my motor (1.2A) is in. Would you happen to have any other insights?


text:
ESP32 preferences. One error returned, all others work. SOLVED
I am using the Preferences.h library in my Arduino code. I initialize some values. I save them with the preference library. I then modify all the values, then read back the original saved values.
All the values, except one, are restored with the associated get instruction. The one still shows the modified value. I can't see why it is wrong.
Can someone point out my error with calibratedWeight? And if you see some other general errors with the code, please point them out. (I'm not a programmer)
#include <Preferences.h>

Preferences preferences;

int currentFile = 1;
int outputRate = 10;           // milliSeconds
float outputGain = 1.23;
int zeroWeight = 900;          // dac value to produce Zero on scale
int calibratedWeight = 2800;   // dac value equal to 100lb calibration weight.
float DACmultiplier = 20.1;

//---------------------------------------
void savePreferences() {
    preferences.begin("ScaleSetup", false);      // false for read/write
    preferences.putInt("currentFile", currentFile);
    preferences.putInt("outputRate", outputRate);
    preferences.putFloat("outputGain", outputGain);
    preferences.putInt("zeroWeight", zeroWeight);
    preferences.putInt("calibratedWeight", calibratedWeight);  // ???
    preferences.putFloat("DACmultiplier", DACmultiplier);
    preferences.end();
}

//---------------------------------------
void getPreferences() {
    preferences.begin("ScaleSetup", false);        // false for read/write

    currentFile = preferences.getInt("currentFile", currentFile);
    outputRate = preferences.getInt("outputRate", outputRate);
    outputGain = preferences.getFloat("outputGain", outputGain);
    zeroWeight = preferences.getInt("zeroWeight", zeroWeight);
    calibratedWeight = preferences.getInt("calibratedWeight", calibratedWeight);  // ???
    DACmultiplier = preferences.getFloat("DACmultiplier", DACmultiplier);
    preferences.end();
}

//============================================
void setup() {
  Serial.begin(115200);
  Serial.println();

  preferences.begin("ScaleSetup", false);        // false for read/write
  preferences.clear();
  preferences.end();
  delay(90);

  savePreferences();
  Serial.println("\n save preferences");
  Serial.println("\n Original asigned values. \n");

  Serial.printf("currentFile: %i\n", currentFile);
  Serial.printf("outputRate: %i\n", outputRate);
  Serial.printf("outputGain: %f\n", outputGain);
  Serial.printf("zeroWeight: %i\n", zeroWeight);
  Serial.printf("calibratedWeight: %i\n", calibratedWeight);  // ???
  Serial.printf("DACmultiplier: %f\n", DACmultiplier);

  Serial.println("\n modify values. \n");

  currentFile = 5;
  outputRate = 50;           // milliSeconds
  outputGain = 0.45;
  zeroWeight = 1333;         // dac value to produce Zero on scale
  calibratedWeight = 2200;   // dac value equal to 100lb calibration weight.
  DACmultiplier = 12.34;

  Serial.printf("currentFile: %i\n", currentFile);
  Serial.printf("outputRate: %i\n", outputRate);
  Serial.printf("outputGain: %f\n", outputGain);
  Serial.printf("zeroWeight: %i\n", zeroWeight);
  Serial.printf("calibratedWeight: %i\n", calibratedWeight);  // ???
  Serial.printf("DACmultiplier: %f\n", DACmultiplier);

  Serial.println("\n Get original saved preferences. \n");
  getPreferences();

  Serial.printf("currentFile: %i\n", currentFile);
  Serial.printf("outputRate: %i\n", outputRate);
  Serial.printf("outputGain: %f\n", outputGain);
  Serial.printf("zeroWeight: %i\n", zeroWeight);
  Serial.printf("calibratedWeight: %i\n", calibratedWeight);  // ???
  Serial.printf("DACmultiplier: %f\n", DACmultiplier);

//  Serial.println("Restarting in 10 seconds...");
  delay(10000);
//  ESP.restart();
}

//============================================
void loop() {}

The following is the result.
 save preferences

 Original asigned values.

currentFile: 1
outputRate: 10
outputGain: 1.230000
zeroWeight: 900
calibratedWeight: 2800
DACmultiplier: 20.100000

 modify values.

currentFile: 5
outputRate: 50
outputGain: 0.450000
zeroWeight: 1333
calibratedWeight: 2200
DACmultiplier: 12.340000

 Get original saved preferences.

currentFile: 1
outputRate: 10
outputGain: 1.230000
zeroWeight: 900
calibratedWeight: 2200
DACmultiplier: 20.100000

I don't see anything wrong with your code, but then I'm not familiar with this library.  begin() appears to return a success/fail and various put function can return short values on failure.  Just as a sanity check, I would make sure all these are returning expected values.

I wonder if I corrupted something earlier and it is messed up now. I thought the preferences.clear(); function might fix that if it was the problem. I will try and test for success/fail somehow. Thanks for looking at this.

i would debug this kind of a problem by renaming calibratedWeight to abc123 just to see if it is related to the name

When I change it to abc123 it returns the correct value. Then when I change all the abc123 back to calibratedWeight it then does not work, it returns the same result I originally showed. I think changing it to abc123 made a new entry rather than overwrite calibratedWeight. And when I went back to calibratedWeight the problem remains. But I thought preferences.clear(); should have cleared everything.

I changed preferences.begin("ScaleSetup", false);   to preferences.begin("Scale_Setup", false);   I was sure this would fix it, but I get the same result.

Maybe I need to Reboot Windows. :)

I'm sure I know what the problem is. 16 characters when 15 characters is the maximum allowed.

"Note: Namespace name is limited to 15 chars"  I don't understand Namespace, but I guess the same applies to variable names. It works with a 15 character name.

You're allowed to post an answer to your own question.

So, did this preferences.putInt("calibratedWeight", calibratedWeight); return 0?

I was about to try that but I had thought about the length. I still want to do a couple of tests, but at the time I was more concerned about getting the rest of my code done. I will post more later.

At the end of the comments above I said I thought the problem was with the variable name length.
Today I tried the debug option and then ran the code. And the following error message was included in the com output.
[E][Preferences.cpp:163] putInt(): nvs_set_i32 fail: calibratedWeight KEY_TOO_LONG
So I guess I was right. I didn't know anything about the debug option before.


text:
Arduino LiquidCrystal library code prevents ESP32 from running. For 16x2 character display
See bottom for solution.
I am trying to run the Arduino LiquidCrystal library example HelloWorld.ino on an ESP32. It seems like it never even executes the Setup() loop. The ESP resets after eight seconds and then repeats the cycle.
I have used character LCD many times before (with Arduino) but always using I2C. For the current design I am eliminating the I2C to parallel chip and I am instead driving the LCD directly from the ESP32. I am using 4 bit mode to reduce the number of pins required. I have connected Register select, Enable, and D4-D7. These details are not relevant since the ESP32 does not even run with the LiquidCrystal library.
I have looked at the library code and I didn't see anything that I thought would be a problem. But I am a hardware designer (for 36 years) and not a programmer. I use the Arduino IDE because it is quick and easy to test hardware.
The library code can be found here. https://github.com/arduino-libraries/LiquidCrystal/tree/master/src
This is what I get from the serial monitor.
rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1240
load:0x40078000,len:13012
load:0x40080400,len:3648
entry 0x400805f8
ets Jun  8 2016 00:22:57

I tried the example code, and when that didn't work so I added a couple of serial print lines to the code. I am listing that below.
#include <LiquidCrystal.h>

const int rs = 26, en = 25, d4 = 16, d5 = 17, d6 = 18, d7 = 19;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  Serial.begin(115200);
  Serial.println("Start");

  lcd.begin(16, 2);
  lcd.print("hello, world!");
}

void loop() {
  delay(1000);

  lcd.setCursor(0, 1);
  lcd.print(millis() / 1000);

  Serial.println(millis() / 1000);
}

Details that I didn't list above. I am powering the LCD from 5 volts. The LCD data/control lines are specified as VinLo = 0.55v and VinHi = 2.4 volts. Not that this matters since the code above never executes. I have used a Arduino Nano powered with 3.3 volts, running the above code, to confirm that the display actually works under these conditions. I really want this to work with an ESP32-C3. I tried that originally but switched to the ESP32 because it wasn't working with the code.
I hope someone can provide some guidance here. My other option is not using the library and writing my own code, which ends up being brute force and simplistic.
EDIT:
A big thanks to Majenko who was spot on. After removal of the call the code executed properly.

My guess: the constructor calls ::init(). ::init() calls ::begin(). ::begin() uses delays. Those delays may depend on things that aren't configured yet when the constructors are running, and lock up causing a WDT. That library looks to be poorly written TBH. Remove the call to begin() in the ::init() function.

I just recently was having a similar issue. I was trying to get the I2C display to work on an ESP32 using the adafruit library, without success. I then went ahead and used another LCD library. (Debugging the library was out of scope for me, since all I wanted to do was test the I2C bus).

Tipp: Install https://github.com/me-no-dev/EspExceptionDecoder. You can then paste the line that says "Backtrace" from the ESP32 crash dump into that tool and get a nice stack trace. Very helpful.

@PMF The code did not execute so there was no backtrace to examine. Majenko was spot on with his comment to "Remove the call to begin() in the ::init() function." I removed that call and now the code executes and works properly.

My guess:

the constructor calls LiquidCrystal::init().
LiquidCrystal::init() calls LiquidCrystal::begin().
LiquidCrystal::begin() uses delays.

Those delays may depend on things that aren't configured yet when the constructors are running, and lock up causing a WDT.
Remove the call to begin() in the LiquidCrystal::init() function and it should at least get past running the constructor so it gets to run the rest of your code.
Quite why they have that call in there is beyond me.  Rule number one of writing an Arduino library: never perform any operations more strenuous than assigning variables in the constructor as resources you may rely on may not have been initialized yet.

I guess the reason was that they wanted the display to also work if you don't call begin() in setup(). The AVR boards have no exception handling, so the general rule seems to be "Let's always do a best guess what the user wanted when something is not right"


text:
Coding Debugging
This program is supposed to act as a Decimal To Binary Converter, the LeD's acting as output.
The problem is that this function returns Garbage Value

const int LED1 =1, LED2 =3, LED3 =5;
void setup()
{
  Serial.begin(9600);
  pinMode (LED1, OUTPUT);
  pinMode (LED2, OUTPUT);
  pinMode (LED3, OUTPUT);
}
void loop()
{
  int x = 0;
  x = Serial.read();
  x = x-48;
  switch(x){
    case 0:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, LOW);
      break;
    case 1:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, LOW);
      break;
      case 2:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, LOW);
      break;
      case 3:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, LOW);
      break;
      case 4:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, HIGH);
      break;
      case 5:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, HIGH);
      break;
      case 6:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, HIGH);
      break;
      case 7:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, HIGH);
      break;
  }
 Serial.write(x);
}

If you want some help, you should at least put some effort in writing a decent question: What are you trying to achieve? What have you done so far? What do you expect your program to do? What is it doing instead?

That massive program can be compressed into just a handful of lines:
const int LED1 = 1,
          LED2 = 3,
          LED3 = 5;

void setup() {
    Serial.begin(9600);
    pinMode (LED1, OUTPUT);
    pinMode (LED2, OUTPUT);
    pinMode (LED3, OUTPUT);
}

void loop() {
    if (Serial.available()) {
        int x = Serial.read();
        x = x - '0';
        digitalWrite(LED1, x & 0x01);
        digitalWrite(LED2, x & 0x02);
        digitalWrite(LED3, x & 0x04);
        Serial.print(x);
    }
}

Note the use of Serial.print() not Serial.write().  If you use Serial.write() then it prints the ASCII character associated with the number you feed it - in your case characters 0 to 7 (none of which are printable).
Also, unless you check for there actually being something available for you to read from the serial you'll only get a brief flicker of something meaningful (too fast for the eye to see) and then it will just return -1, which with 48 subtracted from it would be -49, which would be "complete garbage".

How does x & 0x01 works?

It's called a bitwise operation. I returns just the first bit of x, so 0 or 1.  With 0x02 it returns the second bit, so 0 or 2. 0x04 returns the third bit, so 0 or 4.  0 is LOW, anything above 0 is HIGH.

why do we use 0X04 and not use 0X03 if we want the third bit?

Because 0x03 is the first two bits combined. 1+2=3. Binary.

So we are moving according to according to numbers that are 2^(something) ??

That is what binary is, Yes.

There are a couple of issues:

The function loop() doesn't return anything, by definition. Functions that do return a value return it with a statement like `return(someValue); Did you mean to say that it prints garbage on the terminal?
If you want to print a value on the terminal, you need to use the the Serial.print(someValue) function; Serial.write() sends a binary value and that is probably not what you wanted. The binary values 0 - 9 represent non-printing characters so I'm not surprised that the terminal printed some odd graphic characters.

-


text:
Getting values from multiple thermistors - one value glitches all over the place

I have a circuit with preferably long wires that get data from thermistors. The Arduino sends this data (formatted in JSON) to a web server where it can be collected by another program.
Some of these values appear correct, while others do not.
[
{
    "dht11": {
        "temperature": 73.4,
        "humidity": 41,
        "heat-index": 77.15
    },
    "thermistors": {
        "therm1": {
            "temp": 71.21,
            "resistance": 12727.27
        },
        "therm2": {
            "temp": 76.22,
            "resistance": 12045.51
        },
        "therm3": {
            "temp": nan,
            "resistance": -19393.41
        }
    }
}
]

code:
#define THERMISTORPIN A0
#define THERMISTORNOMINAL 10000
#define TEMPERATURENOMINAL 25
#define NUMSAMPLES 25
#define BCOEFFICIENT 4050
#define SERIESRESISTOR 10000
#define THERMISTORPIN2 A5
#define THERMISTORPIN3 A3
#define DHTPIN 2
#define PHOTORESISTOR 3
#define DHTTYPE DHT11
int samples[NUMSAMPLES];
int samples_two[NUMSAMPLES];
int samples_three[NUMSAMPLES];
int stuckintime;
#include <SPI.h>
#include <Ethernet.h>
#include "DHT.h"
byte mac[] = {
  0x00, 0x00, 0x00, 0x00, 0x00, 0xEE
};
IPAddress ip(192, 168, 1, 3);
EthernetServer server(80);
DHT dht(DHTPIN, DHTTYPE);
void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  dht.begin();
  analogReference(EXTERNAL);
}

void loop() {
  uint8_t i;
          float average;
          float average_two;
          float average_three;
          float stuckintime;
          for (i = 0; i < NUMSAMPLES; i++) {
            samples[i] = analogRead(THERMISTORPIN);
            samples_two[i] = analogRead(THERMISTORPIN2);
            samples_three[i] = analogRead(THERMISTORPIN3);
            delay(10);
          }
          for (i = 0; i < NUMSAMPLES; i++) {
            average += samples[i];
            average_two += samples_two[i];
            average_three += samples_three[i];
          }
          average /= NUMSAMPLES;
          average = 1023 / average - 1;
          average = SERIESRESISTOR / average;
          float tempreading;
          tempreading = average / 10975;
          tempreading = log(tempreading);
          tempreading /= BCOEFFICIENT;
          tempreading += 1.0 / (TEMPERATURENOMINAL + 273.15);
          tempreading = 1.0 / tempreading;
          tempreading -= 273.15;
          tempreading = tempreading * 9 / 5 + 32;
          average_two /= NUMSAMPLES;
          average_two = 1023 / average_two - 1;
          average_two = SERIESRESISTOR / average_two;
          average_two = average_two;
          float tempreadtwo;
          tempreadtwo = average_two / 11811;
          tempreadtwo = log(tempreadtwo);
          tempreadtwo /= BCOEFFICIENT;
          tempreadtwo += 1.0 / (TEMPERATURENOMINAL + 273.15);
          tempreadtwo = 1.0 / tempreadtwo;
          tempreadtwo -= 273.15;
          tempreadtwo = tempreadtwo * 9 / 5 + 32;
          average_three /= NUMSAMPLES;
          average_three = 1023 / average_three - 1;
          average_three = SERIESRESISTOR / average_three;
          float tempreadthree;
          tempreadthree = average_three / THERMISTORNOMINAL;
          tempreadthree = log(tempreadthree);
          tempreadthree /= BCOEFFICIENT;
          tempreadthree += 1.0 / (TEMPERATURENOMINAL + 273.15);
          tempreadthree = 1.0 / tempreadthree;
          tempreadthree -= 273.15;
          tempreadthree = tempreadthree * 9 / 5 + 32;
          float h = dht.readHumidity();
          float t = dht.readTemperature();
          float f = dht.readTemperature(true);
          float hif = dht.computeHeatIndex(f, h);
  EthernetClient client = server.available();
  if (client) {
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (c == '\n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/json");
          client.println("Connection: close");
          client.println("Refresh: 0");
          client.println("");
          client.println("[");
          client.println("   {");
          client.println("    \"dht11\": {");
          client.print("          \"temperature\": ");  client.print(f);        client.println(",");
          client.print("          \"humidity\": ");         client.print(h);        client.println(",");
          client.print("          \"heat-index\": ");   client.print(hif);  client.println("");
          client.println("     },");
          client.println("    \"thermistors\": {");
          client.println("        \"under-bed\": {");
          client.print("             \"temp\": ");          client.print(tempreading);      client.println(",");
          client.print("             \"resistance\": ");    client.print(average);  client.println("");
          client.println("       },");
          client.println("        \"side-bed\": {");
          client.print("             \"temp\": ");          client.print(tempreadtwo);      client.println(",");
          client.print("             \"resistance\": ");    client.print(average_two);  client.println("");
          client.println("       },");
          client.println("        \"top-bed\": {");
          client.print("             \"temp\": ");          client.print(tempreadthree);        client.println(",");
          client.print("             \"resistance\": ");    client.print(average_three);    client.println("");
          client.println("       }");
          client.println("     }");
          client.println("   }");
          client.println("]");
          break;
        }
        if (c == '\n') {
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          currentLineIsBlank = false;
        }
      }
    }
    delay(1);
    client.stop();
  }
}

I have no idea what is causing this to happen - pushing RESET doesn't fix it at all, reconnecting wires does not fix it, any help?
(Please tell me what else to include if you need it.)

Your code would help somewhat...

@Majenko - added (ignore any redundancy in the code, i should really clean it up but i'm trying to fix it before i do that)

I suggest you write a function to do the maths. Having multiple lines of redundant code hinders investigations.

@NickGammon I found another piece of code that used different maths, but put it in a function - https://gist.github.com/viktorahlstrom/af1ebe275d54df104bdc

Looks a lot simpler. :)

Here's a major problem:
void loop() {

  uint8_t i;
          float average;
          float average_two;
          float average_three;
          float stuckintime;
          for (i = 0; i < NUMSAMPLES; i++) {
            samples[i] = analogRead(THERMISTORPIN);
            samples_two[i] = analogRead(THERMISTORPIN2);
            samples_three[i] = analogRead(THERMISTORPIN3);
            delay(10);
          }
          for (i = 0; i < NUMSAMPLES; i++) {
            average += samples[i];
            average_two += samples_two[i];
            average_three += samples_three[i];
          }

The variables average, average_two, and average_three have undefined values. Thus it isn't surprising that when you add something to them, they are still undefined.
Local variables must be initialized (eg. to zero in your case).
Also, you have two variables named stuckintime - I would do something about that.


text:
RC servo misbehave using arduino and MPU6050
I am a beginner.. I am trying to control RC servo using Arduino based of data from MPU6050.
I am using library I2Cdev to communicate with gyro and to get yaw, pitch and roll. I am using example script which I have modified to control servo based on received data.
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

Serial.print("ypr\t");
Serial.print(ypr[0] * 180 / M_PI);
Serial.print("\t");
Serial.print(ypr[1] * 180 / M_PI);
Serial.print("\t");
Serial.println(ypr[2] * 180 / M_PI);

pitch_angle = (ypr[1] * 180 / M_PI) + 90;
roll_angle = (ypr[2] * 180 / M_PI) + 90;

Serial.print(pitch_angle);
Serial.print("\t");
Serial.println(roll_angle);

pitchServo.write((int)(pitch_angle));
rollServo.write((int)(roll_angle));

Without servo being connected everything works well.
But after I plug in servo after few second being still (it seems to even follow movement of gyro) it starts to shake and then probably whole Arduino stops working (serial transmission of data stops) and Arduino has to be restarted.
100 95
ypr 12.21   10.51   5.49
100 95
ypr 12.23   10.31   5.48
100 95
ypr 12.25   10.15   5.45
100 95
ypr 12.27   10.02   5.45
100 95
ypr -13.31  30.81   55.76
120 145
ypr 20.53   -21.36  -52.59
68  37
ypr 64.96   35.38   10.25
125 100

I tried to plug two 100 nF capacitors across power and ground of the servo and I tried to connect servo in to different power source than Arduino.
EDIT:
Servo is not fixed with MPU6050 so there shouldn't be any resonance at least on the mechanical base.
Wiring is very simple:

Any idea? Thanks

Is the mpu6050 mounted on the servos or in a fixed position?

Please show your wiring. If it stops when the servo is connected it sounds like it is not getting enough power. If you tried a different power source, did you connect the grounds together?

I have just edit my question.. Thanks for effort.

As far as I can see from the photo, if you have the different power source connected (out of photo) it is also connected to the Arduino power (it is hard to tell). The external power should go to the servo only, not the Arduino. However the grounds need to be connected.

sorry for the photo - there is no external power source .. breadboard is connected straightly to the arduino

At the end two pull-up resistors and one capacitor solved the problem.
I followed instruction here:
http://www.instructables.com/id/Brushless-Gimbal-with-Arduino/step3/Using-the-Accelerometer-and-Gyro/
Now it works well.. Thank you all.


text:
ATtiny25 - assembly - BOD disable for sleep mode - error
If I understood the AVR instruction manual correctly, the ATtiny 25 can disable the BODlevel2 fuse by software, but when compiling with Studio 7 (version 7.0.132), I get the error "Undefined symbol: BODS & BODSE".

BODLEVEL fuses are set correctly. L:0x62 H:0xDD E:0xFF

; init brown out detection disable for sleep mode
        ldi     r23, (1<<BODS)|(1<<BODSE) ; En 2 fois 1- pour autoriser ecriture
        out     MCUCR, r23                ; Envoyer autorisation ecriture
        ldi     r23, (1<<BODS)|(0<<BODSE) ; Ecrire valeur a envoyer dans R23
        out     MCUCR, r23                ; Envoyer R23 dans MCUCR

; init WDT for interrupt mode
        ldi     r23, (1<<WDCE)|(1<<WDE)
        out     WDTCR, r23
        ldi     r23, (1<<WDIE)|(0<<WDE)|(0<<WDP0)|(1<<WDP1)|(0<<WDP2)|(0<<WDP3) ; sec time out WDT interrupt; no system reset
        out     WDTCR, r23
        sei                   ; global interrupt enable bit is active

L1_INTERIEUR:                 ; init sleep modes
        ldi     r23, (1<<SM1) ; Power-down mode
        out     MCUCR, r23
        in      r23, MCUCR
        ldi     r23, (1<<SE)  ; sleep mode enabled
        out     MCUCR, r23    ; put MCU into sleep

L1A_INTERIEUR:
        in R15,SREG
        wdr
        sleep

which AVR instruction manual are you referring to? ... which section?

So the assembler doesn't recognize "BODS" symbol, as those "bit names", unlike registers or instructions, are the part of user manual existing for human convenience only. What's so surprising? Use numbers or define symbolic constants yourself...

run cat iotn25.h | grep BODS in where the toolchain is stalled give me this #define BODS    7, and #define BODSE   2.

@hcheung What does some C include file do with assembler?

@Matt, it define the bit position of BODS an BODSE bit in the MCU Control Register of the ATtiny25 that is used in the assembly.

@hcheung And so? Assemblers can not read C include files. While humans can read user manuals as well.

@Matt Of course this is possible. The GCC frontend pipes the assembler source through the preprocessor before giving it to the actual assembler, if the file extension is upper-case "S". Been there, did it.

@matt, we are all here to help OP who don't know the answer. I provided the value of what those values should be and where to find it. It is way better than "What's so surprising, define yourself"...  Sometime one have to admitted you don't know what you don't know... +1 for me as per the busybee, been there, done that.

The Microchip Studio uses the GNU toolchain or the XC8 toolchain. Unfortunately you did not tell us, which you use for your project.
The common solution is to include the corresponding header file to let the preprocessor replace the symbols with the defined values:
#include <iotn25.h>

; init brown out detection disable for sleep mode
        ldi     r23, (1<<BODS)|(1<<BODSE) ; En 2 fois 1- pour autoriser ecriture

; ...

Or to add "iotn25.h" to the dependencies in the "Solution Explorer".
Now you need to make sure that the preprocessor runs before the assembler. Both toolchains behave identically, if you name the assembler source with an uppercase extension of ".S".
The GNU toolchain does this according to its documentation:

You can use the GNU C compiler driver to get other “CPP” style preprocessing by giving the input file a ‘.S’ suffix.

For the XC8 toolchain, the documentation tells us explicitly about this and an interesting option in chapter 8.3.4.1:

The -x assembler-with-cpp language option ensures assembly source files are preprocessed before they are assembled, thus allowing the use of preprocessor directives, such as #include and C-style comments with assembly code. By default, assembly files not using the .S or .sx extension are not preprocessed.


text:
RTC DS1307 module not working
I have a problem with an RTC: it doesn't work correctly. When I try to read date or time, I only see the characters "àààààààà" or or the program is blocked.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <RTClib.h>

DS1307 rtc;
DateTime rtcTime;

void setup() {
  //zainicjowanie generatora liczb losowych
  randomSeed(A0);
  Wire.begin();
  rtc.begin();
}

void loop() {
  rtcTime = rtc.now();
  int mm = rtcTime.minute();
  Serial.println(mm);

  delay(500);
}

This function blocks my program:
String timeRTC(){
  DateTime now = rtc.now();
  String Hour = "0" + String(now.hour());
  String Minutes = "0" + String(now.minute());
  String Seconds = "0" + String(now.second());

  if (Hour.length() == 3) {
    Hour = Hour.substring(1);
  }
  if (Minutes.length() == 3) {
    Minutes = Minutes.substring(1);
  }
  if (Seconds.length() == 3) {
    Seconds = Seconds.substring(1);
  }

  return Hour+":"+Minutes+":"+Seconds;
}

I can't find what is causing this problem. I use an Arduino Uno in the WOKWI emulator.
String dateRTC(){
  DateTime now = rtc.now();
  String Day = "0" + String(now.day());
  String Month = "0" + String(now.month());
  String Year = String(now.year());

  if (Day.length() == 3) {
    Day = Day.substring(1);
  }
  if (Month.length() == 3) {
    Month = Month.substring(1);
  }

  return Day+"-"+Month+"-"+Year;
}

String timeRTC(){
  DateTime now = rtc.now();
  String Hour = "0" + String(now.hour());
  String Minutes = "0" + String(now.minute());
  String Seconds = "0" + String(now.second());

  if (Hour.length() == 3) {
    Hour = Hour.substring(1);
  }
  if (Minutes.length() == 3) {
    Minutes = Minutes.substring(1);
  }
  if (Seconds.length() == 3) {
    Seconds = Seconds.substring(1);
  }

  return Hour+":"+Minutes+":"+Seconds;
}

Could you provide a link to your WOKWI project?

I use free version of WOKWI. This is link for my project: https://file.io/y1XjwyqHjhNk

The link says “The transfer you requested has been deleted.”

I shared the file again:  https://easyupload.io/b0e4w8

What do you mean by "blocked my program"?

Where is the Serial.begin() specifying the used baud rate? And it seems, that the function  timeRTC() is not used in your program, so how does it block the program?

Unresponsive/frozen program.

I modified it many times trying to solve the problem, hence the shortcomings in the code. I have included two RTC functions in the main post

You don't have a problem with the RTC: if you call Serial.begin() in
setup(), and remove everything in your loop() after
Serial.println(mm);, the program works as expected. Your problem is
elsewhere. Most likely you are corrupting memory, which leads to
unpredictable behavior.
Side note: if you switch to Adafruit's RTClib (called simply “RTClib” in
the library manager), you can simplify timeRTC() to this:
String timeRTC() {
    return rtc.now().timestamp(DateTime::TIMESTAMP_TIME);
}


text:
Is it possible to use analogWrite() using an external Power Supply Unit?
As far as I know, my Arduino Nano can perform analogWrite() ranging from 0 to 1023 for 0 to 5 V respectively, but I want to control a DC motor which requires 9 V for good performance. Is it possible to do so?

Yes, that is possible.
analogWrite() sends out a 5 V PWM signal (3.3 V on some Arduinos) from a pin. You can't use this PWM signal to drive a motor directly; an Arduino IO pin can't deliver enough current for that.
You will have to get a separate 9 V power supply that can supply enough current for the motor, and use a BJT or MOSFET to switch that 9 V with the PWM signal from the Arduino, or use a dedicated motor driver IC or module.
There are plenty of schematics for this on the interwebs.


text:
Arduino sketch behaves differently depending on version of Arduino IDE
I am assisting some friends on an Arduino Uno project, and we've noticed that when using some earlier versions of the Arduino IDE (In this case 1.0.5), the sketch behaves as desired. However, when using 1.6.5, the program behaves differently. The sketch in question is here:
https://github.com/CymaSpace/Programs---Sketches/tree/master/Tim%20Gorbunov/a3%20with%20monosetting/a3
I have noticed that when enabling verbose compilation output, the size of the compiled binary is different between the two different IDE versions. There are also some warnings in the older IDE that are not present in the newer version. There is at least one other version before 1.6.5 that is behaving the same way as 1.0.5 (it's a later version but at the moment I don't know which, I will see if I can find out and post it here later).
Any idea why the two sketches might be behaving differently and how to go about troubleshooting the problem? This occurred on both a windows and mac computer. Thanks!

Because they're using different versions of the compiler.

@IgnacioVazquez-Abrams Is there a way to rectify the differences or at the very least to figure out what has changed between the two compiled sketches?

You can use avr-objdump to disassemble the compiled binaries.

Could you be more specific about how the behaviors differ? Maybe you can pinpoint the specific function that is behaving differently? You could try to disassemble and look for the differences, or upload the ELF files somewhere to get help on this.

The sketch is intended to display colors on a strip of WS2812b's based on sound input from two MSGEQ7's. In the older version, the animations stop when there is no more audio input. In the new version, the animations continue even if there is no input coming in. This is somewhat of a simplified explanation. I'm thinking that the code likely needs to be refactored, as there are a few flaws that were pointed out that could be making the sketch behave erratically. After refactoring the code, I will retest it and if it's still having problems, I'll upload the ELF files and disassemble the binaries

There are also some warnings in the older IDE that are not present in
  the newer version.

It is a huge mistake to disregards those warnings, especially:

warning: array subscript is above array bounds

You declared an array int useColor[2]. Its length is 2 and its indices
can be either 0 or 1. Yet you are using useColor[2], which is out of
bounds and likely to corrupt memory.
From the language point of view, this is called undefined behavior,
which means that anything can happen. In particular, it could very
well happen that the program behaves as you expect... which seems to be
the case with IDE 1.0.5. Simply changing the compiler version, or event
the compiler settings, can change the behavior.

Good point. I think the best thing to do at this point might be to revisit the code, clean it up, resolve any errors, and make sure there isn't any undefined behavior. It might be a waste of time to compare the binaries if the code has inherent problems. I'm going to try to refactor some of it and see if the discrepancy still exists. Thanks for the tips and for catching that array out of bounds problem!

@Hendeca: I tried some minimal cleanup on your code. Check your github repo for the pull request.

Thanks very much! Very helpful. We will test this out and keep refactoring from there. Also, this is collaborative and I was unaware that this is an earlier version of the code. I'll edit the question to point to the new version of the code. I will likely just do the same changes you made in your pull request to the newer sketch. If you so desire, feel free to put in another pull request on the new sketch. Sorry about the confusion and thanks again for your help, it's much appreciated!

The original code was contributed to by many different people over a long period of time. I went through and completely refactored and cleaned up the code. It now works and I believe that the array out of bounds problem was likely the culprit. To me it explains most reasonably why it would behave so different between two different compilations on different versions of the Arduino IDE. Accepting this as the correct answer. Thanks!


text:
Arduino Due for camera control?
Could one use the Arduino Due to control camera module like OV5642 and send the data to spi device? My project is to capture image with OV5642 and then to send the image data(RGB565) to other device via spi. For this STM32 must be enough, but I'd be happy if I can use the arduino IDE. Because it is much easier to program.
Could you please let me know, if you can use the Due for this task?

The DUE doesn't have lots of memory. Depending on what you want to do, that might also be a constraint. You should detail more what you want to do.

What I want to do is to take a bayer-raw image data from OV5642 camera module and then send the data to beagle bone black or whatever via spi. If it is needed, I can use frame buffer or RAM.

Why not connect the camera directly to the BBB?

http://stackoverflow.com/questions/23860620/interfacing-with-a-custom-camera-in-linux-on-the-beaglebone

yep, the arduino seems to be totally redundant in this scenario.

ah... I didn't want this situation. Actually what I'm going to use is not the BBB. It was just an assumption. The spi master will be some board not using MCU. So the question is, is the Due capable of taking and sending 5MP data? I didn't know that this is so difficult question to understand.

And please note that I'm not meaning Uno. This is ARM arduino

I'm voting to close this question as off-topic because it is an old question which has been abandoned for years without the specifics to make it answerable ever having been provided.  The only "answer" is really a comment to this fact, and none better are likely to be possible.

You are still not giving the full picture, pun intended.
I'll give you an example of what sort of info is missing.
For example, what's the frame rate? What's the color depth of the sensor?
If you look at the SAM3x TRM, it says that the SPI is clocked at max 65MHz.
So, the (simplified) math would say:
24bit/pixel * 5Mpixel / 65MHz =  1.846 seconds
And that doesn't even account for acquisition time, so if you do not have fully working DMA on both sides, it's probably even worse.
And it will be worse, because you cannot stuff in RAM in one go the entire image.
But maybe that's good enough for you, however it's not possible to say because of the missing info.


text:
Using arduino Due for camera control
Could the arduino Due take and send image data from 5MP camera module to PC in the following condition?

frame rate = 1fps
resolution = 2592 x 1944
format = 10 bit bayer raw RGB
interface : parallel ports (DVP) between camera and Due
           spi between Due and PC(or SD card)
FIFO(frame buffer): would not be used
SDRAM: would not be used
(But if it is needed, I would SDRAM via spi. Also I can use a frame buffer like AL422B. But if it is possible I would avoid using them.)

The camera would send 50Mbit image data per second and they will be transferred via 8 parallel lines(D0~D7) to the Due. And then they would go to PC directly or after passing SDRAM. But how can one evaluate if the 84Mhz is enough to do this job by calculation?
Arduino Due specs
https://www.arduino.cc/en/Main/arduinoBoardDue
camera module example (OV5642)
http://www.uctronics.com/cmos-camera-adapter-board-for-omnivision-image-sensor-p-248l.html
But this is not what I want to use. In my project I need to build a camera module and it would not include FIFO unless it's highly recommended.

So a quick feasability assessment:
2592 W * 1944 H * 10 bit = 50388480 bits
50388480 bits / 8 bit data bus = 6298560 packets
84000000 clocks per second / 6298560 packets = ~13 clock cycles per packet
I think that by itself, from a purely data perspective, without looking too deep into datasheets, you could feasibly read data from a port and push it out the USB port, and clock the data in less than 13 cycles. But what this means is you'd have to get into the nitty gritty of the processor and figure out how to do that as low level as possible because DigitalRead() and Serial.print() aren't going to cut it as they won't be fast enough.
The real challenge is that the above totally depends on being able to clock the data from the sensor yourself, which if I recall correctly, these sensors can actually be pretty picky about their clock.
I would highly recommend a FIFO, that way the sensor data can be clocked to it as fast as it wants to be clocked, and then you could read from the FIFO at your own pace as it will clock data out at exactly the rate you want it. Also 1 FPS is a pretty lofty goal if you are only a beginner. Like I said, it is probably possible, but it requires a lot of optimizations and planning that are not very straightforward to implement, especially if you are just starting out.

Thank you for the reply. But I wonder if it is possible for the ARM to 'save' data on sdram or sd card via spin. It seems there are more factors I should care. Like interrupts in cpu causing data loss.

There is no such thing as SPI connected SDRAM. You could write the data to an SD card, but the data throughput on that is going to be much slower than what you'll be reading the data at. In that case I would once again recommend using a FIFO, that way you can read from it at the same speed you are writing to the card.


text:
Adjust time calculation after Timer0 frequency change
I have an Arduino Nano with an 328P and need all 6 PWM pins.
Thus, I had to adjust the prescaler and WGM Mode of Timer0.
It is now in phase correct PWM mode with a prescaler of 1.
TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
TCCR0B = _BV(CS00);

Now I need a working time calculation for other libraries, but since
Timer0 had that duty everything is out of order now.
I tried adjusting the wiring.c
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

to this
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 510))

But it's like I didn't change anything.
(tested other settings that were changed so it was compiled anew )
Whole Code:
void setup() {

  // Set Timer 0, 1 and 2
  // Register A: Output A and B to non-inverted PWM and PWM mode to phase correct.
  // Register B: Pre Scaler to 1.
  TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
  TCCR0B = _BV(CS00);

  TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
  TCCR1B = _BV(CS10);

  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20);
  TCCR2B = _BV(CS20);

  pinMode(8, OUTPUT);

}
void loop() {

  digitalWrite(8, LOW);
  delay(65000);
  digitalWrite(8, HIGH);
  delay(65000);

}

All of your settings are correct. My best guess if you maybe modified the wrong wiring.c. The best way to diagnose this is to go to File > Preferences and check the compilation checkbox under "Show verbose output during". Then click verify, copy the output into a text editor and search for wiring.c and see where it is pulling it from, then open the file and verify that your changes are there.

When I clean the tmp folder and verify anew he shows:
This.
And that is also the wiring.c I corrected :(

I don't know what to say, by all means that should work. Another option would be to just scale the times yourself. You could wrap this in a macro a la #define SCALE_UP(x) x<<6 and then use it like such delay(SCALE_UP(1000))

That is the weird thing, the real value seems to be really arbitrary.
I tried two nanos and one Uno, both have the same results.
And when I try to calculate the the value for delay I get 64000, but when I
insert that it's only like 800ms instead of 1000ms. For testing purpose I already threw out all #includes it's just the Register change and digitalWrite and delay now.

How are you measuring? Do you have an oscilloscope by chance?

No I don't have one.
I have an LED that blinks with the code above and now I added
a Serial output to the arduino IDE. When I put the delay at 200000 I get approx. 1050ms

Oh I just noticed... when I can use millis() to measure the, well, millis and they seem correct, then this implies that the internal timekeeping is alright.
Just delay seems to have a bug. sigh
Anyway. Thanks for helping Jake!

Ah, that makes sense due to how these functions are set up in wiring.c. Can you try something for me, try running delayMicroseconds(1000000); and let me know if that is more accurate.

Also, what version of Arduino are you using?

It seems that delayMicroseconds() has the bug aswell. it doesn't even cause a ms delay.

Strange, delayMicroseconds() uses a different mechanism than delay() so I was wondering if it might not be affected by this. I've posted an answer summarizing our findings.

It seems that delayMicroseconds() has the bug aswell. it doesn't even cause a ms delay. - Please post code that supports this assertion.

The code from above, just replace the delay(65000) with delayMicroseconds(). I put the value to 16000000L because I have a 16Mhz CPU. The LED just looks dim, but doesn't turn off and on every second. If I compare it with a simple millis() - startMillis the delay takes 5ms with 16000000L and 9ms with 128000000.

Fixing the timekeeping functions with your PWM settings is not so
simple. You should at least try to rewrite ISR(TIMER0_OVF_vect),
micros(), and probably delay(). Here is why:
First, there is a rounding problem. Time is kept using two global
variables:
volatile unsigned long timer0_millis;
static unsigned char timer0_fract;

The first one is what millis() returns. The second one keeps track of
how much time has passed since the last full millisecond, and it does so
in units of 8 µs. The two variables are incremented by
ISR(TIMER0_OVF_vect) like this:
m += MILLIS_INC;  // temporary copy of timer0_millis
f += FRACT_INC;   // temporary copy of timer0_fract

On a normal Uno configuration, the ISR is called every 1024 µs.
Then MILLIS_INC is 1 and FRACT_INC is 3. With your timer
configuration, the ISR is called every 31.875 µs (510 cycles), then
MILLIS_INC should be 0 and FRACT_INC should be 3.984375. But since
we are dealing with integers, it will be rounded down to 3, and your
millis() will tick about 25% too slow.
A simple fix would be to
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 512))

in order for FRACT_INC to be 4 and millis() to be 0.4% too fast. Or
you could make timer0_fract a 16-bit variable and have it count clock
cycles, just to avoid this error. Either option should fix millis(),
but you still have a problem with micros().
micros() works by reading both timer0_overflow_count (incremented by
1 in the ISR) and the actual counter value. Since your counter is now
going alternatively up and down, it will be harder to compute a
microsecond count from these readings. Maybe you could take two
consecutive readings of the counter, just to know whether it is going up
or down...
And then there is delay(), which relies on micros(). If you fix
micros(), delay() should work fine. If not, You could rewrite
delay() to use millis() instead, which should be easy but you will
loose some accuracy.

Thanks for the sophisticated answer! At this point also thanks to @jakec for discussing the problem with me!

Since your counter is now going alternatively up and down Why is the TCNT0 going up or down? It's going up and every time it overflow the ISR is called. Am I missing something? I tried to solve this by increasing the timer0_overflow_count once every 64 times only, and on the micros() function return the time as return ((m << 8) + (t % 64)) * (64 / clockCyclesPerMicrosecond()); So I do a mod on the TCNT0 counter as my Timer is ticking 64 times faster. But although the micros() seem to be ok delay() is still running faster and I'm not understanding why...

@Lefteris: The counter is going up and down because the OP configured it in “phase correct PWM” mode.

Correction on the above, modulo was wrong, I'm dividing by 64 on the return function now: return ((m << 8) + (t/64) ) * (64 / clockCyclesPerMicrosecond()); Still the problem remains with delays function which I don't understand

@EdgarBonet If I have understood correct, the TCTN0 register increases every CLK/64 tick. So it is only going up. It is reset every time it overflows and TIMER0_OVF_vect ISR is called. So still not understanding what phase correct PWM has to do with this.

@Lefteris: Read the datasheet: “The Phase Correct PWM mode is based on dual-slope operation: The counter counts repeatedly from BOTTOM to TOP, and then from TOP to BOTTOM.”

@EdgarBonet Yes I've just read this. Thank you

THIS IS AN INCOMPLETE ANSWER - Edgar knows what he's talking about, listen to him
I am currently working with this same thing but in an ATMega2560. This website helped me understand the millis() function better. The timer overflows every 510 counts (see datasheet, pg 123 for the atmega2560). I believe it is 510 and not 512 because it counts up and down, but does not repeat a count at the top or bottom - for example if you count starting from 1 up to 10 and then back down (without repeating 10) you will have counted 19 times, not 20. This counter starts at 0, counts to 255, and then back to 0, triggering an overflow before hitting 0 again. This is is 256 (count up including 0 and 255) + 254 (count down, not including 255 or 0) = 510.
I wrote a python script to visualize the effect of these changes and trying to account for them. This counts to 10 million, so it takes time to run, but by the end, even with scaling, the error if simply adjusting millis() after the fact could be ~7 seconds.
#! /usr/bin/env python
import numpy as np

realT = np.zeros(10000000)
timer0_millis = np.zeros(10000000)
timer0_fract = np.zeros(10000000)
i=0

for i in range (1,10000000):
    timer0_millis[i] = timer0_millis[i-1] + 1
    timer0_fract[i] = timer0_fract[i-1] + 3
    realT[i] = i*31875
    if timer0_fract[i-1] >= 125:
        timer0_fract[i] = timer0_fract[i-1] - 125
        timer0_millis[i] = timer0_millis[i-1] + 1

adjusted = timer0_millis*510/(256*64)

print "after 100 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[99], realT[99]/1000000, adjusted[99])
print "after 1000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[999], realT[999]/1000000, adjusted[999])
print "after 10000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[9999], realT[9999]/1000000, adjusted[9999])
print "after 100000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[99999], realT[99999]/1000000, adjusted[99999])
print "after 1000000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[999999], realT[999999]/1000000, adjusted[999999])
print "after 10000000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[9999999], realT[9999999]/1000000, adjusted[9999999])

You wrote: “I believe in phase correct mode the timer overflows every 510 counts, not 512 as indicated by Edgar”. Please, read my answer again, and do not misquote me.

Sorry, I was refering to this line "#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 512))" - I have updated my comment, correct me if I am wrong here, I didn't intend to misquote

There is a very good reason for having 512 instead of 510 in this line. Read my answer and you will understand.

Okay, so you are adding two timer counts, each being 62.5ns, to account for the error caused by the forced round-down?

In my application I could not modify wiring.c, so as a quick fix I inserted a coefficient to scale relative values returned from millis(). With that said I was trying to model what my changes looked like compared to the proper fix - which I count this as. Also, does this error matter as much when millis() is used for relative timing, such as now=millis() and while(millis() - now < 100) (i.e. is it a constant error or does it vary; can it be used to scale the condition)?

Yes. With 510, rounding makes millis() 25% too slow, whereas 512 makes it 0.4% too fast. As for your second question, you may try to formulate it as a proper question, and show in code how exactly you “inserted a coefficient”.

If it is 25% too slow, could this account for the error: now=millis() and then while(millis() -now < x*100) with x=4/3? I'm sorry, this is my first time posting on this forum and I thought I had included some useful information, but I guess I should leave the answers up to the experts.

Edgar, if you would like to continue helping me I decided that instead of answering a question with questions of my own and potential misinformation I would ask a question

Thanks to Edgar's answer and Nebsie's explaination on how the counter exactly works I could come up with my own implementation of how to rectify delay and micros() that - so far - seems to work fine on my Arduino Uno.
I'm not saying that this is the most precise implementation, especially I have my doubts on micros() if for example an timer overflow occours between reading t1 and t2, but it is one that so far for me works well.
First thing - according to Edgar's recommendation I defined:
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 512))

However this doesn't affect timing of micros() or delay().
Function micros() I changed to read two times from TCNT0 - to determine whether it is counting upwards or downwards. This is done with the "if (t1 > t2)" clause. The overflow count "m" is multiplied by 510, because the counter elapses after 510 steps. Then the calculated counter value "t" is added to this, divided by the number of clocks per Microsecond. (Note: Prescaler = 1, therefore no further multplication).
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t1, t2;
    uint16_t t;

    cli();
    m = timer0_overflow_count;
#if defined(TCNT0)
    t1 = TCNT0;
#elif defined(TCNT0L)
    t1 = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

#if defined(TCNT0)
    t2 = TCNT0;
#elif defined(TCNT0L)
    t2 = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

    if (t1 >= t2) {
        t = 510 - t2;       // counter running backwards
    } else {
        t = t2;             // counter running upwards
    }

#ifdef TIFR0
    if ((TIFR0 & _BV(TOV0)) && (t2 > 1))        // if overflow flag is set -> increase m
        m++;
#else
    if ((TIFR & _BV(TOV0)) && (t2 > 1))
        m++;
#endif

    SREG = oldSREG;

    return ((m * 510) + t)  / clockCyclesPerMicrosecond();
}

HOWEVER - this seems to work fine but I had issues to begin with (before editing this again). Due to the counter running much faster, every 268 seconds the unsigned long datatype of micros() overflows and starts from zero again. This led to an unwanted lockup of delay(), especially if long delay times, like in my case delays of one second per loop iterations are used. Therefore I also had to add an overflow detection to the delay() function in arduino wiring.c.
If the overflow occurs, timing might not be very precise. But since this is once overy 268 seconds it may be acceptable. So far with this change the delay function works fine again on my side.
void delay(unsigned long ms)
{
    uint32_t start = micros();
    uint32_t elapsed = 0;

    while (ms > 0) {
        yield();
        while ( ms > 0 && (micros() - 1000) >= (start + elapsed)) {
            ms--;
            elapsed += 1000;
        }
        if( start > micros() ) {    // overflow detected
            start = micros();       // reset start
            elapsed = 0;            // reset elapsed
        }
    }
}

You have set MICROSECONDS_PER_TIMER0_OVERFLOW to a proper value, however, this is only ever used by MILLIS_INC, which in turn is only ever used by millis(). This means that the other timing functions, such as micros(), delay(), delayMicroseconds() break when timer0 is changed. This is kind of a bug, and it may be fixed in a future version, but for now, the Arduino libraries are expecting you to leave timer0 alone. The best workaround is to only use millis() for your timing critical functions.


text:
How to change the direction of a stepper motor using the AccelStepper library?
I'm using a Nema 17 stepper motor (200 steps) and a DRV8825 motor driver. This is the configuration I am using:

I am using a 9 V power supply. The dirPin is connected to pin 3 on the Arduino board, and my stepPin to pin 2.
What I'm trying to do is move the motor 100 steps clockwise and then move it 100 steps anti-clockwise, so that it returns to the starting position. This is the code I am using:
#include <AccelStepper.h>

#define dirPin 3
#define stepPin 2
#define motorInterfaceType 1

int SPR = 200;

AccelStepper stepper(motorInterfaceType, stepPin, dirPin);

void setup() {
  pinMode(dirPin,OUTPUT);
  pinMode(stepPin,OUTPUT);
  // put your setup code here, to run once:
  stepper.setMaxSpeed(200);
  stepper.setAcceleration(30);
}

void loop() {
  // put your main code here, to run repeatedly:
  stepper.moveTo(100);

  stepper.runToPosition();
  delay(1000);

  stepper.moveTo(-100);

  stepper.runToPosition();
  delay(1000);
}

I have two issues:

Before moving the motor 100 steps, it moves a couple of steps (like 15°), and then it starts moving, first 100 steps, and then 200 steps. That would be the first iteration, and I don't understand why it moves those 200 steps. And then, in the following iterations, the motor just moves 200 steps.

It only moves in one direction. I can't get it to move anti-clockwise.

the wiring diagram shows connections different from the code

Just been troubleshooting something similar, where stepper only moves one direction. Turned out my arduino was the problem - the dir pin was 1v low, 3v high instead of 5v like it should've been.

The moveTo() function takes absolute positions, so if you want to move in both directions, you should adjust the target positions accordingly.
You can modify your loop() function as follows:
void loop() {
  stepper.moveTo(100);
  stepper.runToPosition();
  delay(1000);

  stepper.moveTo(0); // Move back to the starting position
  stepper.runToPosition();
  delay(1000);
}


text:
Unable to find PCA9685 module when using the I2CScanner library: no servo movement
I am trying to use an Adafruit PCA9685 servo driver module with an ELEGOO Mega 2560 board.
I am supplying the servo driver board with 5 V and tested all the wires to make sure. I tested the servo without the board and it works fine.

I2CScanner code:
#include "I2CScanner.h"

I2CScanner scanner;

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

    scanner.Init();
}

void loop()
{
    scanner.Scan();
    delay(5000);
}

What exact board is this? Looks like an Arduino Due, in which case you would be using the wrong pins. Try to use the pins labeled "SCL" and "SDA".

@PMF the exact board i am using is the elegoo mega 2560 and have put the pins in the "SCL" and "SDA" near the "AREF"

I'm not exactly sure about this board, but have you tried the other pins marked "SCL" and "SDA" (Pin 20/21 I think, near the green Led)

@PMF It should be the exact same as the Arduino Mega 2560, I have tried those pins also the older version "A4" and "A5" pins but it still didn't detect anything. Thx for helping btw.

what is the result when you run the code? ... please copy and paste into your post... no pictures please

@jsotola --- Scan started ---
No I2C devices found
--- Scan finished ---

The library you're using there looks ok, but just to be safe: Have you tried to use the standard I2C sample program instead? It's under Examples->Wire->WireScan. Try also with Wire1 instead of Wire.

Insert Wire.setClock(31304); after scanner.Init(); and say whether or not that makes any difference to output. You say "I am supplying the servo driver board with 5 V". Is that what the orange wire is plugged into? I can't tell from the picture.

The I2C bus needs a set of pull up resistors. When buying assembled I2C devices, the designer may include I2C pull up resistors but not connect them. This is because, according to this sparkfun.com tutorial, you only need about 4.7K Ohms of pull up resistance. Adding multiple I2C boards to the same bus all with their own pull up resistors will lower this resistance and may damage I2C drivers. So, it is up to the end-user to decide which I2C board to connect the pull up resistors on.

The breakout manufacturer (Adafruit in this case, I think) would write if that was necessary. But they explicitly state that it already has pullups.