text:
What is the purpose of Galileo (or other unremovable chips)
I know the Arduino is a nice quick and dirty prototyping board. You quickly test your idea, and if you want to proceed you can do so with AVRs.
Your options are:

Upload the program to Arduino, then remove the AVR chip and make a PCB (with the bootloader)
Start from scratch with AVR (not always feasible because many libs are in Arduino)

Now what is the purpose of a system that has processors that cannot be removed? For example the Arduino Galileo.
Sure, you can do many things with it, but bottom line, you cannot remove the processor and do something with it.
As an example, imagine you are prototyping a system you wish to, then, market and sell. That is feasible with the Arduino Uno family.
But what if you did in in Galileo? Even if it worked, you couldn't sell your system because you rely on the prototyping board. You cannot remove the processor.
Am i missing something?

Edit: As Chris points out, this answer is more about the simple AVR Arduinos. For comment on the Galileo and other more complex MCUs, please refer to Chris' answer.
For Arduino compatibility you can program the Arduino boot loader into the microcontroller using the ICSP pins. You do not need a chip from an Arduino board, you just solder a blank one in. Once the boot loader is on there you can use the Arduino IDE to upload sketches via the UART.
It is not necessary to use the Arduino system to write programs. You include the Arduino library files in a normal C++ project in many different IDEs and use the avr toolchain to compile and avrdude to upload.
Update:
Here is an example of a board I just got back from PCBA. (The picture was sent by the PCB company for checking). Initially I made the board using an Arduino Pro Mini 3.3V, SD card breakout board, LSM303DHLC accelerometer breakout from Pololu, and Real Time Clock (RTC) breakout. Once everything was working I drew up a PCB in Eagle CAD, using the core of Arduino Pro Mini board plus the individual SD card, LSM303DLHC and RTC chips. I also added a 3.3V boost converter so I could get a constant 3.3V off 2 AA batteries.

The board has the ICSP pins broken out. Actually, you will find they are broken out on most Arduino boards. Using another Arduino as ISP I can program the Arduino boot loader via the ICSP pins, and then sketches can be uploaded via the UART using the Arduino IDE. In the IDE the board that is selected is "Arduino Pro Mini 3.3V 8MHz".
The Arduino boot loader is a small piece of firmware that runs on startup. It allows you to send a program over the UART which it stores into FLASH memory itself. It is not absolutely necessary. You can program the chip using the ICSP as well. It is really convenient however. Using software like xloader you can upload Arduino programs without the IDE. Really handy when other people are using the board and you don't want to share your code. Alternatively, you can write a script for avrdude to do it.
This project is for a university so I'm leaving it as Arduino compatible. In a commercial engineering environment, I would choose a more appropriate MCU (one with lower power consumption for a battery device) and rewrite the program to be more efficient and not rely on the Arduino and third-party libraries.

Would the drive-by down-voter care to explain? This answer is right on - I build projects exactly this way. I even prototype with an Arduino Mega 2560, then recompile for, and download to a bare ATMega328p on my project board. A few #defines manage the pin assignment differences. --
A compensating upvote from me.

thanks geometrikal and jRobert. never worked with the ISCP pins before, but it seems like a fairly easy process.

Not the downvoter, but worth noting that while this is a nice generic answer, it's mostly about the 1/2-layer suitable AVR based Arduinos.  The Galileo cited in the question is an x86 based computer module in a drastically different league of capability and manufacturing complexity.

The pentium-class x86 based Galileo mentioned in the question title appears intended to meet project needs which have (memory, compute, or interface) requirements beyond the capability of the simple AVR (or perhaps even ARM) based Arduino boards.   It's not uncommon in the Arduino realm to see people trying to use the little processors for tasks which exceed their capability, and it appears intended to address that problem.
While one can breadboard the equivalent of the AVR based Arduinos, or duplicate the functionality of those or even the simpler ARM-based boards on a hobbyist-designed 2 layer PCB, implementing something like the Galileo would require a many-layer board designed by an experienced PCB designer.  For low-volume uses, someone would probably just buy the existing boards and use them (there is a longstanding market of embedded control modules intended for such use) - only at high volumes would it be cost effective to re-implement the board or its equivalent.

You are right. There are however people that use an arduino for hobby, and don't want to invest more time into learning to make PCB and programming bare AVRs. For some people getting some leds to blink is already very hard.
Also look at the amount of Arduino shields that are available. The target group of Arduino's has shifted from hobby electronics people to just regular people wanting to get some project working. People are okay with sacrificing an entire arduino board, adding some shields and putting it inside a Tupperware box. As long as it solves their problem, or does something cool.

Arduino boards, with or without removable chips, provide a lot of facilities ready to go for experimenters, prototypers, students, artists and other tinkerers who aren't necessarily interested in the electronics but just want a programmable controller to get a job done. They can often be the cheapest way to build a one-off system once you consider the labor to build a less expensive board.
It's really easy to program AVR chips on a breadboard or, in most cases, right on the custom project board. You don't need Arduino to do that. I've built up and programmed ATMega328p projects without ever taking my Arduino out of the box.
This is a project I prototyped on an Arduino Mega2560 and later ported to the project board with soldered-in chip. The cable is a USB FTDI serial cable, a stock item that connects any chip with a TTL UART directly to a computer USB port. (The green daughter board is an X-10 RF transmitter and the reason I prototyped this project on a larger CPU).

Often I develop project code solely on the project board; it's just about as easy. About the only advantages I get from using the larger board is multiple serial lines so I don't have to keep switching my terminal app off and on to allow down loading, and I can include lots of extra debugging code and libraries that I won't need in the project.
Your favorite tool set will work either way. The Arduino IDE, Eclipse, or bare-nekkid ARVdude at the command line. If your project code needs the Rx/Tx pins, you may need to build one board with jumpers to disconnect the project's serial hardware while you're downloading.


text:
Arduino code for XBee
I am trying to send analog data, from a LM35, using an XBee (series 1 - XB24).
My setup:

Transmitting Module: XBee with USB explorer+Arduino+LM35 (temperature sensor)
Receiving Module: XBee with XBee shield+Arduino

I read analog data using the Arduino and send it through the XBee in the USB explorer, then the receiving XBee module receives it and shows it in the serial monitor of the Arduino.
I have tried many ways but I can't reach it and I have figured out that my problem lies in the Arduino code.
So, please can anyone help with some demo code for this project?

Can you post what code you have so far, and what part you think is broken?

You probably want to take a look at Robert Faludi's book Building Wireless Sensor Networks, published by O'Reilly. He describes, step by step, a very similar project, but without the Arduino.
Or Alasdair Allan's Distributed Network Data, also published by O'Reilly, which has a similar project using an Arduino.
Also, take a look at Robert Faludi's blog TMP36 Instructions: Simple Sensor Network.

source: Stack Exchange

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

sort: votes


text:
Reading setting from microSD
I modified the SD sketch for ESP8266 to read WIFI setting from a file named CONFIG.TXT. The text file's content format is SETTING=VALUE. Ex.
SSID=AP001
KEY=AP001

I manage to separate the SETTING and VALUE
My code:
#include <SPI.h>
#include <SD.h>

File myFile;

void readWifiConfig() {
  Serial.println("Initializing SD card...");
  char temp;
  bool isSetting = true;
  if (!SD.begin(4)) {
    Serial.println("Initialization failed!");
    return;
  }
  Serial.println("Initialization done.");
  myFile = SD.open("CONFIG.TXT");
  if (myFile) {
    Serial.println("CONFIG.TXT");
    while (myFile.available()) {
      temp = myFile.read();
      if (isSetting == true) {
        if (temp == '=') {
          Serial.print("="); //Writes '=' to console
          isSetting  = false;
        }
        else {
          Serial.print(temp); //Writes SETTING part to console
        }
      }
      else {
        if (temp == '\n' || temp == '\r') {
          isSetting = true;
          }
        else {
          Serial.print(temp); //Writes VALUE part to console
          }
        }
    }
    myFile.close();
  } else {
    Serial.println("Can't open CONFIG.TXT");
  }
}

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

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

}

Output:
Initializing SD card...
Initialization done.
CONFIG.TXT
SSID=AP001
KEY=AP001

I want to write the values to their corresponding variables and I don't know how.
char* ssid;
char* key;

I don't see a question

You can't just write to a pointer, you need to allocate a buffer and copy the data there.

New and improved code.
File format:
$SETTINGNAME=SETTINGVALUE;

New code:
#include <SPI.h>
#include <SD.h>

File configFile;
uint8_t filePosition;
uint8_t workingIndex = 0;
uint8_t settingNameValuePositions[16][3];
uint8_t temporaryBufferPosition = 0;
char temporaryBuffer[32];

void setPosition(uint8_t mrk) {
  settingNameValuePositions[workingIndex][mrk] = filePosition;
}

uint8_t getPosition(uint8_t idx, uint8_t mrk) {
  return settingNameValuePositions[idx][mrk];
}

void addToBuffer(char inp) {
  temporaryBuffer[temporaryBufferPosition] = inp;
  temporaryBufferPosition++;
}

void resetBuffer() {
  temporaryBufferPosition = 0;
  memset(temporaryBuffer, 0, sizeof(temporaryBuffer));
}

char* requestSetting(char *settingName) {
  for (int i = 0; i < workingIndex; i++) {
    uint8_t nS = getPosition(i,0); //$
    uint8_t eQ = getPosition(i,1); //=
    uint8_t vE = getPosition(i,2); //;
    bool isFound = false;
    resetBuffer();
    for (int g = nS; g < eQ - 1; g++) {
      configFile.seek(g);
      addToBuffer(configFile.read());
    }
    if (strcmp(temporaryBuffer,settingName) == 0) {
      isFound = true;
      resetBuffer();
    }
    for (int g = eQ; g < vE - 1; g++) {
      configFile.seek(g);
      addToBuffer(configFile.read());
    }
    if (isFound) {
      isFound = false;
      return temporaryBuffer;
    }
  }
  return "0";
}

bool readConfigFile(char* fileName) {
  //Serial.println("INITIALIZING SD CARD");
  if (!SD.begin()) {
    //Serial.println("INITIALIZING SD CARD FAILED");
    return false;
  }
  else {
    //Serial.println("INITIALIZING SD CARD COMPLETED");
    //Serial.println("OPENING FILE: " + String(fileName));
    configFile = SD.open(fileName);
    if (!configFile) {
      //Serial.println("ERROR OPENING FILE: " + String(fileName));
      return false;
    }
    else {
      //Serial.println("FILE " + fileName + " OPENED");
      //Serial.println("SEARCHING FOR MARKER POSITIONS");
      while (configFile.available()) {
        char fileChar = configFile.read();
        filePosition = configFile.position();
        switch (fileChar) {
          case '$':
            setPosition(0);
            break;
          case '=':
            setPosition(1);
            break;
          case ';':
            setPosition(2);
            workingIndex++;
        }
      }
    }
    return true;
  }
}

void setup() {
  Serial.begin(115200);
  readConfigFile("CONFIG.TXT"); //FILE NAME
  Serial.println(requestSetting("SETTINGNAME"));
}
void loop() {
}

uint8_t settingNameValuePositions[16][3];

If you have more than 16 variables it's going to crash your webserver.
If your config file has more than 256 characters, then you should use short instead of uint8_t.

Somehow I managed to do it but my code is un-optimized. Please let me now if I've done something that isn't good.
I changed the content format to this so it's much easier for me. (CONFIG.TXT)
SSID%&WIFIAP001&%KEY%&PASS1234&

New Code.
#include <SPI.h>
#include <SD.h>

File myFile;
char wifiSsid[63];
char wifiKey[63];
char temp;
char settingSsid[5] = "SSID";
char settingKey[4] = "KEY";
char settingTemp[10];
char valueTemp[63];
int settingTempLastPos = 0;
int valueTempLastPos = 0;
int percentCount = 0;
int andCount = 0;
bool isSetting = true;
bool ssidValueFound = false;
bool keyValueFound = false;

void readWifiConfig() {
  Serial.println("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("Initialization failed!");
    return;
  }
  Serial.println("Initialization done.");
  myFile = SD.open("CONFIG.TXT");
  if (myFile) {
    Serial.println("CONFIG.TXT");
    while (myFile.available()) {
      temp = myFile.read();
      if (temp == '%') {
        percentCount++;
        isSetting = true;
        if (percentCount == 2) {
          //Serial.println(settingTemp);
          if (strcmp(settingSsid,settingTemp) == 0) {
            Serial.println("SSID SETTING FOUND");
            //IF FOUND RAISE FLAG FOR ADDING VALUE TO SSID CHAR ARRAY
            ssidValueFound = true;
            }
          else if (strcmp(settingKey,settingTemp) == 0) {
            Serial.println("KEY SETTING FOUND");
            //IF FOUND RAISE FLAG FOR ADDING VALUE TO SSID CHAR ARRAY
            keyValueFound = true;
            }
          memset(&settingTemp[0], 0, sizeof(settingTemp));
          settingTempLastPos = 0;
          percentCount = 0;
        }
      }
      else if (temp == '&') {
        andCount++;
        isSetting = false;
        if (andCount == 2) {
          //Serial.println(valueTemp);
          if (ssidValueFound) {
            //Serial.println(valueTemp);
            memcpy(wifiSsid,valueTemp,63);
            //Serial.println(wifiSsid);
            ssidValueFound = false;
            }
          else if (keyValueFound) {
            //Serial.println(valueTemp);
            memcpy(wifiKey,valueTemp,63);
            //Serial.println(wifiKey);
            keyValueFound = false;
            }
          memset(&valueTemp[0], 0, sizeof(valueTemp));
          valueTempLastPos = 0;
          andCount = 0;
        }
      }
      else {
        if (isSetting == true) { //setting
          settingTemp[settingTempLastPos] = temp;
          settingTempLastPos++;
        }
        else if (isSetting == false) { //value
          valueTemp[valueTempLastPos] = temp;
          valueTempLastPos++;
        }
      }
    }
    //Serial.println(settingTemp);
    myFile.close();
  } else {
    Serial.println("Can't open CONFIG.TXT");
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(10);
  readWifiConfig();
  Serial.println(wifiSsid);
  Serial.println(wifiKey);
}

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

}

Output:
Initializing SD card...
Initialization done.
CONFIG.TXT
SSID SETTING FOUND
KEY SETTING FOUND
WIFIAP001
PASS1234

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

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


text:
Changing preferences.txt to 4-space tabs, how to AutoFormat existing code?
Title says it all really, but to elaborate, in my preferences.txt file, I've changed the editor.tabs.size variable to 4, which works wonderfully, and now produces 4-space tabs as do my other IDEs for all the languages I write in.
However, I was told that using the Tools->AutoFormat feature would update all lines in my previously-written sketches that had the standard 2-space tabs with the new 4-space tab layout.
This isn't so. Whether I CTRL-a to select all and run the Auto Format function, or whether I leave everything de-selected, nothing happens.
Should auto-format "fix" the 'incorrect' indenting to the new style? If so, what am I missing?
I'm currently on Arduino IDE 1.8.5 on Linux Mint, if that makes a difference.

The auto formatter (astyle) uses a separate configuration to the editor (crazy, I know, but that's the Arduino mentality for you...).
It uses a separate configuration, which is in the lib folder of your Arduino program, called formatter.conf.

Copy that file to the same location as preferences.txt so it doesn't get overwritten when you upgrade the IDE.
Edit the file and change indent=spaces=2 to indent=spaces=4

The auto format should now be the same as the editor format.

Good grief. I'll test it here shortly @Majenko. Thanks

Wow. What a meticulously ridiculous way to do things. Answer accepted as it worked. I'll have to make notes for this and update my automation routines, as I can see this going downhill in the future on new setups.

The auto formatter (astyle) uses a separate configuration to the editor - with what possible justification?

@NickGammon I wish I knew. When I implemented astyle in UECIDE it just read the same formatting settings (plus extras that don't apply) for the editor...

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


text:
ESP8266 - How to know if incoming connection is from AP or station network?
I have an ESP8266 module connected with my Arduino configured as a server, with both AP and station modes (AT+CWMODE=3) activated, and I want to know if an incoming connection comes from the AP's network or the station's network. This is the package I'm receiving, and it's exactly the same whether it comes from one or another network:
+IPD,0,437:GET /?uuid=7be547af980d13c5&cmd=10 HTTP/1.1
Host: 192.168.0.222:51813
Connection: keep-alive
Cache-Control: max-age=0
Accept: */*
Origin: http://127.0.0.1:8020
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
DNT: 1
Referer: http://127.0.0.1:8020/domo_ctrl/www/index.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: es-419,es;q=0.8,en;q=0.6

At first I thought that it would reject packages addressed towards another IP (AP's IP is different from station's IP), but since this IS the gateway, it receives ALL incoming traffic. Please help!
EDIT:
This is the firmware and other stuff shown by AT+GMR:
AT+GMR

AT version:1.1.0.0(May 11 2016 18:09:56)
SDK version:1.5.4(baaeaebb)
Ai-Thinker Technology Co. Ltd.
Jun 13 2016 11:29:20
OK

Which firmware do you have running on your ESP8266?

Hi @RobertoLoGiacco, I edited my question to include firmware info.

I don't think the default AT firmware allows to automatically reject packets because that would probably require a higher degree of control, but looking at the Expressif documentation about the AT command set I've discovered you can actually retrieve the remote address rather than the local one, just by using the same command you were using but with a different parameter
AT+CIPDINFO=1

Not sure though this actually might solve your problem.

This actually solves it! Thx!! It relies on both networks being on separate addresses though, so you can't have both on 192.168.0.0, for example (if you are one to do such things, and I've seen production environments with such network configuration... a complete IP nightmare).

Glad to hear my long shot turned out to be on the spot :-)


text:
Nano resets or freezes on calling a function
I'm controlling a light bulb with my Arduino Nano from serial or RF (via nRF24L01+) and I'm passing the commands as a string. After I get all the variables (3 ints) I try calling the function execOrder but no matter what I put in there, the Arduino just hangs or resets. Code is as follows:
#define SSR 3
#define SW 4
#define nanoID 1
bool isPWM = false;
int value;

// Módulo RF
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"
RF24 radio(9,10);
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };
#define PayLoad 20

#include <MemoryFree.h>

void setup() {
  pinMode(SSR, OUTPUT);
  pinMode(SW, INPUT_PULLUP);
  digitalWrite(SSR, LOW);
  value = 0;
  Serial.begin(9600);
  Serial.println("------ CEACI SAS -- Controller Module ------");
  Serial.println("Module No: " + String(nanoID));
  // Inicializar RF
  Serial.println("Inicializando RF");
  radio.begin();
  radio.setRetries(15,15);
  radio.setPayloadSize(PayLoad);
  radio.setPALevel(RF24_PA_MIN);
  radio.setDataRate(RF24_250KBPS);
  radio.setCRCLength(RF24_CRC_16);
  delay(100);
  radio.openWritingPipe(pipes[1]);
  radio.openReadingPipe(1,pipes[0]);
  radio.startListening();
  //radio.printDetails(); //RF Debug
  Serial.println("RF listo!");
  Serial.print("freeMemory()=");
  Serial.println(freeMemory());
}

void loop() {
  if (Serial.available()) {
    Serial.println("Rcvd Serial!");
    String msgRcvd = Serial.readString();
    int ID = msgRcvd.substring(4,5).toInt();
    int cmdCode = msgRcvd.substring(10,11).toInt();
    int cmdVal = msgRcvd.substring(16).toInt();
    //Serial.println("ID: "+String(ID)+", CMD: "+String(cmdCode)+", VAL: "+String(cmdVal));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    //execOrder(ID,cmdCode,cmdVal);
  } else if (radio.available()){
    int RFlen=0;
    char msgBuff[]="";
    RFlen = radio.getDynamicPayloadSize();
    delay(10);
    radio.read(&msgBuff, RFlen);
    String msgRcvd(msgBuff);
    int ID = msgRcvd.substring(4,5).toInt();
    int cmdCode = msgRcvd.substring(10,11).toInt();
    int cmdVal = msgRcvd.substring(16).toInt();
    //Serial.println("ID: "+String(ID)+", CMD: "+String(cmdCode)+", VAL: "+String(cmdVal));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    //execOrder(ID,cmdCode,cmdVal);
  } else {
    chkSwitch();
  }
}

void execOrder(int ID, int CMD, int VAL){
  if (ID == nanoID || ID == 0){
    switch(CMD){
      case 0:
        State();
        break;
      case 1:
        value = VAL;
        OnOff();
        break;
      case 2:
        value = VAL;
        PWM();
        break;
    }
  }
}

I wanted to process the incoming string in a function, but it resets as well.
By the way, I'm using MemoryFree library to check if I'm out of memory, and there's plenty of it, so I don't really know where's the problem. Any help would be greatly appreciated!
EDIT:
For the serial part I can do the following (my original code):
if (Serial.find("MOD=")) {
  int ID = Serial.parseInt();
  if (ID == nanoID || ID == 0) {
    Serial.find("CMD=");
    int command = Serial.parseInt();
    int cmdVal = 0;
    if (command != 0){
      Serial.find("VAL=");
      cmdVal = Serial.parseInt();
    }
    Serial.println("MOD: "+String(ID)+", CMD: "+String(command) + ", VAL: " + String(value));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    execOrder(ID,command,cmdVal);
  }
}

And it works flawlessly. But I don't know how to achieve the same results with the RF input. The problem seems to be with using so many strings.

Your problem is not due to memory shortage, but because you are erroneously using pointers.
Even with your fix you are doing the same mistake, you are just not incurring into the same problem by luck as you are not addressing anything new after the bad definition of your variable msgBuff.
Putting all that into simple terms, you should change your code and probably read some articles on C pointers as it looks like you have a Java background (like me).
Your issue is in the char msgBuff[]=""; statement which should be moved after the the call to obtain the payload size and turned into char msgBuff[RFlen];:
int RFlen=radio.getDynamicPayloadSize();
char msgBuff[RFlen];
delay(10);
radio.read(&msgBuff, RFlen);

Ok, I solved it like this:
if (radio.available()){
    int RFlen=0;
    char msgBuff[]="";
    RFlen = radio.getDynamicPayloadSize();
    delay(10);
    radio.read(&msgBuff, RFlen);
    int ID = msgBuff[4] - '0';
    int cmdCode = msgBuff[10] - '0';
    int cmdVal = msgBuff[16] - '0';
    if (cmdCode == 2){
      cmdVal *= 100;
      cmdVal += 10*(msgBuff[17]-'0');
      cmdVal += (msgBuff[18]-'0');
    }
    execOrder(ID,cmdCode,cmdVal);
}

The problem is with using strings, but I don't know why since there's plenty of memory. Anyway, I hope this helps anyone else with the same issue.


text:
Help managing the fallout from timer0 mode and prescaler change on ATMega2560 without modifying wiring.c
For a driving application I need the PWM mode to be phase correct and the prescaler to be 1. The issue is that the board I am working with has the load hooked up to a PWM pin reliant on timer0. The firmware running on this board makes use of the delay(), delayMicroseconds(), and millis() functions from wiring.c. The goal is to make the timer0 change, shown below, and then make small modifications where the firmware calls the wiring.c timing functions. My approach was to find a scaling factor to be applied to the call of these functions. The scaling factor I came to was 32.12549, calculated by taking the wiring.c expected timer0 behavior: prescaler=64 and TOV0 flag every 256 counts, and comparing it to the actual values after my change: prescaler=1 and TOV0 flag every 510 counts
Calculation: 64*256/510=32.12549
Timer0 change:
// Set timer0 to phase correct PWM
TCCR0A = TCCR0A & 0b11111100 | 0x01;

// Set prescaler for timer0 to 1
TCCR0B = TCCR0B & 0b11111000 | 0x01;

The other timers are all configured in phase correct PWM mode, with a prescaler of 1.
...When I apply this scaling factor to a value returned from millis() to keep time it works well. For example the two pieces of code below proved to be equivalent through the timer0 change:
Use of millis() before timer0 change:
//current time
long unsigned now = millis();

//delay for 1 second
while(millis() - now < 1000){}

Use of millis() after timer0 change:
//current time
long unsigned now = millis();

//delay for 1 second, with x32.125 scaling coefficient
while(millis() - now < 32125){}

The two snippets of code above both delayed for 1 second
Now comes the problem: when I try to apply that same scaling factor to delay() or delayMicroseconds() it seems to give unreasonable delays...
Use of delayMicroseconds() before timer0 change:
// wait 1.5ms for mux to switch
delayMicroseconds(1500);

...this delays for 1.5ms
Use of delayMicroseconds() after timer0 change:
// wait 1.5ms for mux to switch, with x32.125 scaling coefficient
delayMicroseconds(48188);

...this delays for ~20ms.
Assuming this is still linearly scalable:
 if 48188 -> 20ms, therefore 1.5ms -> 3614
But when the following code is used...
// wait 1.5ms for mux to switch, scaled
delayMicroseconds(3614);

...this delays for ~4.5ms
Why is it that delayMicroseconds() and delay() cannot be linearly scaled to account for a timer0 change? Furthermore, is there any simple modification to how these functions are called or utilized that can account for the effect of changing timer0?

You might want to check the Arduino source code. It seems like delayMicroseconds doesn't even use timer0. Does your code use any interrupts, as that would skew the result of delayMicroseconds? Did you run out of PWM pins on the Mega, that you need to use timer0?

Yes, timer0 must be used here. The code does use interrupts, which might be effecting this (I hadn't notice that delayMicroseconds() doesn't utilize micros(), which blocks interrupts; I assumed it did since delay() does) - although I am using a scope to measure the output (toggling a pin on either side of the delay) and the delay is repeatable, where-as our interrupts may happen at any time during the code. If it is an interrupt causing the issue I would expect the delay to vary as the loop runs, which it does not. I'll do my best to read through the source code for delayMicroseconds()

I think you are right actually, and I think the interrupt that is causing this mistake could actually be the timer overflow interrupts. By changing the clock speeds (I actually increased the clock speed of all PWM timers) I caused each clocks TOVn interrupt flag to be raised every 31.875us, as opposed to the standard operation which is every 1024us.

The millis() roll over
By making Timer 0 faster, your millis() will roll over much more
often than normal: every 37.1 hours instead of every 49.7 days. Thus,
when you “scale” millis(), you should be careful to do it in a
rollover-safe way. From the code you show, it appears that you are doing
exactly the right thing. Well done! Don't change anything. Don't be
tempted to scale the value returned by millis().
The overflow in delayMicroseconds()
As this function just burns cycles in a busy loop, it is not affected by
your configuration of Timer 0. You can just use it as is, with no
scaling. Beware however that it's argument should always be smaller than
16384 (on a 16 MHz board). Otherwise it will overflow when it is
multiplied by 4 in order to get a loop count.
For example, when you call delayMicroseconds(48188);, the function
computes the number of loop iterations to make as
48188 × 4 − 5 = 61675 (modulo 216)
Then, it burns about 15 ms of CPU time (0.25 µs per
iteration), which is close to the 20 ms you see. For the
difference, see below.
The cycles burned by the Timer 0 ISR
This ISR, which keeps the millis() counter updated, is supposed to run
every 1024 µs. Each time it runs it burns a few cycles, but it's
usually not a big deal. With your new timer configuration, it is now
running far more often: every 31.875 µs.
From the numbers you give in the question, I would say the ISR is
eating about 20% of your CPU power: when you call
delayMicroseconds(3614);, that function burns 3614 µs of CPU
time, yet you measure a delay of about 4500 µs. The difference is
taken by the Timer 0 ISR.
Use another timer for millis()
If you can spare a timer, you could both restore the normal behavior of
millis() and avoid wasting so much CPU in the Timer 0 ISR:

configure Timer 0 to not trigger interrupts
configure your spare timer just like the Arduino core would normally
configure Timer 0
write an overflow ISR for your spare timer that just calls the Timer 0
overflow ISR.

This way your spare timer is basically replacing Timer 0. Example using
Timer 2:
// This Timer 2 overflow ISR simply forwards the call to the Timer 0
// overflow ISR from Arduino core.
ISR(TIMER0_OVF_vect);
ISR(TIMER2_OVF_vect, ISR_NAKED) {
    TIMER0_OVF_vect();
    asm volatile("reti");

    // Alternatively, just:
    // asm volatile("jmp __vector_16");
}

void setup()
{
    // Set timer0 to phase correct PWM
    TCCR0A = (TCCR0A & 0b11111100) | 0x01;

    // Set prescaler for timer0 to 1
    TCCR0B = (TCCR0B & 0b11111000) | 0x01;

    // Disable Timer 0 interrupts.
    TIMSK0 = 0;

    // Configure Timer 2 to replace Timer 0.
    TCCR2A = _BV(WGM20)   // fast PWM, TOP = 0xff
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(CS22);   // clock at F_CPU / 64
    TIMSK2 = _BV(TOIE2);  // enable overflow interrupt

    pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
    // Blink the LED at 1 Hz.
    uint32_t now = millis();
    static uint32_t last_toggle;
    if (now - last_toggle >= 500) {
        last_toggle += 500;
        digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    }
}

I wrote a “naked” ISR to avoid having plenty of CPU registers saved and
restored twice (once by each ISR in the call chain), but then I had to
put the return instruction explicitly in assembly (ret and reti
would be equivalent in this instance). The version with jmp is
slightly more efficient, but you have to know the “real” name of the
ISR, which is MCU-dependent (__vector_16 on an Uno).
Notice that with this technique micros() will not work, as it reads
TCNT0 directly. And delay() will not work either because it relies on
micros().

Fantastic response, thank you. It seems delayMicroseconds() is not going to be reliable, and based on the length delays my project requires I think relying exclusively on millis() would be fine. We are using all the timers for PWM outputs at this point, and as you can probably deduce from that we have a fairly weighed down microcontroller. I believe the other timers are 16-bit, so would roll-over way less often - I'm starting to think we cannot handle timer0 being sped up and still manage the communications and calculations in a reliable fashion.

Out of interest, how did you come to this conclusion: "From the numbers you give in the question, I would say the ISR is eating about 20% of your CPU" ?

How did you configure the other timers? Could they work in fast PWM mode at 977 Hz? You may want to add this info to the question. Arduino configures the only 16-bit timer in 8-bit mode anyway. 2) Out of 4500 µs, 3614 are spent inside delayMicroseconds(3614). The rest, namely 886 µs (i.e. 20%) is eaten by that ISR.

Things are changing as I dig into this, and it looks like getting away from timer0 is important enough to merit hardware modifications. Also, I am using an ATMega2560, which has 4x 16-bit timers (1,3,4,5) and 2x 8-bit timers (0,2). I have to go back through the firmware and verify that we have them set as 16-bit (does Arduino default all timers to 8-bit?), but it seems you have given me more than enough reason to dedicate my effort to working away from timer0.


text:
Arduino Uno Wifi Module ESP8266 AT Command Test error
When i Connected Rx>Rx (Rx Of module To Pin 0 Of Arduino) And Tx>Tx ( Tx Of Module To Pin 1 Of Arduino), The AT Command Test shows The Following error With Scrambled Words, but when I Connect Rx>Tx (Rx Of Module To Pin 1 Of Arduino) And Tx>Rx(Tx Of Module To Pin 0 Of The arduino), The AT Command Test Shows a Blank Screen. I Connected VCC, CHPD and RST Of Module to 3v Of Arduino and GND Of Module To GND Of Arduino. So How Do I Connect Arduino To Wifi Module which passes the at command test, Btw i Have an Intermediate, ie Motor Shield, I Connected Motor Sheild To Arduino And Then I connected Wifi Module To Motor Shield. Listen So  I need To Connect Wifi Module To Arduino, such that there isnt any error. what do i do?

You cannot connect an Arduino's digial pins 1 and 0 to both an ESP8266 and the serial USB,  unless you disable their use by the ATmega, for example hold it in reset if you are just trying to borrow the Arduino's USB serial.

many ESP8266's operate at 74880baud by default - this is 115200 * 26 / 40 ... because most ESP's use a 26Mhz crystal as opposed to a 40Mhz one

@ChrisStratton - unless the unposted code doesn't open the serial port as discussed here

Sounds like a baud rate issue as others have mentioned. Posting code would make things clearer. Please read How do I ask a good question?.

You have three hardware serial devices: the ATmega's pins 0 and 1, the ESP8266, and the USB serial converter to which the serial monitor is linked. You can only connect two of these, not all three. If you want to connect the serial monitor directly to the ESP8266, you have to disconnect the ATmega pins 0 and 1, either electrically or by making sure they are not activated for serial. If you want to insert the ATmega and its program between the serial monitor and the ESP8266, then you have to move the ESP8266 connections to some other ATmega pins and use a software serial instance on them.

The first connection you made between arduino and esp which resulted in some random data means both are communicating whereas the second connection where the screen shows blank means communication hasnt been established on account of incorrect wiring. So your first connection tx>tx and rx>rx is correct.
The only two area which you need to check is the baud rate and the mode of return. Some Esps work at 115200 with mode carriage return. So you can try different combinations of baud rate and mode to check which one does your Esp support.

"Random data" normally means the baud rate is to high.  No data means its to low (or 'broken' in some other way)

@Matt you might be right but in this case the results are observed when wiring is interchanged. Your point would have been valid when the connection is correct and the above mentioned observation would have been observed on changing baud rate. Here the connection itself is an issue.


text:
Serial loop stopped after a while, I don't know why
I am very new to Arduino. I wrote a program in order to read some registers in a I2C device. I receive HEX datas.
So the Arduino LEONARDO is connected to the external board using the 2-wires-bus.
Then informations are sent to my computer by using Serial.println.
My problem is my Arduino stops working after a while, maybe 25 or 30 loops. Sometimes I loose communication and I have to reboot the Arduino.
I guess it's an overflow issue or I'm loosing connection randomly :
int dt = 500;
int dt2 = 1000; // used for delay duration
#include "Wire.h"
#include <Process.h>
#define pot_address 0x25 // each I2C object has a unique bus address, the MCP40

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

}

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

  Wire.beginTransmission(pot_address);
  Wire.write(0); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
  byte b = Wire.read();

  Wire.beginTransmission(pot_address);
  Wire.write(1); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte c = Wire.read();

   Wire.beginTransmission(pot_address);
  Wire.write(2); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte d = Wire.read();

  Wire.beginTransmission(pot_address);
  Wire.write(3); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte e = Wire.read();

  Wire.beginTransmission(pot_address);
  Wire.write(4); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte f = Wire.read();

  Serial.print("b");
  Serial.println(b, HEX);
  Serial.println("-");
  Serial.print("c");
  Serial.println(c, HEX);
  Serial.println("-");
  Serial.print("d");
  Serial.println(d, HEX);
  Serial.println("-");
  Serial.print("e");
  Serial.println(e, HEX);
  Serial.println("-");
  Serial.print("f");
  Serial.println(f, HEX);
  Serial.println("-");

 delay(dt2);

}

On each transaction, you request 8 bytes from the MCP40 (second argument of Wire.requestFrom()), yet you read only one (one single call to Wire.read()).

Add:
while(!Serial) ;

I'll make sure the Leonardo is in sync with the Serial communication.
It is the case because the Leonardo is USB native thus the Serial communication works differently.


text:
Float to integer conversion for control program crashes arduino
I have a program which estimates battery capacity, range as well as runs different control loops on an arduino MEGA2560 to control an eBike. I was using floating points which gave me quite a slow sampling frequency (10Hz). I now changed this to use integers by multiplying everything by at least 1000 so I can still keep a 3 decimal accuracy. However, as soon as the Arduino leaves setup and starts running loop, it crashes and restarts. I have a doubt that this could be due to the fact that my program takes too much RAM. How could I solve this?
Here is my code:
    #include <EEPROM.h>
    #include <memorysaver.h>
    //#include <TFT_HX8357.h> // Hardware-specific library
    #include <URTouch.h>
    #include <URTouchCD.h>
    #include <memorysaver.h>
    #include <UTFT.h>

    //TFT_HX8357 myGLCD = TFT_HX8357();       // Invoke custom library#include <TFT_HX8357.h> // Hardware-specific library
    //
    //TFT_HX8357 myGLCD = TFT_HX8357();       // Invoke custom library

    UTFT myGLCD(ILI9481,38,39,40,41);
    URTouch myTouch(6, 5, 4, 3, 2);

    int  buttonst, horn=5, throttle=8, powermode=1, alarmsystem=1, xtouch, ytouch, k1=0, k2=0,modechange,ncycles, p=9, divider=12, addresstd=0, kpow[3]={0,0,0}, kcur[3]={25,0,0}, ksp[3]={0,0,0};
    long pushed, pushedt, timesp, timespm1, powtimesm, factor, powtimesp, start, elapsed, powtime, powresttime, shuntvoltage, batvoltage, current, power, consumah, capacstore, consumwh, consumbatper, consumbatrange, distance, distanceint, throttlein, throttleout, distancedisp, Totaldist, velocity, Totaldistcheck;
    long throttlesmooth, capaccheck, capacactual,consumahstore, errorpower[2], errorpoweri, errorpowerli, errorcuri, errorcurrent[2], errorpowerl[2], diff, errorspeed[2], errorisp, outspeed, outcurrentctl, outspeedctl, elapsedtot, errorsmooth[2];
    float internresistance=0.00112;

    long batteryspec[6][56]={{4200,4000,3940,3900,3876,3860,3852,3844,3826,3809,3795,3783,3765,3744,3728,3710,3692,3672,3650,3631,3613,3591,3573,3556,3532,3508,3488,3463,3439,3417,3399,3380,3366,3352,3332,3312,3291,3273,3253,3237,3217,3196,3176,3150,3123,3087,3051,2994,2929,2868,2796,2727,2650,5261,2502},//5A discharge 18650GA SPEC
      {1,2,15,47,85,133,186,244,309,383,447,506,554,612,681,735,793,852,921,1007,1081,1150,1236,1300,1358,1438,1518,1587,1667,1747,1822,1888,1955,2014,2072,2152,2232,2317,2389,2466,2524,2594,2658,2722,2786,2847,2925,2983,3063,3133,3186,3245,3293,3330,3357,3368},
      {4200,4020,3980,3945,3927,3914,3904,3890,3874,3860,3843,3821,3797,3776,3756,3734,3713,3695,3675,3652,3634,3614,3593,3569,3543,3522,3500,3480,3459,3441,3419,3398,3378,3360,3339,3321,3301,3278,3254,3230,3199,3164,3128,3085,3037,2990,2937,2878,2837,2795,2746,2693,2648,2598,2549,2496},
      {0,7,33,84,151,223,294,377,457,521,574,646,718,785,851,931,1011,1091,1171,1251,1323,1397,1469,1547,1632,1701,1778,1853,1928,1994,2088,2175,2258,2333,2413,2487,2562,2634,2706,2775,2842,2908,2697,3023,3074,3116,3159,3205,3234,3261,3287,3314,3333,3352,3365,3379},//3A discharge 18650GA SPEC
      {4200,4131,4094,4073,4054,4038,4028,4015,4003,3985,3965,3945,3921,3894,3870,3850,3830,3811,3795,3775,3759,3739,3716,3692,3674,3648,3623,3601,3578,3561,3542,3522,3502,3486,3467,3445,3423,3401,3374,3350,3324,3291,3253,3210,3168,3123,3075,3026,2964,2897,2838,2781,2715,2652,2585,2502},
      {0,0,36,84,154,223,289,356,420,489,553,620,686,761,838,908,985,1054,1134,1214,1283,1358,1438,1523,1584,1667,1755,1835,1920,2002,2085,2170,2255,2327,2402,2482,2567,2644,2724,2791,2850,2908,2964,3015,3058,3095,3132,3167,3207,3245,3271,3295,3320,3336,3354,3365}}; //1A discharge 18650GA SPEC

    long cyclicspec[2][44]={{0,894,7151,16090,26400,37500,50950,61680,74190,85360,96540,107260,118880,130950,142120,154640,168040,182350,194860,208270,219890,234200,246700,262800,276200,291400,303900,317300,3271500,341500,354000,364000,374500,383460,395080,405800,418300,431700,444000,455900,468800,481900,491600,499700},
      {3441,3435,3342,3292,3235,3178,3121,3078,3014,2957,2921,2892,2842,2792,2750,2721,2679,2643,2607,2564,2543,2507,2479,2436,2407,2379,2357,2336,2336,2336,2336,2336,2336,2321,2300,2279,2271,2243,2229,2214,2193,2179,2164,2157}};

    extern uint8_t BigFont[];
    extern uint8_t SevenSegNumFont[];

    void EEPROMWritelong(int address, long value)
          {
          //Decomposition from a long to 4 bytes by using bitshift.
          //One = Most significant -> Four = Least significant byte
          byte four = (value & 0xFF);
          byte three = ((value >> 8) & 0xFF);
          byte two = ((value >> 16) & 0xFF);
          byte one = ((value >> 24) & 0xFF);

          //Write the 4 bytes into the eeprom memory.
          EEPROM.write(address, four);
          EEPROM.write(address + 1, three);
          EEPROM.write(address + 2, two);
          EEPROM.write(address + 3, one);
          }

    long EEPROMReadlong(int address)
          {
          //Read the 4 bytes from the eeprom memory.
          long four = EEPROM.read(address);
          long three = EEPROM.read(address + 1);
          long two = EEPROM.read(address + 2);
          long one = EEPROM.read(address + 3);

          //Return the recomposed long by using bitshift.
          return ((four << 0) & 0xFF) + ((three << 8) & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF);
          }

    long pidcurrent_control() {

  long dt, outcurrent=0, outpower=0;
     int i=0, descurrent, despower;
     i++;
     dt=millis()-powtime;
     powtime = millis();
     if (powermode==1) { //Furo default mode
      if (current>40000) {
        descurrent=40000;
        errorcurrent[1]=descurrent-current;
        if (i>=2) {
          //Integrate the error
        errorcuri+=errorcurrent[1]*dt;

        outcurrent=(kcur[0]*errorcurrent[1]+kcur[1]*errorcuri+kcur[2]*((errorcurrent[1]-errorcurrent[0])/dt));
        }
        errorcurrent[0]=errorcurrent[1];
        return outcurrent;
        }
        if (((batvoltage*current)/1000)>2000000) {
         despower=2000000;
          errorpower[1]=despower-batvoltage*current/1000;
          if (i>=2) {
        //Integrate the error
        errorpoweri+=errorpower[1]*dt;
        outpower=kpow[0]*errorpower[1]+kpow[1]*errorpoweri+kpow[2]*((errorpower[1]-errorpower[0])/dt);
        }
        errorpower[0]=errorpower[1];
        return outpower;
        }
        }
      else { //Eco mode
       despower=550000;
       errorpowerl[1]=despower-batvoltage*current/1000;
          if (i>=2) {
          //Integrate the error
          errorpowerli+=errorpowerl[1]*dt;
          outpower=kpow[0]*errorpowerl[1]+kpow[1]*errorpowerli+kpow[2]*((errorpowerl[1]-errorpowerl[0])/dt);
        }
        errorpowerl[0]=errorpowerl[1];
        return outpower;
        }
        }

    void cyclescaling() {
    int j=1;
     if (ncycles<=499000) {
     while ((ncycles<cyclicspec[0][j-1])||(ncycles>cyclicspec[0][j])){
               j++;
        }
        factor=(cyclicspec[1][j-1]+(ncycles-cyclicspec[0][j-1])*(cyclicspec[1][j]-cyclicspec[1][j-1])/(cyclicspec[0][j]-cyclicspec[0][j-1]))/cyclicspec[1][0];
    }
    else {
        factor=(cyclicspec[1][41]+(ncycles-cyclicspec[0][41])*(cyclicspec[1][42]-cyclicspec[1][41])/(cyclicspec[0][42]-cyclicspec[0][41]))/cyclicspec[1][0];
    }
    }

    long pidspeed_control() {
    int isp, dtsp;
    isp++;
    dtsp=millis()-powtimesp;
    powtimesp = millis();
    errorspeed[1]=46000-velocity;
    if (isp>=2) {
        errorisp+=errorspeed[1]*dtsp;
        outspeed=(ksp[0]*errorspeed[1]+ksp[1]*errorisp+ksp[2]*((errorspeed[1]-errorspeed[0])/dtsp));
        }
        errorspeed[0]=errorspeed[1];
        return outspeed;
    }

    void throttlesmoothing() {
     int i=0, dtsm;
     i++;
    long currentmap=map(throttlein,800,3600,0,40000);
     dtsm=millis()-powtimesm;
     powtimesm = millis();
     errorsmooth[1]=currentmap-current;
          if (i>=2) {
          //Integrate the error
          throttlesmooth=kcur[0]*errorsmooth[1];//+kcur[2]*((errorsmooth[1]-errorsmooth[0])/dtsm);
        }
        errorsmooth[0]=errorsmooth[1];
    }

    void SOC() {
      int currentref=current/p, compbat=batvoltage/14;
      int j=1,l=1;
      long stateofc1=0, stateofc2=0;

      if (currentref<=1000){
        while (((compbat)>batteryspec[0][j-1])||((compbat)<batteryspec[0][j])){
               j++;
        }
        capacactual=(batteryspec[1][55]-(batteryspec[1][j-1]+(compbat-batteryspec[0][j-1])*(batteryspec[1][j]-batteryspec[1][j-1])/(batteryspec[0][j]-batteryspec[0][j-1])))*p;
        Serial.println("\n");
        Serial.println(current);
            Serial.println(batvoltage);
                Serial.println(batteryspec[1][j-1]);
      }

     if ((currentref>1000)&&(currentref<=3000)){
        while (((compbat)>batteryspec[0][j-1])||((compbat)<batteryspec[0][j])){
               j++;
        }
        stateofc1=(batteryspec[1][55]-(batteryspec[1][j-1]+(compbat-batteryspec[0][j-1])*(batteryspec[1][j]-batteryspec[1][j-1])/(batteryspec[0][j]-batteryspec[0][j-1])))*p;

         while (((compbat)>batteryspec[2][l-1])||((compbat)<batteryspec[2][l])){
               l++;
        }
        stateofc2=(batteryspec[3][55]-(batteryspec[3][l-1]+(compbat-batteryspec[2][l-1])*(batteryspec[3][l]-batteryspec[3][l-1])/(batteryspec[2][l]-batteryspec[2][l-1])))*p;
        capacactual=stateofc1+(currentref-1)*(stateofc2-stateofc1)/(3000-1000);
      }

       if ((currentref>3000)&&(currentref<=5000)){
        while (((compbat)>batteryspec[2][j-1])||((compbat)<batteryspec[2][j])){
               j++;
        }
    //    stateofc1=(batteryspec[3][55]-(batteryspec[3][j-1]+(compbat-batteryspec[2][j-1])*(batteryspec[3][j]-batteryspec[3][j-1])/(batteryspec[2][j]-batteryspec[2][j-1])))*p;

         while (((compbat)>batteryspec[2][l-1])||((compbat)<batteryspec[2][l])){
               l++;
        }
    //    stateofc2=(batteryspec[3][55]-(batteryspec[3][l-1]+(compbat-batteryspec[2][l-1])*(batteryspec[3][l]-batteryspec[3][l-1])/(batteryspec[2][l]-batteryspec[2][l-1])))*p;
        capacactual=(batteryspec[3][55]-(batteryspec[3][j-1]+(compbat-batteryspec[2][j-1])*(batteryspec[3][j]-batteryspec[3][j-1])/(batteryspec[2][j]-batteryspec[2][j-1])))*p+(currentref-1)*((batteryspec[5][55]-(batteryspec[5][l-1]+(compbat-batteryspec[4][l-1])*(batteryspec[5][l]-batteryspec[5][l-1])/(batteryspec[4][l]-batteryspec[4][l-1])))*p-(batteryspec[3][55]-(batteryspec[3][j-1]+(compbat-batteryspec[2][j-1])*(batteryspec[3][j]-batteryspec[3][j-1])/(batteryspec[2][j]-batteryspec[2][j-1])))*p)/(5000-3000);

      }

    if (currentref>5000) {
       while (((compbat)>batteryspec[4][j-1])||((compbat)<batteryspec[4][j])){
               j++;
        }
        capacactual=(batteryspec[5][55]-(batteryspec[5][j-1]+(compbat-batteryspec[4][j-1])*(batteryspec[5][j]-batteryspec[5][j-1])/(batteryspec[4][j]-batteryspec[4][j-1])))*p;
    }

    }

    void autonomy() {

      if (modechange==1) {
       consumah=0;
      }

        power=batvoltage*current/1000;
        SOC();

        if (capacactual!=capaccheck) {
          capaccheck=(capacactual+capaccheck)/2;
        }

      if (abs(capacactual-capacstore)>=100){
         EEPROMWritelong(8,roundf(capacactual));
         capacstore=capacactual;
      }

      consumah += 1000*current*elapsed/1000/3600;
      capaccheck -= 1000*current*elapsed/1000/3600;
      consumwh += 1000*current*elapsed/1000/3600*batvoltage;
      elapsedtot += elapsed;
      consumbatper = (capaccheck)/(batteryspec[1][55]*p)*100;
      if (distance==0) {
        switch (powermode) {
          case 1: consumbatrange=45*batvoltage*capaccheck/980;
          break;
          case 2: consumbatrange=35*batvoltage*capaccheck/550;
          break;
        }

      } else {
      consumbatrange = distance/consumah*(capaccheck);
      }
      myGLCD.printNumI(consumbatrange/1000, 2, 350,275);
      myGLCD.printNumI(power/1000, 2, 350,205);
      myGLCD.printNumI(current/1000, 1, 30,50);
      myGLCD.printNumI(ncycles/1000, 1, 30,50+16*2);
      myGLCD.printNumI(consumbatper,1,350,50);
      myGLCD.printNumI(batvoltage/1000,1,350,50+16*2);

      return 0;

    }

    void speedometer() {
    int sense=digitalRead(46);
    long sensecst=691150*3;//x1 000 000

    if (sense==LOW) {
       timesp=millis()-timespm1;
       timespm1 = millis();
       velocity=3600/1000*sensecst/(timesp);//m/h
       if (timesp>1000) {
           velocity=0;
       }
    } else {
      if ((millis()-timespm1)>2000) {
        velocity=0;
      }
    }
    }

  void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      start=millis();
     // pinMode(43, OUTPUT);//Speedo power
     // pinMode(46, INPUT);//Speedometer
      pinMode(A2, INPUT);//Throttle in
      pinMode(A7, INPUT);//Battery voltage
      pinMode(A4, INPUT);//Shunt
      pinMode(throttle, OUTPUT);
      pinMode(11, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(47, INPUT);
      analogWrite(10,255);
      analogWrite(11,255);

      myGLCD.InitLCD(LANDSCAPE);
      myTouch.InitTouch(LANDSCAPE);
      myGLCD.fillScr(0,0,0);
      myGLCD.setColor(VGA_WHITE);
      myGLCD.setBackColor(0,0,0);
      myGLCD.setFont(BigFont);
      myGLCD.print("FURO SYSTEMS",(480-16*12)/2,16);
      myGLCD.print("WELCOME",(480-16*7)/2,(320-16)/2);
      myGLCD.setDisplayPage(0);
      delay(2000);
      myGLCD.clrScr();
      myGLCD.print("FURO SYSTEMS",(480-16*12)/2,16);
      myGLCD.fillRoundRect((480-3*16-8)/2,320-16*2-4,(480-3*16-8)/2+3*16+6,228);
      myGLCD.print("ECO", (480-3*16)/2, 320-16*5);
      EEPROMWritelong(4,1000);
      ncycles=EEPROMReadlong(4);
      cyclescaling();

      for (int m=1; m<=5;m+=2) {
      for (int n=0; n<=55;n++) {
        batteryspec[m][n]*=factor;
        }
      }

      current=analogRead(A4);
      current=current/internresistance*5*1000/1023/75;

      batvoltage=analogRead(A7);
      batvoltage=batvoltage*5*1000*divider/1023;

      SOC();
      capaccheck=capacactual;
      capacstore=EEPROMReadlong(8);

      if (capacactual>capacstore) {
      ncycles+=1000;
      EEPROMWritelong(4,ncycles);
      EEPROMWritelong(8,roundf(capacactual));
      }

      if (capacactual<500) {
        powermode=2;
        myGLCD.fillRoundRect((480-4*16-8)/2,320-16*2-4,(480-4*16-8)/2+4*16+6,228);
        myGLCD.print("FURO", (480-4*16)/2, 320-16*5);
      }//3.21V per cell
      EEPROMReadlong(addresstd);
      Totaldist=EEPROMReadlong(addresstd);
      Totaldistcheck=Totaldist;
      digitalWrite(43,HIGH);
    }

    void loop() {
       throttlein=analogRead(A2);
       throttlein=throttlein*5*1000/1023;
       //throttlesmoothing();
       throttleout=throttlein/1000*255/5;
       analogWrite(8,throttleout);

       modechange=0;
        if (digitalRead(47)==LOW)
        {
          if (buttonst==1) {
          pushed = millis();
          }
          buttonst=0;

          if ((millis()-pushed)>=2000)
          {
           distancedisp=0;
          }
          }

         if (digitalRead(47)==HIGH) {
          if (buttonst==0) {
            modechange=1;
            pushedt=millis()-pushed;
            if (pushedt<1900){
           if (powermode==1)
          { powermode=2;
           myGLCD.clrScr();
           myGLCD.print("FURO SYSTEMS",(480-16*12)/2,16);
           myGLCD.fillRoundRect((480-4*16-8)/2,320-16*2-4,(480-4*16-8)/2+4*16+6,228);
           myGLCD.print("FURO", (480-4*16)/2, 320-16*5);
          }
          else
          {
            powermode=1;
            myGLCD.clrScr();
            myGLCD.print("FURO SYSTEMS",(480-16*12)/2,16);
            myGLCD.fillRoundRect((480-3*16-8)/2,320-16*2-4,(480-3*16-8)/2+3*16+6,228);
            myGLCD.print("ECO", (480-3*16)/2, 320-16*5);
          }
          }
          }
          buttonst=1;
         }

    batvoltage=analogRead(A7);
    batvoltage=batvoltage*5*divider*1000/1023;
    //speedometer();
    current=analogRead(A4);
    current=current/internresistance*5*1000/1023/75;
    elapsed = millis() - start;
    start = millis();

    if (modechange==1) {
       distance=0;
    }
    distanceint = (velocity/3600*elapsed/1000);//m
    distance += distanceint;
    distancedisp += distanceint;
    Totaldist += distanceint;

    if (abs(Totaldist-Totaldistcheck)>=100) { //later do it upon switch off
      EEPROMWritelong(addresstd,round(Totaldist));
      Totaldistcheck=Totaldist;
    }

    autonomy();

    if (velocity>45000) {
    outspeedctl=pidspeed_control();
    outcurrentctl=pidcurrent_control();
    long throttleout1=min(outspeedctl,outcurrentctl);
    throttleout=min(throttleout1,throttlesmooth);
    //analogWrite(throttle, map(throttleout, 0,5,0,255));
    } else{
    outcurrentctl=pidcurrent_control();
    throttleout=min(throttlesmooth,outcurrentctl);
    //analogWrite(throttle, map(throttleout, 0,5,0,255));
    }

    myGLCD.setFont(SevenSegNumFont);
    myGLCD.printNumI(velocity, (480-32*3)/2, (320-50)/2);
    myGLCD.setFont(BigFont);
    myGLCD.printNumF(distancedisp, 1, 30,175);
    myGLCD.printNumI(Totaldist, 30,175+2*16);

    }

emmm, you should maybe jut READ the battery value and not guest it...

Your program does nothing: save for the #includes, everything is inside a big comment that starts on line 10 with /*. Please edit the question and post your actual code.

That is a lot of code to look at. Not sure anyone will. So some helpful pointers instead. Break down your code (into many functions?).   Start by calling only a few bits of it, then add more until the problem occurs.  Also, at this complexity, it might be worth it to abandon the Arduino paradigm and use real Atmel debugging hardware / software so that you can single step through your code.

@EdgarBonet Sorry about that just edited it.

Actually just solved it, it was a mistake with the UTFT library! Using printnumI instead of printNumF

Please write your own anwser and set this question as resolved.

I actually solved this issue and noticed a few things for those interested: the printNumI() function was making the arduino crash as it was badly initiated with an extra argument. Once I solved this and replaced all my printNumF with printNumI I noticed a significant increase in sample rate of about 3-4ms per line changed. In addition, going from float to int calculation didn't change much as the TFT screen takes enormous amounts of computing power: takes me from 333Hz of sampling frequency to about 10Hz with the screen.


text:
Temperature on two 7-segments displays
I'm new to the arduino board and my teacher gave us a project with little to no teaching about the language the board uses, or how to effectively program with it.
I'm trying to read temperature from a DHT11 and display it on two separate 7-segments displays. I've been trying to do this by editing a code he provided us that makes one display count from 0 to 9. I've been to hook up and read the DHT11 and split the temperature into two variables. But I have no idea how to make the variables display on the seven segment displays. My code is.
//DHT11 set up
#include <dht11.h>
dht11 DHT11;
void setup()
{
   DHT11.attach(4);
   for (int i = 0; i < 4; ++i)
    pinMode(i, OUTPUT);
   for (int i = 8; i < 11; ++i)
    pinMode(i, OUTPUT);
}
static int temp = DHT11.fahrenheit();
static int digit_0 = temp % 10;
static int digit_1 = temp - digit_0;
static int digit_2 = digit_1 / 10;
// Output pins.
static int output[] = {0,1,2,3};
// 8421 code lookup table.
static int segs_encoding[][4] =
  {{0,0,0,0},   //=0
    {0,0,0,1},  //=1
    {0,0,1,0},  //=2
    {0,0,1,1},  //=3
    {0,1,0,0},  //=4
    {0,1,0,1},  //=5
    {0,1,1,0},  //=6
    {0,1,1,1},  //=7
    {1,0,0,0},  //=8
    {1,0,0,1}}; //=9
// Outputs an 8421 decimal digit on the output pins from
// base to base + 3 in big endian order.
void show(int base, int num) {
 for (int i = 0; i < 4; ++i) {
   if(segs_encoding[num][i] == 1) {
     digitalWrite(base + 3 - i , HIGH);
   } else {
     digitalWrite(base + 3 - i , LOW);
   }
  }
}
// Output a 2 digit decimal value.
void show_2digit_decimal(int num) {
// force value to displayable range because show() doesn't do any sanity
  if (num < 0)
    num = 0;
  if (num > 99)
    num = 99;
  // display it.
  show(0, num%10);
  show(8, num/10);
}
void loop() {
  static int i = 0;
  show_decimal(i);
  delay(1000);
// Increases the counter.
  ++i;
  if (i == 10)
    i = 0;
}

Let me know if you guys need pictures of my breadboard set up, thanks for any help you guys can provide.

You need to at the very least tell us which IO pins the second digit of the display is on. The language the board uses is basically standard c with a few additions for controlling the IO pins.

I'm assuming you mean the pins on the arduino board? The second one is connected to pins 8, 9, 10, 11.

The show() function already has support for specifying the first pin of the display. So if the second digit is starting at pin 8 and connected in the same order then it should be as simple as:
// Output a 2 digit decimal value.
void show_2digit_decimal(int num) {
  // force value to displayable range because show() doesn't do any sanity checks
  if (num < 0)
    num = 0;
  if (num > 99)
    num = 99;
  // display it.
  show(0, num%10);
  show(8, num/10); // int/int always rounds down to the nearest int
}

You will also have to add the appropriate pinMode(<pin>, OUTPUT); commands to the setup() function to make the pins outputs.
----- update
To get the temperature to display first get rid of these lines, they aren't doing anything useful
static int temp = DHT11.fahrenheit();
static int digit_0 = temp % 10;
static int digit_1 = temp - digit_0;
static int digit_2 = digit_1 / 10;

And then change the loop function to being
void loop() {
  show_2digit_decimal(DHT11.fahrenheit());
  delay(500);
}

Although unless the teacher is completely incompetent you should have been able to work that out yourself, it's not exactly rocket science. If unsure take a guess and try it first before asking. The logic is simple enough that you should be able to work it out. For syntax errors the compiler error messages will normally tell you exactly what's wrong.

I added that to my code, but I'm getting a compiling error. My new code looks like

I edited my new code into the question.

What error are you getting. "a compiler error" is totally useless. 2) what happened to the rest of the code? Your loop() function has vanished. What is the program supposed to do after it's done the setup? Arduino has a hidden top level which in c would be written as main(){setup();while(1) loop();}. You need a loop() function if you want anything to happen.

I brought back the loop function and that fixed the error. I'm trying to get the first digit of the temperature to display on 7 segment display and the second digit to display on the second 7 segment display. I know that the code in the loop function wont do that, I just have no idea what to change it too to make it do that.

See the update in the answer

Okay the first display is correct but second one isn't lighting up. I assume it has something to do with my wiring. Thanks for all the help!

There are many issues with this code:

The compiler says “error: ‘show_decimal’ was not declared in this
scope”. Indeed, you named the function show_2digit_decimal(), so
you should call it by that name.
The compiler also said: “warning: ‘output’ defined but not used”.
There is no valid reason to leave something defined that you do not
use. Just remove it.
You also have a function named sertup() that you defined but never
used. It looks like a typo. You should remove the function, and put
it's current contents inside setup().
You have the variables digit_0, digit_1 and digit_2 that serve
no useful purpose. Remove them as well.
You wrote, at top level: static int temp = DHT11.fahrenheit(); Don't
do this. This kind of initialization happens before setup(), i.e.
before you had a chance to attach() the sensor to its pins.
Your array segs_encoding is not a 7-segment encoding, it's just
the binary encoding of the numbers. You don't need it: the processor
already knows how to count in binary, and you can replace
segs_encoding[num][i] by num>>i&1. If you really have 7-segment
displays, you need 7 pins for each, unless you multiplex them. Search
this site for “7 segment” to see how to drive them.
The section
if(segs_encoding[num][i] == 1) { digitalWrite(base + 3 - i , HIGH); ...
can be simplified to
digitalWrite(base + 3 - i , segs_encoding[num][i]); or, considering
the previous point, to digitalWrite(base + 3 - i , num >> i & 1);
The test if (num < 0) num = 0; if (num > 99) num = 99; can be
written more succinctly by using the function Arduino provides for
that: num = constrain(num, 0, 99);
In loop(), you are only displaying a counter. You probably should
display the temperature instead.

All the previous comments lead to the following version of the code:
#include <dht11.h>

const int units_base_pin = 0;  // units on pins 0..3
const int tens_base_pin = 8;   // tens on pins 8..11

dht11 DHT11;

// Outputs a number in binary on the output pins from
// base to base + 3 in big endian order.
void show(int base, int num) {
    for (int i = 0; i < 4; ++i) {
        digitalWrite(base + 3 - i , num >> i & 1);
    }
}

// Output a 2 digit decimal value.
void show_2digit_decimal(int num) {
    // force value to displayable range because show() doesn't do any sanity
    num = constrain(num, 0, 99);
    // display it.
    show(units_base_pin, num%10);
    show(tens_base_pin, num/10);
}

void setup() {
    DHT11.attach(4);
    for (int i = 0; i < 4; ++i)
        pinMode(i, OUTPUT);
}

void loop() {
    show_2digit_decimal(DHT11.fahrenheit());
    delay(1000);
}


text:
How high of a baud rate can I go (without errors)?
The standard is 9600 baud. That's just the standard. Using a Arduino Uno SMD R2, what is the highest practical baud rate I can achieve?
Bonus points for the audacious: how would you go about creating an error checking mechanism and then increasing the baud rate ridiculous high to get high transfer rates?

It's worth noting that Arduino boards that use FTDI USB-serial ICs can go REALLY fast. The common FT232 can go 3 Megabaud (that's 3,000,000 baud) without issues. The use of a ATmega16U2 is the limiting factor.

My clone Arduino Nano that I got from eBay maxed out at 1,099,999. Seriously. It did. Once it reached 1,100,000, the output was garbled. laqq`na`fca`fga`fga`bcngaah````iin`ha`a`a`bga`fga`bcqpahhqfq```fh`oopa`bca`fca. It uses a CH340 chip for USB comms.

There are several factors here:

How high of a baud-rate can the ATmega328P MCU achieve?
How high of a baud-rate can the USB-Serial interface achieve?
What is the oscillator frequency on the ATmega328P?
What is the oscillator frequency on the USB-serial interface (if it has one)?
How tolerant is the USB-serial interface of baud-rate mismatch?

All of these factors are relevant to determining the maximum achieveable baud rate. The ATmega328P uses a hardware divisor from it's clock-rate to generate the base-clock for the serial interface. If there is no integer ratio from the main clock to the bit-time of the desired baud rate, the MCU will not be able to exactly produce the desired rate. This can lead to potential issues, as some devices are much more sensitive to baud-rate mismatch then others.
FTDI-based interfaces are quite tolerant of baud-rate mismatch, up to several percent error. However, I have worked with specialized embedded GPS modules that were unable to handle even a 0.5% baud rate error.
General serial interfaces are tolerant of ~5% baud-rate error. However, since each end can be off, a more common spec is +-2.5%. This way, if one end is 2.5% fast, and the other is 2.5% slow, your overall error is still only 5%.

Anyways. The Uno uses a ATmega328P as the primary MCU, and a ATmega16U2 as the USB-serial interface. We're also fortunate here in that both these MCUs use similar harware USARTs, as well as 16 Mhz clocks.
Since both MCUs have the same harware and clock-rate, they'll both have the same baud-rate error in the same direction, so we can functionally ignore the baud error issue.
Anyways, the "proper" answer to this question would involve digging up the source for the ATmega16U2, and working out the possible baud-rates from there, but since I'm lazy, I figure simple, empirical testing will work.
A quick glance at the ATmega328P datasheet produces the following table:

So given the max stated baud-rate of 2 Mbps, I wrote a quick test program:
void setup(){};

void loop()
{

  delay(1000);
  Serial.begin(57600);
  Serial.println("\r\rBaud-rate = 57600");
  delay(1000);
  Serial.begin(76800);
  Serial.println("\r\rBaud-rate = 76800");
  delay(1000);
  Serial.begin(115200);
  Serial.println("\r\rBaud-rate = 115200");
  delay(1000);
  Serial.begin(230400);
  Serial.println("\r\rBaud-rate = 230400");
  delay(1000);
  Serial.begin(250000);
  Serial.println("\r\rBaud-rate = 250000");
  delay(1000);
  Serial.begin(500000);
  Serial.println("\r\rBaud-rate = 500000");
  delay(1000);
  Serial.begin(1000000);
  Serial.println("\r\rBaud-rate = 1000000");
  delay(1000);
  Serial.begin(2000000);
  Serial.println("\r\rBaud-rate = 2000000");
};

And then looking at the relevant serial port with a serial terminal:

So it appears the hardware can run at 2,000,000 baud without problems.
Note that this baud rate only gives the MCU 64 80 clock-cycles per byte, so it would be very challenging to keep the serial interface busy. While the individual bytes may be transferred very rapidly, there is likely to be lots of time when the interface is simply idle.

Edit: Actual Testing!
The 2 Mbps is real:

each bit-time is 500 ns, which matches exactly with what is expected.
Performance issues! Overall packet length:
500 Kbaud:

1 Mbaud:

2 Mbaud:

Note: The noticeable overshoot is due to poor scope probe grounding practices, and is probably not real. I'm using the ground-clip-lead that's part of my scope probe, and the lead-inductance is likely the cause of the majority of the overshoot.
As you can see, the overall transmission length is the same for 0.5, 1 and 2 Mbaud. This is because the code that is placing the bytes in the serial buffer is poorly optimized. As such, you will never achieve anything better then an effective 500 Kbaud, unless you write your own serial libraries. The Arduino libraries are very poorly optimized, so it probably wouldn't be too hard to get a proper 2 Mbaud, at least for burst transmissions, if you spent a bit of time on it.

Nice illustration of the throughput limitation!

@jippie - I had the scope up, and was running the program in my answer that cycles through baud rates. It was very little additional work, and does illustrate the issue quite nicely. Also, the segmented memory on my scope is awesome.

DS2000 series? Does lowering the bitrate to 250kb actually double the time of the transmission? I think I can still easily spot the start/stop bits in the 500kb image.

@jippie - 4000 series. I loves me some 4 channels.

If you skip the Serial library, you can get much faster.

@Cybergibbons - Yep. See the note at the end about optimization.

Wow I thought that the 9600 baud was pretty good for an AVR device but I never expected 2 MBPS!

@AnnonomusPerson - If you switch to a 20 Mhz clock, you can do 2.5 Mbps.

@FakeName 20 Mhz main crystal or on the USB chip?

@AnnonomusPerson - You'd need to swap both, or use a FTDI usb-serial interface with a 20 Mhz ATmega328P oscillator. The ATmega328P can't do 2.5 Mbps without a 20 Mhz crystal/resonator. The same is true for any ATmega16U2 interfaces.

Great answer! Just one small correction: at 2 Mb/s, each byte transmission takes 80 CPU cycles, not 64. This is because, time-wise, each byte is worth 10 bits (1 start, 8 data, 1 stop).

@EdgarBonet - You are quite correct (and whoops). Fixed.

This is a great answer with one exception in that it doesn't account for the affects of the physical media (wire/cable used to connect to the other device). This will also be a major limiting factor in useful baud rates. Serial communication is pretty boring with just one device (loopback included). ::grin::

@linhartr22 - Wires only really come into play if they're long, as in 12"+. I think it's probably unlikely that too many people are using 100 foot long cables too much. Besides, the question was how high the arduino/ATmega baud rate can go, not how high an arbitrary cable assembly can go.

@ConnorWolf, I don't know if I agree 100% with this statement, "Since both MCUs have the same harware and clock-rate, they'll both have the same baud-rate error in the same direction, so we can functionally ignore the baud error issue."  I don't see how being the same UART would guarantee error in the same direction, as individual chips can still vary randomly right?--and although the chips both are the same freq, which means serial freq calculation error is in the same direction, I know the chips don't use the same clock source (16U2 uses crystal, 328 uses separate ceramic oscillator).

@GabrielStaples - You're missing the error I'm talking about. Basically, the way the ATmega UARTs work is they use an integer divider from the MCU clock to generate the serial timing. As such, some baud rates cannot be directly achieved, as the ratio between the baud rate and the system clock is not an integer. Generally, in this situation, the closest option is chosen, which results in the error I'm talking about here (abs(closest option - target baud) = err). This error will be matched between the two different parts.

While chips can vary, the operation of the UART is deterministic, so if you drive two parts with the same clock source, you'll get the same outputs (minus some small potential jitter).

@ConnorWolf, I see, so what this implies is that if you want to maximize the possibility of two devices to talk at a very high baud-rate, since this is asynchronous communication, you should have them both use the same frequency clock so that their actual baud-rates are skewed in the same direction, thereby aligning their bit-timing better? Is that right? ie: a 16MHz Arduino with a 16MHz USB to UART device is better than a 16Mhz Arduino with a 20MHz USB to UART device?

Basically, the issue is that you have a MCU with a 20 MHz clock, you might get a -1.5% error from the baud-rate divisor and the oscillator variance could be -1%. Then, if talking to a MCU with a 16 MHz osc which produces a +2% divisor error, and a +1.5% oscillator error, all your errors sum up to 5% in total. However, if you share the same reference oscillator frequency, the baud rate divisor errors match, so they cancel out, and the only relevant factor becomes the oscillator error.

Edit: Yeah, you've got it. However, the baud-rate generation logic is specific to a device/line-of-devices,so comparing between different manufacturers can be complicated.

I see now. I just checked the ATmega328 datasheet. Here's another table (from pg. 175) you might want to throw in your answer under the first one. It helps calculate the baud-rates to verify their errors in the table, and it makes it clear to me how they got their errors. For example, 115.2k shows -3.5% error for asynchronous normal mode (U2Xn=0). The formula goes: 16e6/(16*(8+1)) = 111111.11bps. That's the closest option. So, the error is 111111.11/115200 = 0.9645 = -3.5%.

Funny that the 1MBPS baud and 2MBPS baud will take the same time to transmit. It's because of the bytes not being copied fast enough?
This might also mean that you won't be able to receive the bytes at this speed. Ofcourse you can receive 1 byte at 2Mbaud, but for receiving multiple bytes, it depends on how fast the Arduino clears the serial buffer (and thus another byte can be received).

@Paul - The arduino doesn't do anything. The ATMega328p, on the other hand, does lots of stuff. Anyways, The throughput issues are a function of the efficiency of the transmit interrupt handler speed. As a rule, the code in the default arduino libraries is, well, really poor quality. It should be entirely possible to saturate the serial link for at least short bursts.

Do you think that  adding de-bouncing caps (~10-2pf) to ground may increase the stability?

@tuskiomi - What? No, the issue is the inductance of the ground clip wire that's part of my scope probe. The proper solution is to use a probe tip ground, but unless you're specifically trying to measure things like risetime, as long as you know the ringing isn't real, it's not a significant issue.

@ConnorWolf I'm not sure. for example, over on my question, The capacitors negated most  of the spiking, which would not happen if it was a probe thing.

@tuskiomi - That's to be expected, since the capacitors slow down the edge-rate, which means the inductance of the ground clip has a smaller effect. The point is, the spiking is 1. not harmful, 2. in the great majority of the cases, not actually real, but rather a measurement artifact. Additionally, if anything, the capacitors are worse for the circuit, since they're a load directly on the output drivers of the IC driving the bus. In general, there are very few cases where you ever want to add capacitance to a data bus.

Basically, before starting to stick capacitors everywhere, learn to use your tip ground, and check with that. Here is a white-paper by Teledyne LeCroy on the topic. Here is another from Tektronix.

Remember, even if your data rate is relatively slow, it's the edge rate that determines the effect the ground lead inductance has, rather then the edge frequency. Even slow little devices like ATMega ICs can produce quite fast edges.

There is also the issue of the ceramic resonator used for the MCU clock on some Arduinos, e.g. Arduino Uno (they don't technically lie on the product page, but the quartz oscillator is used only for the USB helper MCU, not the main microcontroller). It introduces an up to 0.5% error. This may or may not be significant, depending on the circumstances (for instance, using the second serial port). Perhaps cover this as well in the answer?

The error accumulates, so the last bit's time may already be off by close to 5% due to the ceramic resonator. How much can be tolerated as the accumulated error? 8%?

I am a bit late to the party, but how do we know the baud rates are real for USB Serial? I thought USB Serial baud rate as seen by software is fake, because the real bit rate is fixed by the USB protocol, with its own headers, checksums, acknowledgements? (Speed then is limited to fixed choices of Low, high, full, etc, soldered into hardware - then software only has UART-like API for CDC devices, but not actual UART)

@SassaNF - For devices where there isn't a separate USB-serial converter (either a AVR,  FTDI device or similar), the baud rates are indeed not real. However, most AVR arduino boards have separate converters with a real (albeit TTL-level) serial link between the converter and the actual MCU.

@ConnorWolf ah, I see, I didn't realize that. How is the computer-side baud rate linked to that? Is it somehow communicated over to the "arduino" side through some part of USB protocol? (what's the importance of matching computer-side and arduino-side baud rate)

The Arduino Serial Monitor window limits you to 115200, but that's not the highest baud rate capable. You can read the Atmel and the FT232 (or whatever you're using) datasheets to find out the maximum but I am able to successfully use 230400 (twice as fast as the largest the Arduino Serial Monitor supports) with no issues.
If you want to see the results in your computer, you will need another serial monitor that supports other baud rate options. I like CoolTerm and Termite.
Do note that this heavily depends on your clock speed as well.
Here's a calculator to help you with calculating what's possible.

As you start going faster and faster, the limitation becomes the Serial library - it's implementation isn't very efficient.

website of link is dead

"The Arduino Serial Monitor window limits you to 115200," - That's no longer true. It goes up to 2Mbps

Error checking is actually very easy and there is an AVR lib that does this in a one liner.
Read up on  util/crc16.h and you should be good to go in no time with the included examples.
CRC is quite robust and fast for simple applications.

This is probably one of the few aspects where el-Cheapo boards differ from original boards. The maximum serial transfer rate is pretty much only limited by the quality of the board and its layout. Once the serial data enters either AVR or USB interface chip, the data will be processed differently from the serial UART protocol.
Keep in mind though that the microcontroller has some basic hardware to shift in/out serial data to/from the IO pins, but the absolute maximum rate is limited to the 16MHz clock (for AVRs). Once a byte is moved to the serial buffer, the UART hardware will take over and push out / pull in the bits on its own. An AVR at best reaches 16M instructions per second and the interrupts used to fill the serial buffer have some overhead (at least 8 clock ticks for the interrupt handling + instructions to save current state + several instructions for actually filling the buffer). At a given bitrate, the protocol will run at a whopping n bits per second, but your controller needs more time to fill the serial buffer than it needs to actually output the data, resulting in a lower average throughput than you expect and the UART idling for a relatively long time. Disadvantage is the increased probability for bit errors.
Another effect to remember is that all the overhead required to push data out onto UART (or pull it in) cannot be spent in your actual program, again affecting the average practical throughput. You can only use every instruction cycle once, either for filling the buffer or for computing the main loop.
The maximum throughput is therefore dependent on the application you use (how fast is data generated/computed/ready to move to/from the serial buffer) and the actual 'physical' bitrate is only a small part of the design decision.

I really, REALLY doubt any of the boards out there have layout issues severe enough to prevent a 2 Mhz signal from working fine. 2 Mhz isn't exactly high frequency.

@FakeName At least one board on my desk here has increased BER when I push serial speed. I usually use 9600, that is more than enough for most applications and is robust.

No kidding! Huh. I wonder how bad the layout has to be to have that happen? I'd suspect it's not layout as much as poor-tolerance resonators/crystals, though.

High baud-rates, particularly if U2Xn = 1 in the USART, tend to get pretty cranky about mismatch.

@FakeName I'm a dinosaur, I kinda like "9600 8N1" for all the wrong legacy reasons you can think of ;o)

Hell, I use 9600 myself for most debugging crap. It's not just you. It's just occationally I need to push a lot of data around, and knowing the limits is important.

I wouldn't be surprised if the increased BER is due to a cheap fake serial chip. (FTDI counterfeit) @ConnorWolf


text:
How to implement the Arduino Extended Database library in a custom class?
I am struggling to implement a custom class that uses the Arduino Extended Database Library (EDB.h). The purpose of my custom class is to manage my application's internal database.
While searching for a solution I found this, which seems very relevant: the code and goal are the same as mine.
But my problem with that Q&A is that I am not able to implement the given solution as I don't fully understand the way it should be written.
For the sake of trying to give the best support for explanation, I upladed the code below. Feel free to explain me how to modify it.
Thank you.
EDIT: Following duplicate comments, I'll try to be more precise in my question.

Indeed, I even posted the link.
If I did it's for a specific reason: I do not understand the solution.
May be you could help ? Thx Juraj

I think it is explained good there

Juraj, sure it must be good if one have the knowledge, which I haven't.
In clear: do you understand that I do not understand the given explanation ?
If its good enough for you, and you understand it, may be you could  please give me more details on how to implement it ? Thanks

simplified: you can't give a class member function, where function is required.

@Juraj That's not entirely correct.

@CodeGorilla, I know. can you explain it better than in the answer to the referred question?

It is difficult to answer this question because I'm not sure what you have managed to achieve.  Sorry if some of it seems a bit basic.
Look at Majenko's answer to the question.  If you want to use this EDB class then you need to define two functions:
  void configWriter( unsigned long address, byte data );
  byte configReader( unsigned long address );

You need to be able to access the single instance of these functions from anywhere in the code, so the need to have global scope.  When they are global you can assign them to pointers by using the function name and no brackets/parenthesis.  i.e.
aPtr = configWriter;

So the call to create the EDB instance would be:
 configDB = new EDB( configWriter, configReader );

Now you could create the EDB instance using a class member function.  To do this you have to make the function a static member, which means it has no access to the class's data. (in its simplest terms static means there is only one of the things it is referring to) i.e.
class myEDB
{
  public:
    static void configWriter( unsigned long address, byte data );
    static byte configReader( unsigned long address );
...
};
configDB = new EDB( myEDB::configWriter, myEDB::configReader );

Essentially its the same thing, but the code is compartmentalised better and you end up with neater code.
However, if you are only ever going to have one instance of the myEDB class then you can have a static member variable that hold the value of this.  You set this value in the class constructor.
class myEDB
{
  public:
    static void configWriter( unsigned long address, byte data );
    static byte configReader( unsigned long address );
    myEDB() {pInstance = this;}
  private:
    static myEDB* pInstance = nullptr;
...
};
configDB = new EDB( myEDB::configWriter, myEDB::configReader );

When configReader or configWriter is called it checks to see if the member pInstance has a non null value, if it doesn't then it creates a new instance.  The then use this pInstance to access the functions and variables for the instance of the class.  (This is the design pattern for a single instance class or singleton).
SO what should YOU do?
Start simply, define two global functions that do what you need as per the top of this answer.  If you get stuck, if you need more info feel free to ask or comment.

Hello and Thank you again Code Gorilla. I posted my code following your explanation, and the resulting compilation errors. Can you help me to understand these errors, and modify the code accordingly ?


text:
Getting incorrect output from ADC over SPI in Arduino Uno
I am trying to read data from an ADC ADCS7476 (datasheet) using SPI on Arduino Uno. I am using the following code to read the data from the ADC and printing it on serial monitor. However, the code is always printing 0. I never used SPI before and I am not able to debug the issue, does anyone know where I am going wrong.
I am using the following connections:

ADC's SCLK to Pin 13 on Ardunio
ADC's SDATA to Pin 12 on Arduino
ADC's CS to Pin 10 on Arduino

Code:
#include <SPI.h>
#define cs 10

SPISettings settingsA(250000, MSBFIRST, SPI_MODE0);
byte highbyte,lowbyte;
unsigned int data;

void setup() {
  Serial.begin(9600);
  pinMode(cs, OUTPUT);
  digitalWrite(cs, HIGH);
  delay(1000);
  SPI.begin();
}

void loop() {
  SPI.beginTransaction(settingsA);
  digitalWrite(cs, LOW);
  delayMicroseconds(1);
  highbyte = SPI.transfer(0xFF);
  lowbyte = SPI.transfer(0xFF);
  digitalWrite(cs, HIGH);
  delayMicroseconds(1);
  SPI.endTransaction();
  data= ((unsigned int)highbyte << 8 ) + lowbyte;
  Serial.println(data);
  delay(100);
}

apart from the #include and #define having a space (but since the compiler does not complain I think it is just a wrong copy-paste), I can't see anything obviously wrong. So, just for the most basic questions, 1) is the circuit powered? 2) does the ADC have its own power supply or you are powering it from the arduino 5V? 3) if the former, did you connect th two grounds? 4) is the adc powered at 5V? 5) Can you attach an oscilloscope to the data and clock lines to see what is on the bus?

see the BarometricPressureSensor example of the SPI library

You can't delay this little  delayMicroseconds(1);  Minimum workable value is 3 or 4 per the Arduino Reference section.

You also don't need this line at all  SPISettings settingsA(250000, MSBFIRST, SPI_MODE0);  The default settings use 4 MHz, clock, MSBFIRST, SPI Mode 0. The part works with up to 20 MHz clock, so 4 would be fine.  At 16 MHz, 1 uS is 16 clocks, so digitalWrite or two to another pin after taking CS low would give a short delay for the conversion to get started.

@frarugi87 The circuit is powered from the arduino 5v and the two grounds are connected. I will attach the oscilloscope screenshots by tonight or tomorrow.

@CrossRoads Should I have to increase the delay?

delayMicroseconds(1) I think results in 0 delay.  Change to 3 or 4, that will be the lowest usable value.

I am leaving this answer in case anyone stumbles across this question in the future
In a super frustrating, anti-climactic end, it turns out that the ADC chip itself was not working properly. I tested the (faulty) chip using the code above and observed the output of data pin on the oscilloscope and the output was the same square wave irrespective of the input. I managed to find a new ADC and I tested it and it was working correctly. But this raises a new issue for me, this is the third ADC chip I tested that was working correctly, the first two were faulty. It is very unlikely that it is a manufacturing issue and I used the same connections and the same code to test all three of them. Maybe it has to something to do with soldering, because AFAIK that's the only thing that's different.  If anyone knows anything else that might have gone wrong, I'm all ears.


text:
Any source code for connecting a tinyshield to another tinyshield?
I recently purchase 2 tinycircuit smart watch. I am wondering if anyone knows if there is any source code for me to reference on how do I connect one tinyshield to another tinyshield. I understand that a tinyshield is both a master and slave. I am trying to connect 2 tinyshield to each other such that I could transmit data between those two tinyshield.
Currently, when I upload the code into two tinyshield, the receiving tinyshield can't seem to be receving any thing, while the sender tinyshield is sending over data
Sender code
#include <SoftwareSerial.h>

SoftwareSerial mySerial(12, 11); // RX, TX

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial) {
    Serial.print("connecting"); // wait for serial port to connect. Needed for native USB port only
    }
    mySerial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int vert = 200;
  int LDRReading = 100;
  delay(1000);
  Serial.print("LDR : ");
  Serial.print(LDRReading);
  delay(1000);
  Serial.print(" acc: ");
  Serial.println(vert);
  sendData(LDRReading, vert);
}

void sendData(int ldr, int accel)
{
    mySerial.write(((ldr >> 7) & 0x7F) | 0x80); // Upper 7 bytes and first bit
    mySerial.write(ldr & 0x7F); // Lower 7 bytes
    mySerial.write((accel >> 7) & 0x7F); // Upper 7 bytes
    mySerial.write(accel & 0x7F); // Lower 7 bytes
}

Receiver Code
#include <SoftwareSerial.h>
#include <SPI.h>

SoftwareSerial mySerial(12, 11); // RX, TX

void setup() {
  // put your setup code here, to run once:
 // initialize serial communication:
  Serial.begin(9600);
  while (!Serial) {
    }
    mySerial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int result=0,acc=0;
if (getDataFromSerial(&result, &acc))
{
    // use accel and ldr
}
  if(result!=0&&acc!=0){
    Serial.print(result);
    Serial.print(acc);
  }

}

boolean getDataFromSerial(int *p_ldr, int *p_accel)
{
    boolean foundData = false;

    while ((!foundData) && (mySerial.available() >= 4))
    {
        if (!(mySerial.peek() & 0x80))
        { // If the first byte in the buffer is not a valid start, discard it
            mySerial.read();
            continue;
        }

        *p_ldr = mySerial.read() & 0x7F;
        *p_ldr = ((*p_ldr) << 7) | (mySerial.read() & 0x7F);
        if ((*p_ldr) & 0x2000) (*p_ldr) |= 0xC000; // This is the sign extension

        *p_accel = mySerial.read() & 0x7F;
        *p_accel = ((*p_accel) << 7) | (mySerial.read() & 0x7F);
        if ((*p_accel) & 0x2000) (*p_accel) |= 0xC000; // This is the sign extension

        foundData = true;
        }
         return foundData;
    }

That depends on the shields, that you are using. As I understood from the Tinycircuits product page the modules need different communication methods. Some use Serial, some SPI and others I2C. Please give us more details and what you have tried so far.

I have tried connecting the tinyshield to tinyshield via serial to serial.

Please put all new information into your question by editing it. We are trying to build a coherent Q&A database to help others. 2. We still need more information. Are you trying to connect 2 master shields (those with the Atmega328p on them), or different shields? And what have you tried so far? There are tons of Serial code out there and the chip is the same as in the Arduino Uno and Nano, so you can reuse many of them.

My apology, I have edited my question and included my codes for what I have try.

while (!Serial)  Serial.print("Who's writing this ?"); looks a bit silly (or like a philosophical paradoxon) to me :)

Besides connecting Rx-Tx and Tx-Rx you have to connect both GND too. (Just in case)

Have you tried to simply immediately send all data received from Software Serial over Serial? That would show, if the data actually get's read. Currently you are doing a lot with the data, before actually sending it, including discarding data. You should first look, if the correct data get's received correctly


text:
Arduino Due with Logitech F710 gamepad
I'm having Arduino Due board and Logitech F710 Wireless Gamepad. I have connected the receiver dongle to native port of Due board via OTG cable.
As the native usb host library supports only keyboard and mouse,
pease help me with correct library for connecting my gamepad with Due board without usb_host_shield as I have budget constraint and space constraint.
Thanks in advance

it is unclear what you are wanting to do ... what are the two things that you want to connect together?

Logitech F710 Wireless Gamepad -> USB OTG -> Arduino Due (Native Port)

here is a project that may get you started ... https://tutorial.cytron.io/2019/05/01/interfacing-logitech-wireless-gamepad-f710-using-arduino/

This is done with the help of external usb shield. I want to make use of the usbhost built-in Due board. Default it only supports keyboard and mous. I want to know how to extend that to Logitech f710 Gamepad.

that library shows you how to talk to the gamepad ... you will have to adapt the code to your device


text:
Im having another problem with my code the error is "redefinition of 'AF_DCMotor motor'?
Heres the code
#include <AFMotor.h>

AF_DCMotor motor(1, MOTOR12_8KHZ);
AF_DCMotor motor(2, MOTOR12_8KHZ);
AF_DCMotor motor(3, MOTOR34_1KHZ);

void setup()  {
  Serial.begin(9600);
  Serial.printIn("Motor Test!");
  motor1.setSpeed(15); //set speed of motor
  motor2.setSpeed(15); //set speed of motor
  motor3.setSpeed(15); //set speed of motor

}
void loop() {
  Serial.print("tick");
  motor1.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor1.run(RELEASE);
  delay(5000);

  Serial.print("tack"); //first song starts
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor1.run(RELEASE);
  delay(9000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //first song ends
  motor1.run(RELEASE);
  delay(20000);

  Serial.print("tick");
  motor1.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(5000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(FORWARD);
  delay(1000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

   Serial.print("tock");
  motor2.run(FORWARD);
  delay(1000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //first song stops
  motor2.run(RELEASE);
  delay(14000);

  Serial.print("tock"); //first song stops
  motor3.run(RELEASE);
  delay(11000);

  Serial.print("tick"); //first song stops
  motor3.run(FORWARD);
  delay(22000);

  Serial.print("tock"); //first song stops
  motor3.run(RELEASE);
  delay(19000);
}

Here is the error:
   ^~~~~~

   motor

snowmanDC_Motor:13:3: error: 'motor3' was not declared in this scope

   motor3.setSpeed(15); //set speed of motor

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:13:3: note: suggested alternative: 'motor'

   motor3.setSpeed(15); //set speed of motor

   ^~~~~~

   motor

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino: In function 'void loop()':

snowmanDC_Motor:18:3: error: 'motor1' was not declared in this scope

   motor1.run(FORWARD);

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:18:3: note: suggested alternative: 'motor'

   motor1.run(FORWARD);

   ^~~~~~

   motor

snowmanDC_Motor:47:3: error: 'motor2' was not declared in this scope

   motor2.run(FORWARD);

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:47:3: note: suggested alternative: 'motor'

   motor2.run(FORWARD);

   ^~~~~~

   motor

snowmanDC_Motor:115:3: error: 'motor3' was not declared in this scope

   motor3.run(RELEASE);

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:115:3: note: suggested alternative: 'motor'

   motor3.run(RELEASE);

   ^~~~~~

   motor

exit status 1
redefinition of 'AF_DCMotor motor'

Do you have V1 or V2 shield? They have different library.

@Tommy, you are still at it ... congratulations for not giving up .... I can tell you right now, you will have a long battle until you tell us what hardware you have and how you connected it

You consistently fail to use libraries that you have installed. Or you are sure you have installed. Instead of repeatedly throwing the same code at us with a different library you should instead take a step back and look more into how you are going about installing libraries and why, maybe, the IDE can't find them.  https://www.arduino.cc/en/guide/libraries

Comments are not for extended discussion; this conversation has been moved to chat.

Adafruit has a V1 and a V2 motor shield. They have different libraries too. AFMotor.h is for the V1 shield. From the error, I can tell you installed V2 lib. For that you need to include:
#include <Adafruit_MotorShield.h>

I needed to install the Adafruit v1 library Thanks for the help tho, Im new to all of this stuff. but now its saying another error "redefinition of 'AF_DCMotor'

I fixed the question to the new question, the new error is in there too

On line 3,4, and 5, you used same name "motor" for all three instances. Changed those to motor1, motor2, and motor3