text:
Problem in AT+CIPSEND(CTRL-Z) GPRS GMS A6
I am using GPRS GSM A6 with arduino uno to post data to web server. After sending AT commands to module I get OK response after every command,
AT+CIPMUX=0

OK
AT+CGATT=1

OK
AT+CSTT="internet","",""

OK
AT+CIICR

OK
AT+CIFSR

10.65.87.210

OK
AT+CIPSTART="TCP","xxx.xxx.xxx.xxx", 80

CONNECT OK

OK
AT+CIPSEND

> POST http://xxx.xxx.xxx.xxx/Code/ HTTP/1.1
Host: xxx.xxx.xxx.xxx
Content-Type: application/x-www-form-urlencoded
Content-Length: 18

Data=GPS Data Sent
AT+CIPCLOSE

>

To terminate AT+CIPSEND you have to send CTRL-Z. I am sending CTRL-Z using this statement in code,
Serial.write(0x1A)

But the module doesnot respond to this, and treats the next command (AT+CIPCLOSE) as data.
Please Help... Thanks in Advance!!!

Also just so you know x-www-form-urlencoded requires + instead of spaces and any non-alphanumeric characters must be percent encoded https://en.wikipedia.org/wiki/Percent-encoding

RTFM: https://github.com/espressif/esp8266_at/wiki/CIPSEND
You need to close the input steam with "+++" to return to command mode.

You can use AT+CIPSEND= instead of AT+CIPSEND

To terminate AT + CIPSEND just apply the next command:
Serial.write(26);

or
gsm.write(26);

where gsm is the UART channel of gsm module.


text:
Read from serial monitor till timeout
Is is possible to read from serial window till timeout?
Actually, what I am looking for is a function that reads from serial monitor, and if no data is available in serial monitor, then it should wait for some time and if still no data is arrived it should return.
Something like,
Serial.read(int timeout);

That's nearly what Serial.readString() does, only you have to set the timeout in advance.  However, such an approach may or may not be what is best for your ultimate goals.

source: Stack Exchange

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

sort: votes


text:
Sending A String from a Website to Arduino
I'm quite new to Arduino and have looked at many tutorials featuring an Arduino requesting data from a web server through a Wifi Shield, but haven't seen one featuring the sending of data from a website/server to an Arduino. I'm attempting to use a JavaScript then PHP script to send a string variable to the Arduino, which would then of course run its code at this point. Is this possible if I have a Wifi Shield and the Arduino's IP address?

Can you clarify if you want the Arduino to be a server or client?

send a string variable to the Arduino, which would then of course run its code - server

As @MattClark said, Arduino would be the server

However the question read: looked at many tutorials featuring an Arduino requesting data from a web server through a Wifi Shield - the Arduino requesting data from a web server makes it sound like a client to me.

If you really want the Arduino to be a web server (that is, you connect to it with your web browser) then I made a library a little while back to simplify processing the get/post/pathname/cookie arguments.
See Tiny web server for Arduino or similar.
Example code (that comes with the library) turns on various LEDs (presumably connected to pins on the Arduino) upon getting a "get" request like this:
http://10.0.0.241/?on=4&off=5

That would turn on pin 4 and turn off pin 5. Obviously you change the IP address to suit your network, and use a suitable MAC address.
// Tiny web server demo
// Author: Nick Gammon
// Date:  20 July 2015

#include <SPI.h>
#include <Ethernet.h>
#include <HTTPserver.h>

const int LOW_PIN = 3;
const int HIGH_PIN = 5;

// Enter a MAC address and IP address for your controller below.
byte mac[] = {  0x90, 0xA2, 0xDA, 0x00, 0x2D, 0xA1 };

// The IP address will be dependent on your local network:
byte ip[] = { 10, 0, 0, 241 };

// the router's gateway address:
byte gateway[] = { 10, 0, 0, 1 };

// the subnet mask
byte subnet[] = { 255, 255, 255, 0 };

// Initialize the Ethernet server library
EthernetServer server(80);

// derive an instance of the HTTPserver class with custom handlers
class myServerClass : public HTTPserver
  {
  virtual void processPostType        (const char * key, const byte flags);
  virtual void processGetArgument     (const char * key, const char * value, const byte flags);
  };  // end of myServerClass

myServerClass myServer;

// -----------------------------------------------
//  User handlers
// -----------------------------------------------

void myServerClass::processPostType (const char * key, const byte flags)
  {
  println(F("HTTP/1.1 200 OK"));
  println(F("Content-Type: text/html\n"
            "Connection: close\n"
            "Server: HTTPserver/1.0.0 (Arduino)"));
  println();   // end of headers
  println (F("<!DOCTYPE html>\n"
             "\n"
             "\n"
             "<title>Arduino test</title>\n"
             "\n"
             "\n"));

  } // end of processPostType

void myServerClass::processGetArgument (const char * key, const char * value, const byte flags)
  {

  int which = atoi (value);
  if (which >= LOW_PIN && which <= HIGH_PIN)
    {
    if (strcmp (key, "on") == 0)
      {
      digitalWrite (which, HIGH);
      print (F("
Turning on pin "));
      println (which);
      }
    else  if (strcmp (key, "off") == 0)
      {
      digitalWrite (which, LOW);
      print (F("
Turning OFF pin "));
      println (which);
      }
    else
      {
      print (F("
Bad action: "));
      fixHTML (value);
      println (F(""));
      }
    }
  else
    {
    print (F("
Bad pin number: "));
    fixHTML (value);
    println (F(""));
    }

  }  // end of processGetArgument

// -----------------------------------------------
//  End of user handlers
// -----------------------------------------------

void setup ()
  {
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip, gateway, subnet);

  for (int i = LOW_PIN; i <= HIGH_PIN; i++)
    pinMode (i, OUTPUT);
  }  // end of setup

void loop ()
  {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (!client)
    {
    // do other processing here
    return;
    }

  myServer.begin (&client);
  while (client.connected() && !myServer.done)
    {
    while (client.available () > 0 && !myServer.done)
      myServer.processIncomingByte (client.read ());

    // do other stuff here

    }  // end of while client connected

  client.println(F("
OK, done."));

  client.println (F("\n"
                    ""));

  // give the web browser time to receive the data
  delay(1);
  // close the connection:
  client.stop();

  }  // end of loop

Library source on GitHub at nickgammon/HTTPserver.
The library is designed to allow you to receive cookies, POST data, pathnames (on the URL) and GET parameters.

On the yun, this functionality is built-in via the bridge. Here's an example.
Via the shield, you now end up writing your own webserver and responding appropriately.
I'm guessing it makes more sense to use the client (the web browser) to make the calls than the backend php, but in either case, once the webserver is up and going on the arduino, you're just using it like any other server.

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


text:
ESP8266 problem as Web server
I asked a previous question about esp8266 that made a lot of things clear for me that esp8266 is very powerful and can be independently used as the webserver now, I have used the following library(https://github.com/sandeepmistry/esp8266-Arduino) to achieve this thing as I found a tutorial(https://learn.adafruit.com/esp8266-temperature-slash-humidity-webserver/code) to help me out.
Now this is the code that was in the tutorial and is working fine
/* DHTServer - ESP8266 Webserver with a DHT sensor as an input

   Based on ESP8266Webserver, DHTexample, and BlinkWithoutDelay (thank you)

   Version 1.0  5/3/2014  Version 1.0   Mike Barela for Adafruit Industries
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <DHT.h>
#define DHTTYPE DHT22
#define DHTPIN  2

const char* ssid     = "--MYRouterID";
const char* password = "--MYRouterPassword";

ESP8266WebServer server(80);

// Initialize DHT sensor
// NOTE: For working with a faster than ATmega328p 16 MHz Arduino chip, like an ESP8266,
// you need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold.  It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value.  The default for a 16mhz AVR is a value of 6.  For an
// Arduino Due that runs at 84mhz a value of 30 works.
// This is for the ESP8266 processor on ESP-01
DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266

float humidity, temp_f;  // Values read from sensor
String webString="";     // String to display
// Generally, you should use "unsigned long" for variables that hold time
unsigned long previousMillis = 0;        // will store last temp was read
const long interval = 2000;              // interval at which to read sensor

void handle_root() {
  server.send(200, "text/plain", "Hello from the weather esp8266, read from /temp or /humidity");
  delay(100);
}

void setup(void)
{
  // You can open the Arduino IDE Serial Monitor window to see what the code is doing
  Serial.begin(115200);  // Serial connection from ESP-01 via 3.3v console cable
  dht.begin();           // initialize temperature sensor

  // Connect to WiFi network
  WiFi.begin(ssid, password);
  Serial.print("\n\r \n\rWorking to connect");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("DHT Weather Reading Server");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  server.on("/", handle_root);

  server.on("/temp", [](){  // if you add this subdirectory to your webserver call, you get text below :)
    gettemperature();       // read sensor
    webString="Temperature: "+String((int)temp_f)+" F";   // Arduino has a hard time with float to string
    server.send(200, "text/plain", webString);            // send to someones browser when asked
  });

  server.on("/humidity", [](){  // if you add this subdirectory to your webserver call, you get text below :)
    gettemperature();           // read sensor
    webString="Humidity: "+String((int)humidity)+"%";
    server.send(200, "text/plain", webString);               // send to someones browser when asked
  });

  server.begin();
  Serial.println("HTTP server started");
}

void loop(void)
{
  server.handleClient();
}

void gettemperature() {
  // Wait at least 2 seconds seconds between measurements.
  // if the difference between the current time and last time you read
  // the sensor is bigger than the interval you set, read the sensor
  // Works better than delay for things happening elsewhere also
  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis >= interval) {
    // save the last time you read the sensor
    previousMillis = currentMillis;

    // Reading temperature for humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
    humidity = dht.readHumidity();          // Read humidity (percent)
    temp_f = dht.readTemperature(true);     // Read temperature as Fahrenheit
    // Check if any reads failed and exit early (to try again).
    if (isnan(humidity) || isnan(temp_f)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }
  }
}

Now this is my modification of code(of esp8266) as I am willing to communicate it over serial with my arduino which will further send data to the esp8266 when it requests using the attached sensor to the batteries(I am making a solar related project).
Its only a basic code but the problem is that it compiles and runs ok but I am only able to access the web page once and that is also only the root. The other links do not open up or when I try to even reload the web page root it stuck and browser says error timed out
Here is code
void handle_root() {
  //server.send(208, "text/plain", "
Hello from the weather esp8266, read from /temp or /humidity
");
  String sendx = "
This Page Shows the Basic Info
";
//  Serial.write("MP");
//  delay(20);

//  while(Serial.available()>0)
 // {
  //  rec = Serial.readString();
  //}
  rec = "TESt";
  if(rec[0] == AllMain)
  {
     sendx += "
Running on Main Power Now
";
     sendx += "
" + rec + "
";
  }
  else if(rec[0] == HouseMain)
  {
    sendx += "
Home on Main Power
";
    sendx += "
" + rec + "
";
    sendx += "Turn on Hospital Main";
  }
  else if(rec[0]==HospitalMain)
  {
    sendx += "
Hospital on Main Power
";
    sendx += "
" + rec + "
";
    sendx += "Turn on House Main";
  }
  else
  {
    sendx += "
" + rec + "
";
    sendx += "
Turn on House Main
";
    sendx += "
Turn on Hospital Main
";
  }
// sendx +=  "Temp";

    server.send(200,"text/html",sendx);
  delay(100);
}
void thm()
{
 // if(Serial.available())
  {
//    Serial.println("thm");
    String sendx = "signal sent... go back to previous page to verify";
  //  sendx += "Go Back";
    server.send(200,"text/html",sendx);
    delay(100);
  }
}
void thos()
{
 // if(Serial.available())
  {
//    Serial.println("thos");
    String sendx = "signal sent... go back to previous page to verify";
 //   sendx += "Go Back";
    server.send(200,"text/html",sendx);
    delay(100);
  }
}
void setup(void)
{
  // You can open the Arduino IDE Serial Monitor window to see what the code is doing
  Serial.begin(115200);  // Serial connection from ESP-01 via 3.3v console cable

  // Connect to WiFi network
  WiFi.begin(ssid, password);
  if(debug)
    Serial.print("\n\r \n\rWorking to connect");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    if(debug)
      Serial.print(".");
  }
  if(debug)
  {
    Serial.println("");
    Serial.println("DHT Weather Reading Server");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
  }
  if (mdns.begin("esp8266", WiFi.localIP())) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handle_root);

 server.on("/thm", thm);
 /*server.on("/thm", [](){  ===== I have tried this inline as well no luck ====
   Serial.println("thos");
    String sendx = "signal sent... go back to previous page to verify";
    server.sendContent(sendx);
 });*/
  server.on("/thos",thos);

  server.begin();
  if(debug)
    Serial.println("HTTP server started");
}

void loop(void)
{

  server.handleClient();
}

Now please I would also appreciate your help for the commented portion of my code dealing with serial communication in function handle_root but it would be more than enough if you can point out my misconception or error or point me in right direction


text:
How do I use an Arduino as a USB output device for a 2x16 display?
Can I make a USB 2x16 display using an Arduino?
I want to control a 2x16 character lcd display using USB, not com port/serial.
I need it to appear as a HID device when connected to the computer.
Please advise me.
Thanks

What kind of HID device do you think it should be? HID devices are inputs to a computer, not outputs (in general).

Why do you not want it to appear as Serial? USB HID are much harder to interact with than a simple Serial device. Using Python, you could easily write a program to interact with the device.

I want to make a simple USB 2x16 lcd display device using Arduino, something which we can plug into the USB and use for displaying any message like a plug and play 2x16 lcd display.

If you truly want to make this a USB HID device and not the usual USB serial one, you should probably look at a board such as the Leonardo or Due or Teensy or Feather M0 where the USB is directly handled by the application processor, or else look into reprogramming the ATmega16u2 on an Uno.

HID's generally are input devices to your computer, if you do want your computer to send data to the device you will need an application to do it.
So your best bet is to have a windows app to communicate with your arduino using a virtual com port ( as it does already) and send data as you require

HID can be used for data to the device as well, it simply isn't specialized for it.

@IgnacioVazquez-Abrams Yes you are right, which is why i was careful enough to use the word generally :)

So, if it is possible use it as a HID output device, are there any chances for me to make a USB 2X16 lcd display device using Arduino?

@Josh what do you mean by HID output device?
output for the computer?

Yes, output strings from the computer to display on the 2x16 lcd by making it a HID device. How to achieve this?

From what I know your best bet is to create a simple python program to send the required data to your arduino and then the arduino receives, processes the data and displays the data on the screen.
https://www.dropbox.com/s/635papy9py7jjvp/serial_arduino.py?dl=0
This sample code is used to turn on/off the led at pin 13, i.e. if I receive 'h' turn led on, if i receive 'l' turn led off

This still needs com port configuration. I want to make a simple Plug N Play device using Arduino just like any usb keyboard,mouse, pen drives which require no com port configurations. We don't select COM3/COM5 when we use usb devices. I want to make a normal usb device which can be used.

Yes. please understand that irrespective of whether you use a virtual com port or not, you will need to write your own application in order for your computer to communicate with the arduino. If you want to do it in HID mode, you may need to create your own [drivers] (http://stackoverflow.com/questions/30208215/what-data-can-a-hid-device-receive) and modify the arduino library. So your best option is to use it in virtual com port mode, create a python app similar to that in the link i had shown earlier, it will be much easier as well as portable

@josh There wont be a need to configure the com port, you can just scan the current options and get your program to do the rest (http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python)

HID doesn't require a specific driver (or rather, all USB-capable OSes already have a generic HID driver), simply a program that talks to the HID susbsystem.

@evolutionizer I don't mind writing my own program in Python / C#. As long as it's not very complex code, it's ok. Scanning com ports is certainly an option but it will be slow and could make the user wait on Windows. That's why, I want to develop a plug n play device that just works seamlessly.

@IgnacioVazquez-Abrams So, if all OS's have a built-in HID driver, how do I communicate to Arduino over HID to send data using Python/C#? I have only seen arduino HID input devices like keyboard,mouse. Are there any examples of the pin connections & sample program for sending strings out to arduino from PC using HID?

@Josh: V-USB has several command line programs that show interacting with the HID driver.

@IgnacioVazquez-Abrams Do you mean that I need to use COM ports even if Arduino acts as a HID device? You mean HID does not replace COM ports?

No. You access the HID driver.

@IgnacioVazquez-Abrams I just googled about V-USB. Sorry, didn't know it  was related to micro controller.I thought you V-USB meant serial


text:
digitalPin giving lower voltage than Vcc
I am using an ATTINY88 for a project that requires to turn on an LED. Right now I am using pin PA1(ADC7/PCINT25). I noted, however, that when the pin is ON, I get about half the voltage that is connected to Vcc. I checked the voltage in other pins and they are close to Vcc. Will anyone know, what could be the reason for this?
I figure this pin has an internal resistor enable, but I am not certain.

Do you have a resistor in series with the LED?

I disconnected everything from the pin and I still get half the Voltage in Vcc when that pin is HIGH. In fact, all the pins on that side of the chip give half the voltage when they are on, while other pins give voltage near Vcc. I think those pins on that side of the chip have a resistor enable???

this behaviour might happen if you have PA1 set as input and pull up resistor enabled. Check the datasheet for Port A sub-section. It defines that it will source current when enabled.

is there a way to disable such resistor? I have that pin set as OUTPUT

You should connect the AVCC pin to VCC. From the datasheet (emphasis
mine):

AVCC is the supply voltage pin for the A/D converter and
  a selection of I/O pins. This pin should be externally connected to
  VCC even if the ADC is not used. [...]
The following pins receive their supply voltage from AVCC:
  PC7, PC[5:0] and (in 32-lead pack- ages) PA[1:0]. All other I/O
  pins take their supply voltage from VCC.

That sounds like a really bizarre design choice to me... reminds me why I use PIC and not Atmel chips ;)

@Majenko It is little bit bizare, but connecting AVcc to Vcc is stated in every datasheet for every AVR with AVcc pin. And yet it's common rookie mistake.

It probably makes internal wiring in the chip simpler, and possibly reduces noise.

do you know why is this needed (connecting AVcc to Vcc)?. My circuit works just fine without that connection and it includes several AnalogReads....also, I wonder if it will increase battery consumption? I will test this.

@Camilo: Why it is needed? The excerpt of the datasheet I quoted is, I think, quite explicit. Your circuit may work without that because 1) the internal logic is powered through VCC, 2) the AVCC node is getting some parasitic power through some I/O pins or some internal gates.

@NickGammon I would have thought it would have increased noise. Digital switching noise from the pins used for digital purposes imposed on the analog circuitry.

Yes, but those are the analog (ADC) pins anyway (of course you can use them for digital if you want). Having the ADC pins have two power sources could be complex (one for digital work, one for analog work). So if you stick to using the "digital-only" side for digital switching and the analog-side for analog reading, the two power supplies now keep them separate, rather than running an internal wire, with its digital noise from digital switching, from one side of the chip to the other. So I wouldn't call it bizarre. It sounds quite sensible to me.

That indeed fixed the problem. it should be noted that that part of the chip includes several analog pins as well as two or three digital pins. On the other hand, connecting aVCC to Vcc, actually reduced current by a few mA. It should also be noted that that connection requires a 100nf ceramic capacitor and a small inductor, to cut any noise form external voltage variations.

@Camilo: This is listed as an "analog noise canceling technique". If you do not use the ADC, you can connect AVCC just like VCC, with only the 100 nF cap.


text:
How to measure the state of charge of a battery in arduino
This questions has been formulated several times with not clear answer, and I wonder if there is one.
it is well stablished from several sources that measuring the voltage of a battery alone is not good indicator of the State of Charge (SOC) of the battery because voltage does not decline proportional to the soc.
Another solution (http://fritzing.org/projects/battery-charge-level/) suggest measuring the voltage (with analogread) between two resistors connected to the gnd and vcc of the circuit (I presume this constantly draw power) and then choose what is the critical voltage of the circuit.
However, my question is how to measure the SOC of a battery using units of 0 to 100% in arduino?

Are you asking about how to make up a circuit with two resistors, or how to convert the analogRead result into a number from 0 to 100%, or something else?

What type of battery/charger? I'm using a Li-Ion (4.2V to 2.75V). By measuring the voltage I can determine the percentage of power left. I actually make it 0 to 100 from around 3.2V, as I don't want people to drain the battery completely (Li-ion rechargable).

I noted that the state of charge of a batery in many graphs I found is shown as percentage values from 0 to 100%. My question is how are those percentage calculated for any given battery? My  guess is that if the batery has let's say 2700 mAh, how much of that is left at any given time, but I am not certain.

The datasheet of the battery gives you a discharge curve. You can e.g. create a lookup table that converts the battery voltage to a percentage of charge remaining based on this graph. As for the voltage divider; choosing large value resistors will make the current lost negligible. Adding a small capacitor could be used to stabilize the voltage if very high resistance values are used. If the battery is connected directly to the AVR chip, you can use the internal bandgap voltage to measure the battery voltage.

THe answer here and here
My answer to the 1st question contains links to "Battery University" which tells what can be achieved and what effort is required.

To do it correctly, you need a coulomb counter. Something like this.
Even that is not fully sufficient, as the charge that can be obtained from a battery depends on various factors, such as temperature and ageing.
More recent batteries have somewhat flat discharge curve, when it comes to voltage, till they run flat, then the voltage drops significantly.
Which means that you would need a very accurate voltage meter.
However the starting point is that you must be able to count how much charge is going in and out.


text:
does INPUT_PULLUP uses power?
When using a digital pin as input, one has the option of using the internal arduino resistor, which is connected to VCC; that is setting the digital pin as INPUT_PULLUP, and then the pin reads HIGH. Does this uses electricity?.
I mean the resistor is connected directly to VCC and I presume electricity is constantly flowing through the system, no?.
as oppose to having the pin as just INPUT?

I presume electricity is constantly flowing through the system - only if there is a load. With no load there is nowhere for it to flow, except as leakage current, as Ignacio Vazquez-Abrams said.

You can measure the current when using INPUT_PULLUP. https://hackingmajenkoblog.wordpress.com/2016/08/12/measuring-arduino-internal-pull-up-resistors/  I measured mine on a 3.3v 328p 8mhz and I calculated it to be 0.108ma

Only the leakage current on the input itself is constantly consumed if there is no external connection. This is usually much less than the waste caused by having the input floating.

If a voltage between 0.8 V and 2 V is applied to the input for a prolonged period of time, this situation becomes critical and
  should not be ignored, especially with higher bit count and more dense packages [...]. For example, if an 18-bit
  transceiver has 36 I/O pins floating at the threshold, the current from VCC can be as high as 150 mA to 200 mA.

There is not really a load applied to the pin with the INPUT_PULLUP.  I am using only for a push button, for a counter.

The pullups have a value between 20k and 50kOhm. If the input is connected to ground (button pressed), between 0.1mA and 0.25mA is flowing through the resistor. So bare anything.

What happens if the switch is open? Does it use power?

@Basj basically; no current will go though the resistor when the switch is open. Though I found out there is a tiny amount (1 µA max) of leakage current

See Deviation of power consumption between datasheet and real world? - there we established that leaving the pins input consumed considerably more power than input_pullup. That was with the pins not connected to anything.

Is there a typo here or am I reading wrong?   You said leaving pins as INPUT is more than INPUT_PULLUP, but your experiments show 0.35 µA for INPUT and 1.25 µA for INPUT_PULLUP

@rfii Yes, I did say that, and indeed it contradicts what I wrote. However as a general principle you are not supposed to leave chip inputs "floating", and configuring for input, with nothing connected, does that. You would probably get variable results depending on what noise was present near the inputs. I should probably re-measure the examples I gave on the quoted page.

Thanks your website is very helpful in how it tests everything so orderly

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


text:
IR sensor readings at different voltages
I am currently working on a photo-transistor like this:
http://www.ebay.com/itm/10pcs-ITR8307-S18-TR8-Optical-Switches-Reflective-Phototransistor-Output-/381374566327?hash=item58cbb20fb7:g:lgoAAOSwr81UQ7KG
It very nicely allows me to identify colors white, green and black. The problem I am having is that the Arduino is powered with batteries so the readings for those colors change as voltage in the batteries reduces.
I tried to make the reading proportional to the voltage in the system, but this still gives different values, I guess the readings change non-linearly as voltage changes.
I wonder what will be the solution to this problem: Specifically, how to make the reading of an IR sensor the same for the same color at different voltages?
This is the code I am using so far:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

void loop() {
// read the input from the IR sensor on pin A0:
float sensorValue = analogRead(A0);
// read the voltage in the system by connecting pin A1 to Vcc, with the same resistor value used in the IR sensor:
float Vref = analogRead(A1);

// adjust reading value to voltage in system:
float AdjustedReading = sensorValue/Vref;

Serial.println(AdjustedReading);
delay(100);
}

How it it connected? How are you powering you arduino?

What is Vref connected to...?

the device is powered with 2 aa batteries. The Attemega328 works well at voltages as low as 1.8v. but in the ranges from 3.5v (the maximum with 2 AA batteries) to 1.8 v, for the same color I get different IR readings, which prevents me of setting thresholds to define each color.

The circuit is very similar to this: http://blog.huntgang.com/2014/06/17/arduino-tcrt5000-build-ir-sensor/  the only difference is the polarity of the IR emitter which has to be inverted for the phototransistor I am using.

That doesn't show what Vref is. Is it by chance connected direct to the Vcc pin of the ATMega? I.e., connected to V+ of the battery? If so it will always read the same value and is of absolutely no use in this situation. Instead you need to back-calculate the Vcc vaue from reading the internal 1.1V band-gap reference voltage.

It sounds to me like your system works, but you have trouble if your voltage drops.
First of all here's 2 tips that might solve your problem.

instead of just making 1 reading do 10 and take an average - this reduces noise.
the voltage reference is allready based on the voltage that powers the system so with your adjusted reading you try to accomplish something which has already happened an therefore has the opposite effect and actually increase the error.

see http://tronixstuff.com/2013/12/12/arduino-tutorials-chapter-22-aref-pin/ for a very good explanation.

Add a RC filter to removes random fluctuations in the signal from you photoresistor

see https://electronics.stackexchange.com/questions/17754/where-to-place-a-capacitor-to-smoothen-ir-sensor-reading for a short description and the calculated example.
If however it is correct, and your readings of colors don't follow a linear scale, you would have to deduce that actual curve and apply it in the code - but that might not be easy.
So it would be much more easy to remove that variable by ensuring that the voltage is constant. Most Arduino boards have an 5V onboard voltage regulator that will keep the voltage exactly at 5 Volt when connected to battery via the power Jack!
(USB bypasses this regulator and have a little voltage drop so it is sligthly lower than 5V, and more very prone to fluctations if coming from a AC source affecting your analog read considerably)
The battery connected onboard voltage regulator however requires a higher input to do the regulation so the battery needs to supply atleast 6.2V or higher, in your case you would have to use a voltage source of less than 6.2V if this is the source of your problems.
(the voltage regulator on original arduino boards needs voltage of 1.2V higher than the needed output - clones might differ and require upto 2v more than the needed output)
hope this can help solve the issue
Mikael


text:
Where is the Aref pin for Attitny88
I would like to use the external analog refence voltage in an Attiny88 project I am working on that will be powered with batteries.
However, the datasheet for this processor does not show an Aref pin like other versions of the attiny, like attiny85 and attiny84, where it is usually the pin PA0 or PB0. Does anyone know where is the pin for the external voltage reference in attiny88 (e.i. Aref pin)? Does this chip has the functionality for an external analog reference voltage?

As shown in the detailed information for the ADMUX register in the ADC section of the datasheet, the ATtiny88 has no external voltage reference. Consider using a ATmega8 or ATmega88PB instead.


text:
Sending a value from one arduino to another
I wonder if it is possible to send a value from one  arduino to another.
Basically, I have one arduino measuring let's say weight, but I want to display that value using an lcd in another arduino.
Is it possible to  send the value to a pin using analogwrite or digital write in the arduino doing the measurement and use analogread/digitalread at the other arduino making the display?
I do not know if this is possible but what is attractive is that one can have several arduino making weight measurements, all showing up in the display of just one central one...

You could have the LCD Arduino be an I2C master and all the weighing Arduinos be slaves. There's an example of master/slave communication and wiring here: https://www.arduino.cc/en/Tutorial/MasterReader.
I2C supports up to 128 devices and the wiring is very simple.

Exactly what I too was looking for thanks!

Yes it is possible,The answer provides one of the basic methods to do so
Connections
   Arduino1          Arduino2
     TX--------------->RX
     RX--------------->TX

Arduino1 Sketch:
void setup(){
 Serial.begin(9600);
 delay(2000);
}

void loop() {
 ////read sensor data to a variable
 Serial.println(sensorDataVariable);
 delay(2000); //Not to flood serial port
}

Arduino2 Sketch :
int byteRead;
void setup(){
 Serial.begin(9600);
 delay(2000);
}

void loop() {
  /* check if data has been sent from the computer: */
  while (Serial.available()) {
    /* read the most recent byte */
    byteRead = Serial.read(); //now byteRead will have latest sensor
                              // data sent from Arduino1
  }
  //Write code to display the values to LCD
}

hope this helps

Will this option be limited to only two arduinos? I would like several arduinos transmitting weigh values to a central arduino.

you can but use Arduino 2 sketch on all other receivers,,broad cast form one arduino and receive from many,,,you should do more research

How can we achieve this if we would like to do vice versa ? Arduino 2 is sending data to Arduino 1.

To tie multiple Arduinos together you need to come up with some kind of networking topology and some form of networking protocol.
Requirements are:

The Arduinos must not (electrically) interfere with each other
There must be some way to know which Arduino is sending what and where to

The two points could be addressed by having a separate connection for each Arduino but that ends up complicated, and there are only limited resources on an Arduino for creating such connections (you really need to use the hardware UART ports and the Uno has only 1. The Mega has 4).
A better solution is to use a bus system (also known as a multi-drop network).  There are a number of existing and well supported methods for doing this.  In the automotive system the CAN Bus is used.  In industry the RS-485 system is heavily used.
Personally I prefer RS-485 since it is well established.  There are a number of standard protocols that run on RS-485, such as MODBUS, but for the Arduino world I wrote my own light weight protocol specially which is far simpler to get going with.  You can find out more here: https://github.com/MajenkoLibraries/ICSC


text:
Sending and receiving different types of data via I2C in Arduino
I have found a few good tutorials on how to send and receive data via I2C in connected arduinos. My limitation is now how to transmit different types of data like for instance, long, float, etc. Right now the communication via I2C using the wire library only allows transmission of numbers between 0 and 255. How can one transmit different types of numbers?.
In my code a master receives three types of data from the slave, and it send data of a fourth variable to the slave.
here is the code for the master
#include <Wire.h>

const int SLAVE_ADDRESS = 8; //Slave arduino ID
int table[]={0,0,0}; //the data will be transmited via table as to allow different data to be transfer.
void setup ()
{
Wire.begin ();
Serial.begin (9600);  // start serial for output
}  // end of setup
void loop()
{
Wire.requestFrom(SLAVE_ADDRESS, 3);// request 3 bytes from slave device #8

for(int i=0;i<3;i++)//organizes the data from the slave in the table
{
int c = Wire.read(); // receive a byte as character
table[i]=c;
}
//displays the data
 Serial.print('\n');
   Serial.print(table[0]);
    Serial.print('\t');
   Serial.print(table[1]);
    Serial.print('\t');
   Serial.print(table[2]);
   Serial.print('\n');

delay (500);

// transmit just this variable to the slave
int Work=1;
Wire.beginTransmission (8);
Wire.write (Work);
Wire.endTransmission ();
}

here is the code for the slave
#include <Wire.h>
int table[]={0,0,0};
int Work=0;

void setup() {
Wire.begin(8);                // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event
Wire.onReceive(receiveEvent); // register event
}

void loop() {
int x=120;
int y=1200;// gets converted to an strange # because is larger than 255
int z=3;
  table[0]=x;
  table[1]=y;
  table[2]=z;
}

void requestEvent()
{
  uint8_t Buffer[3];
  Buffer[0]=table[0];
  Buffer[1]=table[1];
  Buffer[2]=table[2];
  Wire.write(Buffer,3);
}

void receiveEvent(int howMany)
{Work = Wire.read();}

I2C is truly a powerful option of Arduino, for too many reasons; yet the amount of tutorials available are not that many and unfortunately are too complicated for the average person.
After working on this for 2 days, I think I have a way to transfer pretty much anything between master and slaves and viceversa. Note that I2C does not transfer floats or even integers larger than 255, there are several ways to go about this and here is a good tutorial
http://www.gammon.com.au/i2c
and even a library: http://forum.arduino.cc/index.php?topic=171682.0
The solution I found was simpler. Basically we convert any value, string, number, text, float, you name it, and turn into a variable char, which can be transferred via I2C. Once transferred, you can convert back to a number although in my case below, I just wanted to display the data from the slave.
Here is the code. I provide comments on different parts for clarity. I hope this helps. it worked for me.
//master
#include <Wire.h>

char t[10]={};//empty array where to put the numbers comming from the slave
volatile int Val; // varaible used by the master to sent data to the slave

void setup() {
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
}

void loop() {
  Wire.requestFrom(8, 3);    // request 3 bytes from slave device #8

//gathers data comming from slave
int i=0; //counter for each bite as it arrives
  while (Wire.available()) {
    t[i] = Wire.read(); // every character that arrives it put in order in the empty array "t"
    i=i+1;
  }

Serial.println(t);   //shows the data in the array t
delay(500); //give some time to relax

// send data to slave. here I am just sending the number 2
  Val=2;
  Wire.beginTransmission (8);
  Wire.write (Val);
  Wire.endTransmission ();
}

here the other part
    //slave
#include <Wire.h>

char t[10]; //empty array where to put the numbers going to the master
volatile int Val; // variable used by the master to sent data to the slave

void setup() {
  Wire.begin(8);                // Slave id #8
  Wire.onRequest(requestEvent); // fucntion to run when asking for data
  Wire.onReceive(receiveEvent); // what to do when receiving data
  Serial.begin(9600);  // serial for displaying data on your screen
}

void loop() {
  int aRead = analogRead(A0); //plug a potentiometer or a resistor to pin A0, so you can see data being transfer
  float x = aRead/1024.0*5.0; //generate a float number, with this method you can use any time of data pretty much

  dtostrf(x, 3, 2, t); //convers the float or integer to a string. (floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, empty array);
  Serial.println(Val);         // print the character
 delay(500);
}

// function: what to do when asked for data
void requestEvent() {
Wire.write(t);
}

// what to do when receiving data from master
void receiveEvent(int howMany)
{Val = Wire.read();}

How you request the same size (3) of string as the one you creates? where is the NULL terminator ?

Moreover your dtostrf is very wrong, how the total size of the string is 3 and you have 2 numbers after the point ? 1.2 is 3 chars, how can it have 2 chars after the point ?

This is not a good way, split the value into bytes, make it a byte array and cast it back to, for example, a float. float myFloat = *(float *)&byteArray; What it does, takes the address of the byteArray and cast the byte array (for example uint8_t byteArray[4];) to a float pointer and access it contents. You really doesn't need such expensive translation to a string.

I believe that for your scenario, i.e. sending different types of variables, the EasyTransfer library (by Bill Porter) would be an elegant solution. The library can be found here: https://github.com/madsci1016/Arduino-EasyTransfer. There are implementations for serial, I2C, and VirtualWire and the examples provided are pretty self-explanatory.
The handling is very easy. After including the library, you create an EasyTransfer object, define a data structure that basically represents a "container" of your data and this can consist of different variables.
struct RECEIVE_DATA_STRUCTURE{
  //put your variable definitions here for the data you want to receive
  //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO
  int blinks;
  int pause;
};

Once the "container" is filled, i.e. the variables are set on the sender side, they are sent with a simple command
  ET.sendData(I2C_SLAVE_ADDRESS);

On the receiver side, you define an identiacl data structureand receive the data by
ET.receiveData();

Hope this helps.

Thanks, that library is promising. I looked it over but could not find a tutorial to communicate via I2C. The tutorial I found was using tx/rx. is there any example you are aware of?.

I found that easy transfer does not allow slave to master transfer. the slave can receive data from master, but the master can not from the slave. the library will require some changes, that have not been outdated: http://forum.arduino.cc/index.php?topic=171682.0

The github page there is a folder EasyTransferI2C which is also included when you download the ZIP file. In that folder there is an Examples folder, in which you find the sketches for the sender (which is called EasyTransfer_TX_Example) and the other one for the receiver  (EasyTransfer_RX_Example)

I tried the exampled but it only send data from the master to the slave, it does not offer the opportunity to send from slave to master. In the arduino forum above, a person said he improved the library to have that function but it does not appear in github

Sorry, I cannot help you further on this.

I have used it only in one direction (master --> slave). Not sure if the following could work. Have you tried to define both on the master and slave side two data structures with the same content, one for receiving, and one for sending, and try to send it in both directions?

Hmm, I did not try that. I look over the library and was not obvious to me that the slave -->master communication was possible. I ended up going back to the wire library and transmitting values converted to character, which can be transferred easely via i2c. Thanks for you help.

Use the 'I2C_Anything' library, available here. I use it in all my I2C projects.  It is extremely simple and works great. Here's the entire .h file
// Written by Nick Gammon
// May 2012

#include <Arduino.h>
#include <Wire.h>

template <typename T> unsigned int I2C_writeAnything (const T& value)
  {
  Wire.write((byte *) &value, sizeof (value));
  return sizeof (value);
  }  // end of I2C_writeAnything

template <typename T> unsigned int I2C_readAnything(T& value)
  {
    byte * p = (byte*) &value;
    unsigned int i;
    for (i = 0; i < sizeof value; i++)
          *p++ = Wire.read();
    return i;
  }  // end of I2C_readAnything


text:
Atmega328P Prescaler to Microseconds
For a bitbanging project I'm working on, I need to measure microseconds as accurately as possible. The function micros() won't work for me here because of the unpredictable times at which it might roll over. I have been using this project by Louis Frigon as an example:
https://web.archive.org/web/20140627135927/http://www.sigmaobjects.com/toyota/
In this document he sets his Atmega8's prescaler value:
// Timer 0 prescaler = 8 ( 1 count / us )
TCCR0 = _BV(CS01);

Do I understand that after these instructions, TCNT0 counts up by nearly precise microseconds?
If so, what math could I use to set my prescaler for measuring microseconds? The 328P has a higher clock speed, does that mean I won't be able to do this?

Note that the rollover is not an issue. The limited resolution of micros() (4 µs) could be.

The 328P has a higher clock speed

The 328P will run at whatever speed you clock it, up to a maximum that
depends on the supply voltage. Most 328P-based Arduinos are clocked at
16 MHz though.

what math could I use to set my prescaler for measuring microseconds?

You can't. You would have to set the prescaler to 16 if you want the
timer to count microseconds. You can set it to 8 or to 64, but there is
no intermediate setting in between.
Maybe you could leave the prescaler at 8 and count half-microseconds
instead?

Edit: On the 328P, Timer 0 has two control registers, named
TCCR0A and TCCR0B. To set it to normal counting mode at F_CPU/8,
you have to:
TCCR0A = 0;
TCCR0B = _BV(CS01);

If you are programming in plain C, the first line is not needed (but it
won't hurt either), as the initial value of TCCR0A is zero on reset.
If you are using the Arduino core library (and you write setup() and
loop() instead of main()), then you do need this first line, as the
Arduino core configures Timer 0 for PWM at 977 Hz. But note
that the Arduino core also uses Timer 0 for timekeeping
(millis(), micros() and delay()). Thus you may want to use another
timer.
You could switch to Timer 2 by replacing every “0” with a “2” on
the register and bit names of the two lines above. Then you would also
replace every occurrence of TCNT0 in the code with TCNT2.

I've set my prescaler and I'm on my way. Thank you. I don't fully understand how it works, still, but I'm reading about it.


text:
Message Interpreter and Handler - How to store a function name in a struct?
For a project, I need to store an array of structures in PROGMEM. Array MessageTable[] will be composed of about ten struct InMessage elements. InMessage looks sort of like this:
struct AvcInMessage {
  MessageHandler  msgHandler;
  byte            dataSize;
  byte            data[8];
  char            description[20];
};

MessageHandler is not a data type... yet. I'm not really sure what data type to use. I want to be able to pick a message from the table and then call MessageTable[x].msgHandler() if that makes sense. I'm almost positive that this involves a pointer. Does someone here have an idea about what I'm looking for?

It might be I'm misunderstanding, but it looks like you want to store in PROGMEM an array of structs containing a reference to an object... That looks a little overkill: do you need to have different message handlers for each item in the array?

typedef void (*MessageHandler)(void);   // def messagehandler as pointer to func

struct AvcInMessage {
  MessageHandler  msgHandler;
  byte            dataSize;
  byte            data[8];
  char            description[20];
} InMessage[] = {
   {
      function1, <datasize>, {<byte0>, <byte1>, ..., }, "DescriptionHere"
   },
   // etc, for however many elements InMessage[] has.
};

The typedef defines a "pointer to function of void returning void" - fix up the argument count and types, and the return type to your needs. We're assuming each element's function has the same kind of arglist and return type. (Update: Sorry for the bug in my first iteration).
The next statement both defines the array of struct and initializes N of them. Provide an element count in the [] if you don't have a full set of initializers at compile time.

I think I understand what you mean, but it doesn't compile. I get expected unqualified-id before ')' token.

should that be typedef void (*MessageHandler)(void);

@JaromandaX has it (thank you!). I've updated my answer.

Confirming that the revised code works. Thank you very much, both.

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


text:
Unusual use of << operator... not a bit shift?
Poking through the example code of SDFS, I saw the following:
static ArduinoOutStream cout(Serial);
// F stores strings in flash to save RAM
cout << F("\ntype any character to start\n");

What exactly is << doing in this case? Moreover, F seems to never be defined prior to this. This seems like a useful trick, but I don't understand how it works.
full code available here: https://github.com/greiman/SdFs/blob/master/examples/SdInfo/SdInfo.ino

What exactly is << doing in this case?

It's directing the data into an output device (stream).

http://www.cplusplus.com/doc/tutorial/basic_io/

Yes, it's confusing using the same symbols for more than one thing...

Moreover, F seems to never be defined prior to this.

F() is a macro. It's defined by the Arduino core in WString.h:
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))

Thank you. Your last line there uses the < and > symbols in ways I've never seen as well, along with the pointer. These seem not to be logical or arithmetic operators, so what do I call them in a google search to understand your answer?

@BoThompson those are template

Compared to the < logical operator and the < arithmetic operator, what would you call that set of symbols?

To address your confusion with the bitshift operator;
It indeed is commonly used as a the arithmetic operator for bitshift, but appears to be 'overloaded', so that when used with streams, it is an 'insertion operator'.

In particular, stream insertion and stream extraction overloads of
  operator<< and operator>> return T&.

https://en.cppreference.com/w/cpp/language/operator_arithmetic
Basically there would be two definitions of the "<<" operator function:
function <<(integer){//Shift bits}
function <<(stream){//Join streams}


text:
Setting Fuse Bits From Arduino IDE?
I've come to understand fuse bits in the last few weeks. I'm working on a bitbanging project on an Arduino Pro Micro, and the signals I'm working with are around 30uS each. For this reason, I think I'll need to unset the CKDIV8 to unlock the full 16MHz speed of my micro controller.
Regardless, I can't figure out how to even do that. Is it possible to modify fuse bits through the Arduino IDE? If so, where?
The only other info I've found on this subject so far is that I can do it by chaining two micro controllers together, but at that point we're getting into application specific stuff and I'm nervous to play with the fuse bits by myself until after I've followed a step-by-step guide. I'd hate to, say, erase the bootloader.

There are 8MHz pro micro boards and there are 16MHz pro micro boards. The difference is a different resonator or crystal (and an other voltage regulator). None of them have the CKDIV8 fuse set. I'm curious, what is your project?

I'm (for the last 12 months) trying to capture and interpret messages sent by the head unit of my car's stereo. It uses AVCLAN. My intention is to capture specific button presses so that I can interact with my phone over bluetooth through the buttons already in my car. The bluetooth component I'm using is a BK8000L.

The Arduinos are shipped without CKDIV8 enabled.
New chips without bootloader and the chips after chip erase are having CKDIV8 active.
And you can change the clock prescaller in software, but it mess up everything that depends on it. Delays, serial baud rate and USB as well.
However fuse setings are stored in boards.txt definition file. None of the bootloaders would work with default settings. They are usually compiled for 16MHz @5V and  8MHz @3.3V with xtal or resonator. But the custom boards may have much more options.


text:
How to make C++ code compatible with Arduino IDE?
I wrote some code in C++ (Used libraries like fstream, vectors etc.) Now when I transferred the code to Arduino it wouldn't compile so I added the following library: https://github.com/maniacbug/StandardCplusplus I downloaded the IDE from here: https://www.arduino.cc/en/main/software
Now almost all my code works: All the libraries I've used work except for fstream which I've used to read a specific file.
Now is there a certain problem with the 'StandardCplusplus' library and how can I counter this problem.
Plus can someone give me an alternative for fstream that works with Arduino. Was reading a bmp image using C++. Now fstream works in a certain way (reads the file in a certain way). Is there some alternative to fstream.

Work with Atmel Studio and their compiler?

When you run that library on the Arduino and ask it to open a file, where do you imagine it would read the file from? Your Arduino has no hard disk or other file system.
One way to solve this is to include a library that emulates a read-only file system in the Arduino's flash. I dunno whether this exists (such libs do exist for for some other targets, for instance for the Nintendo DS), but it would be a bit of overkill IMO.
Another way is to include the data that is in the file in your program, as a const (expr) array of bytes, and read from that array instead of from the file. But if you have a library that is coded to use file read calls this would require some rewriting.
A third approach would be to do the reading and interpreting of the file on your host PC, output the interpreted content to a const (expr) byte array, and include that in your application. This frees you from having to include the bmp-read code in your image.

seem a lot easier to use atmel studio and their compiler that let you use Macros...

AVR GCC can compile c++, but Arduino IDE isn't the most suitable tool to do that all. With a tool like Atmel studio, he could create a "memory partition" in the internal memory, i see project were dev kit where transform into fat32 USB stick,therefore he would have a "file system".

Well you can add a filesystem if you add an SD Card reader. You'd just have to replace part of the code with the SD library... However this better be done on a Mega 256 or better.

The Arduino IDE does compile your code using the avr-g++ compiler. In other words, it is C++.

Was reading a bmp image using C++.

This isn't practical on the smaller Arduinos, at least, because they have so little RAM. They also don't have a file system. There is a streaming library for output, which is very handy for streaming out things to Serial, LCDs, etc.
One of the replies here mentioned that if you switch to Atmel Studio you can look at the datasheet and get down to the intricacies of the hardware. Well, you can certainly do that as well with the IDE. All the hardware registers are available for use. I often use the "bare" registers for timers, watchdog, interrupts etc.
Also Atmel Studio only runs on Windows. You are out of luck if you use a Mac or Linux.
There is also a port of the Standard Template Library for the Arduino, if you want to use vectors, lists, maps etc.
There is also another port of the STL which may work better and be easier to install.

Are you using Arduino UNO? Look at the datasheet and see how much RAM the Arduino has. Assuming you are using Arduino Uno, it should be around 2kilobyte or less. So it is highly likely not to have enough memory to read the BMP file. Even if you are trying to read very small BMP file, the code reading the file would vary depending where you are reading the BMP file from (SD Card, SPI Flash memory, etc.) It cannot read files directly from your computer using just fstream.

To answer your compile problem.. Are you using c++11? The issue could be that Arduino Compiler may not support entire C++11 features.
So if you cant find an alternative for fstream (I dont know any) then you have to find a different way compile the C++11 code and upload it. You can do this with a Makefile, avr-gcc. Its plenty of generators out there.

While C++ version features can be an issue, in this case it is far overshadowed by the fact that the library is trying to perform tasks that aren't possible on the Arduino.


text:
arduino boards manager configuration
I installed the Arduino IDE 1.6.4, and used the "boards manager" to install the package for Arduino Due.
I am using c++11 in my project so i need to add the compiler.cpp.extra_flags=-std=gnu++11 like i did in the /Applications/Arduino.app/Contents/Java/hardware/arduino/platform.txt file (i am on MacOSX).
It seems that arduino is ignoring that file and using a configuration coming from somewhere else.
Where is the downloaded package installed? Can it be configured?

Did you try looking under where the preferences file is stored?

@IgnacioVazquez-Abrams you are right, there it is, in the packages folder. Write it as an answer and you will get the accept points!

Ok, as @IgnacioVazquez-Abrams suggested: the configuration files for the plugins can be found in the Arduino ide preferences directory. Click the menu Arduino->Preferences (under macosx) at the bottom of the window there is the clickable path of the preferences.txt file. In the same folder as that file you will find a packages folder, where the plugins are downloaded.


text:
What minimum equipment is needed to program the Freematics Vehicle Data Logger?
I was looking for a GPS/OBD2 data logger that logs data to an SD card and eventually arrived at the Arduino powered Freematics Vehicle Data Logger. It's great that it's programmable, but I have no experience with Arduino.
Reading the documentation, it says that I program the device either by USBasp or Arduino as ISP. The USBasp is a dongle programmer, but I don't know what is meant by Arduino as ISP.
My goal is to use this device to log data. I don't plan to extensive write programs for it. What is the minimum equipment that I need to have in order to be able to write a bit of code and flash it to the device?

"Arduino as ISP" refers to using an Arduino board in place of a USBasp.  It involves loading a specific sketch onto the Arduino then using the SPI port (and a few other pins) as the programming interface to the target.
It is most often used to program blank chips for use in breadboards by people who don't have a USBasp.  Great for moving your project from the Arduino board to a breadboard without having to buy a hardware programmer.


text:
Managing timer intervals using millis at random intervals
I am doing a project which needs to meet the following specifications.

On receiving an SMS arduino will start switching 1st relay on after some
  time duration(say 30 Seconds) relay 1 will be turned off and it will now turn on 2nd relay for (say 20seconds) so on 1>2>3>4.

The problem im facing is managing the time intervals between the switching process,i did think of using millis() i.e (currentMillis-previousMillisx>Intervalx) as in blinkWithoutDelay ,how ever this will work only once as i dont not know when will the next SMS come to the system ,if the user decides to send the message after 1hour currentMillis-previousMillisx will always return true so i cannot keep the motor on for (Say 30 seconds) and same will happen with all 4 cases.
If there is any alternative logic for this problem please suggest me or can i just add RTC for my project to manage time easily
Thank You

Well, you need a sort of tracking for your active relay, don't you? So you just have to reset that tracking variable and the previousMillis variables and you are done.
Some code (note: untested and moreover I don't know how you are receiving the SMS)
// The intervals for the different relays
const byte Intervals[] = {30, 20, 10, 5};

// The current state. 0 means relay 1 on,
// 1 means relay 2 on, 2->3 and 3->4, while
// 4 means no relay activated
byte currentState = 4;

unsigned long previousMillis;

void loop()
{
    if (received_sms)
    {
        currentState = 0;
        previousMillis = millis();
        digitalWrite(RELAY1, HIGH);
        // Maybe turn off all the other relays?
    }

    if (currentState < 4)
    { // Active state: check if we should advance
        unsigned long currentInterval = ((unsigned long)Intervals[currentState])*1000;
        while ((millis() - previousMillis) >= currentInterval)
        { // Advance to the next step
            switch(currentState)
            {
                case 0: // Advance from state 0 to 1
                    digitalWrite(RELAY1, LOW);
                    digitalWrite(RELAY2, HIGH);
                    // Maybe turn off all the other relays?
                    previousMillis += currentInterval;
                    currentState = 1;
                    break;
                ...
                // cases 1, 2, 3
                ...
                default:
                    // It should never reach this
                    previousMillis = millis();
                    currentState = 4;
                    break;
            }
        }

    }
}

(a) Using a switch/case statement to select which relay to work on, with four blocks of nearly identical code (instead of using an array with pin numbers, and a single block of code) is odious.  (b) Although the while   (in the if (currentState < 4) block) works ok, it functions as an if statement and IMO should be written as such.

if(received_sms){} block made my day " previousMillis=millis()" inside that will now allow me to get the offset from the point i recieved the SMS ,,Thanks You

@jwpat7 I agree that if the code is nearly identical the switch/case can be rewritten in a more concise form, but often (almost always) you have to do something else in the cases (and that's why when dealing with simple - and complex - state machines my mind always implements it as switch/case). In this case, however, this could be simplified. The while, however, is much more secure than the if. Since previousMillis is not reset to millis() but just incremented (more precise), if some function blocks the thread for too much time you can lose one step; with the while you can recover it

I do not really understand your problem. More specifically,
“currentMillis-previousMillisx will always return true” does not make
sense, as it is not a boolean expression (it's unsigned long).
Anyway, the technique shown in blinkWithoutDelay is the way to go. Here
is my (untested) version:
const int relay_count = 4;  // we have 4 relays
const int relay_pins[relay_count] = {2, 3, 4, 5};
const unsigned long durations[relay_count] = {30000, 20000, 15000, 10000};
bool sms_received();  // you implement this one

void loop()
{
    static int current_relay = -1;  // meaning: no active relay
    static unsigned long last_switch;
    unsigned long now = millis();

    // If no relay is active, wait for an SMS.
    if (current_relay == -1) {
        if (sms_received()) {
            // Switch on first relay.
            current_relay = 0;
            digitalWrite(relay_pins[current_relay], HIGH);
            last_switch = now;
        }
    }

    // Otherwise, switch relays when it is time to do so.
    else if (now - last_switch >= durations[current_relay]) {
        digitalWrite(relay_pins[current_relay], LOW);
        if (++current_relay == relay_count) {
            current_relay = -1;  // no active relay
        } else {
            digitalWrite(relay_pins[current_relay], HIGH);
            last_switch = now;
        }
    }
}

BTW, you did not specify what should happen if you receive an SMS while
one of the relays is active. I assume the SMS are only acknowledged when
no relay is active. Otherwise you would have to change the code.

You could use timer interrupts. I've (successfully) used the TimerOne library. There are countless other libraries that allow you to use timer interrupts easily. "Start" the timer when you receive the SMS message. You could use a pair of boolean flags to keep track of the two relays with one timer.

i am now using TimerOne ,,,it however is not the best method and not very safe

@Lokanath I'm curious. Why do you say that?

Interrupts are good but how ever you cannot pass values to the ISR,as far as i know ISR will execute when the timerExpires and uses the values of variables current values at the expiry point inside ISR which i totally cannot control which makes program unpredictable

@Lokanath You could use global variables and declare them as 'volatile'. This tells the compiler to reload the variable every time you reference it as opposed to using a copy from a register.

ya you are right,,,usage of interrupts needs more than beginners knowledge,,,if you know how to use it you can manage them


text:
How to calculate actual Baud Rate and its percent error?
I am using an Arduino Uno, and I need to create a program that calculates the actual baud rate and the percent error for all standard baud rate in Arduino monitor program.

It's listed in datasheets. The table is called: "Equations for Calculating Baud Rate Register Setting"

Welcome to Arduino:SE. Please be aware that this is not a free design house or an on-demand online technical encyclopedia. You might find it helpful to review the site tour and Help Centre and, in particular, [ask].

See http://wormfood.net/avrbaudcalc.php

Jasmine, if you found the below answer helpful, please upvote it and/or mark it as the answer. That's a good way of thanking @EdgarBonet for his hard work. See https://stackoverflow.com/help/privileges/vote-up to understand why voting is important.

First, look at the code used by the Arduino core library to configure
the USART baud rate register: it's in
HardwareSerial::begin(). The general formula is
uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;

but beware of the hard-coded exception. You can replicate that part of
the code in your own.
Then, look at the ATmega328P datasheet. More specifically, at section
24.4.1. Internal Clock Generation – The Baud Rate
Generator. Here you find the formula
BAUD = F_CPU / (8*(UBRR0 + 1))

assuming the U2X0 bit has been set (again, beware of the hard-coded
exception). Combine both formulas and you get the actual baud rate.


text:
How do I merge two programs in Arduino?
So I have an esp8266 nodemcu which I flashed a program called Deauther 2.0. I spent the past two hours trying to merge another Sketch. Which I failed miserably.
What I am trying to achieve:
When I first power up my nodemcu it should load the Deauther program. But when I press the built in flash button it should load the second sketch.
What I have tried to fix the problem:

Add my own clock.cpp to the Deauther sketch and edited the top part of the sketch:
const int button = 0;

int temp = 0;

 void setup() {

 pinMode(button, INPUT)

 }

 void loop() {

 temp = digitalRead(button)

 if (temp == HIGH ) {

 // run the code below

}

Some other stuff which I don't want to mention.

Any ideas on how to fix this?
Thanks!

There's no magic way to merge two sketches. In the general case, it may be impossible. You need to understand what one sketch does and how it does it, understand what the other does and how, and write a third sketch which combines both things. Debug any problems which arise in the usual ways.

the OP is not talking about merging the two sketches. .... the OP is talking about using one sketch to load another sketch

Anyone asking a basic question like this has no legitimate use for a WiFi deauther. There are so many amazing things you can do with an ESP8266. Why do you have to chose the malicious usage?

@per1234 I am not using the deauther for malicious purposes I only test it on my own network.

To be able to merge the sketches you must ensure that both will not try to access the same pins/resource in ways that are incompatible. For example if both need to input from serial you will need to adjust things so the input you send it will reach the correct code.
Once you have made sure of that it is often simplest to first refactor both sketches to avoid any type of delay-like code or anything that halts execution while waiting for something to happen and instead go with state-machine based that just loops constantly and uses timestamps to manage when to actually do stuff.
For example the second sketch has the format:
void loop(){
    //do stuff

    delay(1000);
}

You should refactor that to
unsigned long last_run = 0;

void loop(){
    unsigned long current_millis = millis();
    if(current_millis - last_run > 1000){
        last_run = current_millis;
        //do stuff that never blocks

    }
}

Once that is complete and you made sure there is no name conflict between the sketches for the functions/globals you can simply append the loop() and setup() functions into a new loop() and setup()


text:
How to create custom bootloader with accompanying program loader for ATMega2560
Just for some context, I have created a custom board based on the ATMega2560. I currently have the original Arduino Bootloader for the ATMega2560 and have no problems uploading code via the USB Port on TX0 and RX0.
What I am hoping to achieve is creating a custom Bootloader that allows me to upload my .hex binaries to flash but in a proprietary way, so that any program cannot be uploaded to it with the standard Wiring Protocol used by Arduino IDE. In addition, I will need a custom PC based program that can upload the code via the USB port.
The reason why I need this is that I will have this device out in areas where I would not want someone taking the device and uploading their own program to it and screw it up. I know it sounds paranoid, however, it would be preferred to have this feature so I can update the firmware via the USB Port without using the Wiring protocol.
Has anyone accomplished this before?
TL;DR
Want to upload custom Bootloader to Arduino Mega so that I can upload my firmware with a proprietary programmer via the USB Port on TX0 and RX0 because I am paranoid.

The source of the bootloaders is publicly available, so a simple thing would be to make a minor modification, for example XOR each incoming byte with 0xEE. That would mean the bootloader wouldn't work with normal uploading programs (the IDE) but with a modified uploader.
However even simpler would be to upload your code using ICSP and not include a bootloader at all. Or, leave the bootloader there but turn off the BOOTRST fuse so that the processor ignores it.
That way, it takes some effort for people to replace your code.


text:
Writing and Reading data from RTC module EEPROM_Arduino
i have took below code from https://lastminuteengineers.com/ds1307-rtc-arduino-tutorial/. i am not understand what these codes are doing. please help me to understand.
Wire.write((int)(eeaddress >> 8)); // MSB
Wire.write((int)(eeaddress & 0xFF)); // LSB

Thanks

how many bits long is eeaddress?

These two lines write a 16 bit (2 8-bit) value, which is signed -32768..32767 or unsigned 0..65535.
Assume a value in bits: 10101010 11001100
Statement 1:
Wire.write((int)(eeaddress >> 8)); // MSB

The first statement shifts the value 8 bits (positions) to the right; this is called the MSB (Most Significant Byte, the left 8 bits). Bits on the right are clipped / fall off. Thus
10101010 11001100

will become
00000000 10101010

When casted to an 8 bit value you get:
10101010

Statement 2:
Wire.write((int)(eeaddress & 0xFF)); // LSB

The second statement will get the LSB (Least Significant Byte). This used the AND operator, meaning a bit is only 1 if both values are 1. 0xFF is the 'mask'
Original value: 10101010 11001100
Mask:           00000000 11111111
                ----------------- AND (&) operator
Result:         00000000 11001100

As you can see only the right 8 bits are kept. When casting this to an 8 bit value:
11001100

Do you also know why there is an int cast ((int)...)?

@Gerben; actually I would either expect a 8 bit type cast (uint8_t or int8_t  cast as the result is always 8 bits, or no cast at all, as the caller probably expects an 8 bit variable. Even if the caller expects 16 bit (which would be unnecessary much), the 8 bit argument will automatically be casted to 16 bits, without a need for a cast in the two lines provided in this code.

Thank you. Seems like the Wire library will cast it (back) into an uint8_t anyways.

@Gerben, true, thus casting it within the calling write method is not needed.

Thanks @Michel Keijzers

If the answer helped you, upvote the answer (the arrow next to the answer). If the answer solves your problem, accept the answer (icon next to the answer).


text:
Arduino nano stk500_getsync() attempt 1 of 10: not in sync: resp=0xe1
I have been building a project using an arduino nano clone. It uses the CH340 chip. It worked perfectly, and a week later it now doesnt.
When I want to upload code in arduino IDE I get the error below
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe1

To try to fix the issue, I bought a USBasp board to program the nano, however, when I run AVRdude, it reads
avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: error: programm enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
     Double check connections and try again, or use -F to override
     this check.}

If anyone can help please do
Thanks


text:
How to delete first voltage reading?
I'm trying out a new ADC, ADS1262, below is the code. I want to discard the first voltage reading.
*/
#include <SPI.h>
#include <SoftwareSerial.h>
#include <math.h>
#include <ads1262.h>

#define PGA 1                     // Programmable Gain = 1
#define VREF 2.50                 // Internal reference of 2.048V
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)

ads1262 PC_ADS1262;                     // class

float volt_V=0;
float volt_mV=0;
volatile int i;
volatile char SPI_RX_Buff[10];
volatile long ads1262_rx_Data[10];
volatile static int SPI_RX_Buff_Count = 0;
volatile char *SPI_RX_Buff_Ptr;
volatile int Responsebyte = false;
volatile signed long sads1262Count = 0;
volatile signed long uads1262Count=0;
double resolution;

void setup()
{
  // initalize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN, INPUT);                  //data ready input line
  pinMode(ADS1262_CS_PIN, OUTPUT);                   //chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);               // start
  pinMode(ADS1262_PWDN_PIN, OUTPUT);                // Power down output

  Serial.begin(9600);
  //initalize ADS1292 slave
  PC_ADS1262.ads1262_Init();                      // initialise ads1262
  Serial.println("ads1262 Initialised successfully....");

 }

void loop()
{
  volatile int i,data;

 if((digitalRead(ADS1262_DRDY_PIN)) == LOW)               // monitor Data   ready(DRDY pin)
  {
    SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();      // read 6 bytes conversion register
    Responsebyte = true ;
  }

  if(Responsebyte == true)
  {
    for(i = 0; i <5; i++)
    {
      SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i);
    }
    Responsebyte = false;
  }

  if(SPI_RX_Buff_Count >= 5)
  {

    ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];  // read 4 bytes adc count
    ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
    ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
    ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];

     uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)| ((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|      ads1262_rx_Data[3]);//get the raw 32-bit adc count out by shifting
     sads1262Count = (signed long) (uads1262Count);      // get signed value
     resolution = (double)((double)VREF/pow(2,31));       //resolution= Vref/(2^n-1) , Vref=2.5, n=no of bits
// Serial.print(resolution,15);
     volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
     Serial.print(volt_V,8);

   }

  SPI_RX_Buff_Count = 0;

}

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

Why not just read the voltage reading once in setup()?   Right after the init. A dummy read there, and then no extra variables or logic in the loop() code.   Simple enough.    Or even make the 'get a reading' code into a function/subroutine.  Call it once at the end of the setup() function, first reading is eaten and call 'get a reading' function in loop() as desired.  Again, no extra variables or logic required.

@lornix: Simplest solution so far! As a matter of practice in any project using an A/D, I read it couple of times as part of its setup and again after any configuration change.

Here is what the code shown in the other answer will do.
int read_first = 0;

That allocates read_first and sets it to zero.
if (read_first ) {
    volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
    Serial.print(volt_V,8);
}
else {
   // discarded first result, now we've read the first one
   read_first = 1;
}

First time in, read_first evaluates false, so the else branch will be taken, and read_first set to 1.  Note that no reading has been taken yet, so the  “// discarded first result, now we've read the first one” comment is incorrect and irrelevant.  Second and later times in, read_first evaluates  true, so volt_V readings will be taken and printed.
To correct the problems with that code, use an approach like the following.
int useReading = 0;
...
volt_V = resolution*(float)sads1262Count;
if (useReading ) {
    Serial.print(volt_V,8);
    // and otherwise use the reading as desired
}
useReading = 1;

After this takes a first reading, it doesn't use that reading because useReading evaluates false.  Subsequent readings get used because useReading is turned on after the first reading.


text:
How do I do a register read?
Below is the sketch I'm using with the TI 32-bit adc ADS1262. I've been trying to achieve maximum resolution by setting the MODE2 register gain to 101, which is 32V/V. The default PGA setting is 000 or 1V/V. The line I set the gain is: "PC_ADS1262.ads1262_Reg_Write(MODE2, 5<<4 | 2);" I think it is probably set for the 32V/V, but I was wanting to do a register read to make sure where it is actually set at. I do not know how to do the register read, any suggestions?
The ADS1262 datasheet page 85 shows a RREG read register command, but I simply do not know how to use it. BTW, with the adc connected to a 10mV voltage the best results I get are 0.00997589244 volts or 0.00997589149 volts. It jumps between those two voltage readings. So the increment is 0.00000000095 volts. That's pretty good precision, but its not 32-bit. ADS1262 datasheet
 example.ino
 this example gives differential voltage across the AN0 And AN1 in volts
 Hooking-up with the Arduino
 ----------------------
|ads1262 pin label| Pin Function         |Arduino Connection|
|-----------------|:--------------------:|-----------------:|
| DRDY            | Data ready Output pin|  D6              |
| MISO            | Slave Out            |  D12             |
| MOSI            | Slave In             |  D11             |
| SCLK            | Serial Clock         |  D13             |
| CS              | Chip Select          |  D7              |
| START           | Start Conversion     |  D5              |
| PWDN            | Power Down/Reset     |  D4              |
| DVDD            | Digital VDD          |  +5V             |
| DGND            | Digital Gnd          |  Gnd             |
| AN0-AN9         | Analog Input         |  Analog Input    |
| AINCOM          | Analog input common  |                  |
| AVDD            | Analog VDD           |  -               |
| AGND            | Analog Gnd           |  -               |
-----------------------------------------------------------------
*/
#include <SPI.h>
#include <SoftwareSerial.h>
#include <math.h>
#include <ads1262.h>

#define PGA 32
#define VREF 2.50                 // Internal reference of 2.048V
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)

ads1262 PC_ADS1262;                     // class

float volt_V=0;
float volt_mV=0;
volatile int i;
volatile char SPI_RX_Buff[10];
volatile long ads1262_rx_Data[10];
volatile static int SPI_RX_Buff_Count = 0;
volatile char *SPI_RX_Buff_Ptr;
volatile int Responsebyte = false;
volatile signed long sads1262Count = 0;
volatile signed long uads1262Count=0;
double resolution;

void setup()
{
  // initalize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN, INPUT);                  //data ready input line
  pinMode(ADS1262_CS_PIN, OUTPUT);                   //chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);               // start
  pinMode(ADS1262_PWDN_PIN, OUTPUT);                // Power down output

  Serial.begin(9600);
  //initalize ADS1292 slave
  PC_ADS1262.ads1262_Init();                      // initialise ads1262
  Serial.println("ads1262 Initialised successfully....");

 }

void loop()
{
  volatile int i,data;

 if((digitalRead(ADS1262_DRDY_PIN)) == LOW)               // monitor Data             ready(DRDY pin)
  {
    SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();      // read 6 bytes  conversion register
    Responsebyte = true ;
  }

  if(Responsebyte == true)
  {
    for(i = 0; i <5; i++)
    {
      SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i);
    }
    Responsebyte = false;
  }

  if(SPI_RX_Buff_Count >= 5)
  {

    ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];  // read 4 bytes adc count
    ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
    ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
    ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];

     uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)|   ((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|ads1262_rx_Data[3]);//get the raw 32-bit adc count out by shifting
     sads1262Count = (signed long) (uads1262Count);      // get signed value
     PC_ADS1262.ads1262_Reg_Write(MODE2, 5<<4 | 2);  //Here is where I set the gain
     resolution = (double)((double)VREF/pow(2,31));       //resolution= Vref/(2^n-1) , Vref=2.5, n=no of bits
    // Serial.print(resolution,15);
     volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
     volt_mV   =   volt_V*1000;                           // voltage in mV
     Serial.print("Readout voltage");
     Serial.print(" : ");
     Serial.print(volt_V,9);
     Serial.print(" V ,");

   }

  SPI_RX_Buff_Count = 0;

}

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

How many digits does float/double give you? https://en.wikipedia.org/wiki/Single-precision_floating-point_format

Not sure if this is what you want Mikael but I did "Serial.print(resolution,35);" and got 0.00000003890134334564208984375000000

In AVR gcc float and double are 32-bit (single precision). This gives from 6 to 9 significant decimal digits precision (as stated in the wiki). You loose 8-bits of information when converting from 32-bit integer to 32-bit floating point.

I think the answer to your original question is 10 digits. For example, 9.997589244mV. But the last two digits are not really that precise and should be rounded off, to 9.9975892, giving 8 digits. That is probably in the 24-bit accuracy area. Do you agree?

Yes, 32-8 is 24 :).

Here are the important parts of the code I use to READ or WRITE to registers in the ADS1263 chip... I hope this helps you over this hurdle...
// The ADS1263 2 byte commands.
// Note the 3 msb are the command, the remaining bits are the starting register address.
// Refer to table 37 on page 85 of the SBAS661B.PDF for details of the ADC command map.
// Read XXXn nnnn register(s) starting at address XXXr rrrr. The first byte 001r rrrr and the second byte 000n nnnn.
// Write XXXn nnnn register(s) starting at address XXXr rrrr. The first byte 010r rrrr and the seconf byte 000n nnnn.
const byte WREG = 0x40; // 0b01000000 ADS1263 Command Write 40h + reg address.
const byte RREG = 0x20; // 0b00100000 ADS1263 Command Read  20h + reg address.
const byte MASK = 0x03; // 0b00000011 mask out the msb's and limit block size from 0 to 3 bytes.

unsigned int ads1263_Read_Reg(byte thisRegister, byte bytesToRead)
{
byte inByte = 0;
unsigned int result = 0;
byte readStatus = 0;
byte readCRC = 0;

... REDACTED
// ADS1263 expects the register address in the lower 5 bits of the byte. So no shifting of the bits is necessary:
// Now combine the address and the command into one byte bit masked to add the read register command.

byte dataToSend = thisRegister | RREG;
byte lengthToRead = byte bytesToRead & MASK; // Enforce a maximum of 3 bytes.

... REDACTED

SPI.transfer(dataToSend);
result = SPI.transfer(0x00);
lengthToRead--;
if (lengthToRad > 0)
    {
    result = result << 8;
    inByte = SPI.transfer(0x00);
    result = result | inByte;
    lengthToRead--;
    }

... REDACTED

Serial.print("Register Data: ");
Serial.println(result, BIN);

... REDACTED
}

If you used an array for a read buffer you would not have to enforce a maximum of four bytes at a time reading as unsigned int can only hold four bytes...


text:
How to do weigh scale zeroing (tare weight)?
I'm using the sketch below for a weighing scale. The sketch prints out the load-cell voltage just fine. I can't figure out how to let the scale run a couple seconds to stabilize, then use the current voltage reading (nothing on the scale) as the "Zero" voltage. Then subtract that "Zero" voltage from future readings to get the actual voltage for any weight placed on the scale. For example, let's say the nothing on the scale voltage is 0.5 volts. Then a 10 LB weight is added and the voltage goes up to 1.5 volts. So the actual voltage increase from the weight is 1.5 minus 0.5, or 1.0 volts.
#include <ads1262.h>

const float VREF = 2.50;  // Internal reference

ads1262 PC_ADS1262;  // ADC object

void setup() {
  // initialize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN,  INPUT);   // data ready input line
  pinMode(ADS1262_CS_PIN,    OUTPUT);  // chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);  // start
  pinMode(ADS1262_PWDN_PIN,  OUTPUT);  // power down output
  Serial.begin(9600);

  // initialize ADS1292 slave
  PC_ADS1262.ads1262_Init();
  Serial.println("ads1262 Initialised successfully....");
}

void loop() {
  // Nothing to do unless data ready is asserted.
  if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;

  // Get a reading and convert to voltage.
  uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
  signed long reading = (uint32_t) buffer[1] << 24
                  | (uint32_t) buffer[2] << 16
                  | (uint32_t) buffer[3] <<  8
                  | (uint32_t) buffer[4] <<  0;
  float voltage = VREF / (1UL<<31) * reading;

  // Report a smoothed-out reading.
  Serial.println(voltage, 8);
}

So you want it to wait 2 seconds and save a tare value?, and use that for adjustment of the outputs later?

You start out with a variable named Tare initialized to zero float Tare = 0.0; put in a conditional like if (millis() > 2000 & Tare == 0.0) Tare = voltage; and always report voltage - Tare.
float Tare = 0;

void loop() {
  // Nothing to do unless data ready is asserted.
  if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;
  // Get a reading and convert to voltage.
  uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
  signed long reading = (uint32_t) buffer[1] << 24
    | (uint32_t) buffer[2] << 16
    | (uint32_t) buffer[3] <<  8
    | (uint32_t) buffer[4] <<  0;
  float voltage = VREF / (1UL<<31) * reading;
  if (millis() > 2000 & Tare == 0.0) Tare = voltage;
  // Report a smoothed-out reading.
  Serial.println(voltage-Tare, 8);
}

If you want to make it smarter, add a button for tare and maybe if you have a calibration weight, add a button for calibrating.
float scale= 1.0;
const float calib_weight = 500.0; // grams?
...
if(tareButton | (millis() > 2000 & Tare == 0.0)) Tare = voltage;
if(calibrateButton) scale = calib_weight / (voltage-Tare) ;
...
Serial.println((voltage - Tare)*scale,8);
...

The direct answer to your question is to wait for the scale to settle and store the Tare voltage; then subtract it from future readings.
But that only works if the scale's transfer function (Voltage as a function of weight, or V(f)) is linear (weight = Voltage * CONSTANT). Otherwise you need to keep the Tare in weight units, do the full conversion of voltage to weight on subsequent readings, and subtract the Tare weight from that.

Thank you for that. My main problem right now is the code itself. I'm simply a novice with the Arduino C++.  How to store a voltage after the adc has run a little bit and then name it "Tare".

You start out with a variable named Tare initialized to zero float Tare = 0.0; put in a conditional like if (millis() > 2000 & Tare == 0.0) Tare = Voltage; and always report voltage - Tare.


text:
Power Arduino Due and 6 servo motor with Battery
I would like to create a project contains 6 servo motors and Arduino Due board, but I have no idea how to operate should I use only a 9V battery only or in addition to 4 AAA battery?

That highly depends on the servo motors and how long this project should last with the batteries. You need to give us more details. Look at the data sheets for the servos and see, how much current they draw. With this and the capacity of your batteries you can estimate if this can work. For this also refer to this question

Hello,
i want to know what is the best way to power an arduino due and a 6 servo motors and a HC-05 bluetooth module.
Since the arduino due operating voltage is 3.3V an the servo motors operating voltage is 4.8 ~7.2V  and the HC-05 bluetooth module can operate with 3.3v.
What is the best way to power them ?

There is no best way in general. With your setup you may use a 9V battery as input for the Due (over the power jack, which wants voltage between 7V and 12V) and using a voltage regulator to get maybe 6V from your 9V battery voltage for your servos. Make sure, you get a regulator that can give you enough current for the 6 servos (You can find this info in the datasheet of the servo motors).
Of course you can also drive your project with 2 different battery packages, like you have described it in your question. Note, that you have to connect both grounds to make this work.


text:
Resistor pull-ups for ESP8266
I'm using 4.7kOhm resistor as pullups for GPIOs 2,0,2,16, CH_PD and RESET, and also 4.7kOhm pulldown for GPIO 15. The ESP8266 boots and works fine. Would it be okay for a long shot? Should I use 10kOhm instead of 4.7kOhm?

I use 10k and have never had an issue - Note: I don't use any pullup for RESET (I think it's reset, it's one of CH_PD or RESET in any case), as all my ESP modules (07/12E/12F based) have "on board" pullup. I've also never had a pullup for GPIO16 because I've never used it for anything, and it's state at power on is irrelevant - only reset and ch_pd (obviously) and 0/2/15 are "important" at power on

Would it be okay for a long shot? - what is a "long shot" in this instance?

@NickGammon "in the future"

@JFetz2191, that should be "long haul"  ... as in "Would it be ok in the long haul?"...... "long shot" means "something that is most likely to fail"

Oh, OK, I thought it might have meant "over a long distance".

In general it makes little or no difference what the value of resistor you use is.
The only things it can affect are:

The current consumption while a button is pressed - a lower value resistor will cause more current to flow while for the time the button is pressed (it makes no difference at other times).
The LOW voltage (VIL) read at the IO pin if the button has a high resistance (for example if it's on the end of a 500m length of cable).
Noise immunity - a lower value resistor will pull the pin up "harder" making it more difficult for noise induced in a long wire (see the previous point, too) from causing a false button press (although this is less of a concern with modern digital inputs that tend to all have Schmitt triggers).

10k is often chosen not because it's "better" than any other value, but purely because it's more common that many other values, and it's in the right kind of ball-park for most setups.  It's low enough to give good noise immunity while being high enough to not cause undue current flow while the button is pressed. But more importantly, it's a resistor that everyone has in their kit, and is most likely the most common resistor used in a number of other places in the circuit as well. It's a good all-rounder as far as resistors go.
To take a closer look at the current flow aspect - if you are running (as with an ESP8266) at 3.3V and you have a 10k resistor the current flow, when the button is pressed and the resistor connected directly to ground, though the resistor would be (I=V/R) 3.3/10,000 = 330uA. If you used a 4.7k resistor (as you are doing at the moment) the current rises to 3.3/4,700 = 702uA. Yes, that's just over double the current, but twice peantus is still peanuts. So 4.7k, under most general circumstances, is perfectly fine.
However if power consumption is a real concern and you want to keep all consumption to an absolute minimum switching to 100k (as you often see in low-power circuits) would be beneficial, since 3.3/100,000 is 33uA.
If your input is connected to a momentary button which will be pressed for fractions of a second at a time it's not that much of an issue. But if the input is connected to a switch that could be activated for days or weeks at a time it obviously becomes of greater interest.
So in short: when running on batteries higher value pullup resistors are better, but when running off a power supply it really makes no difference.

If you need pull-up just for buttons and similar inputs, 100k is pretty fine. But if you use open-drain bus (e.g. I2C), then resistor values have to be calculated properly. If you want to achive 400kHz speed on I2C, even 4k7 might not work and you may need 3k6 or even lower. It depends on the total capacitance of all traces and devices attached.


text:
SD begin affecting OLED display
Okay, I'm using u8g2 library for my OLED display. After calling SD.begin(4) function, I cannot display anything on my OLED.
I'm using U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); constructor from u8g2 library since I'm using I²C for the display and SPI for microSD reader. I removed the CS Pin 4 from SD.begin() and I can now display something on the OLED.
How did supplying CS Pin parameter to SD.begin() function affected the I²C OLED display?

Pins 4 and 5 are the I2C pins that belong to the built in I2C peripheral on the Arduino. You have to put your CS line for the SPI SD card on a different pin.
EDIT:
The answer above is relevant to the Arduino ATMega328-based board, not ESP8266-based NodeMCU board. This answer is not relevant to ESP8266 or NodeMCU with regard to hardware I2C, as the ESP8266 does not have a dedicated hardware I2C peripheral.

I'm using ESP8266 (NodeMCU v3) and pin numbers for I2C is D1 & D2 (printed on the board). Man, this caused confusion to me. Thanks for the explanation.

The NodeMCU docs say to use Pin 8 for SPI (SD Card) slave-select.


text:
Set a pin HIGH when crash occurs
I'm using an ESP8266 (NodeMCU v3). I want to set a PIN high if a soft wdt reset occurs (not expecting one). Is there a way I can do that?
Can I attach something on TX pin of the board and watch for crash dump? Maybe another Arduino?

@LookAlterno that's a very useful article and program but it's pretty architecture specific. I don't think there is any way to use it with ESP8266 without an almost complete rewrite of the code.

The ESP provides a reset reason API, which lets you differentiate between a crash and a normal reset:
extern "C" {
  #include "user_interface.h"
}

const char * const RST_REASONS[] =
{
  "REASON_DEFAULT_RST",
  "REASON_WDT_RST",
  "REASON_EXCEPTION_RST",
  "REASON_SOFT_WDT_RST",
  "REASON_SOFT_RESTART",
  "REASON_DEEP_SLEEP_AWAKE",
  "REASON_EXT_SYS_RST"
};

// .. in setup():

const rst_info * resetInfo = system_get_rst_info(); //populate reset info
String diag = String(RST_REASONS[resetInfo->reason]); // turn enum index to string

if(diag == "REASON_SOFT_WDT_RST") digitalWrite(TX, HIGH);// check string, take action

The ESP8266 should  hold the pin LOW when it is active, letting it go high then signals that the program has crashed.

It sounds like the idea is to drive the pin low when operating properly, but rely on the WDT-triggered reset making it a high impedance input which can be overridden by an external pullup resistor.


text:
Arduino Pro Mini (5v) I2C pullups
I recently bought an ESP-WROOM-32 module and I want it to talk to my Pro Mini via I2C. Do I have to pull-up the lines to the 3.3v side (ESP32)? Since the Pro Mini runs at 5v, I think it's a bad idea to pull-up the lines from that side.

That would work. 3.3V is high enough for the 5V arduino to register as a HIGH. Just make sure you disable the internal pull up resistors on the Arduino. The default I2C library enables those for some reason (which it shouldn't imho).

@Gerben, the i2c signal needs to be 3.5V for an atmega328p at 5V. A digital input requires 3.0V, but the i2c needs 3.5V.

Indeed; Vih is 0.7*Vcc, so according to the datasheet you'd need at least 3.5V. But my guess is it will work just fine. If not, you could use two mosfets to create a I2C level shifter

note that you can feed your esp32 3.6v within spec.

@Gerben It works, I pulled-up the lines with 4k7 resistors on 3v3 side. Since the ESP32 has a higher core speed, I need to put a 5ms on every request for the Pro Mini to keep up.