text:
Splitting Integers
I have bluetooth (HC-05) connected on Serial port of Arduino Mega and two TM1637, I am receiving Strings from an Android phone with an app with two Time picker (Fajar and Zohar)
I am sending time which is set by time picker in a formatted way.
The format is
< : Start of number delimiter.
ID : is the number 1 or 2 (1 for Fajar and 2 for Zohar), it indicates from which time picker the data has come.
HH : Hours, set from time picker.
MM : Minutes, set from time picker.
> : End of number delimiter.

Here in the example, first data which comes in is <10320> , which is starting delimiter "<" first digit "1" is the ID from Fajar time picker,03 Hours and 20 minutes and ending delimiter ">". Second data is <21830>, which is from Zohar time picker and vice versa.
I am parsing the incoming string and converting them into integers using the code found on Arduino Forum.
const char startOfNumberDelimiter = '<';
const char endOfNumberDelimiter   = '>';

void setup ()
 {
 Serial.begin (9600);
 Serial.println ("Starting ...");
 } // end of setup

void processNumber (const long n)
 {
 Serial.println (n);
 }  // end of processNumber

void processInput ()
 {
 static long receivedNumber = 0;
 static boolean negative = false;

 byte c = Serial.read ();

 switch (c)
   {

   case endOfNumberDelimiter:
     if (negative)
       processNumber (- receivedNumber);
     else
       processNumber (receivedNumber);

   // fall through to start a new number
   case startOfNumberDelimiter:
     receivedNumber = 0;
     negative = false;
     break;

   case '0' ... '9':
     receivedNumber *= 10;
     receivedNumber += c - '0';
     break;

   case '-':
     negative = true;
     break;

   } // end of switch
 }  // end of processInput

void loop ()
 {

 if (Serial.available ())
   processInput ();

 // do other stuff here
 } // end of loop

with the code above, i can convert string to integers and remove delimiters.
See output of the code in serial monitor.

Problem is : I have to separate ID and Hours and Minutes from that integer and wrap Hours and Minutes that up in
int8_t Digits [] = {1, 2 , 3 , 4 };

Here {1,2,3,4} is {H,H,M,M} Hours and Minutes which displays digits on one of the TM1637.
and also ID with "1" should change the digits on one of the TM167 and the ID with "2" should change digits on another TM1637.
Here is my full code :
#include "TM1637.h"

#define CLK1 2
#define DIO1 3

#define CLK2 4
#define DIO2 5

TM1637 Display1 (CLK1, DIO1);

TM1637 Display2 (CLK2, DIO2);

const char startOfNumberDelimiter = '<';
const char endOfNumberDelimiter   = '>';

void setup ()
{
  Display1.set ();
  Display1.init ();

  Display2.set();
  Display2.init();

  Serial.begin(9600);
  Serial.println ("Starting ...");
}

void loop ()
{
  if (Serial.available ())
    processInput ();
  fajar();
  zohar();
}

void processNumber (const long n)
{
  Serial.println (n);
}  // end of processNumber

void processInput ()
{
  static long receivedNumber = 0;
  static boolean negative = false;

  byte c = Serial.read ();

  switch (c)
  {

    case endOfNumberDelimiter:
      if (negative)
        processNumber (- receivedNumber);
      else
        processNumber (receivedNumber);

    // fall through to start a new number
    case startOfNumberDelimiter:
      receivedNumber = 0;
      negative = false;
      break;

    case '0' ... '9':
      receivedNumber *= 10;
      receivedNumber += c - '0';
      break;

    case '-':
      negative = true;
      break;

  } // end of switch
}  // end of processInput

void fajar ()
{
  int8_t Digits [] = {1, 2 , 3 , 4 };
  Display1.display (Digits);
  Display1.point(POINT_ON);
}

void zohar ()
{
  int8_t Digits [] = {1, 2 , 3 , 4 };
  Display2.display (Digits);
  Display2.point(POINT_ON);
}

Please Help
EDIT : Here is my edited code with Majenko shown technique.
#include "TM1637.h"

#define CLK1 2
#define DIO1 3

#define CLK2 4
#define DIO2 5

uint8_t fajar[4];
uint8_t zohar[4];

uint8_t address = 0;
uint8_t ptr = 0;

TM1637 Display1 (CLK1, DIO1);

TM1637 Display2 (CLK2, DIO2);
void setup ()
{
  Display1.set ();
  Display1.init ();

  Display2.set();
  Display2.init();

  Serial.begin(9600);
}

void loop ()
{
  int c = Serial.read();
  switch (c) {
    case '<': // Start of string - reset everything
      address = 0;
      ptr = 0;
      break;
    case '>': // End of string

       fajartime (); // Edited
       zohartime (); // Edited

      break;
    default:
      if ((c >= '0') && (c <= '9')) {
        if (address == 0) {
          address = c - '0';
        } else if (ptr < 4) {
          switch (address) {
            case 1:
              fajar[ptr] = c - '0';
              break;
            case 2:
              zohar[ptr] = c - '0';
              break;
          }
          ptr++;
        }
      }
  }
}

void fajartime ()
{

  Display1.display (fajar);
  Display1.point(POINT_ON);
}

void zohartime ()
{

  Display2.display (zohar);
  Display2.point(POINT_ON);
}

Thank you

You're thinking the wrong way. At the moment you are receiving individual characters, then combining them into a single integer, and then you want to split that integer back into individual characters. But you start with individual characters already. You don't need, nor want, to convert the string into an integer to then split it again.
If you take each character as it comes in as a separate number and store it separately you have no need for splitting.
For instance, you could have two 4-byte arrays for the two times. You don't need to store the first byte, since it's just an indicator of destination (we can call it a register address if you like).
A simple Finite State Machine for receiving in the correct way will make things easier:
uint8_t fajar[4];
uint8_t zohar[4];
uint8_t address = 0;
uint8_t ptr = 0;

int c = Serial.read();
switch (c) {
    case '<': // Start of string - reset everything
        address = 0;
        ptr = 0;
        break;
    case '>': // End of string
        // Do whatever with the data here
        break;
    default:
        if ((c >= '0') && (c <= '9')) {
            if (address == 0) {
                address = c - '0';
            } else if (ptr < 4) {
                switch (address) {
                    case 1:
                        fajar[ptr] = c - '0';
                        break;
                    case 2:
                        zohar[ptr] = c - '0';
                        break;
                }
                ptr++;
            }
        }
}

You could simplify things by combining zohar and fajar into a single 2D array keyed on the address (though take care that address never gets an invalid value in that case), or you can reduce memory usage by only having one 4-byte array if you don't care about keeping the data separate at all times (you use it and throw it away as soon as it's arrived).

Ahh! i have realized that, the code that i got from an Arduino Forum takes single characters from Serial and make an integer of that, I was thinking in a wrong way!
I am new to pointers, i haven't actually used it before - can you please check my code again.. i have edited the question.
thank you

Using void fajartime (); etc in the middle of your code isn't calling the function - it's defining the function prototype. Lose the void.

ohh! My bad, I have edited that again, Please check

Looks reasonable - though I don't know about the functions you use to display - if they take a 4-byte array like that or not.

Also you only really need to update the display for the address you have at the time.

That works! YAY! , How can i add more displays.? I can add more Time pickers with different address or IDs

Just add more arrays and matching address entries in the main FSM.

I'm not sure I know what you need help with.  You have code that reads a 5 character string from between .

If i == 1 you pass the remaining 4 characters to fajar.
If i == 2 you pass the remaining 4 characters to zohar.

You then need a function to convert the 4 characters into 4 separate integers.  You might need to map these integers onto a code that displays the correct lights or you might have a library to do this already.  (You already have the code for this function).  All you need to do then is push the number to the display.  That might be the problem you have, but how you do that depends on you library and connections.
TM1637 Displays[2] = {(CLK1, DIO1), (CLK2, DIO2)};
void loop()
{
    char buffer[1 + 5 + 1 + 1];
    buffer = readNumber (buffer);
    if (buffer[0] == '1')          // Treating as a character not a number.
        fajar(&(buffer[1]));
    else
        zohar(&(buffer[1]));
}
void fajar(char const* buffer) { displayValue(1, buffer);}
void zohar(char const* buffer) { displayValue(2, buffer);}
void displayValue (const int& displayID, char const* buffer)
{
    int numericValues[4];
    convertToNumbers (buffer, numericValues);  // The code in the switch statement.
    Display[displayID].display (numericValues);
    Display[displayID]..point(POINT_ON);
}

The above code is only a guide, never compiled and it is riddled with issues that could, if bad data was received, cause a major problem.  You are going to have to add error and bounds checking before you do anything more than dev test it, but it should work :)


text:
Arduino & RPi communication via GPIO
so I'm working on communication between arduino and RPi via GPIO pin.
It's basically connecting them by using a cable jumper. So I have a 2 channel relay shield attached to my arduino, and I've been wondered how do I connect them to RPi. I need help for this problem, any advice would be appriciated. I'll post the GPIO pin below.
Thankyou

Do you really need the arduino? you can attach the relays to the rPi directly.

@ratchetfreak Thankyou for your answer, yes I do need the arduino, the relay is attached on my arduino,  you can attach the relay to RPi by using the cable jumper, but I don't really know how it work

Why not just use the serial cable?  Have you considered using the Raspberry Pi to program the Arduino then for communications also?  That's what I do for my solar plant modults.

I assume you are using Arduino UNO. Pi's digital logic is at 3.3 V and that of Arduino Uno is at 5 V. Anyway to send data from Pi to UNO, you can connect the pins directly. UNO can recognise both the logic levels of Pi's output. But to receive data from UNO to Pi, make sure you build a voltage divider using resistors, that brings 5V output from UNO's pin to 3.3 V. Also the grounds of both Pi and UNO should be connected to each other.

Thanks, I really appreciate it. The thing is I've attached relay channel shield on top of my arduino. So i just connect them like
RPi           pin 1 to   Arduino GND 5v
Like that?

why are you using relay shield?

@tbh Using relay shiled so i can attach another device called xbee(cc2530) for wireless transmission

to send data from pi to arduino and then send that data wirelessly via zigbee?

What on earth does a realy shield have to do with connecting an xBee? I think you are a little confused about what you actually want to do and are suffering from a severe case of xy-problem.

using zigbee for wireless transmission to another device

If you want to use an xBee for Pi communication then connect the xBee to the pi. It uses UART communication (very simple to wire up) or you can use a USB "explorer" board to plug it in to the USB socket. They use simple AT commands to configure them that are well documented. There is no role for the Arduino here.

We actually don't understand what do you want to do. You said you want to use ZigBee for wireless communication. You are not mentioning what data have to be transferred from where to where.

@Majenko there's no role of xBee here, it just between arduino(attached with relay shield) and RPi

@MITURAJ sorry for missunderstand, I'm not using this xBee things now, I've just thinking how do I connect my arduino that was attached with relay shield to RPi by using GPIO port. Why I use relay shield? Because It's for my next project, and also what for xBee it's also for my next project

Okay, remove the shield from UNO, zigbee etc and connect Pi and UNO as mentioned in this answer to make them communicate. Connections depend on what are the components you use and what you want to do with it.

@MITURAJ so for example RPi will send pin 4 HIGH, and arduino will receive the information, I've write the code, the problem is , how do I pin the right GPIO port from my  RPi to arduino. The thing is my next project and this problem right still have some sort of relation , so I need to attach my relay shield to my arduino

Answer for that is what I have given here.

@MITURAJ thankyou , i really appreciate that, also thanks for your time for spending in here

What you are asking really makes no sense at all.
You are starting from the mid-point of your project and wondering how to communicate using bare GPIOs without really knowing what it is you want to communicate and what you want to do with that data - or at least you haven't made any of that clear to us.
It is unclear what you want to do with the shield from the Pi. Do you want to control the relays on it by sending instructions from the Pi? Do you want the Pi to send and receive data through the XBee? Either way the Arduino is pretty redundant in the system and in fact gets in the way more than is useful.
If it's just relays you want then it would be far simpler to wire cheap relay modules direct to the GPIOs of the Pi - then you don't have to worry about "how to communicate" - you just turn the relays on and off.
If you want to communicate with the XBee there are far simpler shields available that will plug directly into a Pi. Indeed, there are some good shields around for the Pi ("Hats" I think they call them) which give you an Arduino footprint and an XBee socket together.
The Arduino is completely pointless in this system. And anyway, if you wanted to make the two systems communicate there are far easier ways than with bare GPIO pins. Serial, for a start. The simplest ever method is to just plug the Arduino into the Pi's USB. That way it gets power and data all in one go. Just like using it with a computer.

source: Stack Exchange

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

sort: votes


text:
Does old/low charge battery affects internal clock?
Totally newbie in eletronics here, but could not find the answer for this one.
When a battery is nearly-exhausted, it's voltage and or amperage dims, right?
My question is if this kind of scenario (running low battery) would affect the arduino internal clock using only it.
I'm using arduino to a device that will operate remotely (with a 9V battery), and also logs intervals using the time function.
If battery is near-exhausted, then will this skew the numbers I get?

Microprocessor clock crystal frequencies can vary a few parts per million when microprocessor supply voltages vary significantly.  For example, a Czechoslovakian blog article (which was mentioned in avrfreaks.net and is shown in automatic-translated form at translate.google.com) shows a nearly-negligible drop of about 14 PPM as supply voltage for an Atmel ATtiny2313 rises from 2.4 V to 3.5 V or drops from 5 V to 3.5 V.  In the results, crystal frequency was about 4000000 Hz near 2.4 V and 5 V, and drops to 3999945 Hz near 3.5 V.
I refer to that 14 PPM frequency change as nearly negligible because typical inexpensive crystals have ±50 PPM or worse accuracy and stability specifications, and ±50 PPM or worse allowance over temperature changes of a few degrees, and somewhat larger allowances as the crystal's load capacitance varies by a few pF.  Thus, crystal frequency changes due to supply voltage changes are negligible compared to changes due to other causes.

Let's assume by "internal clock" you mean the internal oscillator, as the arduino's processor does not have a built-in real-time clock (something that is meant to keep track of real time like seconds/minutes/hours.)
The arduino is not like a motor where it runs slower if a lower voltage is applied. If the voltage goes too low, the arduino will just reset. Once it resets, the program running in it just starts over again, unless the battery voltage is so low it can't even start up.
If you're feeding it with a 9V battery, you're going through the 5V linear regulator on-board, which is not very energy efficient. Keep that in mind if your goal is to create a project that is meant to run a long time on the 9V battery. See the notes at http://www.gammon.com.au/power for tips on reducing the power used by an arduino and/or ATMega-based project.

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


text:
Non intrusive current sensor with unreliable (strange) readings
I have a project where I will mount 6 non intrusive current sensor model SCT013 (100A/50mA) manufactured by yhdc.com on an Arduino Mega.
Virtual ground and Burden resistors are 1% tolerance.
To start testing I mounted 2 sensors using the principles of connection found at (http://www.homautomation.org/2013/09/17/current-monitoring-with-non-invasive-sensor-and-arduino/). Code below.
#include "EmonLib.h"                   // Include Emon Library
EnergyMonitor emon0;                   // Create an instance
EnergyMonitor emon1;                   // Create an instance

int Calib = 60;

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

  emon0.current(A0, Calib);             // Current: input pin, calibration.
  emon1.current(A1, Calib);             // Current: input pin, calibration.

   }

   void loop(){

double Irms0 = emon0.calcIrms(1480);
double Irms1 = emon1.calcIrms(1480);

Serial.print("Sensor0: ");
Serial.print(Irms0);
Serial.print(" Amps ");

Serial.print("Sensor1: ");
Serial.print(Irms1);
Serial.println(" Amps ");

}
//------------end------------

The code I found is for UNO and a single sensor and I just added a second, it works fine and sensors do independent readings well.
Both sensors are mounted on the same test live wire so I have to get more or less the same readings most of the times and it is precisely the case with readings floating between sensors on the order of 100s of miliamps.
My problems are:

Even with no load I get, on both sensors, a reading that varies from 270 to 320mA
When I connect a hair dryer that consumes in one mode 10A and in
another mode 5A the readings are a lot closer to the expected (I am
also checking with a clamp meter)

The problem seems to be the no load condition and the imprecise readings at low currents.
I could exclude readings under a certain value on my code to solve the no load problem but them I would be ignoring real electrical measurement situations.

Paulo, to avoid confusion please edit the information in your comment into the question body.  Click 'edit' in the "share edit close flag" group and change the question.  Also please note that "a reading that rovers around 30mA" does not make sense in English.  Do you mean that it hovers near 30mA, ie, stays near 30mA?  Or do you mean that it roves, that is, moves at random, near 30mA?  If so, say what the high and low readings are.  Also show your ADC setup() code and the ADC reading code and say if you used shielding or shielded wire, etc

Every time you use a real clamp meter, you should zero it out before measuring.
The hall effect sensors you describe are the same way. There's magnetic pull from the earth and other sources that need to be corrected for. When you draw 5 or 10 amps, that noise is masked out. They are likely still apart roughly the same # of ma as the baseline reading.
Once you subtract the no-load load from each, maybe on startup, you should get a lot better readings in terms of accuracy and precision.

Hi, I would like to understand where this imprecision comes from. Even with the sensor plug disconnected I get these 270 to 320mA readings. And these values are entirely dependent on the value I put on the variable Calib. The problem seems to start at the Arduino A0 pin inwards. What If I use an external AD converter? Thanks

offsets are common and needed. if you're sensor can read 10A, then each ADC level is ~40ma, and ACDs tend to bounce a few levels each each reading, sometimes more, particularly built-in ones. smoothing caps and an external ADC would help precision, but you still need to calibrate for accuracy.


text:
How to calculate step delay?
I'm struggling with get suitable step delay while driving a stepper motor.
How to calculate exact step delay for 1.8deg/step stepper motor?
Give some example calculation.

Welcome to Arduino SE. Please realize that this is not a free design house, homework-answering service or an on-line technical encyclopedia, copied out to you on demand. People will help you take the next step if your question shows that you've done as much as you possibly could on your own - which your post doesn't. Please revise your question showing your work and findings so far. Or delete the question if Internet searches give you your answer anyway.

Convert the RPM of the motor to RPS.
Take reciprocal to get seconds per revolution.
Divide it by 360 to get seconds per degree.
Multiply by 1.8 to get seconds per step.

How to calculate exact step delay for 1.8deg/step stepper motor?

each rpm = 360 degrees * rpm / 60 second.
So the time, between each step, is resolution / (60 * rpm), where resolution = 1.8deg/step in your case.


text:
How to correctly use functions that return pointers to multiple typedef'ed types in Arduino IDE?
I have a program that typedef's two structs. Each one has a corresponding function that returns a pointer to it....
typedef struct {
  int x1;
} x;

x *a;

x *f(void) {
  return a;
}

typedef struct {
    int  y1;
} y;

y *b;

y *g(void) {
  return b;
}

void loop(void) {

}

void setup(void) {

}

This program produces the following error when compiled under the Arduino IDE...
sketch_nov10a:18: error: 'y' does not name a type

 y *g(void)

If we copy/paste to switch the order of the two blocks like so...
typedef struct {
    int  y1;
} y;

y *b;

y *g(void) {
  return b;
}

typedef struct {
  int x1;
} x;

x *a;

x *f(void) {
  return a;
}

void loop(void) {

}

void setup(void) {

}

...then we instead get the following error...
sketch_nov10a:18: error: 'x' does not name a type

x *f(void)

...so apparently the Arduino IDE only supports functions that return pointers to the first typedef'ed type defined in the file?
Is there a rational to this? How would you implement the above code to get it to compile under the Arduino IDE (it works fine in gcc).

The Arduino IDE, rather annoyingly, tries to "help" you by generating function prototypes for functions, something it sometimes fails to do.
You can make your code compile by adding one yourself:
typedef struct {
  int x1;
} x;

x *a;

x *f(void) {
  return a;
}

typedef struct {
    int  y1;
} y;

y *b;

y *g(void);    // <------------------ ADD THIS
y *g(void) {
  return b;
}

void loop(void) {

}

void setup(void) {

}

I have a post about how to avoid the quirks in the IDE which may help you.
If you just move your code into a separate .CPP file and leave the main sketch blank, it will compile, if you add this line to the start of the .CPP file:
#include <Arduino.h>

The Arduino IDE uses gcc, so it isn't a problem with the compiler exactly, it is a problem with how it "helps" you.

This is the correct answer and solves the problem, but so unsatisfyingly... :/ Thanks!

but so unsatisfyingly - yes, I know. In order to save teaching newbies about function prototypes they have created a monster that behaves in a way that confuses non-newbies. :)

I tracked this down and I'd classify it as a logic bug in the arduino-builder tool. See this new answer for details.

Cause
Ok, I've pinned down the root of this issue.
The arduino-builder program is responsible for mangling the sketch INO file into a cpp file to be fed into gcc. Among other things,  it scans the file for function definitions and then adds prototypes for all the found functions.
The prototypes are added as a block just before the first function declaration in the file.
Unfortunately this strategy fails any time there is the following sequence....

a function definition
a type definition
a function definition that depends on the type defined in #2

...since the prototype for the function defined in #3 ends up being added before the type definition in #2 on which it depends, creating the compilation error.
The code responsible for this behavior is here...
https://github.com/arduino/arduino-builder/blob/b91cea8c8a42803b0b40dcdde2d1165c4e225457/src/arduino.cc/builder/ctags_runner.go#L83
A more robust strategy would be to add each function prototype before the first function definition that calls the function being prototyped.
Workaround
In the meantime, a workaround is to move all type definitions to be before the first function definition in the source code.
Rearranging the above example program like so...
typedef struct {
  int x1;
} x;

typedef struct {
    int  y1;
} y;

x *a;

x *f(void) {
  return a;
}

y *b;

y *g(void) {
  return b;
}

void loop(void) {

}

void setup(void) {

}

...resolves the error, at the expense of code clarity.

It would be hard to get the builder to work in all circumstances (for example if you use #define to obscure your intent). Effectively it needs to know what the compiler knows, so effectively they need to turn it into a compiler to do the job properly. Your suggestion works (as does mine) but this is not something people normally expect to have to do.

bigjosh, Thank you for a small and working sketch that shows the problem !
It is probably a bug of the Arduino preprocessing before handing it over to the compiler, as @nick-gammon wrote.
When I rewrite the code in my own way (in a normal sketch, a *.ino file), the error message is gone. I use a more modern style of the struct typedefs, and I declare first the typedefs and after that the variables and after that the functions.
I suppose that when multiple include files are used, then this might not be possible.
// declare the typedefs.
struct x {
  int x1;
};

struct y {
  int  y1;
};

// create variables (pointers)
x *a;
y *b;

// Arduino functions
void loop(void) {
}

void setup(void) {
}

// Your own functions
x *f(void) {
  return a;
}

y *g(void) {
  return b;
}

I hope the data of the struct is located somewhere, because the sketch has only pointers and no valid memory location that they can point to.

You wrote x and y struct definitions, rather than typedefs.  That approach is not "newer" than that in the question; if anything, it's older.   Note, the code you show shouldn't compile correctly unless you add struct before x *a; and y *b;.  See the first answer to Difference between 'struct' and 'typedef struct' in C++?,

@JamesWaldby-jwpat7 Did you try to compile it ? I'm using the C++ way where the struct/union/enum create a new type. I understand that it can cause a problem, when a similar name gets hidden. That's about how far my knowledge stretches. It is not wrong, and I consider it even as normal C++ programming. I'm happy to learn new things though.

Ignore the “shouldn't compile correctly” part of my comment (which is true in C not C++, as I noticed too late to edit) .  It might be worthwhile to ignore the whole comment :) but I'll leave it there for the link.


text:
Send events to Azure IoT Hub combined with deep sleep mode
I use a Node MCU ESP8266. I have a working C app sending temperature and humidity sensor data to Azure IoT Hub continuously. I see events/messages coming in at Azure.
Now I'd like the app to only send data every minute or so. So I implemented a deep sleep scenario. The problem is my messages are queued but not sent.
My suspicion is that the IoTHubClient_LL_DoWork() does not send the data immediately before the device is going into deep sleep. But I don't know enough about C or the AzureIoT SDK. Here is my code:
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <WiFiUdp.h>

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include <sys/time.h>

#include <AzureIoTHub.h>
#include <AzureIoTProtocol_MQTT.h>

#include <ArduinoJson.h>

#define IOT_CONFIG_CONNECTION_STRING "CONNSTRING"

#define DEVICE_ID "NodeMcu"

#define WIFI_SSID "SSID"
#define WIFI_PW "PW"

#define MESSAGE_MAX_LEN 256

static bool messagePending = false;
static bool messageSending = true;

static int messageCount = 1;

static IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;

void setup()
{
    delay(1000);

    Serial.begin(115200);

    connect();
    initTime();

    iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(IOT_CONFIG_CONNECTION_STRING, MQTT_Protocol);
    if (iotHubClientHandle == NULL)
    {
        Serial.println("Failed on IoTHubClient_CreateFromConnectionString.");
        while (1);
    }

    //IoTHubClient_LL_SetOption(iotHubClientHandle, "product_info", "HappyPath_AdafruitFeatherHuzzah-C");
    //IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, receiveMessageCallback, NULL);
    //IoTHubClient_LL_SetDeviceMethodCallback(iotHubClientHandle, deviceMethodCallback, NULL);
    //IoTHubClient_LL_SetDeviceTwinCallback(iotHubClientHandle, twinCallback, NULL);
}

void loop()
{
    if (!messagePending && messageSending)
    {
        char messagePayload[MESSAGE_MAX_LEN];
        readMessage(messageCount, messagePayload);
        sendMessage(iotHubClientHandle, messagePayload);
        messageCount++;
        delay(5000);
    }

    IoTHubClient_LL_DoWork(iotHubClientHandle);
    delay(10);
}

void connect()
{
    delay(10);

    if (WiFi.status() == WL_CONNECTED)
    {
        Serial.println("Already connected...");
        return;
    }

    // Connect to WiFi network
    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(WIFI_SSID);

    WiFi.begin(WIFI_SSID, WIFI_PW);

    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println("");
    Serial.println("WiFi connected");
}

void initTime() {
    time_t epochTime;

    configTime(0, 0, "pool.ntp.org", "time.nist.gov");

    while (true) {
        epochTime = time(NULL);

        if (epochTime == 0) {
            Serial.println("Fetching NTP epoch time failed! Waiting 2 seconds to retry.");
            delay(2000);
        } else {
            Serial.print("Fetched NTP epoch time is: ");
            Serial.println(epochTime);
            break;
        }
    }
}

void readMessage(int messageId, char *payload)
{
    float temperature = readTemperature();
    float humidity = readHumidity();
    StaticJsonBuffer<MESSAGE_MAX_LEN> jsonBuffer;
    JsonObject &root = jsonBuffer.createObject();
    root["deviceId"] = DEVICE_ID;
    root["messageId"] = messageId;

    // NAN is not the valid json, change it to NULL
    if (std::isnan(temperature))
    {
        root["temperature"] = NULL;
    }
    else
    {
        root["temperature"] = temperature;
    }

    if (std::isnan(humidity))
    {
        root["humidity"] = NULL;
    }
    else
    {
        root["humidity"] = humidity;
    }

    root.printTo(payload, MESSAGE_MAX_LEN);
}

float readTemperature()
{
    return random(20, 30);
}

float readHumidity()
{
    return random(30, 40);
}

static void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, char *buffer)
{
    IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char *)buffer, strlen(buffer));
    if (messageHandle == NULL)
    {
        Serial.println("Unable to create a new IoTHubMessage.");
    }
    else
    {
        //MAP_HANDLE properties = IoTHubMessage_Properties(messageHandle);
        //Map_Add(properties, "temperatureAlert", temperatureAlert ? "true" : "false");
        Serial.printf("Sending message: %s.\r\n", buffer);
        if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, NULL) != IOTHUB_CLIENT_OK)
        {
            Serial.println("Failed to hand over the message to IoTHubClient.");
        }
        else
        {
            messagePending = true;
            Serial.println("IoTHubClient accepted the message for delivery.");
        }

        IoTHubMessage_Destroy(messageHandle);
    }
}

static void sendCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void *userContextCallback)
{
    if (IOTHUB_CLIENT_CONFIRMATION_OK == result)
    {
        Serial.println("Message sent to Azure IoT Hub");
    }
    else
    {
        Serial.println("Failed to send message to Azure IoT Hub");
    }
    messagePending = false;
}

You need to call IoTHubClient_LL_DoWork until all messages are processed and only after that you can go to sleep.
Check the following code:
void IoTHubFullSendReceive()
{
  IOTHUB_CLIENT_STATUS Status;

  while ((IoTHubClient_LL_GetSendStatus(IoTHubClientHandle, &Status) == IOTHUB_CLIENT_OK) && (Status == IOTHUB_CLIENT_SEND_STATUS_BUSY))
  {
      IoTHubClient_LL_DoWork(IoTHubClientHandle);
      ThreadAPI_Sleep(50);
  }
}


text:
Arduino due temperature reading shows random temperatures
I am using an Arduino Due board to read three temperatures from three separate smt160-30 digital sensors but the program is behaving very randomly. the code I am using is one I got from arduino official site and changed the structure to get three temp readings and display them on a 16x2 lcd. The problem is when I use one sensor the output is reasonable but when I use all three the temperature showing are all off by 4 degrees. also I tried removing the line lcd.print(temperature1, 1) and the output temperatures changed. Is this odd behavior because of SRAM issues ? if so how can I find out about it and fix it ?
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

unsigned long now;
unsigned long lastSample;
unsigned int sampleSize;

unsigned int highCount1;
unsigned int highCount2;
unsigned int highCount3;

unsigned long lastOutput;

float temperature1;
float temperature2;
float temperature3;
float hcf1, hcf2, hcf3;
float ssf;

int sensorPin1 = 23;
int sensorPin2 = 24;
int sensorPin3 = 26;

void setup(){

    pinMode(sensorPin1, INPUT);
    pinMode(sensorPin2, INPUT);
    pinMode(sensorPin3, INPUT);

    digitalWrite(sensorPin1, LOW);
    digitalWrite(sensorPin2, LOW);
    digitalWrite(sensorPin3, LOW);

    lastSample = 0;
    sampleSize = 0;

    highCount1 = 0;
    highCount2 = 0;
    highCount3 = 0;

    temperature1 = 0;
    temperature2 = 0;
    temperature3 = 0;

    lastOutput = 0;

    delay(2000);
    lcd.setCursor(0, 0);

}

void loop() {
    now = micros();
    if (now - lastOutput > 3000000) {
        lcd.clear();

        hcf1 = highCount1;
        hcf2 = highCount2;
        hcf3 = highCount3;

        ssf = sampleSize;

        temperature1 = ((hcf1 / ssf) -0.32)/0.0047;
        temperature2 = ((hcf2 / ssf) -0.32)/0.0047;
        temperature3 = ((hcf3 / ssf) -0.32)/0.0047;

        lastOutput = now;
        sampleSize = 0;

        highCount1 = 0;
        highCount2 = 0;
        highCount3 = 0;

        lcd.print(temperature1, 1);
        lcd.print(" ");

        lcd.print(temperature2, 1);
        lcd.print(" ");

        lcd.print(temperature3, 1);

    }
    if (now - lastSample > 50) {
        sampleSize++;
        highCount1 = highCount1 + digitalRead(sensorPin1);
        highCount2 = highCount2 + digitalRead(sensorPin2);
        highCount3 = highCount3 + digitalRead(sensorPin3);
        lastSample = now;
    } else {
        delayMicroseconds(10);
    }
}

Thank you!

Did you read about this smt160 sensor ? It relies on the calculation of duty cycle of the square wave output from the sensor, to calculate the temparature.

temperature = (dutyCycle) -0.32)/0.0047

The square wave output has to be sampled at 8KHz or at 125us for no loss of information. This block samples that data.

if (now - lastSample > 50) {
sampleSize++;
highCount1 = highCount1 + digitalRead(sensorPin1);
highCount2 = highCount2 + digitalRead(sensorPin2);
highCount3 = highCount3 + digitalRead(sensorPin3);
lastSample = now;
      }
else {
          delayMicroseconds(10);
      }

when you increased the number of code lines , information loss also increased, cz more number of instructions have to be executed now , till reaching the corresponding digital reads.

So if I put it in a for loop to guarantee the needed sample it should work right ? is there better way to do this ? thank you for responding

I don't think so. This is already running in loop under void loop(). So It may still have the same problem.

One solution is to shift the start of sampling of three sensors. Divide the time frame into 3 parts. First time frame only for sampling and displaying the temp of sensor 1, second one only for second sensor, first sensor would be idle. Like that. But the temperature update interval will increase.

I don't understand how to divide it into different time frames. Is it possible to create a function for getting temperature and call it three times for each sensor ? if so how do I write the function where is the exit point of it ?

You have to code some logic using if conditions and  a variable to keep track of time passed. Based on the value of that variable , call functions for processing sensor 1, 2 or 3.

I ran the code for 1 sensor without any adding additional code and the temp seemed to be stable and pretty accurate with a sampleSize of 31600 so I wrote this function with 31600 sample rate with 10 microsecond intervals and it does work can I just go with this ?

float GetTemp(int pinN){
for(int i =0; i < 31600; i++){
highDuration = highDuration + digitalRead(pinN);
delayMicroseconds(50);
}
hcf = highDuration;
dutyCycle = highDuration / (float) 31600;
temp = (dutyCycle - 0.32)/0.0047;
highDuration = 0;
return temp;
}

yea if this worked, you can write the same function for the next two sensors too...And just call this function one by one from the main code


text:
Smart way to map digital pins to a for loop over analogue pins
First post here and I have very little Arduino/c programming knowledge so forgive me my ignorance.
I am processing 18650 cells for a little powerwall project. I am using an Arduino pro mini atmega328p(5v) to read battery slot voltages and to turn on/off the tp4506 when the voltage reaches 3.85 volts for long term storage.
I am getting good voltage readings and after some trouble having a common ground with the tp4506 I think I have isolated it with a couple diodes.
I am using a 30N06L n channel mosfet to switch the tp4506's on and off, shutting them off to get the reading then back on till next voltage reading. I am learning a lot and having fun with it.
My problem stems from me not really having firm grasp of terminology or Arduino C. I cannot find my solution from search engine results after a few hours searching on and off.
I am using a for loop over 3(for now) analogue pins to get my voltage readings. What I can't figure out is how to map those pins to the digital pins controlling the mosfets from the loop. I have a few different versions of this project just trying to get a feel for what is the most efficient way to do it(I like the loop). How do I map or correlate AO with D2 and so forth. It's very frustrating not being able to type what I want out in a way that get's me some code I can learn from so I hope another human can understand my issue.
const int aRefVoltage = 5.00;
float voltage         = 0;

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

void loop() {
// put your main code here, to run repeatedly:
// read the input on analog pin 0-2

  for (int i = 0; i < 3; i++) {
    int sensorValue = analogRead(i);
    delay(700);

// float voltage = sensorValue * (aRefVoltage / 1024.0);
    voltage = sensorValue*aRefVoltage/1024.0;
// print out the value you read:
    Serial.print( F("  Slot-") );
    Serial.print(i + 1); // +1 to match slot number
    Serial.print( F(" = ") );
    Serial.print(voltage);
    Serial.print( F(" Volts") );

    if (i == 2) Serial.println("     ");
    Serial.println( F("") );
  }

}

What is the smartest way to map analogue "i[0]" to the digital pin 2 to turn on that slots mosfet while using the for loop? Switch case? I hope I was clear enough in my question.
Thank you
edit: inb4 I get chewed out.
I am not looking for the answer to be handed to me. I would like a link to a tutorial that will show me how to use i[1] either in or out of the loop so I can use it....or how to use it.  An explanation from my would be hero would be nice too.
My searches all got me very rudimentary for loop examples and endless tutorials on how to turn analogue pins into digital pins. Surprising amount of tutorials on how to do that out there.

edit 2
A ce pin? That sounds handy I will have to look into that. I am sure my use of diodes would make an engineer shake his head. I have limited supplies on hand and this is really my first project where I have a use for my tinkering.
On each analogue pin I have two 10k resistors. One to pull down and the other to prevent the batteries from sending juice back through the analogue pin.
I spent several hours trying to use the 1.1 volt internal reference but even after calculating what my 1.1 actually was my results were not as accurate and it just seemed like slapping a dmm across the rail and dialing the knob on the buck converter was practical.
https://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/
and
    internal1.1Ref = 1.1 * Vcc1 (per voltmeter) / Vcc2 (per readVcc() function)
For diodes I have a 1N4001 between the battery negative on tp4506 chip and  ground. If I did not have it there power was flowing back through the chip. I was also playing with a 3v zener on the positive side to block .5 volts to my analogue reading when no battery present in slot.
I have no doubt I am doing it incorrectly I wasn't expecting those issues and was just trying to hack a solution together, luckily my aim is not charging to 4.2 or I would be up a creek.
Thank you again for taking the time to show me the code I needed. I should be able to figure it out from here. As long as I am moving forward I am content. I had been at it for ten hours by the time I broke down and made this post. I was pretty burnt out and knew if I could just see an example I would be good to go.

edit 3
const int aRefVoltage        = 5.00;
const int readVoltagePins[3] = { A0, A1, A2 };
const int chargePin[3]       = { 2, 3, 4 };
const int hysteresis         = 0.10;
float voltage                = 0;

void setup() {
  // put your setup code here, to run once:
  for (int i = 0; i < 3; i++) {
    pinMode(chargePin[i], OUTPUT);
  }
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  // read the input on analog pin 0-2

  for (int i = 0; i < 3; i++) {
    digitalWrite(chargePin[i], LOW);
    delay(1500);
    int sensorValue = analogRead(readVoltagePins[i]);
    float voltage = (float) sensorValue * (5.0 / 1024.0);

    // Write here code to turn on the digital pin on (once) if the voltage
    // is too low and off (once) with hysteresis.
    // The digital pin is: chargePin[i]

    if (voltage <= 1.50) {
      digitalWrite(chargePin[i], LOW);
      Serial.print( F("  Slot-") );
      Serial.print(i + 1); // +1 to match slot number
      Serial.println( F(" = NFG || Empty ") );
      break;
    }

    else if (voltage <= (3.85 - hysteresis)) {
      digitalWrite(chargePin[i], HIGH);
      Serial.print( F("  Slot-") );
      Serial.print(i + 1); // +1 to match slot number
      Serial.print( F(" = ") );
      Serial.print(voltage);
      Serial.println( F(" Volts & Charging") );
    }

    else if (voltage >= (3.85 + hysteresis)) {
      digitalWrite(chargePin[i], LOW);
      Serial.print( F("  Slot-") );
      Serial.print(i + 1); // +1 to match slot number
      Serial.print( F(" = ") );
      Serial.print(voltage);
      Serial.println( F(" Volts & !Charging") );
    }

  }
  delay(5000); // increase later
  for (int i = 0; i < 3; i++) {
      if (i == 2)
      Serial.println("     ");
  }
}

This is what I have for code for now. I am just leaving the b- disconnected on the cloned charging boards. Let me know what you think @Jot

Is the programming code for A0 to D2 the same as for the other pins ? Then you could put the pin numbers in an array and run them in a for loop.
The TP4056 has a CE pin, why don't you use that to turn then on and off ?
The accuracy of reading a voltage with an Arduino depends on the accuracy of the voltage reference. You use the VCC 5V as reference. Is your 5V a stable and accurate 5.00V ? Did you measure the 5V pin of the Arduino board ?
Did you protect the analog inputs with a resistor ?
What did you do with the diodes ? Can you show a schematic (it can be a photo of a drawing) ?
An array with analog pins and digital pins:
const int readVoltagePins[3] = { A0, A1, A2 };
const int chargePins[3] = { 2, 3, 4 };

In the setup, set the digital pins as outputs:
for (int i=0; i<3; i++)
{
  pinMode (chargePins[i], OUTPUT);
}

In the loop, use a similar for-loop. I declare the locally used variables locally.
for (int i=0; i<3; i++)
{
  int sensorValue = analogRead(readVoltagePins[i]);
  float voltage = (float) sensorValue * (5.0 / 1024.0);

  // Write here code to turn on the digital pin on (once) if the voltage
  // is too low and off (once) with hysteresis.
  // The digital pin is: chargePins[i]
}

Reaction to edit 3
The idea of StackExchange is to have a question with an answer. Both the question and the answer can be polished along the way to create something that is helpful for others.
Developing a Arduino sketch is something else. I don't know either what the best way is to reply.
What about taking the average value of about 30 (5 to 1000) samples ? If the voltages are not steady, then averaging will help a lot.
The internal voltage reference of 1.1V is not bad, but the actual voltage can be between 1.0 and 1.2V. It is different for each Arduino board. You can measure the AREF pin with a multimeter after setting the 1.1V reference and put the measured voltage in the sketch in the calculation.
If the power to the Arduino board is a good 5.0V and the Arduino is always at the same room temperature, then the internal voltage of 1.1V can be used to measure a battery with 20mV accuracy, and perhaps 5mV with a lot averaging.
You use a delay to slow down the sketch. It is okay to do a digitalWrite over and over again during charging or during idle. In the comment I wrote to do that once, because I was anticipating to use millis instead of delays.
Because of the delay, the if_else_if_else_if is nice and straightforward code.
An integer can not be 5.0 or 0.10. Please check your whole sketch for 'float' versus 'int'. If floating point is needed, then use floating point. The voltage is a 'float', therefor it is best to use 'float' everywhere the voltage is used, for example the hysteresis.
I still don't understand the diodes. Can you make a schematic ?
Using a mosfet is probably okay, but I have to see the schematic.

I am not sure the correct way to reply to you so I edited my question.

While looking into the ce pin I realize that I have clones of the tp4056. I have a tc4056 and a 4056e. Talk about rabbit holes. The data sheet on the tc doesn't show a ce pin for 8 but a chrg. Is there anything wrong with using the mosfet to supply/cut power to these clones? http://jimlaurwilliams.org/wordpress/?p=4731

@ether Added a section: Reaction to edit 3

I can't thank you enough for your input. I have 3 slots working well, I will fix the float/int issue, easy enough. I also have to work out the hysteresis a bit better, maybe save the last read and compare. I installed fritzing this morning but then got sidetracked. I will try and get to it but the weekend is almost over so don't hold your breath. The diodes aren't being used. Solved by just leaving the bat - unattached. Not sure how cool that is but it is working just fine as is.

Also as for the voltage readings. They are consistently .01 volt off of my meter. Since the initial function is to get to 3.85 for storage I am not too concerned about the accuracy just yet. I have noticed that all the batteries I have brought up to 3.85 sag back down after a few loops also. I am assuming it is saturation of sorts. Until the next phase I would be content with less accuracy.

Fritzing does not make normal schematics. The free version of Eagle was used a long time. Today some prefer KiCad for hobby use. I read at hackaday.com that they prefer KiCad because it is open source. You can draw something on a piece of paper with a pen and make a photo of it.

OK, bare with me, the work week does not afford me much time.

Here is a drawing, I hope it is legible. freeimage.host/image/kLfXZ and here is a pic of my cigar box lid. freeimage.host/image/kL8fq thinking maybe shouldn't be having those battery leads running under the buck boost converter. and here is the rats nest. freeimage.host/image/kLMiI

The 10k to protect A0 is good. The 10k to keep the gate low is also good. Sometimes a protection resistor of 100 ohm is used for the gate: http://www.pighixxx.com/test/portfolio-items/connect-a-mosfet/ The charging module is not ment to be used like that. Keeping the charging module connected to the 5V input and switch the GND input and keep the BAT+ connected to the batteries... it depends on the charger module what will happen. Can you measure the current from the charger to the batteries when the mosfet is turned off ?

I will, I am also wondering if they will stop themselves at 4.2 while wired without the b- or if they would just keep going. I will run some tests this weekend.  Thanks for the interest.

What I can't figure out is how to map those pins to the digital pins controlling the mosfets from the loop.

you probably will have to do a better job articulating what "mapping" an analog pin to digital pins means.
If the issue is "associating" an analog pin with a digital pin, a struct would do, like this:
typedef struct {
  uint8_t apin; //analog pin
  uint8_t dpin; //digital pin associated with the analog pin
} PIN_TYPE;

PIN_TYPE pins1, pins2; //two sets of pins

 ...
 if (analogRead(pins1.apin) < BAT_THRESLOW) turn_on(pins1.dpin); //if voltage is too low, start charging it
 if (analogRead(pins2.apin) > BAT_THRESHIGH) turn_off(pins2.dpin); //if voltage is too high, stop charging.

Obviously, the logic should be more comprehensive to avoid oscillation.

Dear @dannyf, due to a mistake my "Reaction to edit 3" got somehow into your answer. Please ignore or remove it.


text:
Whats wrong with my code?
Basically what i am trying to do is use an ir remote to turn an rgb on/off and have a few preset colors as well as being able to increase/decrease red/green/blue independently. I don't know much about C/C++ so this is really hard to troubleshoot.
#include <IRremote.h>

int rbright;
int gbright;
int bbright;
int before;
int RECV_PIN=12; //data out of IR receiver connects to pin 12
int redPin=11;
int greenPin=10;
int bluePin=9;
int steps=5;
IRrecv irrecv(RECV_PIN);
decode_results results;

//uncomment this line if using a Common Anode LED
#define COMMON_ANODE

void setup()
{
    before=0;
    rbright=80;
    gbright=0;
    bbright=80;
    irrecv.enableIRIn(); // start the receiver
    pinMode(redPin, OUTPUT);
    pinMode(greenPin, OUTPUT);
    pinMode(bluePin, OUTPUT);
}

void loop()
{
    if (irrecv.decode(&results)) {
        if (results.value==B54A3AC5){ //Code to turn the LED ON/OFF
            if(before==0){ // if the LED was turned off, then we turn it on
                digitalWrite(redpin,HIGH);
                digitalWrite(greenpin,HIGH);
                digitalWrite(bluepin,HIGH);
                before=1; //LED is now turned on
            }
            else{
                digitalWrite(redpin,LOW);
                digitalWrite(greenpin,LOW);
                digitalWrite(bluepin,LOW); //if the LED was turned on, then we turn it off
                before=0;
            }
        }
        if (results.value==B54A8A75 && before==1){ //Code to decrease the red
            if(rbright-255/steps<0){
                analogWrite(redpin,rbright);
            }
            else{
                rbright=rbright-255/steps;
                analogWrite(redpin,rbright);
            }
        }
        if (results.value==B54A7A85 && before==1){ //Code to increase the red
            if(rbright+255/steps>255){
                analogWrite(redpin,rbright);
            }
            else{
                rbright=rbright+255/steps;
                analogWrite(redpin,rbright);
            }
        }
        if (results.value==B54AB24D && before==1){ //Code to decrease the green
            if(gbright-255/steps<0){
                analogWrite(greenpin,gbright);
            }
            else{
                gbright=gbright-255/steps;
                analogWrite(greenpin,gbright);
            }
        }
        if (results.value==B54A32CD && before==1){ //Code to increase the green
            if(gbright+255/steps>255){
                analogWrite(greenpin,gbright);
            }
            else{
                gbright=gbright+255/steps;
                analogWrite(greenpin,gbright);
            }
        }
        if (results.value==B54A0AF5 && before==1){ //Code to decrease the blue
            if(bbright-255/steps<0){
                analogWrite(bluepin,bbright);
            }
            else{
                bbright=bbright-255/steps;
                analogWrite(bluepin,bbright);
            }
        }
        if (results.value==B54ACA35 && before==1){ //Code to increase the blue
            if(bbright+255/steps>255){
                analogWrite(bluepin,bbright);
            }
            else{
                bbright=bbright+255/steps;
                analogWrite(bluepin,bbright);
            }
        }
        if (results.value==B54AA956 && before==1){ //Code yellow
            setColor(255, 255, 0);
        }
        if (results.value==B54A2AD5 && before==1){ //Code purple
            setColor(80, 0, 80);
        }
        if (results.value==B54AEA15 && before==1){ //Code aqua
            setColor(0, 255, 255);
        }
        irrecv.resume();
    }

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
    red = 255 - red;
    green = 255 - green;
    blue = 255 - blue;
#endif
    analogWrite(redPin, red);
    analogWrite(greenPin, green);
    analogWrite(bluePin, blue);
}

The errors i get are

rgbcontrolir_ino.ino: In function ‘void loop()’:
  rgbcontrolir_ino.ino:35:24: error: ‘B54A3AC5’ was not declared in this scope
  rgbcontrolir_ino.ino:37:20: error: ‘redpin’ was not declared in this scope
  rgbcontrolir_ino.ino:38:20: error: ‘greenpin’ was not declared in this scope
  rgbcontrolir_ino.ino:39:20: error: ‘bluepin’ was not declared in this scope
  rgbcontrolir_ino.ino:43:20: error: ‘redpin’ was not declared in this scope
  rgbcontrolir_ino.ino:44:20: error: ‘greenpin’ was not declared in this scope
  rgbcontrolir_ino.ino:45:20: error: ‘bluepin’ was not declared in this scope
  rgbcontrolir_ino.ino:48:22: error: ‘B54A8A75’ was not declared in this scope
  rgbcontrolir_ino.ino:50:19: error: ‘redpin’ was not declared in this scope
  rgbcontrolir_ino.ino:54:17: error: ‘redpin’ was not declared in this scope
  rgbcontrolir_ino.ino:56:22: error: ‘B54A7A85’ was not declared in this scope
  rgbcontrolir_ino.ino:58:19: error: ‘redpin’ was not declared in this scope
  rgbcontrolir_ino.ino:62:17: error: ‘redpin’ was not declared in this scope
  rgbcontrolir_ino.ino:64:22: error: ‘B54AB24D’ was not declared in this scope
  rgbcontrolir_ino.ino:66:19: error: ‘greenpin’ was not declared in this scope
  rgbcontrolir_ino.ino:70:17: error: ‘greenpin’ was not declared in this scope
  rgbcontrolir_ino.ino:72:22: error: ‘B54A32CD’ was not declared in this scope
  rgbcontrolir_ino.ino:74:19: error: ‘greenpin’ was not declared in this scope
  rgbcontrolir_ino.ino:78:17: error: ‘greenpin’ was not declared in this scope
  rgbcontrolir_ino.ino:80:22: error: ‘B54A0AF5’ was not declared in this scope
  rgbcontrolir_ino.ino:82:19: error: ‘bluepin’ was not declared in this scope
  rgbcontrolir_ino.ino:86:17: error: ‘bluepin’ was not declared in this scope
  rgbcontrolir_ino.ino:88:22: error: ‘B54ACA35’ was not declared in this scope
  rgbcontrolir_ino.ino:90:19: error: ‘bluepin’ was not declared in this scope
  rgbcontrolir_ino.ino:94:17: error: ‘bluepin’ was not declared in this scope
  rgbcontrolir_ino.ino:96:22: error: ‘B54AA956’ was not declared in this scope
  rgbcontrolir_ino.ino:100:24: error: ‘B54A2AD5’ was not declared in this scope
  rgbcontrolir_ino.ino:104:24: error: ‘B54AEA15’ was not declared in this scope
  rgbcontrolir_ino.ino:112:5: error: a function-definition is not allowed here before ‘{’ token
  rgbcontrolir_ino.ino:121:5: error: expected ‘}’ at end of input

The errors i get are it tells you that those macros are undefined. you need to figure out what they are first before you can fix the errors.

redpin bluepin etc where defined in the beginning right? Or did i miss something.and the other alpha numeric codes refer to the ir codes from the remote i will use.

I used the arduino rgb tutorial and the tutorial from great scott on youtube. he used ir library to control led strips with varying brightness. I downloaded the ir libraries and used the irrecvdemo sketch to find the codes on the remote i plan to use

i feel like it has something to do with the brackets

The errors are self-explanatory. You just have to read them carefully.

‘B54A3AC5’ was not declared in this scope

The compiler doesn't know what "B54A3AC5" means. Nor do I, but I gess
you may mean an hexadecimal 32-bit value. If that's the case, write it
with the prefix "0x", as in 0xb54a3ac5.

‘redpin’ was not declared in this scope

Same thing, it doesn't know what "redpin" is. Oh, wait, you have
declared a variable named redPin. Maybe that is what you meant:
"redPin", with an uppercase "P".

a function-definition is not allowed here before ‘{’ token

You tried to define setColor() within the loop() function. You
cannot define a function within a function in C++ (well, you can have
lambdas, but that's irrelevant to your problem).
Had you tried to indent your code properly (like I did in my edit), the
error would have been obvious: there is no closing brace to match the
opening one at the start of loop().

expected ‘}’ at end of input

Another symptom of the problem above.

Edit: After reading your code, I have a few suggestions for making
it clearer are more efficient:

Declare all the constants with the const keyword, at the beginning
of your program. A common convention is to write them in all caps
with underscores, to distinguish them from variables.
Avoid "magic numbers" within your code (e.g. the IR codes), and use
properly named constants instead.
before is hard to understand, give it a name that makes sense. I
suggest leds_are_on. And make it a bool, because it can only be
either true or false.
One way to avoid deeply nested loops is to use return statements to
get out of loop() as soon as you know you have nothing to do.

With these suggestions, I would start the program like this:
#include <IRremote.h>

// Pinout.
const int RECV_PIN  = 12;  // data out of IR receiver
const int RED_PIN   = 11;
const int GREEN_PIN = 10;
const int BLUE_PIN  = 9;

// Number of steps between black and full brightness.
const int STEPS     = 5;

// IR codes.
const uint32_t CODE_ON_OFF     = 0xb54a3ac5;
const uint32_t CODE_LESS_RED   = 0xb54a8a75;
const uint32_t CODE_MORE_RED   = 0xb54a7a85;
const uint32_t CODE_LESS_GREEN = 0xb54ab24d;
const uint32_t CODE_MORE_GREEN = 0xb54a32cd;
const uint32_t CODE_LESS_BLUE  = 0xb54a0af5;
const uint32_t CODE_MORE_BLUE  = 0xb54aca35;
const uint32_t CODE_YELLOW     = 0xb54aa956;
const uint32_t CODE_PURPLE     = 0xb54a2ad5;
const uint32_t CODE_AQUA       = 0xb54aea15;

bool leds_are_on;
int r_bright;
int g_bright;
int b_bright;
IRrecv irrecv(RECV_PIN);

and the loop() would be like this:
void loop()
{
    decode_results results;
    if (!irrecv.decode(&results))
        return;

    // If the LEDs are OFF, the only valid action is to turn them
    // ON.
    if (!leds_are_on) {
        if (results.value == CODE_ON_OFF) {
            digitalWrite(RED_PIN,   HIGH);
            digitalWrite(GREEN_PIN, HIGH);
            digitalWrite(BLUE_PIN,  HIGH);
            leds_are_on = true;
        }
        irrecv.resume();
        return;
    }

    // The LEDs are ON: all codes are valid.
    switch (results.value) {
        case CODE_ON_OFF:  // turn OFF
            digitalWrite(RED_PIN,   LOW);
            digitalWrite(GREEN_PIN, LOW);
            digitalWrite(BLUE_PIN,  LOW);
            leds_are_on = false;
            break;
        case CODE_LESS_RED:
            r_bright = constrain(r_bright - 255/steps, 0, 255);
            analogWrite(RED_PIN, r_bright);
            break;
        case CODE_MORE_RED:
            r_bright = constrain(r_bright + 255/steps, 0, 255);
            analogWrite(RED_PIN, r_bright);
            break;
        // etc...
    }
    irrecv.resume();
}

Thanks I will try some editing and see what I can come up with. the Arduino ide isn't very friendly for writing code. The only code writing exp i have is with BASH scripting. Usually I use a text editor and save the file with the correct prefix and that helps.

Thanks again! This is a lot of help. After reading your first answer i got the code to compile without errors however the code didnt work as expected. it only turned on/off with full brightness not the purple i was expecting. Is there a good site that will define things for me? specifically I don't know what "case" does

@KeithBybee: Any book on C or C++ will tell you about switch/case/break.

After changing over to the formats you suggested I am getting the following error during compilation. "core.a(main.cpp.o): In function main': /usr/share/arduino/hardware/arduino/cores/arduino/main.cpp:11: undefined reference to setup'
collect2: error: ld returned 1 exit status
"

@KeithBybee: That means that you forgot to write setup().

Well i guess that was obvious. So now i have to versions of this sketch. The one i originally wrote with the errors kinked out and of with case/break instead of if statements. The new one doesnt respond to any buttons being pressed and the old one woth the if statements works until i use any red and then it "freezes". If use the preset purple or the increase/decrease it just stops responding. Other than than it seems think think its on when its off. It will only let me turn individual colors if its off first. I tried putting digital write low for each color in the setup but that did not help

@KeithBybee: I think I had a logic error within the if (!leds_are_on) {} block. Should work better now.

1) You are missing the braces for void loop()
2) Oops !! You have to double check - redpin and redPin etc. Case sensitive !


text:
L and ON keeps blinking
I am not sure why the ON LED and the L LED keeps blinking on my Arduino.
I was just trying to implement a simple circuit using breadboard, and everything worked fine until I unplugged one wire with the power turned on. I accidentally made the wire touch something in the Arduino, and the LED in the breadboard became extremely bright. Then the ON LED and the L LED in the Arduino started to keep blinking, and I cannot download code to Arduino anymore. I am using IAR and IAR says AT91SAM3 reset: Communication breakdown after resetting target. Abort debug session?.
I think maybe there is a short cut when the wire touched the Arduino... But how can I determine what the problem is? Thank you very much, I am totally new to Arduino and has very limited knowledge about hardware...

It's dead. Buy another.

You should split your problem in pieces. Like you cannot get communication with your Arduino again, so check first:

If you plug in the Arduino / USB, do you get a message on your computer?
Is it visible in the systems manager?
Is it visible by the IDE?
If you connect an adapter (12 or 9V), does it make a difference?
If you try another Arduino, does it work like it should be?

If you are a beginner, always make sure:

Never change any wiring with the Arduino on
Never have dangling wires, if you do not need a wire for the time being, either remove it completely or put it in a breadboard hole that is not used
Never change components with the Arduino on
After rewiring/adding/changing components, double check first

Update for comment below because it does not fit as comment:
To buy a cheap/fake (but working) Arduino uno, e.g.
Arduino Uno from Aliexpress

Hi, thanks for your advice! The Arduino is visible to the IDE, and I will get another Arduino to check tomorrow. It worked fine before, everything changed since the touch.

I'm afraid something is not working in the Arduino anymore ... and unless you are more expert it might be useful to try to fix it, otherwise buy a new one ... I bought some from China, much cheaper and if something breaks it cost just a few euro.

What an expensive lesson:-(
Is it proper to ask how buy it from China here, can you tell me? I am at Sweden.

First I want to say not everybody likes it and it has some disadvantages. First you have to wait from 2 to 10 weeks, also they are fake (so might have some small differences, so far I didn't have many problems). But you can go to e.g. aliexpress and buy the one in my link (does not fit). Also these have a different chip and you probably need to install CH340G drivers (very easy to install).

Another method to avoid having to buy a new board when you screw something up, is get one with a microcontroller that can be taken out. Half the time, you'll only have damaged the controller and the board survived. Controller is less expensive than a full board. All the first ones had it, not sure about the later ones. Often times you don't need the M3 and an Atmega would've been fine.

@Mast Good comment ... I noticed most cheap ones don't have a separate chip. However, you can use use the programmed chip without the Uno in a finished project.


text:
How to refine ultrasonic readings
I am trying to filter ultrasonic readings using averaging technique. I've also used millis() to measure time from start so that I can calculate readings up to 1 second and average them. I've re-initialized the elapsedTime variable each time to zero in the loop but again when the program execution hits this code the time starts from the time it was before. Is there any way to solve this problem?
This is the code:
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

int dist, ctr, filteredDist;
long rawValue = 0;
unsigned long StartTime = millis();

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}
//********************************************************************************************************************
void loop() {
  delay(500);
  unsigned long elapsedTime = StartTime;

  while (elapsedTime < 1000) {
    ctr++;
    dist = sonar.ping_cm();
    rawValue += dist;
    elapsedTime = millis();
  }
  filteredDist = rawValue / ctr;
  Serial.println(filteredDist);
}

You're looking at absolute times (the time since boot). You need to look at time differences. That means performing subtraction.

@Majenko thanks for your reply. It would be great if you would slightly modify the code.

I can't "slightly" modify the code. It needs a complete rewrite. There's not a lot that can be salvaged there except the ping code.

Look at the BlinkWithoutDelay example, and consider using a library for the averaging - such as my Average library.

elapsedTime=millis(); sets elapsedTime equal to the current value of millis(), which in the sketch above is the total time since the Uno powered up.  Thus  elapsedTime will exceed 1000 any time after the first second of execution, in which case the while won't do anything.
Instead say elapsedTime=millis() - StartTime; within the loop.  Whenever you want to start the averaging cycle again, say StartTime = millis();.
If your only use of elapsedTime is to control the while loop, get rid of that variable; instead of  while(elapsedTime < 1000), say while(millis()-StartTime < 1000).


text:
NodeMCU and expected ';' before wrong ' " '
I am creating a home weather station but the Arduino IDE shows
"expected ';' before 'viewport'".

It detects wrong quotation marks. My code:
     String message2 = "<!DOCTYPE html>";
  message2 += "";
  message2 +=  "<title>Bootstrap Example</title>";
  message2 += " <meta name="viewport" content="width=device-width, initial-scale=1">";
  message2 += "<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">";
  message2 +=  "";
  message2 +=  "";
  message2 += "";
  message2 += "";
  message2 += "
";
  message2 +=  "
Teplotná Stanica
";
  message2 +=  "
Teplota:";
  message2 +=  dht.readTemperature();
  message2 +=  "
";

  server.send(200, "text/html", message2);}

Can someone tell me what´s wrong?
I am using Arduino IDE

Have you looked at your quotes yet? All of them?

I wonder who upvoted this question.

Your question has been answered. Please, accept the answer to close this question.

In C you can not use quotation marks inside quotation marks (thus nested).
Replace
message2 += " <meta name="viewport" content="width=device-width, initial-scale=1">";

to
message2 += " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">";

By using the escape character \  it means that \" is a character (")  instead of the beginning or start of a string.


text:
how to break out servo.write(angle) after it reach the angle?
I used a servo as a grabber so I don't know the angle I need specifically.I need it to break the serve.write(angle) when the grabber holds something.
I used a simple code
#include <Servo.h>
Servo myservo;
void setup() {
  myservo.attach(9);
}
void loop() {
  myservo.write(100);
  delay(500);
  myservo.write(50);
  delay(500);
}

when it holds anything it deos not return to the small angle until I remove the obstacle from its way.

You change the angle in small increments until the sensor triggers:
bool closing = false;
bool openeing = false;
int angle;

void loop(){

    //read touchSensor

    if(sensorHit){
        closing  = false;
    }
    if(closing){
        if(angle <= minAngle) closing = false;
        angle -= 1;
        myservo.write(angle);

    }

    if(opening){
        if(angle >= maxAngle) opening = false;
        angle += 1;
        myservo.write(angle);

    }

}

The to start moving the grasper you set opening or closing to true. You can also add some trigger logic in the places where they get set back to false for the next movement if applicable.

when I control it manually by joystick, if I hold press a little I can not reverse the angle. I don't use touchSensor.


text:
unable to find string literal operator 'operator"" stylesheet'
I am new to programing in C and I get this error:
unable to find string literal operator 'operator"" stylesheet'.

I am making a website for NodeMCU 0.9. My code:
 String message2 = "<!DOCTYPE html>";
      message2 += "<head>";
      message2 +=  "<title>Bootstrap Example</title>";
      message2 += " <meta name="viewport" content="width=device-width, initial-scale=1">";
      message2 += "<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">";
      message2 +=  "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>";
      message2 +=  "<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>";

possible duplicate alright, same author, same code

I think I answered a similar question in a previous answer.
You use "before/after viewport in the fourth line, which should be prefixed with \ to make it an escape code to be treated like a " character instead of the start/end of a string.
Also afaik String is C++, as is the += operator, not C.
See answer


text:
Set EEPROM to initial values when flashing ESP8266
I have a variable uint8_t a_ram which needs to be initialized from the EEPROM variable a_eeprom when the ESP boots up. Whenever a_ram changes, the new value has to be stored to the EEPROM (a_eeprom), so that the ESP will initialize a_ram to this new value after the next reboot.
The problem I have is to understand, how the value of a_eeprom can be initialized for the very first boot. If a_eeprom has not been set before (that means, that a_ram has not been stored to EEPROM yet), my variable will be initialized to 0, which must not be the case.
I could introduce an extra variable to the EEPROM (kind of a flag), which tells me whether a_ram has been stored to EEPROM or not and only initialize a_ram to a_eeprom if that is the case. But as I don't want to spend this memory if it isn't neccessary, I'd like to know if there is a possibility to set an EEPROM value when flashing the ESP.
Btw, I'm using the arduino IDE.

First you should probably research how EEPROM is approximately emulated on a system that doesn't actually have any.

it is written to flash.to location after SPIFS

@Juraj unfortunately I'm not very familiar with this topic. Could you give me a hint about what I should update myself if I did not understand your comment? ;)

@ChrisStratton as far as I understand the ESP, it has an EEPROM onboard and does not only emulate it

@SimSon - you are mistaken.  The ESP8266 has no on-chip EEPROM, and most boards pair it with an SPI flash, not an EEPROM.

I was answering Chris. read the docs http://esp8266.github.io/Arduino/versions/2.0.0/doc/libraries.html#eeprom


text:
Arduino classes, can't get property value
I have tried hard to make a stepper motor work with a class, but I can't get a property returning its value in a method. I get 0 (zero) instead of 26 (expected) from _stepPin.
I have tried this->_stepPin with no success.
Here is the code. See the comments inside.

 class MKSStepperMotors {

   public:
    int _dirPin;
    int _stepPin;
    int _enablePin;

    MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      int _dirPin = dirPin;
      int _stepPin = stepPin;
      int _enablePin = enablePin;

      //Habilitamos el motor
      pinMode(_enablePin, OUTPUT);
      digitalWrite(_enablePin, LOW);

      //Cambiamos la direccion y aumentamos la velocidad
      pinMode(_dirPin, OUTPUT);
      digitalWrite(_dirPin, LOW);

      // Le indicamos el pin de señal
      pinMode(_stepPin, OUTPUT);

    }

    void move(int steps, int stepDelay)
    {

      for (int x = 0; x < steps; x++) {
        Serial.println(_stepPin); //  <-- _stepPin is zero and not 26 as it should
        digitalWrite(_stepPin, HIGH); <-- _stepPin is zero and not 26 as it should
        delayMicroseconds(stepDelay);
        digitalWrite(_stepPin, LOW);  <-- _stepPin is zero and not 26 as it should
        delayMicroseconds(stepDelay);
      }
    }
};

 MKSStepperMotors pedo(28, 26, 24);

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

 void loop() {

      pedo.move(3200,100);

}

When you put the type there, you are creating new variables.  SO in your constructor:
 MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      int _dirPin = dirPin;
      int _stepPin = stepPin;
      int _enablePin = enablePin;

You start by creating three new variables with the same names as the member variables defined in the class.  Throughout the rest of the constructor those get used instead of the ones that are member variables.
You gotta lose the "int" there.
You also have another bug in there.  The constructor may run before the init function if one of these objects gets declared at global scope.  Things like digitalWite and pinMode aren't going to work yet in that case.  A constructor should just have code to initialize variables, it should never touch hardware.  The stuff that uses hardware should be in another member function (usually called begin or init) that you can call from setup.

Did Work !!!!! And I accepted the "init' method suggestion. THANKS

You have redeclared the class member fields in your constructor:
class MKSStepperMotors {

   public:
    int _dirPin;
    int _stepPin;
    int _enablePin;

    MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      int _dirPin = dirPin;
      int _stepPin = stepPin;
      int _enablePin = enablePin;
      ...
    }

The int _dirPin = dirPin; declares a local variable with the same name as your class member _dirPin and shadows it, hence your 3 class members never get initialized!
You should change your constructor as follows:
    MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      _dirPin = dirPin;
      _stepPin = stepPin;
      _enablePin = enablePin;
      ...
    }

Or better, use standard C++ constructor initialization:
    MKSStepperMotors(int dirPin, int stepPin, int enablePin)
    :_dirPin(dirPin),_stepPin(stepPin),_enablePin(enablePin) {
      ...
    }

In this latter example, you don't need to initialize your class members in the constructor body as they are already initialized before the body gets executed (this is idiomatic C++ usage).

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


text:
How do I connect a temperature and heartbeat sensor to an Arduino Uno?
I have been using a temperature sensor and heartbeat sensor separately and I am trying to code for temperature and heartbeat sensors. How do I get its output on the Arduino IDE's Serial Plotter?
Code of temperature sensor:
int val;
int tempPin = 1;

void setup()
{
  Serial.begin(9600);
}
void loop()
{
  val = analogRead(tempPin);
  float mv = ( val / 1024.0) * 5000;
  float cel = mv / 10;
  float farh = (cel * 9) / 5 + 32;

  Serial.print("TEMPRATURE = ");
  Serial.print(cel);
  Serial.print("*C");
  Serial.println();
  delay(1000);

  /* uncomment this to get temperature in farenhite
    Serial.print("TEMPRATURE = ");
    Serial.print(farh);
    Serial.print("*F");
    Serial.println();
  */
}

Please show us your entire sketch and tell us which sensors you are using.

How do I connect a temperature and heartbeat sensor to an Arduino Uno? Buturlin has the only correct answer here: you will have to read the datasheet for the temperature and heartbeat sensors to know how to work with them. that goes for any other sensors you may attach to your arduino. no exception. any answer not utilizing that piece of information is a wrong answer.

That doesn't answer the question.

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review

Buturlin? Who is he?

If you separate your code into functions you may understand what you want to do better.
In the listing above, you have code that reads the temp and prints the temp.  So creating two functions ReadTemp() and ShowTemp() will make the code in loop look cleaner and easier to read.  i.e.
void loop()
{
    const float cel = ReadTemp();
    DisplayTemp(cel);
    delay(1000);
}

float ReadTemp(void)
{
    val = analogRead(tempPin);
    float mv = ( val/1024.0)*5000;
    float cel = mv/10;
    // float farh = (cel*9)/5 + 32;
    return cel;
}
void ShowTemp(const float& cel)
{
    Serial.print("TEMPRATURE = ");
    Serial.print(cel);
    Serial.print("*C");
    Serial.println();
}

In you sketch for the hearbeat monitor you should have some code that reads the heartbeat and some that prints it.  If you create two functions ReadHB() and ShowHB() you will be able to easily add them to the above loop function.
I've never used the serial plotter, but if you wrap it in a function called PlotTemp() and PlotHB() then you can slot them in instead of the Show functions.


text:
SIM800L starts sending garbage values to Arduino after random interval
I have a SIM800L module connected to Arduino Mega's Serial3. SIM800L is powered by 4.2V power supply and I have put a voltage divider between Arduino's TX3 and SIM800L's RX so that the voltage in the line stays about 2V. The TX line of the module is directly connected to Arduino's RX3.
The problem is that when I try to communicate with the module it responds fine but after some AT commands the module starts panicking and start sending random garbage. The code I'm using is a simple Serial to Serial code :
#include<SoftwareSerial.h>

#define mySerial Serial3
//SoftwareSerial mySerial(10, 11);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  mySerial.begin(38400);

}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

Output :

[This is with serial monitor set to 115200 baud rate]

[The garbage values with serial monitor set to 9600 baud rate]
The solutions I have tried so far are :

Put a 220uF cap between SIM800L's VCC and GND. (a 470uF tantalum cap is already included on the module but still to be safe)
Tried various baud rates from 9600 to 115200 (the baud rate setting on the module is set to auto baud rate) but only 38400 works reliably.
Tried to pull the RX3 line up on Arduino with a 100k resistor so that it doesn't float.
Tried to put up to 5s delay between AT commands given to the module but it still goes into panic.

The thing I noticed is that if we enter some wrong command like ATD74xxxxxxxx (which calls a phone number) instead of with proper ending like ATD74xxxxxxxx; the module does the same thing which is spitting garbage values.
Can anybody help me with what is wrong with the module?

Crystal on Arduino might be misbehaving

Why are you limiting the Tx of the Arduino to 2V, I though the SIM800L used 3.7-4.2V?

As per this the Rx level of the module is less than 2.8V which I confirmed too (ran it with high voltage levels and it gave errors on AT commands). I don't know the exact reason why is it so but it does behave nice on lower voltage levels and wacky on higher levels.

I believe GSM modules needs about 2A current for few operations. One of them is calling. Are you providing proer current?

I'm supplying it with a 3A buck converter which in turns is supplied by a 12V 10A bench power supply. Also there's plenty of capacitance on the VCC to compensate for surges so I don't think the power supply is an issue.

It also doesn't depend on the operation. I just created a loop in which I send "ATI" command to get the module info and it runs for may be 5-10 times and then the error loop begins. I have also tried another SIM800L module of the same kind and it behaves the same so it's not a problem with that particular module. Another thing I tried is to use a similar module with SIM900A and it works fine(with 5V supply instead of 4.2V).
I also tried to call the number from another phone and the module rings just fine so receiving calls is not a problem.


text:
SparkFun ESP8266 find out when on battery power and when charging
For one of my projects I use the SparkFun ESP8266 board with an additional LiPo battery in cases power supply goes down.
Now I would like to communicate the power loss - or the fact that the board is running on battery power via WiFi.
Is there a way to find out (in code) when the board switches from mains power to battery and back?

Can I connect ADC pin to ground in order to make this method work? Otherwise what is the easiest way to disconnect ADC pin on esp8266 thing dev board ?

You can implement this software if the voltage is different in both cases.
The voltage from the power supply should be higher than the voltage of the battery, but do not exceed the permissible values.
Then you can use ESP.getVcc() :

ESP.getVcc() may be used to measure supply voltage. ESP needs to
  reconfigure the ADC at startup in order for this feature to be
  available. Add the following line to the top of your sketch to use
  getVcc:
ADC_MODE(ADC_VCC);
TOUT pin has to be disconnected in this mode.
Note that by default ADC is configured to read from TOUT pin using
  analogRead(A0), and ESP.getVCC() is not available.


text:
Temperature Sensor not giving proper values
In my current project I am reading temperature through sensor which is having only two wires.

To read sensor values, I have used below schematic which I have found on Arduino Project Hub site.

In my project I am using below Arduino program.
#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 2

// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");

  // Start up the library
  sensors.begin();
}

void loop(void)
{
  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus
  Serial.print(" Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  Serial.println("DONE");

  Serial.print("Temperature is: ");
  Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
    // You can have more than one IC on the same bus.
    // 0 refers to the first IC on the wire
    delay(1000);
}

After doing all this I am getting this output on serial monitor.

At which step I am doing wrong?

Could you make a change to a 'schematic' to show your connection? How do you actually connect 2 wires? (Your current schematic has 3 connections between sensor and Arduino, and sensor on your picture has only 2 wires..)
Are you aware of the fact that you want to use 'parasite power mode'? In this case you must provide strong pull-up for temperature conversion time.
Take a look at https://datasheets.maximintegrated.com/en/ds/DS18B20.pdf page 11, 'Convert T [44h]' paragraph...

What type or name of the model is your temperature sensor.? It looks like you're trying to connect an analog sensor. But you use the connection schema and code for the digital sensor.

Which model temperature sensor you using?
If you using lm35 temperature sensor,
Serial.print(sensors.getTempCByIndex(0)/9,31); you need add /9.31 to your code, sensors not directly measure the temperature sensors just have variable resistor inside, resistor value changes by temperature after then voltage changes the arduino just measure the voltage, the voltage value divide the 9.31 this result gives temperature Celcius type.
Also you have to unplug 4.7 k resistor it needless.

Oh, indeed. karanrp: I have assumed you are using DS18B20. Check your sensor first.

That looks like a cheap thermocouple from a digital thermometer to me. You need a special chip to run it.

The -127 for your temperature reading is actually the error code for DEVICE_DISCONNECTED_C.
In the library's example code, they put an if that checks for this error code before printing the temperature:
if(tempC != DEVICE_DISCONNECTED_C)
{
  Serial.print("Temperature for the device 1 (index 0) is: ");
  Serial.println(tempC);
}

Since your sensor has only 2 wires, according to Wikipedia, you need a capacitor to power the sensor:

One distinctive feature of the bus is the possibility of using only two wires — data and ground. To accomplish this, 1-Wire devices include an 800 pF capacitor to store charge and power the device during periods when the data line is active.

This should hopefully resolve your issues.

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


text:
Arduino not adding decimals correctly on double variable
I have encountered a strange behavior today.
I can't understand why the sequence is altered after 26.1000.
I get a number 0.0001 less than the desired value (26.2124 instead of 26.2125).
I need precision and can't get it.
Here is the code:
double _pos = 0;

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

void loop() {
  _pos += (0.1125);
  Serial.println(_pos,4);
  while (_pos >26.5) delay(1);
}

and here is the result
0.1125
0.2250
0.3375
0.4500
0.5625
0.6750
0.7875
0.9000
1.0125
1.1250
1.2375
1.3500
1.4625
1.5750
1.6875
1.8000
1.9125
2.0250
2.1375
2.2500
2.3625
2.4750
2.5875
2.7000
2.8125
2.9250
3.0375
3.1500
3.2625
3.3750
3.4875
3.6000
3.7125
3.8250
3.9375
4.0500
4.1625
4.2750
4.3875
4.5000
4.6125
4.7250
4.8375
4.9500
5.0625
5.1750
5.2875
5.4000
5.5125
5.6250
5.7375
5.8500
5.9625
6.0750
6.1875
6.3000
6.4125
6.5250
6.6375
6.7500
6.8625
6.9750
7.0875
7.2000
7.3125
7.4250
7.5375
7.6500
7.7625
7.8750
7.9875
8.1000
8.2125
8.3250
8.4375
8.5500
8.6625
8.7750
8.8875
9.0000
9.1125
9.2250
9.3375
9.4500
9.5625
9.6750
9.7875
9.9000
10.0125
10.1250
10.2375
10.3500
10.4625
10.5750
10.6875
10.8000
10.9125
11.0250
11.1375
11.2500
11.3625
11.4750
11.5875
11.7000
11.8125
11.9250
12.0375
12.1500
12.2625
12.3750
12.4875
12.6000
12.7125
12.8250
12.9375
13.0500
13.1625
13.2750
13.3875
13.5000
13.6125
13.7250
13.8375
13.9500
14.0625
14.1750
14.2875
14.4000
14.5125
14.6250
14.7375
14.8500
14.9625
15.0750
15.1875
15.3000
15.4125
15.5250
15.6375
15.7500
15.8625
15.9750
16.0875
16.2000
16.3125
16.4250
16.5375
16.6500
16.7625
16.8750
16.9875
17.1000
17.2125
17.3250
17.4375
17.5500
17.6625
17.7750
17.8875
18.0000
18.1125
18.2250
18.3375
18.4500
18.5625
18.6750
18.7875
18.9000
19.0125
19.1250
19.2375
19.3500
19.4625
19.5750
19.6875
19.8000
19.9125
20.0250
20.1375
20.2500
20.3625
20.4750
20.5875
20.7000
20.8125
20.9250
21.0375
21.1500
21.2625
21.3750
21.4875
21.6000
21.7125
21.8250
21.9375
22.0500
22.1625
22.2750
22.3875
22.5000
22.6125
22.7250
22.8375
22.9500
23.0625
23.1750
23.2875
23.4000
23.5125
23.6250
23.7375
23.8500
23.9625
24.0750
24.1875
24.3000
24.4125
24.5250
24.6375
24.7500
24.8625
24.9750
25.0875
25.2000
25.3125
25.4250
25.5375
25.6500
25.7625
25.8750
25.9875
26.1000
26.2124
26.3249
26.4374
26.5499

If you want precision it's often better to work in fixed point, that way you can be sure of the significance of the least significant bits.

I do not see any specific difference after 26.2124.
However, in your case you are using 6 digits (e.g. 26.5499). To use an unsigned long/uint32_t you can store easily 6 digits, but only using whole numbers.
However, by adding 1125 every time and dividing the result by 10,000.0 for printing you get exact results.
unsigned long _pos = 0;

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

void loop() {
  _pos += 1125;
  Serial.println((float) _pos / 10000.0,4);
  while (_pos > 265000) delay(1);
}

Thanks, I used this approach, the only problem is that numbers can be negative too (something I did not clarify on the original question).

Than remove unsigned, so you can have negative numbers.

The 8 bit Arduinos don't have precision, or anything even close to precision when it comes to working with decimal values.
There is no such thing as double on an 8-bit Arduino - it is only an alias for float. By using double you aren't gaining any more precision than using float.
Even double isn't perfectly precise. It's more precise than float (on systems that support double), but still far from precise.
People that care about specific levels of precision code using variables of that precision. That's called using fixed point mathematics, and it's what DSPs work in. It's fast, efficient, and precise up to the point that you define it to be.
Fixed point mathematics works by operating in multiples of a pre-defined fraction. That fraction is your precision, or granularity and is the smallest value that can be represented. However, working with large numbers and fine granularity results in very large variables to store all that data - which is why for most things people use float: because it compresses the data down into a very small space - and like a highly compressed MP3 it loses a lot of the data.

The number 0.1125 would written in binary as 0.0001110011001100..., with
an infinite repetition of “1100”. As the float data type has only
24 bits of precision, it can obviously not represent such a number.
Instead, when you write 0.1125 in code, you get the closest
representable number, namely 0.11249999701976776123046875, which is
0.00011100110011001100110011 in binary. Note that AVR-based Arduinos do
not really support double precision: you get a float32 whether you
declare a float or a double.
Furthermore, when you keep adding this number to itself, quite often the
sum is not a representable number. Thus, in addition to the initial
rounding error in the representation of 0.1125, you get an additional
rounding error with the addition. These errors accumulate and you end up
with a value that is significantly off what you expect.
You can avoid accumulating errors by working with integers, and
converting o float only when needed:
void loop()
{
    static long count;
    count++;
    Serial.println(count * 0.1125, 4);
    while (count > 235) delay(1);
}

Note that you still get two rounding errors: in the representation of
0.1125 and in the multiplication. But at least you are not accumulating
a large number of them.

I can't understand why the sequence is altered after 26.2124.

because floats / doubles are not precise representation of their respective values.


text:
Broken serial connection corrupting Arduino values
I have a problem with my homemade fan speed controller powered by an Arduino Nano, which reads a value from Serial (Arduino serial monitor, or Processing sketch) and uses the 0~255 value to set a variable fanspeed1 to set a PWM pin to control the fan speed.
The problem is when I close the Processing sketch, or the Arduino serial monitor, fanspeed1 is changed to max value (the fan speeds up to full speed).
I would like to send serial to set the value and then close the serial monitor, or Processing sketch and the value of fanspeed1 should not change.
If I need to post some code I can simplify my sketch down to a send serial, receive serial, make pin pwm = serial(0~255), but I am guessing there is a simple solution to this unfindable with my googling.
Help please, these fans need controlling...

Showing us your simplified sketch code would be useful here. For now, try to protect 'fanspeed1' from changing when serial communication is not active.

Disable the auto-reset functionality of the board?

It's 0~255, not 256.

You could consider writing/reading the value to/from the EEPROM.
http://arduino.cc/en/Reference/EEPROM
This allows the board to be reset, or even turned off, and retain the value previously set.  What you would be doing is saving the value to the internal memory of the Arduino.  This is resettable and persistent over a "reboot".
Granted, there is a limited number of writes you can do, but that number is high enough (~100k) that you will probably wear out the fan before the EEPROM sector dies.

Syntax
EEPROM.write(address, value)
EEPROM.read(address)
EEPROM.update(address, value)

For objects:

EEPROM.put(address, data)
EEPROM.get(address, data)