text:
Feather MO: How would I change my code to have my txt file data be in columns rather than be staggered?
First of all, I am using the Feather MO Adalogger from Adafruit with the Ultimate GPS Feather hat to collect some GPS data: time stamp (millisec), GPS Coordinates (latitude & longitude), speed (knots), and altitude (meters). The GPS data is stored on a micro SD card and I have the GPS portion of the code working. The data I want is being stored on the micro SD card. My only problem is that I can't get the data to be appropriately put in columns under their respective "headers". I used .print("\t") after each data type in attempt to tab the data into columns. This worked for the "headers" but not for the data itself. Screenshots and code are below. Thanks in advance!
My txt file: Headers

My text file: working GPS data

Code for Headers

Code for data

Don't post sketch images; post the sketch itself, so others can copy-paste them for testing.

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets. Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem. Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant. Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem

The tab '\t' has no fixed number of positions. It can be every 2 or every 8 or anything else. You can try to fill up with spaces. For example the sprintf function can do that. Are you sure you want to show the text file nicely formatted under the headers? It is more common to use the text file as data for visualization tools.

@Jot  I just want my data to be easily copy/pasted into a data manipulation/graphing program like excel or matlab. Any suggestions on how to do that? I copied the data the way it is but it pastes awkwardly into excel. Thanks btw

@user52619 And we want easily copy/pasteable code for testing.

Since I don't like the tab character, I would use only ", " between the numbers with a println() at the end as @jose-can-u-c wrote.

Change the println()s to print()s. Put one println() at the end of the list of data prints.  You want each row of data to not take up more than one line in the text file. A println() starts a new row after printing.
Also, you’ll want to open the text file in a tabular program like Excel or similar. A plain text editor likely won’t utilize tab characters in the way you like.

Thank you so much!! That worked perfectly just how I wanted! (:


text:
Is it possible to read-write the memory of a Gikfun ISD1820 voice recording module?
I just got a Gikfun ISD1820 voice recording module for an Arduino project that I'm working on. I want to be able to record a few seconds message and then send the message over wifi to another Arduino Mega 2560, which will then play back the message.
The ISD1820 module can record and play back short messages and can be controlled from the Arduino, but I want to know if it is possible to access the memory / read-write the memory of the ISD1820 module to accomplish my goal. And how would I do it?
If it is impossible, what hardware should I get instead? Do I need a wave shield with a SD card or a wifi shield with an SD card?
Thanks!

No. You can't. That module can only record and play.
The only possible thing you could do is record onto the chip then play it back recording it on to the Arduino (at ridiculously low quality) - in which case, what would the point of the chip be?
If you want some quality to your recordings you need a powerful microcontroller with an I2S interface and a CODEC chip.  However any powerful MCU (such as the ARM chip on the Due, or the Teensy, or the PIC32 chip on the chipKIT boards) can sample at a reasonable quality through the ADC inputs.
The Arduino Uno can record very short bursts at very low quality (due to lack of memory) without any external hardware (except a suitable microphone preamplifier). The Mega can record slightly more, but the quality will still be very low.

source: Stack Exchange

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

sort: votes


text:
Is this a fake pulse sensor?
A couple of days ago, I purchased a pulse sensor online for a project. Before actually doing anything with it, I wanted to capture and view its analogue waveform output. One while placing my finger on it and one when in the default state, so that I can see the trend or difference in the two waveforms. But when I captured the output, it seems like there is not much difference. Just some random noise I guess. Also, I checked the company website who may have made this one and it all looks good to me.

The image below shows the waveform captured when no finger is placed on the sensor.

The image below shows the waveform captured when my index finger is placed on the sensor.

This is my setup for the sensor for measuring pulses.

This image shows the face of the sensor.

I need some insights from folks here regarding this sensor. Is it showing some junk output? or my understanding is wrong and there's a better way to figure this out/ work with this sensor.

I'm voting to close this question as off-topic because it is not in any way about Arduino, and because even for an SE site where the subject matter could be on topic, the question fails to state details of the measurement taken.

What is a pulse sensor? I don't see what this question has to do with Arduinos.

The second trace looks like a pulse to me. With that kind of sensor you don't get the PQRST traces of an ECG - just a slight bump when you get a pulse.

Ok, that means this sensor does work. I am connecting the output of this sensor to a 24 (~18 ENOB) bit ADC and getting the digital data. What would be the right approach to accurately capturing these bumps using the digital samples while being able to differentiate it from other junk?.

Low pass filter it to remove the random spikes, and then look for the change in signal level through a threshold, maybe with some hysteresis.

To design a low pass digital filter, I need to know the cut off frequency, how do I know that?

You don't need that level of detail. The difference in frequency between signal and noise is big enough that simple averaging of samples is enough.

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


text:
Change the baud rate of HC-05
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup() {
  pinMode(9, OUTPUT);
  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);
  // HC-05 default speed in AT command more
}

void loop() {
  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

I have tried this code but I am not able to change the baud rate. Please suggest me a solution.

Is your Serial Terminal set up with CRLF line endings?

Check you dont have the BT version with the button, then you use the button instead of pin 9

I played a lot with HC-05 and HC-06 until I understand the way they work. Now i've big Android App communicating with HC at 115200 bauds and sending and receving heavy data.
I hope these tips will help you and other guys and save you time:
1) the way the HC-05 and HC-06 detect end of AT command is different:
HC-05 (can be slave and master): each AT command must end by CRLF. So or you add CRLF in your Android code or you select the option "CRLF line ending" in your console.
HC-06 (only slave): need a "time" between AT Command. According to the data sheet if there is more than 1 sec, the HC consider this is the end. Even if your question is about the HC-05 I think it can be VERY interesting to understand the big problem which can happened with the "delay" between AT.
If you use a communication at 9600 bauds and type AT commands on serial monitor and echo both what HC reply and what you send, you will have such things: type AT+VERSION and see on serial monitor AT+OVKERSION  Why ? Because as the delay between each char is long, as soon as the HC had receive "AT" he thinks that's the command and start to reply "OK".
So with a HC-06 you must send the AT command in one "shoot" and then add a delay of 2 sec to be sure.
2) Problem of settings.
The HC save the speed you set as the name and the pin code. So trying to set the pin, name and speed in the setup funcion is not usefull as at each time the Arduino will reset, each time you'll try to set the data.
Also, factory setting of HC seems to be 9600 bauds.
So you have to create a small sketch, which you'll use only ONE time to set the HC. Like this:
Serial.begin(9600);
delay(2000);

// AT+NAMEXXX where XXX is the new name
Serial.print("AT+NAMEJOHNDOO");
delay(2000);

// AT+PINXXXX where XXXX new code (4 number)
Serial.print("AT+PIN1999");
delay(2000);

// AT+BAUDX where X from 1 to 8
// 1 -> 1200 Bauds
// 2 -> 2400 Bauds
// 3 -> 4800 Bauds
// 4 -> 9600 Bauds
// 5 -> 19200 Bauds
// 6 -> 38400 Bauds
// 7 -> 57600 Bauds
// 8 -> 115200 Bauds
Serial.print("AT+BAUD8");

This for HC-06. For HC-05 you must add CRLF and you don't need the delay.
Important: as, at the end of this sketch, the HC is now at 115200 bauds, you must havea serial.begin(115200) for comunicating with it. If you run this sketch two time, the second run will do nothing as the Arduino will try to comunicate at 9600 bauds with a HC listening at 115200.
3) Problem of speed.
On the Arduino, you can use the software serial lib only if you plan to send and receive at up to 19200 bauds. Some say it work at 38400 but I've had problems at this speed.
The best way it to avoid Software serial and use directly the basic RX and TX of the Arduino. Using that you can run at 115200 without any problem.
Even if this answer is a bit "outside the question" I hope this will help you working with the HC.

HC-05+Arduino+Android
The problem is the baud rate of devices. The default baud rate of HC-05 is 38400.  First of all set baud rate of HC-05 by using the AT commands (i.e. AT+UART=9600,0,0) to 9600. This baud rate will work with serial in Arduino as well as in android Bluetooth libraries/app without any problem.


text:
Arduino nano and wemos sd shield
Is it possible use Arduino nano with wemos sd shield? If I can, how to I connect sd shield to arduino and what modification I need to do on library setting?

What's a Wemos SD shield?

No, you can't. The WeMos boards operate at 3.3V, and so does the SD card. If you want to use a 5V Arduino with a 3.3V SD card, you'll need voltage level shifters.
The schematic of the WeMos SD shield will tell you what SD connections go to what pins. Then just google how to use an SD card with Arduino to connect those pins to the correct Arduino pins.


text:
Detecting step motor effort
I'm working on a project using steper motor which turn a threaded shaft (long screw) in order to open or close a water valve (high flow, high pressure).
My fear is that, after a long time of use, the grease on the threaded shaft will dissapear and it can became hard for the stepper motor to rotate correctly the threaded shaft.
In order to tell the user to add grease, I have to know when the stepper needs more effort than before to rotate the threaded shaft. So, would it be possible to detect the "effort" made by the stepper in order to get this information on the Arduino?
Any ideas are welcomed!

I'm voting to close this question as off-topic because it is about electromechanical systems, not about Arduino.

@ChrisStratton is tecnically right, but I think that the solution will depend heavily on the hardware at hand, and I want to know how to solve it with an Arduino (I see this same problem ahead of me).

I suggest that if the answer involves the Arduino, the question might be appropriate to this forum.
If you can mount your stepper motor in such a manner as to apply pressure to a force sensor, you may have a method to resolve your goal.
As the motor rotates, under normal conditions, pressure on the sensor will give you a baseline on which you can base your program for consideration of the amount of force involved.
Picture the motor mounted in the center of a circle, with cut-outs appropriate for the mounting bolts. On the outside of the circle, you would have suitable bearing surfaces to reduce rotational friction. From the motor circle platform, a lever pressing against a fixed point on the outside of the circle provides the contact points for the pressure sensor.
If you will be rotating the motor in both directions, perhaps a pair of sensors mounted to encase the lever would be suitable.
When the screw is new, clean and lubricated, you can collect pressure readings and establish a safe and comfortable range. Those numbers would be fixed into your code and measured during motor activity.
If the activity results in force outside the range, you can either stop or reverse the motor and have the same checks apply.
The logic and code is beyond my capability, but you'd have very few parameters to examine during operation.

Nice idea. As I'm going to have more than one system, with this idea I can also make some statistic, in order to know the limit. Thanks!

After fred_dot_u answer I have made other research. Not sure this can help us (Look Alterno and me), but some post are talking about "can I detect the over intensity".
Here is a very interresting post (in French, but Google Translate can help). The guy use and Arduino to control a step motor using to open a fence. And he wants to detect when the motor need more effort:
http://forums.futura-sciences.com/electronique/687244-lecture-de-lintensite-dun-moteur-un-arduino.html
Here the text from this site, I translated:

QUESTION
Hello everyone, I have a DC motor powered at 30 V. In normal
  operation, it consumes 2.5A (the power supply is OK, no problem on
  that side). It is an electric gate motor (sliding gate). I want to
  control it with an arduino. So far, not too much trouble, I go through
  a MOSFET (for the moment, I do not run the engine in one direction,
  later, I will make a bridge in H to go both ways). All this works well
  but I would also be able to detect when the engine forces (to stop
  it). When the motor forces, it consumes more, so more intensity in the
  circuit. The problem is that an Arduino can not read an intensity, I
  can only read a voltage between 0 and + 5V. So I was thinking of
  putting a resistor in series with the motor and measuring the voltage
  across the resistor with the arduino. If I take a max intensity not to
  exceed 5 A, Ohm's law gives me a resistance of 1 Ohm to have a voltage
  of + 5V (I'm good?) The problem is that a resistance of 1 Ohm at 5A
  will dissipate 25W (R x I x I, I'm always good?). How to solve this
  power dissipation problem? the big resistors I have at the moment are
  3/4 W, they will not take long
My problem is the following: if I take a smaller resistance to have a
  smaller power (like 0.1 Ohm or less), the voltage has its limits will
  be too low to be read by my arduino,
How to do ? Does anyone have an idea?
Thank you in advance for your answers.
Steph.
ANSWER 1 Just amplify the signal: rail-to-rail operational amplifier
  (to power it with a single positive voltage), a non-inverting device
  with a gain of 10 for example.
ANSWER 2 Indeed, it's an idea. So I was thinking of putting a resistor
  in series with the motor and measuring the voltage across the resistor
  with the arduino. . The risk of this type of assembly is:
  - the maximum voltage overshoot (5V) at the input of the uC (ARDUINO) at the change of direction (see ground point).
  - the maximum voltage surge (5V) at the input of the uC (ARDUINO) in the event of a break in the resistance. Explanations: The ARDUINO
  board must have a common point (Ground) and an Ax input, therefore
  when changing polarity (change of direction of the motor) the DDP is
  no longer 0V-> 5V but 0V-> 30V and there it smokes, ditto in case of
  rupture of this resistance. The good solution in my opinion would be a
  system like http://www.gotronic.fr/cat-courant-1125.htm
  Regards

The answer 2 give link to products like the i-Snail-VC: Current Transducer with 0-5VDC Output. Can be linked directly to the PIN of an Arduino.

Link-only answers are prohibited.  To be a valid answer, sufficient technical information must be contained in the answer posting itself that it will still be usable even if the off-site link ceases to function.

Yes, most certainly. Use an ammeter to detect the "effort" required to actuate the motor. Both hall-effect and series measurements are acceptable here. Make sure to sample and average because motors can cause huge current spike (both positive and negative) which confuse naive readings. If your averages are climbing, as they eventually should, you know that it's getting harder to do the work. The hard part is deciding how hard is "too hard", and that depends on a lot of factors you're in the best position of judging.

I think deciding how hard is "too hard" can be made only by testing and set a "range" on the Arduino. In some case, reachin the "too hard" point will need to reverse motor. In my case I can have a range and say "Its not TOO hard,but it start to be not as easy as before so you must add some grease".

A few ways, assuming that it is a DC motor.

Measure the current through the motor: current is proportional to torque, everything else being equal.
Put a strain gauge on the axle.
Put a frictional plate on the axle.

...
Or to completely abandon the idea and control the movement via a position sensor.


text:
interrupt not triggered correctly
I have an arduino uno and want to react to three sensors, which should trigger an ISR.
I wrote the following program, and for sensor 3 it works, however the other two sensor don't seem to trigger an interrupt. I checked the sensors by connected each one to pin A5, and every sensor worked.
Is there a better way to check which pin caused the interrupt than digitalRead()? Is this maybe even my problem?
#define pinDrehen 12
#define pinRevDrehen 13

volatile boolean triggeredAngleSensor1 = false;
volatile boolean triggeredAngleSensor2 = false;
volatile boolean triggeredAngleSensor3 = false;
volatile unsigned int triggeredTimeAngleSensor1;
volatile unsigned int triggeredTimeAngleSensor2;
volatile unsigned int triggeredTimeAngleSensor3;

ISR (PCINT1_vect) // handle pin change interrupt for for A0 to A6 and reset [only A3 to A5 are enabled]
{
  if (digitalRead(A3)){//angle sensor 1
    triggeredAngleSensor1 = true;
    triggeredTimeAngleSensor1 = millis();
  }
  if(digitalRead(A4)){//angle sensor 2
    triggeredAngleSensor2 = true;
    triggeredTimeAngleSensor2 = millis();
  }
  if(digitalRead(A5)){//angle sensor 3
    triggeredAngleSensor3 = true;
    triggeredTimeAngleSensor3 = millis();
  }
}

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

  // pin change interrupt
  PCMSK1 |= bit (PCINT13) | bit (PCINT12 | bit (PCINT11));  // want pin A5 or A4 or A3
  PCIFR  |= bit (PCIF1);    // clear any outstanding interrupts
  PCICR  |= bit (PCIE1);    // enable pin change interrupts for A0 to A6 and reset

  pinMode(pinDrehen, OUTPUT);
  pinMode(pinRevDrehen, OUTPUT);

  //start turning machine:
  digitalWrite(pinDrehen, HIGH);
  digitalWrite(pinRevDrehen, HIGH);
}

void loop() {
  if(triggeredAngleSensor1){
    triggeredAngleSensor1=false;
    Serial.print("Sensor 1 interrupt at time: ");
    Serial.println(triggeredTimeAngleSensor1);
  }
  if(triggeredAngleSensor2){
    triggeredAngleSensor2=false;
    Serial.print("Sensor 2 interrupt at time: ");
    Serial.println(triggeredTimeAngleSensor2);
  }
  if(triggeredAngleSensor3){
    triggeredAngleSensor3=false;
    Serial.print("Sensor 3 interrupt at time: ");
    Serial.println(triggeredTimeAngleSensor3);
  }
  delay(5);
}

This line:
PCMSK1 |= bit (PCINT13) | bit (PCINT12 | bit (PCINT11));  // want pin A5 or A4 or A3

is probably not what you want.
Let's break it down and look at just what you have there.
bit (PCINT13)

The bit function returns the bitmask for a specific bit.  So if you pass it 3 you get a value with the third (counting from 0) bit enabled (1 << 3, or 0b1000, or 0x08).
PCINT13 is 5.  So you have 1 << 5, or 0x20.
So far so good.  Now you OR that with:
bit (PCINT12 | bit (PCINT11))

And this is the bit that's wrong.  Inside is bit (PCINT11) which, with PCINT11 being 3, results in 0x08.  That is then ORed with PCINT12, which is 4.  The result is 8+4. That's 12. The value 12 is then fed through another bit() function, which gives you 1<<12. That, of course, overflows outside of an 8-bit value, so you end up with 0.
The final result is ORed together with the 0x20 from before, which of course remains as 0x20.
What you probably wanted (and intended) is to have:
PCMSK1 |= bit (PCINT13) | bit (PCINT12) | bit (PCINT11);  // want pin A5 or A4 or A3

the logic in the isr is incorrect.
generally, you want to set up the pcint pins so that they respond to an edge.
in the isr (with multiple pin changes), you will need to either 1) preserve and maintain the previous state so to determine which pins have experienced a state change; or 2) use pin change flags.
what you have there can lead to false determination of triggers.

In my application a sensor will be triggered only for a short time (at least while i am reacting to interrupts) and two sensors can not deliver HIGH at the same time, therefor i don't think this is an issue. However i am curious about your two possibilities. Wouldn't i realisiere the first one with (boolean) flags, which would be the second one? (Or are pin change flags some bits in a hardware register and you don't mean flags i set on my own?)


text:
Random(0,2) gives bad results
All I need to do is generate a random integer between 0 and 3 for example.
I am using this function:
void Crossover(int parents[2][3])
{
  int ranDpart;
  int ranDparent;
  for(int i=0; i<10; i++)
  {
    for(int j=0; i<3; j++)
    {
      ranDpart = random(0,3);
      ranDparent = random(0,2);
      newGen[i][j] = parents[ranDparent][ranDpart];
    }
  }
}

where as you see parents is input with size of 2x3 and newGen is 10x3 2D array. As seen here in the code, this function is supposed to randomly take one of parent and a part of this parent to make a new "child". Am I doing something wrong? I think that random gives me bad results. I tried some online compiler and random gives me numbers like "1804289383" even if I tried to make it long. Can you guys help me with random int?

Could you print the values you are getting? That will be helpful.

In what library is that 'random' function defined?

some online compiler ? Well, there's a part of your problem. The other part is in the code that you don't show us. Can you try a real Arduino board ?

I didn't show you the code cause it is little bit long. And btw what do you mean about real Arduino board? I have official arduino board not that chinesse one.

stdlib.h defines a few psuedo-random number functions. I am not familiar with a random function taking two arguments, presumably the low and high end of the desired range, that you've specified in your code.
For what it's worth, in plain old C use the modulo operator to achieve the range you want using stdlib's srand and rand functions:
/* seed psuedo-random number generator during setup with something */
srand(0xdeadbeef);

and in your function simply use modulus to get your range:
int ranDpart = rand() % 3; /* range: 0,1,2 */
int ranDparent = rand() % 2; /* range: 0,1 */

If your ranges should be inclusive e.g. [0,3] and [0,2] then
int ranDpart = rand() % 4; /* 0,1,2,3 */
int ranDparent = rand() % 3; /* 0,1,2 */

https://www.arduino.cc/reference/en/language/functions/random-numbers/random/

this always show me only one exact number. And what I am supposed to write into srand brackets?

@Apuna12. Without srand, random will always return the same sequence. To change that sequence from run to run, you give srand a different start value each time. What value? Choose one, whatever, different from others you previously used.

yep. that helped but I have another problem. I generate random in a cycle. After several cycles it generates only zeros... Is there any way to get through this?

and sometimes other numbers.. for example now it game me only 7s

Unfortunatly, "real random" value don't really exist in computer. If you just call a random function many time, you'll get (in many cases) same result. For that, before calling a random generator, you have to set a "seed".
The example here: https://www.arduino.cc/reference/en/language/functions/random-numbers/random/
give a solution, using:
 randomSeed(analogRead(0));

If the PIN 0 (used in this example) is not connected, you'll get some "noise" on it and this will create the seed for your random function.

this is TERRIBLE advice that leaves a false sense of security. most floating analog inputs only bounce 10-20 levels, meaning your sketch has only 10-20 outcomes. now, if you sample analog pin(s) for a short while, and add up the results, you ca get a much larger seed spread, but the advice on the arduino site is pure garbage from a cryptography perspective...

I agree. The question is "how to get a seed?" On Atari machine, the seed was automaticly "created" by getting position of the screen beam at moment you called random(). Maybe on Arduino wait for a user action and use the "time" of this action? Any ideas welcomed.

read 100 values on 4 pins, summing the result in a long, feeding that long to randomSeed()

Use the LSBs of multiple analogRead(anypin) to form a random number - unfortunately on Arduino the analogRead() is poorly coded so you will have some auto-correlation, even with the LSB approach. It is terribly to use one analogRead(). But that's much much better than summing up multiple analogRead() - the law of large numbers dictates its limited randomness.

if you want to read up more on this: https://dannyelectronics.wordpress.com/2016/03/19/true-random-number-generators/

The random(a,b) function does work. If it doesn't there is something else going on. You mention the program is long. A couple of things to remember when programming Arduinos is that

In C there is no boundary checking, so when an array is indexed out of range unexpected behavior or crashes occur.
Arduinos have very little RAM. The UNO only has 2K. Part of that is used for the stack. When memory runs low the stack can overwrite program variables and again create unexpected results or crashes e.g. endless reboots.

There are some functions that return the amount of free RAM available at run time, use those with Serial.print() for debugging. There are some freeRam() functions here, the last one works well for me (with UNO)


text:
Getting boot mode 1.6 error
When I try to upload my script I get this in my serial monitor:

ets Jan  8 2013,rst cause:4, boot mode:(1,6)
wdt reset

The board I am using is Uno + Wifi
And this is my sketch:
/*
* Arduino Smart Thermometer
*
*/
#include <LiquidCrystal.h> // includes the LiquidCrystal Library
#include <Button.h>
#include <SteinhartHart.h>

//LCD constants
const int rs = 2, en = 3, d4 = 8, d5 = 9, d6 = 10, d7 = 11;

//Thermsistor variables
int ThermistorPin = 0;
boolean degreeChanged = false;
double temp = 0.0;

//Buttons
int decreaseDegreePin = 12;
int increaseDegreePin = 13;
int backlightSwitch = 7;

#define PULLUP false        //To keep things simple, we use the Arduino's internal pullup resistor.
#define INVERT false        //Since the pullup resistor will keep the pin high unless the
                           //switch is closed, this is negative logic, i.e. a high state
                           //means the button is NOT pressed. (Assuming a normally open switch.)
#define DEBOUNCE_MS 50     //A debounce time of 20 milliseconds usually works well for tactile button switches.

Button decreaseDegreeButton(decreaseDegreePin, PULLUP, INVERT, DEBOUNCE_MS);    //Declare the button
Button increaseDegreeButton(increaseDegreePin, PULLUP, INVERT, DEBOUNCE_MS);    //Declare the button
Button backlightSwitchButton(backlightSwitch, PULLUP, INVERT, DEBOUNCE_MS);    //Declare the button

//Variables
int wantedDegree = 20;
int backlight = 255;
int switchPin = 4;
double curTemp;

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers
unsigned long previousDegreeUpdateTime = 0;
unsigned long degreeUpdateDelay = 3000;

//Libraries
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
SteinhartHart thermsistor(ThermistorPin);

void setup() {
  //Initialize backlight
  analogWrite(5,backlight);

  pinMode(switchPin,OUTPUT);

  //Initialize display
  lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display }

  //First display
  updateDegree();
  displayCurrentStatus();
}
void loop() {
  switchHeather();

  //Initialize backlight
  analogWrite(5,backlight);

  //Recalculate degree
  updateDegree();

  //Buttons initialization
  changeDegreeWithButtons();

  //If degree is updated, update display
  unsigned long currentDegreeUpdateTime = millis();
  if(degreeChanged){
    if((currentDegreeUpdateTime - previousDegreeUpdateTime) > degreeUpdateDelay){
      previousDegreeUpdateTime = currentDegreeUpdateTime;
      displayCurrentStatus();
    }
  }

}

void switchHeather(){
  if(wantedDegree > curTemp){
    digitalWrite(switchPin, HIGH);
  }
  else{
    digitalWrite(switchPin, LOW);
  }
}

void updateDegree(){

  curTemp = thermsistor.getTempCelsius();

  if(temp != curTemp)
  {
    temp = curTemp;
    degreeChanged = true;
  }
  else{
    degreeChanged = false;
  }
}

void displayCurrentStatus(){
    //Print degrees to LCD
    lcd.clear();
    lcd.print("Temperatuur:");
    lcd.setCursor(0,1); // Sets the location at which subsequent text written to the LCD will be displayed
    lcd.print(temp);
    lcd.print(char(223));
    lcd.print(" Celcius");
}

void changeDegreeWithButtons(){
  //Read buttons
  decreaseDegreeButton.read();
  increaseDegreeButton.read();
  backlightSwitchButton.read();

  if (increaseDegreeButton.wasReleased()) {
    wantedDegree++;
    lcd.clear();
    lcd.print("Temperatuur:");
    lcd.setCursor(0,1); // Sets the location at which subsequent text written to the LCD will be displayed
    lcd.print("Omhoog naar: ");
    lcd.print(wantedDegree);
  }

  if (decreaseDegreeButton.wasReleased()) {
    wantedDegree--;
    lcd.clear();
    lcd.print("Temperatuur:");
    lcd.setCursor(0,1); // Sets the location at which subsequent text written to the LCD will be displayed
    lcd.print("Omlaag naar: ");
    lcd.print(wantedDegree);
  }

  //Backlight switch
  if (backlightSwitchButton.wasReleased()) {
    if(backlight == 255){
      lcd.clear();
      lcd.print("Backlight: Off");
      backlight = 0;
    }
    else{
      lcd.clear();
      lcd.print("Backlight: On");
      backlight = 255;
    }
  }
}

Why does this happen and how can I fix it? When I use the same script on my Arduin Uno board it does work. The board Uno + Wifi however doesn't.
Also what I used is:

An LCD Screen
3 buttons with resistors
A thermsistor with resistor
A relay (only connected to arduino
External power source

This message indicates that you currently have the ESP8266 rather than the ATmega connected to the USB interface.
In order to upload Arduino sketches to the ATmega, you need to follow the instructions on the sale page to change the dip switches to USB<>ATmega328 mode.

The table is probably sufficient, if not you can puzzle out the German explanatory text or try machine translation.
It's possible you could also install ESP8266 support in your Arduino IDE and run your sketches on the ESP8266 part of the board instead of the ATmega part, however chances are mot of the Arduino headers go to the ATmega, so you would be limited in what peripherals you could connect.

Thank you this makes sense I thought I could just upload everything to ESP8266. But this leaves me with one question. The reason I use the ESP8266 part is because I need to pull data from the internet. If I upload my sketch to the Atmega part how do I pull the data from ESP8266 that I retrieved from there?

In example let's say I have a "String data" in ESP8266" how do I use this "data" variable inside Atmega?

That is both an entirely different question, and one which is too broad to be a fit here.
Do a web search for Arduino + ESP8266 examples and invest some time in studying and trying them.


text:
Problem with PWM function on RGB LED and IR
I'm having an issue in controlling a RGB LED with Arduino and a remote control. When including the library IRRemote.h (version 2.2.3), the blue channel only works in on/off logic instead of PWM. If I remove the library, the PWM logic of the blue channel works normally and it does accept the whole range (0-255). I'm using an Arduino/Elegoo Uno R3 board. What could be causing the issue?
Below the code:
#include "IRremote.h"

int pinRic = 9; // Signal Pin of IR receiver to Arduino Digital Pin 11
IRrecv ricevitore(pinRic);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
#define BLUE 3
#define GREEN 5
#define RED 6
#define IR_BPlus  0xFF3AC5  //
#define IR_BMinus 0xFFBA45  //
#define IR_ON     0xFF827D  //
#define IR_OFF    0xFF02FD  //
#define IR_R    0xFF1AE5  //
#define IR_G    0xFF9A65  //
#define IR_B      0xFFA25D  //
#define IR_W    0xFF22DD  //
#define IR_B1   0xFF2AD5  //
#define IR_B2   0xFFAA55  //
#define IR_B3   0xFF926D  //
#define IR_B4   0xFF12ED  //
#define IR_B5   0xFF0AF5  //
#define IR_B6   0xFF8A75  //
#define IR_B7   0xFFB24D  //
#define IR_B8   0xFF32CD  //
#define IR_B9   0xFF38C7  //
#define IR_B10    0xFFB847  //
#define IR_B11    0xFF7887  //
#define IR_B12    0xFFF807  //
#define IR_B13    0xFF18E7  //
#define IR_B14    0xFF9867  //
#define IR_B15    0xFF58A7  //
#define IR_B16    0xFFD827  //
#define IR_UPR    0xFF28D7  //
#define IR_UPG    0xFFA857  //
#define IR_UPB    0xFF6897  //
#define IR_QUICK  0xFFE817  //
#define IR_DOWNR  0xFF08F7  //
#define IR_DOWNG  0xFF8877  //
#define IR_DOWNB  0xFF48B7  //
#define IR_SLOW   0xFFC837  //
#define IR_DIY1   0xFF30CF  //
#define IR_DIY2   0xFFB04F  //
#define IR_DIY3   0xFF708F  //
#define IR_AUTO   0xFFF00F  //
#define IR_DIY4   0xFF10EF  //
#define IR_DIY5   0xFF906F  //
#define IR_DIY6   0xFF50AF  //
#define IR_FLASH  0xFFD02F  //
#define IR_JUMP3  0xFF20DF  //
#define IR_JUMP7  0xFFA05F  //
#define IR_FADE3  0xFF609F  //
#define IR_FADE7  0xFFE01F  //
#define incFact 30
int  brightFact = 0;
int lv[3];

void fade7()
{
#define delayTime 10 // fading time between colors

  lv[0] = 255; // choose a value between 1 and 255 to change the color.
  lv[1] = 0;
  lv[2] = 0;

  for (int i = 0; i < 255; i += 1) // fades out R bring G full when i=255
  {
    lv[0] -= 1;
    lv[1] += 1;

    analogWrite(RED, lv[0]);
    analogWrite(GREEN, lv[1]);
    delay(delayTime);
  }

  lv[0] = 0;
  lv[1] = 255;
  lv[2] = 0;

  for (int i = 0; i < 255; i += 1) // fades out G bring B full when i=255
  {
    lv[1] -= 1;
    lv[2] += 1;

    analogWrite(GREEN, lv[1]);
    analogWrite(BLUE, lv[2]);
    delay(delayTime);
  }

  lv[0] = 0;
  lv[1] = 0;
  lv[2] = 255;

  for (int i = 0; i < 255; i += 1) // fades out B bring R full when i=255
  {
    lv[2] -= 1;
    lv[0] += 1;

    analogWrite(BLUE, lv[2]);
    analogWrite(RED, lv[0]);
    delay(delayTime);
  }
}

void setColor(int r, int g, int b)
{
  Serial.println("About to write:");
  Serial.println(r);
  Serial.println(g);
  Serial.println(b);
  analogWrite(RED, r);
  analogWrite(GREEN, g);
  analogWrite(BLUE, b);
}

void  translateIR() // takes action based on IR code received
{
// describing Remote IR codes
  Serial.println(results.value, HEX);
  switch (results.value)
  {
    //case IR_BPlus: setBright(true);break;
    //case IR_BMinus: setBright(false);break;
    case IR_OFF: setColor(0, 0, 0); break;
    //COLORS
    case IR_R: setColor(255, 0, 0); break;
    case IR_G: setColor(0, 255, 0); break;
    case IR_B: setColor(0, 0, 255); break;
    case IR_W: setColor(255, 255, 255); break;
    case IR_B1: setColor(255, 20, 0); break;
    case IR_B2: setColor(0, 255, 20); break;
    case IR_B3: setColor(20, 0, 255); break;
    case IR_B4: setColor(255, 20, 255); break;
    case IR_B5: setColor(255, 90, 0); break;
    case IR_B6: setColor(0, 255, 90); break;
    case IR_B7: setColor(90, 0, 255); break;
    case IR_B8: setColor(255, 150, 255 ); break;
    case IR_B9: setColor(255, 191, 0); break;
    case IR_B10: setColor(0, 255, 191); break;
    case IR_B11: setColor(191, 0, 255); break;
    case IR_B12: setColor(120, 255, 255); break;
    case IR_B13: setColor(255, 255, 0); break;
    case IR_B14: setColor(0, 255, 255); break;
    case IR_B15: setColor(255, 0, 255); break;
    case IR_B16: setColor(150, 255, 255); break;

    //END COLORS
    case IR_FADE7: fade7();
  }// End Case

  delay(100); // Do not get immediate repeat
} //END translateIR

void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  ricevitore.enableIRIn(); // Start the receiver*/

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{
  if (ricevitore.decode(&results)) // have we received an IR signal?
  {
    translateIR();
    ricevitore.resume(); // receive the next value*/
  }
} /*--(end main loop )-- */

I give you an upvote for a decently written sketch. Not 100% perfect but better than many others.

By default, the IRremote library uses Timer 2 on an ATmega328P. (Library documentation) This timer is also used for PWM on pins 3 and 11.
This means that you will have to use a different PWM pin for your blue LED (e.g. 9 or 10, controlled by Timer 1).
Alternatively, you could edit the IRremote library to use Timer 1.


text:
How will Arduino sketch and Android app communicate over GPS?
How will I make Arduino with GPS communicate with an Android app? I just need this for my school project.

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.

GPS is no used for that. To send and receive data between Arduino and Android you must use USB, Wifi or Bluetooth.

Android  phones already had a GPS ...

How will i make arduino with gps to communicate with android app? i just need this for my school project.

as gps is one-way communication, you will have to either launch your own birds capable of two way communications, or pick a different school.

I give you +1 danny :)

i don't think that's the actual question, even if the title is less than steller...


text:
Xbee shield to shield connection sends but not receives correctly
Setup:
2XArduino Uno
2x XBees S1
2x Sparkfun xbee shields.
My first arduino reads in values from a photoresistor and sends the values to the second arduino.
I know for sure the arduino is sending  values because when i plugged the second xbee directly into the computer and opened the serial monitor correct values showed up in the serial monitor. But the problem is when i attach the second Xbee onto its sparkfun shield and arduino i get repetitive wrong values .
Can someone please tell me what i am doing wrong?
I am doing this to make sure i get the right values before i beef up the project.
Sender sketch
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <XBee.h>
int photocellPin = A0;     // the cell and 10K pulldown are connected to a0

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

int photocellReading;     // the analog reading from the analog resistor divider
 SoftwareSerial XBee(2,3);
void setup(void) {

  Serial.begin(9600);
  XBee.begin(9600);
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("Wireless LightDimmer");

}
 void loop(void) {
  photocellReading = analogRead(photocellPin);
  lcd.setCursor(0, 1);
  lcd.print("Photocell= ");
  lcd.setCursor(11, 2);
  lcd.print(photocellReading);
  //Serial.println(photocellReading);
  lcd.setCursor(20, 0);
  lcd.print("Measured in lux");

  delay (500);
  lcd.setCursor(20, 3);
  lcd.print(" ");
 // Serial.print("Analog reading = ");
 // Serial.print(photocellReading);
   photocellReading = 1023 - photocellReading;
 unsigned int LEDbrightness = map(photocellReading, 0, 1023, 0, 255);
   Serial.println( LEDbrightness);
    XBee.print(LEDbrightness);

  delay(1000);
}

recieving sketch
#include <SoftwareSerial.h>
#include <XBee.h>

SoftwareSerial XBee(2,3);

void setup() {
 // Begin Serial communication
 Serial.begin(9600);
 }
void loop(){
 while ( Serial.available() > 0) {
 unsigned int num =  Serial.read();
 Serial.println(num);
 delay(2000);
 }
}

Check for Vref u r getting full (1024) ADC value.

The xbee pins can only read up about 1.2V which it will show 256 bit. You should check how much the photoresistor is giving out because it might gives something that is more than the xbee pin can handle.


text:
ATTiny85 Serial communication with Bluetooth Module
For a simple project I would like to use a ATTiny85 connected to a HC-06 Bluetooth Module so it can talk to my Android phone.
I wrote a code for my Arduino Uno and worked as expected. When I changed the code to use on my ATTiny85 I got an error saying that 'Serial' was not declared in this scope and assumed that the ATTiny does not support Hardware Serial.
I need to read a String when received and sleep the MCU when not receiving. I went to use SoftwareSerial and was not able to get a String, just the first char.
I approached it in some was, like defining a char string[10]; as global and string[i] = mySerial.read(); i++; inside the loop, but it keeps not working. Whether it is the sleep, or my work to read data, I couldn't make it work.
Can someone provide a way to put a ATTiny85 to sleep, wake up to receive a String through Serial and sleep til the next data through Serial, please?
To sleep I'm using
void sleep() {
  GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
  PCMSK |= _BV(PCINT3);                   // Use PB3 as interrupt pin
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sei();                                  // Enable interrupts
  sleep_cpu();                            // sleep

  // woke up
  cli();                                  // Disable interrupts
  PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
  sleep_disable();                        // Clear Sleep Enable bit

  sei();                                  // Enable interrupts
}

ISR(PCINT3_vect) {

}

And my loop is something like
char inputString[10];
int i = 0;

void loop() {
  sleep();

  if (serial.available() > 0) {
    char inputChar = serial.read();
    if (inputChar == '2') {    //Char to break
      //Do something and reset i
    } else {
      inputString[i] = inputChar;
    }
    i++;
  }
}

Thanks to all.

You could easily overflow your buffer here. It’s a fixed 10 bytes, but nothing checks to see if you’ve filled it. You might be just trashing the memory by writing outside of the array.

Hello,
I think you should do this:
char inputChar = '';    //this in global
while (serial.available()) {
    inputChar = serial.read();
    if (inputChar == '2') {    //Char to break
        //Do something and reset i
    } else {
        inputString[i] += inputChar;    //= to +=
    }
    i++;
}


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

The above data is continuously printing on console.

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

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

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

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

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

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

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

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

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

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

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

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


text:
Trying to create a beats per minute monitor but having diffuctly with the coding? coding wont print any values
Any advice on what coding to adjust. New to Arduino.
const int sensorPin = A0;
float voltage=0.0;
int sensorVal=0;
int heartbeats=9;
float BPM=0.0;
const int led1=2;
const int led2=3;
int starttime = 0;
boolean counted = false;

void setup() {
pinMode(sensorPin, INPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
Serial.begin(9600);
boolean counted = false;
}
void loop() {

starttime = millis();
while (millis()<starttime+10000)
{
  sensorVal = analogRead(sensorPin);
  if (sensorVal >550 && counted == false)
  {
    counted = true;
  }
  else if (sensorVal < 500)
  {
    counted = false;
  }
}

    BPM = heartbeats*6;
 Serial.println("Your BPM is");
 Serial.println(BPM);
BPM =0;
heartbeats =0;

}

Where are you actually counting the BPM? Also, starttime is too small to store time. Also your method of calculating time is wrong, since it won't cope with millis rollover.

Minor issues in your code could be fixed, but actual beat per minute measurement is a complex processing algorithm far beyond the scope of this site - and not something anyone would want to run on an ATmega based Arduino.  You'll have better luck picking a different project.

I tested your code and it print the values anyway.

Depend on the way you're doing this, but the process of detecting pulse is very simple, as detecting the level of gaz in blood (confusion is often made with Oxymeter which in fact measure "gaz" and not O2 and can be fooled by CO intoxication). In order to get an exact count, I suggest to use interrupt or, maybe have a look at code like those about water flow rate which you must read at a specific velocity, a bit like in your case. Have a lokk here: https://www.sparkfun.com/products/11574 In the document tab of this product, you'll find code.

There's two basic methods of measuring a frequency, which is basically what you are trying to do.
There is Frequency Counting and Frequency Timing. The latter involves measuring the time between successive pulses and calculating the instantaneous frequency from that. Good for rapidly changing frequencies where you need to know the frequency right away.
Frequency counting is what you are attempting, and is basically counting the number of edges that occur within a certain timeframe.
However your method is slightly flawed: chiefly because you forgot to actually count the edges. You wrote some reasonable code for finding an edge, but failed to actually do anything with that edge.
Also your code is blocking for 10 seconds, which may be fine in this scenario, but is not a good habit to allow yourself to get into.
Instead you should consider something more like this:
void loop() {
    static int count = 0;
    static bool counted = false;
    static uint32_t ts = millis();

    int val = analogRead(sensorPin);

    if ((val > 550) && (counted == false)) {
        counted = true;
        count++;
    } else if (val < 500) {
        counted = false;
    }

    if (millis() - ts >= 10000) {
        ts += 10000; // You could assign ts the millis() value, but
                     // by adding 10 seconds it cancels any drift
                     // caused by other delays in your sketch.
        int BPM = count * 10;
        count = 0;
        Serial.print("BPM: ");
        Serial.println(BPM);
    }
}

Assuming the input waveform is a low frequency square wave. Multiple ways to do it.

Use the input to gate a counter on internal clock. It gives the most precise measurement, with a sub-us resolution.
Use external or pcint interrupts to time the start and beginning of an edge.
Wait in between edges.

...
Oversampling and algorithm will help smooth out the measurement.


text:
Storage usage of methods compared to copied code
When you have really small snippets of code that are repeated several times in your micro controller program, is it better to write a method? I mean better in terms of performance and storage usage. I know that when programming for PC, code repetition is a big no go, but what about micro controllers?
In the following example (Arduino Nano with Adafruit 2,8" cap touch display) the snippet should look if the back button is pressed in several screens. I checked in the Arduino IDE how much storage each version takes:
Version 1, 15114 Bytes for complete program:
void battScreen(TS_Point p){
  // some other code
  // ....
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

void alarmScreen(TS_Point p){
  // some other code
  //...
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

void pumpScreen(TS_Point p){
  // some other code
  // ...
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

Version 2, 15234 Bytes for complete program:
void checkBack(TS_Point p){
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

void battScreen(TS_Point p){
  // some other code
  // ...
  checkBack(p);
}

void alarmScreen(TS_Point p){
  // some other code
  // ...
  checkBack(p);
}

void pumpScreen(TS_Point p){
  // some other code
  // ...
  checkBack(p);
}

As you can see, version 2 with the extra method takes 120 Bytes more storage. Is there a rule of thumb when it makes sense to create a new method instead of copying code?

Maybe the following question also gives you some insight: https://stackoverflow.com/questions/144993/how-much-overhead-is-there-in-calling-a-function-in-c

Your comparison is quite strange; functions take LESS space than copying code. I'll try implementing it, since I think there is some other issue with your specific code

Also (except for the interesting result), not to optomize if it is not needed. Mostly readability, maintainability favors above performance or used flash memory.

@frarugi87 This is possible, although I just changed the code as in the question. Maybe (part of) the reason is what Code Gorilla wrote in his answer with copying variables.

It.... depends
A call to function involves a few things

Save the context
Move the parameter(s) to the appropriate registers
Enter the function
Execute
Eventually save the return value to a register
Restore the context
Eventually copy the returned value to the variable

As you can see, quite a lot of things. The bold points are the ones executed also if you don't use a function.
Please note that if these functions are "methods", you have also a "hidden" parameter (the object you are applying the method onto)
So why use functions? Well, you will have to write this code in flash only once instead of more times.
What is best? It depends on your application.

You are calling this function only once? Don't use a function
Your function is really short (for instance, a one-liner)*? Don't use a function
You are running out of flash memory? Use a function
You need a lot of speed? Don't use a function (you add overhead)
You are not in one of the previous cases? Do as you prefer

With one-liner I mean something like, for instance, byte sum(byte a, byte b) { return a + b; }; in this case the function also occupies more space, since the call function instruction is compatible with the byte sum

Please note that usually more readability is more important than performances, so maybe using functions should be encouraged. I mean, in your case I'd probably use them unless there is a problem
What to do if you don't want to use a function? Well, there are other techniques:

Mark the function as inline; this is a hint for the compiler not to create a function but to replicate this every time. This is only a hint, so the compiler may ignore this
Instead of a function write a macro. This will be substituted every time, but the code will be maintainable. As a drawback, it is much harder to debug with the usual methods.

Just a remark: usually smart compilers can guess what is the best option (inline or function) on their own also for non-inline functions. So you can also trust the compiler in 90% of the cases

You haven't mentioned optimization: if you use a function only once the compiler will most likely just place the code inline, thus avoiding the overhead of a function. You can also force a function to be inline, so you have the convenience of no duplicate code coupled with the efficience of inline code.

The optimization is in the last remark; I could have highlighted it more. Moreover how can you force the compiler to inline? I thought that the "inline" keyword was just a hint; is there another keyword to force the inlining?

__attribute__((always_inline)).

The reason I would tend towards the second method more is there is less opportunity for bugs in the second version.
If storage size is a major concern and you know that repeating the code requires less storage, then I would #define it as a macro and get the best of both worlds.
You could improve the code though.  At the moment you are passing copies of the variable into functions, passing const references might use less room, void checkBack(const TS_Point& p){

using void checkBack(const TS_Point& p) indeed reduced the size by 80 Bytes. Thank you for that!

What seems strange though, is that const type& variable  only reduces size with the TS_Point variables, not with int, uint16_t or other normal types, where it increases size. I know this is not the question, but do you know the reason for that?


text:
How to read data from client ESP8266-01?
I need help: my Arduino is not receiving or reading from an ESP8266-01 as a client.
Actually, the ESP01-server and ESP01-client are successfully talking each other but if I attach the Arduino Uno to read the data from the server, nothing happens. It's not receiving at all.
Any help is very much appreciated.

Lua server:
-- GMKSoft
--*************************
--    ESP8266 Server
--*************************

--*************************
--  Static Configuration
--*************************
cfg =
{
    ip="192.168.255.101",
    netmask="255.255.255.0",
    gateway="192.168.0.1"
}
wifi.ap.setip(cfg)

wifi.setmode(wifi.STATIONAP);
wifi.ap.config({ssid="GMKSoft",pwd="GMKSoftESP"});
print("Server IP Address:",wifi.ap.getip())

sv = net.createServer(net.TCP)
sv:listen(8080, function(conn)
    conn:on("receive", function(conn, receivedData)
        print("Received Data: " .. receivedData)
    end)
    conn:on("sent", function(conn)
      collectgarbage()
    end)
end)

Client lua:
-- GMKSoft
--*************************
--    ESP8266 Client
--*************************

--*************************
--  Static Configuration
--*************************
client_ip="192.168.255.102"
client_netmask="255.255.255.0"
client_gateway="192.168.0.1"

wifi.setmode(wifi.STATION)
wifi.setphymode(wifi.PHYMODE_N)
wifi.sta.config("GMKSoft","GMKSoftESP") -- connecting to server
wifi.sta.connect()
if client_ip ~= "" then
    wifi.sta.setip({ip=client_ip,netmask=client_netmask,gateway=client_gateway})
end

tmr.alarm(1, 2000, 1, function()

     if(wifi.sta.getip()~=nil) then
          tmr.stop(1)
          print("Connected!")
          print("Client IP Address:",wifi.sta.getip())
          cl=net.createConnection(net.TCP, 0)
          cl:connect(8080,"192.168.255.101")

          tmr.alarm(2, 5000, 1, function()
            cl:send("Hello World!")
          end)

         tmr.stop(2)
         print("Going to sleep")
         wifi.sta.sleeptype(wifi.MODEM_SLEEP)
      else
         print("Connecting...")
      end
end)

Arduino Code:
#include <SoftwareSerial.h>

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

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // set the data rate for the SoftwareSerial port
  mySerial.begin(115200);
}

void loop() {
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

I would lower the baud rate on the software serial port to 9600.  Other posts on this site suggest ESP to SoftwareSerial works better at that speed.  (You obviously need to lower ESP serial speed too)

Thank you dda for your comment, I try to lowering the bauad to 9600 of the softwareserial and hopefully I get a reading of data from ESP8266-01.

I successfully communicate with two esp01 module as a AP and STATION.
The esp01 as a server, please flash it using NodeMCU-PyFlasher-2.1, and used this bin file nodemcu-master-7-modules-2017-11-23-15-58-17-integer.bin
I build it from  here
Here is the code of the server, I'm using ESPPlorer IDE lua script:
cfg={}
cfg.ssid="GMKWiFi"
cfg.pwd="GMKSoft2627"

dhcp_config ={}
dhcp_config.start = "192.168.1.100"
wifi.ap.dhcp.config(dhcp_config)

print("ESP8266 Server")
wifi.setmode(wifi.STATIONAP);
wifi.ap.config(cfg);
print("Server IP Address:",wifi.ap.getip())

sv = net.createServer(net.TCP)
sv:listen(80, function(conn)
    conn:on("receive", function(conn, receivedData)
        print(receivedData)
    end)
    conn:on("sent", function(conn)
      collectgarbage()
    end)
end)

Here is the Client Code, Im using Arduino IDE
#include <ESP8266WiFi.h>
const char* ssid     = "yourSSID";         // SSID
const char* password = "yourpassword";     // Password
const char* host = "192.168.4.1";         // Server IP
const int   port = 80;                    // Server Port
const int   watchdog = 5000;              // Watchdog frequency
unsigned long previousMillis = millis();

void setup() {
  Serial.begin(115200);
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  unsigned long currentMillis = millis();

  if ( currentMillis - previousMillis > watchdog ) {
    previousMillis = currentMillis;
    WiFiClient client;

    if (!client.connect(host, port)) {
      Serial.println("connection failed");
      return;
    }

    String url;
    url += "R1";

    client.print(url);
  }
}


text:
Reset Arduino Uno R3
I have an Arduino Uno R3 board and I compiled a test code. But now I'm trying to delete it. There are many tutorials with the same way, that is rewrite BLANK CODE. But it's not the genuine way. I want to delete all code that I manually compiled. Because the previous code will also take space in memory and after some time memory will be full. Is there anyone who has the right solution for this problem? Thanks in advance.

Every time you rewrite an Arduino, the previous code is completely wiped out (except for the bootloader, which doesn't change).
You will not fill up your arduino -- it is not like a filesystem where you are continually adding new files. Each new programming/upload overwrites all the existing code.
Uploading a blank sketch is the genuine way to "erase" an unwanted program from an arduino.

When you upload a new sketch the flash memory (Arduino hard disk) is deleted completely and the new sketch is loaded.
If you want a blank code, just upload:
void setup() {
}

void loop() {
}


text:
Conversion between boolean and int went wrong
I have a small problem with conversion from bool array to int. It is working fine until it comes to the 12th cycle of while. I don't know why but this is really weird.
I try to paste here a code where I am doing this conversion.
int* BoolToInt(bool* set) {
  int* ret = (int*)malloc(3*sizeof(int));
  int sum0 = 0;
  int sum1 = 0;
  int sum2 = 0;
  //bool test[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1};
  for(int m=0; m<24; m++) {
    if(m<8) {
      sum0 += (int)set[m] * (pow(2,m));
    }
    if(m>7 && m<16) {
      sum1 += (int)set[m] * (pow(2,(m-8)));
    }
    if(m>15 && m<24) {
      sum2 += (int)set[m] * (pow(2,(m-16)));
    }
  }
  ret[0] = sum0;
  ret[1] = sum1;
  ret[2] = sum2;
  Serial.print("\n ret[0] = ");
  Serial.print(ret[0]);
  Serial.print("\n ret[1] = ");
  Serial.print(ret[1]);
  Serial.print("\n ret[2] = ");
  Serial.print(ret[2]);
  return ret;
}

And this is where I am using this function:
void Fitness(bool** set) {
  int maX = 0;
  int index = 0;
  int* temp;
    for(int i=0; i<10; i++) {
    int* phenotype = BoolToInt(set[i]);
    _fitness[i] = 1000/((phenotype[0] - _colours[0])*(phenotype[0] - _colours[0]) + (phenotype[1] - _colours[1])*(phenotype[1] - _colours[1]) + (phenotype[2] - _colours[2])*(phenotype[2] - _colours[2]) + 1);
    Serial.print("\n phenotype[0] = ");
    Serial.print(phenotype[0]);
    Serial.print("\n phenotype[1] = ");
    Serial.print(phenotype[1]);
    Serial.print("\n phenotype[2] = ");
    Serial.print(phenotype[2]);
    free(phenotype);
  }
  for(int i=0;i<10;i++) {
    temp = BoolToInt(set[i]);
    if(_fitness[i]>maX) {
      maX = _fitness[i];
      index = i;
    }
  }
  setColorOnSecond(temp[index]);
  free(temp);
}

As seen in the Fitness function, I have some debugging prints to see if everything is fine. My main is in the while cycle. Everything is fine and "ret" from BoolToInt function is the same as "phenotype" in Fitness, which is a good thing and this is what I want. But then the 12th cycle comes and phenotype[1] gives me 1200 as int. And of course everything in ret[] is fine(0-255). Am I doing something wrong?
NOTE: bool* set in BoolToInt is 24 bool array (yes 3 numbers as you can see).
NOTE 2: every previous cycle before 12th cycle is good and the result are equal.

Are you trying to encode a bool array into an integer? What whilecycle are you talking about?

Your code doesn't compile. Some variables are missing.

yes of course it won't compile.. this is only a part of evolutionary algoritm.

while is used in main....imagine it as a while and inside of that is this Fitness function

Imagine doesn't work. Post a complete, minimal, working sketch. We can't speculate on unseen code.

Your problem is using pow.  It works in floats.  It may come as some surprise, but pow(2,3) gives 7 when you put it into an int.
Don't waste time on pow for powers of 2.  Just use a bitshift.   It's way smaller and faster.

Where did you see that pow(2, 3) gives 7? My Arduino tells me (int) pow(2, 3) == 8.

Oh, wait, you're right. It gives 8 if 3 is a constant, but 7 if it's a variable.

I've seen enough threads on Arduino.cc where someone is shocked that Arduino gets powers of 2 wrong to know that one pretty well.  I'm guessing that when it is done with constants the calculation is being optimized away and the compiler is smart enough to put 8 in there.

this helped me :)... now it gives me good answers :).. thanks

Let me the first one to say that 1. Boolean to int conversion shouldn't be this complicated and 2. Much simpler ways to do what you are trying to do.
Like this.
If (bool) boolint |= mask;
  Mask = mask << 1;
  ...
You get the idea.

yes I saw this already. But this doesn't solve my problem


text:
Programming Arduino with FTDI via Tx and Rx pins
How program Arduino with a FTDI cable/breakout_board via pins 0 (Rx) and 1 (Tx)?
In case the USB to UART chip (16U2 or other) is broken, you can program Arduino with a FTDI instead of 16U2 or other chip.
What are the connections to reset the Arduino microcontroller automatically when sketch is upload?

has your FTDI a DTR pin?

Yes, DTR and CTS pins

It's exactly the same as for a breadboard Arduino.  That is, connect the DTR pin of your breakout board through a 0.1uF capacitor to the RESET pin. TX and RX then connect to the RX and TX pins of the Arduino respectively, along with of course the ground connection.


text:
Button with switch timer and reset time function + LED feedback. What am I doing wrong?
Beginner here.
I´ve been trying to implement a button function timer working with millis() instead of delay as I want the button to be responsive while the timer is running.
So far I´ve managed to start the counter on the button´s state change and let it time out. Unfortunately all kind of strange behavior is coming out of my sketch and I am yet to understand why.
Help is appreciated.
This is the desired behaviour of the timer:

On startup the Arduino is ready to recieve a button push.
The relay is off (HIGH).
Once the button is pushed:
• The relay state is changed to LOW in order to turn it on
• A green LED switches on.
• A millis() based timer is switched on.
If the user presses the button while the switch is on, the timer is reset to 0 and continues counting.
If the on-time is going to end, a red LED starts blinking. Say in the last minute.
As soon as the timer reaches the specified on-time:
• The green LED switches off
• The relay switches off
• The system returns to step 1. and is awaiting a push.

In my code example the red blinking Led is not implemented yet.
The following code switches the switch and the green LED on but does not switch them off anymore.
//CONSTANTS

#define BUTTON_PIN        2  // Button
int in1 = 7;
int greenLED = 4;
int redLED = 9;

//VARIABLES

int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

//MILLIS
unsigned long previousMillis = 0;
const long interval = 10000;

void setup()
{
  pinMode(BUTTON_PIN, INPUT);
  digitalWrite(BUTTON_PIN, HIGH); // pull-up
  Serial.begin(9600);

  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);

  //SWITCH HANDLERS
  pinMode(in1, OUTPUT);
  digitalWrite(in1, HIGH);

}

void loop(){

    // read the pushbutton input pin:
    buttonState = digitalRead(BUTTON_PIN);
    unsigned long currentMillis = millis();

    // compare the buttonState to its previous state
    if (buttonState != lastButtonState) {

        buttonState = digitalRead(BUTTON_PIN);

        if (currentMillis - previousMillis < interval){
        //SWITCH ON, LED ON
          digitalWrite(in1, LOW);
          digitalWrite(greenLED, HIGH);
        }

        if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            digitalWrite(in1, HIGH);
            digitalWrite(greenLED, LOW);
        }

        // Delay a little bit to avoid bouncing
        delay(50);

        // Reset buttonState:
        lastButtonState = buttonState;
   }
}

For one, you are running code when the button is being pressed, but also when the button is being released (though I don't think that effects anything here). Secondly, the code that checks if enough time has passed only runs when the button is pressed (or released). Thirdly the previousMillis isn't updated when the button is pressed.

Written and tested. I also included the red blinking led.
//CONSTANTS

const int BUTTON_PIN = 2; // Button
const int in1 = 7;
const int greenLED = 4;
const int redLED = 9;

//VARIABLES

int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button
bool relayOn = false;

//MILLIS
unsigned long previousMillis = 0;
const unsigned long interval = 10000;
const unsigned long redLedInterval = 2000;

void setup()
{
  pinMode(BUTTON_PIN, INPUT);
  digitalWrite(BUTTON_PIN, HIGH); // pull-up
  Serial.begin(9600);

  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);

  //SWITCH HANDLERS
  pinMode(in1, OUTPUT);
  digitalWrite(in1, HIGH);

}

void loop(){

    // read the pushbutton input pin:
    buttonState = digitalRead(BUTTON_PIN);
    unsigned long currentMillis = millis();

    // if button is pressed, turn relay on (if it wasn't already on), and reset the timer
    if( buttonState==LOW ) // no need to check for previous state, in this specific case
    {
        previousMillis = currentMillis;
        digitalWrite(in1, LOW);
        digitalWrite(greenLED, HIGH);
        digitalWrite(redLED, LOW);
        relayOn = true;
    }

    // if relay is currently on...
    if( relayOn )
    {
        // turn red led on, if close to turning off the relay
        if (currentMillis - previousMillis >= interval-redLedInterval )
            digitalWrite(redLED, (millis()/300)%2);//blink red led; 300ms on; 300ms off

        // if enough time has elapsed, turn of the relay
        if (currentMillis - previousMillis >= interval)
        {
            // .. turn of relay
            digitalWrite(in1, HIGH);
            digitalWrite(greenLED, LOW);
            digitalWrite(redLED, LOW);
            relayOn = false;
        }
    }
}

Added advantage here is that the timer will never run out if the button is keep being pressed down.

Thanks. This is very nice from you.
Unfortunately all it seems to do is switch both, the greenLED and the relay on as soon as the Arduino is powered. Pushing the button does not sem to have any effect. Could this be a hardware problem?
I was working on a very similar approach to your bool relayOn but with an integer changing between 0 and 1. While this partially worked, I was stuck at the timer reset implementation. I will try and include your solution in my approach and post the results.

Then I think you have your button connected the other way around. Is the button connected to 5v or GND when pressed?

Try changing buttonState==LOW to buttonState==HIGH.

Halleluja! It works!
For some reason the idea that a button state change was important was stuck in my head. I thought that the buttonState==LOW and HIGH states are only working while this state is in fact present, meaning while the button is held pressed and not after that.
I have no way to express the amout of gratitude.

I also find this expression very interesting. Why does this work?
digitalWrite(redLED, (millis()/300)%2);

In that case you need to remove the line that enabled the "pull-up" resistor, as apparently you are using a pull-down resistor on your breadboard.

The state-change of the button is quite useful in a lot of cases. For example; press the button to turn on the relay, and then press the button again to turn of the relay. But in this very specific case, state-change doesn't matter,

millis()/300 gives you the number of 300ms intervals that have elapsed. %2 gives the module 2, so the remainder of /2., or in this case 1 if it's odd, and 0 if it's even. This is a very quick way of blinking a light. The only downside is that most of the time it doesn't start blinking at a millis value that is divisible by 300. So the first blink can be a lot shorter. Or it start with being off. The latter can be problematic if you use a slow blink.

You're welcome by the way. Please press the checkbox next to my answer to accept it (once you are allowed that is).

So let me check if I understand right:  millis()/300 checks "how often" the 300 ms interval fits into the current millis() value, right? Sorry for first grade language. It helps my graphical mind to understand. So (300/300) = 0; 0%2 = 0, thus LOW; (600/300)=2 %2= 0, thus LOW again. (1300/300)=4,3 and 4,3%2=0,3, thus not 0 which outputs to HIGH. Am I getting closer? I know that dividend or divisor have to be ints. Does this mean they are rounded?

1300/300=4 as the remainder is just thrown away. (4%2=0). So with dividing integers the result is rounded down. That's not what they taught us in first grade math q-;

I see. So as a proof of understanding: 1500/300=5; 5%2=1;  So the value is either 0 or 1 because every second full number divided by 2 equals 0. Now I got it.

Yep. So 0-299=>0. 300-599=>1. 600-899=>0. Etcetera

Simple and beautiful.

Would it be difficult to implement a switch everything off again when the button is pressed for 2 seconds?

Then you'd have to add the buttonSate back into the mix. I'd suggest you give it a try yourself first.

I definately will.


text:
Not long tweets published using ESP8266-01 with Arduino UNO
I'm trying to create a setup with which an Arduino UNO sends out a tweet (one random quote) every time a button is pressed. I want to use it as a Mailbox Watcher.
I'm not new to Arduino but ESP8266 is all new to me, so I'm trying to figure things out from how-to articles, youtube videos, etc.
My current setup is an ESP8266-01 attached to an Arduino UNO and I adapted the code found here (link) to my needs. I ended up with something that resembles this:
#include <SoftwareSerial.h>
#include <Bounce.h>

#define DEBUG true

#define APIKEY "THING_SPEAK_KEY" //  api key ThingSpeak
#define TARGET_IP "184.106.153.149"///         //local  direccion IP o Hosting  ThingSpeak
#define TARGET_PORT "80"          ///  port 80
#define ID "WIFI_NAME"  //name of wireless access point to connect to
#define PASS "WIFI_PASSWORD"  //wifi password

#define BUTTON_PIN 8

#define RX_PIN 10
#define TX_PIN 11

SoftwareSerial esp8266(RX_PIN,TX_PIN);

Bounce button=Bounce(BUTTON_PIN, 5);

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

    pinMode(BUTTON_PIN, INPUT);

    initializeModem();

    Serial.println("ready player One");
 }

void initializeModem(){

     sendData("AT+RST\r\n",1000,DEBUG); //

     sendData("AT+CWMODE=1\r\n",1000,DEBUG); //

      String cmd="AT+CWJAP=\"";
      cmd+=ID;
      cmd+="\",\"";
      cmd+=PASS;
      cmd+="\"";
     sendData( cmd+"\r\n",1000,DEBUG); //

     sendData("AT+CIPMUX=0\r\n",1000,DEBUG);

  }

boolean buttonState(){

  if (button.update() && button.read()==HIGH){

      return true;

    }else {
      return false;
      }
  }

void loop() {

if (buttonState()) {

   //  String con tweet
   String  updateTwitterStatus = "The best and most beautiful things in the world cannot be seen or even touched - they must be felt with the heart. Helen Keller #quoteoftheday";
   Serial.println(updateTwitterStatus);

    String webpage = "AT+CIPSTART=\"TCP\",\"";
    webpage += TARGET_IP;
    webpage += "\",80\r\n";
    sendData(webpage,1000,DEBUG);

    // Create HTTP POST Data

    String tsData = "api_key=" APIKEY "&status=" + updateTwitterStatus ;

    String webpage1 = "POST /apps/thingtweet/1/statuses/update HTTP/1.1\n";
    webpage1+="Host: api.thingspeak.com\n";
    webpage1+="Connection: close\n";
    webpage1+="Content-Type: application/x-www-form-urlencoded\n";
    webpage1+="Content-Length: ";
    webpage1+=tsData.length();
    webpage1+="\n\n";
    webpage1+=tsData;

     //// envia   comando AT + cantidad de caracteres

     String cipsend = "AT+CIPSEND=";
     cipsend+= webpage1.length();
     cipsend+="\r\n";

     sendData(cipsend,1000,DEBUG);
     sendData(webpage1,1000,DEBUG);

      //// comando AT de cierre de conexion
     sendData("AT+CIPCLOSE=0\r\n",1500,DEBUG);

              /// DELAY para reenvio de datos a twitter
     delay(10000);  //3 seg
}

}

 //// rutina de depuracion via puerto serial

String sendData(String command, const int timeout, boolean debug) {
    String response = "";

    esp8266.print(command); // send the read character to the esp8266

    long int time = millis();

    while( (time+timeout) > millis()) {
      while(esp8266.available()) {
        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug) {
      Serial.print(response);
    }

    return response;
}

The setup works more or less as expected. It connects ok to the WiFi and so on, but it is only able to publish a tweet if it is not very long. As example, the quote on this example code will no be published whereas if it is half as long, it will be no problem.
In the end, I want to clean up the code and make use of private libraries to tidy things up and leave as few lines of codes as possible on the .ino file, but for testing and debugging purposes, I'm working on the code above.
I realize that a short text should be sufficient for my needs, but the fact of knowing that something is off bothers me to great extend. I have been dealing with this for three long days, so if anyone has an idea it would be much appreciated...
Thanks in advance
EDIT: It seems as the longest tweet I can send is 108 characters long. Together with the AT code to sent it, tha serial monitor gives the following feedback:
AT+CIPSEND=302

Have you tested to find out at what length it doesn't work? "short" and "long" are not specific values, but if you can find out the maximum tweet length that doesn't work, you have made a lot of progress in determining the problem and solution.

that's the next thing I wanted to do, yes. It'll take a while

Edited with the length of the longest tweet possible. Thanks.

wouldn't it be better using a library?

it would be MUCH easier to program the ESP and leave the UNO out of the equation: far more RAM+CPU, only one sketch, no messy serial parsing, better error handling, etc.

thanks @dandavis I thinks this is what I ultimately will do. I just landed on one of these situations where you want to solve the equation even though you won't need it. Any reference or link on how to do it with the stand alone ESP8266?

most of the code should be about the same. lookup an httpClient example on once you install the esp8266 board support into the IDE, and modify it to talk to your server.

It's plausible and likely that you are running out of RAM on the Uno by making extensive use of the String object and it's concatenation function (overloaded + operator).
Every time you + a String object, a new block of RAM is allocated to hold the new string, and that RAM is nearer the "ceiling" of RAM than the previous block. The old blocks are de-allocated, but since they are smaller than the new one, they can't be re-used for new allocations of your continually-larger String, so you eventually run out of contiguous blocks of RAM into which to put your new, longer String object.
One solution here, and pretty much everywhere on an Arduino, is to avoid using the String object, and go with the classic C string handling routines.
I would allocate one buffer char array char buf[512] or whatever you compute your maximum desired total string length to ever be. Then use strncat() to repeatedly concatenate your other parts into that one buffer.
Also consider putting static strings in PROGMEM as described at https://www.arduino.cc/reference/en/language/variables/utilities/progmem/, so you won't be holding all static strings in RAM the whole time, but can copy each as you use it to working RAM as you build up your HTTP request string.
The real killer is += used repeatedly with a String object. Arduino Uno has only 2k of RAM.

Thank you for your answer. As I began to read I understood that all together was over my head, but you explained it very well. I'll see to it tomorrow, but your explanation seems more than plausible. Thanks again!

Well, it has taken me long enough, but thanks to your indications I made it work. Thanks!

But how do you use strncat with strings in PROGMAME, such as strncat(send_buffer, F("TEST"), 4);


text:
HTTPS with ESP8266WebServer?
I see many ESP8266HTTPClient examples, pasting in a fingerprint from an outside website, but I want to host an html page from the ESP8266 in AP mode using HTTPS.
Judging by the lack of examples, and the lack of a domain for a cert in AP mode, I'm thinking this is impossible, but would like confirmation before I give up.
Is it impossible to get the browser's green padlock on an AP-served web page?

The ESP8266 just doesn't have sufficient CPU power to do this reliably.
It is possible, since the EPS8266 SDK docs have an "SSL User Manual" which describes this scenario.
In my experience, using the Arduino core for ESP8266, it doesn't work reliably.
Consider using an nginx reverse-proxy and having that proxy handle SSL negotiation. Understand that this is more for situations where the ESP8266 is local, in a network sense, to the nginx proxy, and you consider your WLAN secure enough.
On the plus side, you have room to grow in key sizes and/or complexity.

thanks for the link, that does help. sadly it's not the arduino core, but i guess i could use 2 ESPs, pretending one's an arduino like the noobs setup...


text:
Communication with socketserver fails after specific number of packets
I'm trying to implement a full-duplex communication between my ESP8266 and a socketserver running on my laptop. In concrete I need each of the devices to initiate communication whenever it needs to. The ESP is measuring temperature all the time and when the temperature changes, I want the ESP to transmit the new temperature to my laptop.
On the other side I want to transmit a command from my laptop whenever I want to know the actual temperature (even if the temperature has not changed).
Therefore I have a python server-script and a python client-script both running on my laptop (see scipts below).
In the loop function on my ESP I'm also running a server and a client (script below).
Sending commands from laptop-client to ESP-server works perfectly. Even at high rates and for days without any problem.
Communicating the other way around (that is sending from ESP-client to laptop-server) seems to work in general, but after numerous packages (usually a few hundreds) have been sent from ESP-client to laptop-server the communication fails and the laptop-server only receives empty byte-strings. After that has happened, also sending commands from laptop-client to ESP-server does not work any more temporarily.
When I shutdown the laptop-server, the ESP needs some time to "calm down" and will then continue working as usual.
Can anyone imagine what causes this behaviour? To me it looks like a buffer overflow or something like that.
I appreciate any help and hints about how to implement the desired functionality (do I actually need to run a server on both my laptop and the ESP?).
Laptop-Server:
import socket
import time

# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

host = "0.0.0.0"
port=1992

# bind to the port
serversocket.bind((host, port))

# queue up to 5 requests
serversocket.listen(5)

try:
  while True:
    # establish a connection
    clientsocket,addr = serversocket.accept()
    try:
        data = clientsocket.recv(1024)
        print(str(addr),":  ",data)
        clientsocket.send("hi there, "+str(addr)+"\n")
        clientsocket.close()
    except:
        pass
except:
  print(" !!! an exception occured !!!")
  serversocket.shutdown(socket.SHUT_RDWR)
  serversocket.close()

Laptop-Client:
import os,sys,re,time,socket,threading,readline

timeout=2

HOST, PORT = "ESP-IP", 1991

response=""
def s_client(data):
    global response
    try:
        response='Error: received no response'

        # Connect to server and send data
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        sock.connect((HOST, PORT))
        sock.sendall(bytes(data + "\n", "utf-8"))

        # Receive data from the server and shut down
        response=str(sock.recv(1024), "utf-8")
    except ConnectionRefusedError:
        response='Error: connection refused by remote host'
    except socket.timeout:
        response='Error: connection timed out'
    finally:
        sock.close()
    return 1

while True:
    try:
        print('  -->  '+s_client(input('_$ ')))
    except KeyboardInterrupt:
        break

ESP-script (containing server and client):
#include <WiFiClient.h>
#include <ESP8266WiFi.h>

IPAddress laptop_ip=(0,0,0,0);
uint16_t TCP_port=1991;
uint16_t TCP_remote_port=1992;
WiFiServer TCPserver(TCP_port);
WiFiClient client;

void ESP_server(void){
  if (!client.connected()) {
    client=TCPserver.available();
  }
  else {
    laptop_ip=client.remoteIP();
    Serial.println("received request");
    int query_l=client.available();
    if(query_l>0){
      String query="";
      for (int nb = 0; nb < query_l-1; nb++){
        query+=(char) client.read();
      }client.read();
      Serial.print("received from laptop: ");Serial.println(query);
      //  Do something with query and return the result
      //  For simplicity I'm just returning a constant value
      client.write("command transmitted");
    }
  }
}

void ESP_client(String message){
  WiFiClient TCPclient;
  if (TCPclient.connect(laptop_ip, TCP_remote_port)){
    TCPclient.print(message);
  }
}

void setup() {
  Serial.begin(115200);
  WiFi.begin("MYSSID","MYPASS");
  Serial.print("connecting with WiFi  ");
  while(WiFi.status()!=WL_CONNECTED){
    Serial.print(".");
    delay(500);
  }Serial.println();
  TCPserver.begin();

  // wait until a command has been received from the laptop
  // ESP_server stores the remote (laptop) ip in laptop_ip
  while(laptop_ip==(0,0,0,0)){
    ESP_server();
  }
}

int temp=0;
void loop() {
  // handle commands sent from my laptop
  ESP_server();

  //  here is a temperature meaurement returning the current temperature
  //  I've replaced it with a temperature generator
  if(temp<30){temp++;}
  else{temp=0;}

  // temperature has changed and needs to be transmitted by this function
  ESP_client((String) temp);
}

The above code differes from the code I'm actually running but it reproduces my problem. I hope that somebody can figure out a misstake or give my some advice about how I could implement things in a better way.
Actually I'm not sure whether the misstake is on laptop- or ESP-side but as the ESP crashes sometimes I think it's the ESP...
I'm using the arduino IDE for flashing, btw.

I found my stupid mistake:
By using try without catching specific exceptions (I know one shouln't do that) in my Laptop-Server script I didn't recognize that I was trying to send unencoded strings.
So,
clientsocket.send("hi there, "+str(addr)+"\n")
has to be
clientsocket.send(bytes(("hi there, "+str(addr)+"\n").encode('utf-8')))
instead.

close the disconnected socket before reconnecting
if (!client.connected()) {
  client.stop();
  client=TCPserver.available();
}

Please excuse my belated response. Unfortunately, that doesn't do the trick...


text:
Stuck in While loop when case is activated. Arduino
I have an arduino uno that controls a light using an ir remote. The sketch works fine until I pressed button c which is case 0x10EF58A7. This case reads in values and dims the light accordingly but the only problem is i can not exit the case when another button on the ir remote is pressed! what should i do!?
#include <SoftwareSerial.h>

#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>

#include <TimerOne.h>

int RECV_PIN = 13;

IRrecv irrecv(RECV_PIN);
decode_results results;
volatile int i=0;               // Variable to use as a counter
volatile boolean zero_cross=0;  // Boolean to store a "switch" to tell us if we have crossed zero
int AC_pin = 7;
int dim2 = 0;                   // led control
int dim = 128;                  // Dimming level (0-128)  0 = on, 128 = 0ff
int pas = 8;                   // step for count;

int freqStep = 65;
char incomingByte;

void setup() {
  Serial.begin(9600);
  // initialize the digital pin as an output.
  pinMode(RECV_PIN, INPUT);
  pinMode(AC_pin, OUTPUT);
  irrecv.enableIRIn(); // Start the receiver
  attachInterrupt(0, zero_cross_detect, RISING);    // Attach an Interupt to Pin 2 (interupt 0) for Zero Cross Detection
  pinMode(AC_pin, OUTPUT);
  Timer1.initialize(freqStep);                      // Initialize TimerOne library for the freq we need
  Timer1.attachInterrupt(dim_check, freqStep);
  // Use the TimerOne Library to attach an interrupt
}

void zero_cross_detect() {
  zero_cross = true;               // set the boolean to true to tell our dimming function that a zero cross has occured
  i=0;
  digitalWrite(AC_pin, LOW);
}

// Turn on the TRIAC at the appropriate time
void dim_check() {
  if(zero_cross == true) {
    if(i>=dim) {
      digitalWrite(AC_pin, HIGH);  // turn on light
      i=0;  // reset time step counter
      zero_cross=false;    // reset zero cross detection
    }
    else {
      i++;  // increment time step counter
    }
  }
}

 void translateIR() // takes action based on IR code received
{

  switch(results.value){

  case 0x10EFD827:
  //power button
   dim = 00;
    Serial.println(" full brightness ");
    break;
  case 0x10EF20DF:
  //circle button
  dim = 128;
    Serial.println("off   ");
    break;
  case 0x10EFF807:
  // button A
  dim = 95;
    Serial.println(" dim level 1   ");
    break;

   case 0x10EF7887:
   //button B
   dim = 50;
    Serial.println("dim level 2     ");
    break;

 case 0x10EF58A7:
 // button C
 {
  while ( Serial.available() > 0) {
 unsigned int num = Serial.parseInt();
 num = map(num, 0, 255, 0, 128);
 unsigned int num1 = map(num, 0, 128, 128, 0);
// num1 = constrain( num1, 0,128);
 dim = num1 ;
   Serial.print(" auto   ");
   Serial.println(dim);

   delay(800);
   Serial.flush();
    //break;
   }
  break;
}
 break;

  case 0x10EF10EF:
//button left
    {
    if (dim<127)
   {
    dim = dim + pas;
    if (dim>127)
    {
     dim=128;
    }
    }
    }
    Serial.print(" dimming ammount=   " );
    Serial.println(dim);
    break;

  case 0x10EF807F:

  //button right
   {
      {
  if (dim>5)
  {
     dim = dim - pas;
  if (dim<0)
    {
      dim=0;  // in vechiul sketch era 1
    }
   }
   }
   }
     Serial.print(" dimming ammount=   ");
      Serial.println(dim);
    break;

   default:
    //Serial.print(" unknown button   ");
    //Serial.println(results.value, HEX);
{}
  }

}

void loop(){
  int i=0;
   if (irrecv.decode(&results)) {

   translateIR();
        irrecv.resume(); // Receive the next value

   }
     delay(700);
 }

What is sending Serial comms to you and how often is it sending?  That while loop is checking for something available from serial.  So obviously something always is.  You also seem to have an extra break after that case and I'm not sure what that is about.

Towards the end there are braces all over the place.  Often times just formatting the code will reveal logic errors that you couldn't see before.  We dont' just line all our blocks and braces up because it is pretty.

The problem is that calling Serial.parseInt() does not remove data from the buffer. So, Serial.available() will not decrease in your case, but increase with every input you give.
You will need to call Serial.read() and then convert the received bytes to a number.
@Majenko generally you're right, but it's okay to use a while loop in this situation. If there is data in the buffer, this data has to be handled. And as the arduino is not capable of multitasking it will need to take the required time, no matter if in the main loop or in a subfunction.

I've just tried it on an ESP8266 and figured out, that Serial.parseInt() does not decrease Serial.available(). As I don't think this depends on the device, but the library, I'd say that's the problem. And about the while loops: there is no way that the routine gets stuck in that special case (except one does not clear/read the buffer) and the time needed to accept data is so essential that it's just fine to do it right at that point! And I can't see a call to read() in that loop, btw...

If you wan't to respond to someone's post, comment under it and don't use your answer for that. This site isn't a discussion forum. And you can edit your own answer to add additional info. Don't put them into the comments.

And I don't know how you tested that, but Serial.parseInt() does remove bytes from the buffer. https://pastebin.com/9MSyyJ4U

@gre_gor I've commented a comment that obviously has been deleted by the author.

@gre_gor I didn't test it by reading, but by doing it. Whatever it says in your link, try it yourself. I'would be curious if it's a bug on ESP

You shouldn't have while loops in your switch/case like that.
In fact, you shouldn't really have while loops at all.
Instead, your case should just set a "state" variable which tells the rest of your loop() function how to handle any serial data that arrives.

Don't use the while loop, set a boolean when the C has been pressed.
Within the loop (main loop, not the while loop within the C key check), check if the boolean is set, and if so, check if there is serial input. If so, handle it, e.g. after or before checking all keys in the switch statement. This way alternatively keys are checked and serial input is handled.
There are good reasons not to use a while loop:

A while loop makes it impossible to do other tasks 'more or less' simultaneously.
A while loop can never end, meaning the device stops responding/functioning.
A while loop which takes too much time can affect the timing of other parts of your sketch.

IF you need a while loop, think twice, after thinking you need one, make sure it always ends within the condition or with a break


text:
Problem with a DHT11 Temperature & Humidity sensor
I'm new in the Arduino world and today i was trying to make a simple program to show the temparature an humidity with this sensor. I made a circuit following one tutorial and nothing happend, the result was Temperature: 0 Humidity: 0.
My question is, what is wrong? Probably the sensor is broken or the code is wrong.
I also need to say that i use a 5K1 resistor in exchange of the 4.7K resistor and accidentally I connected the sensor without the resistance for a few seconds.
This is the code:
#include <DHT.h>
#include <DHT_U.h>

int SENSOR = 2;
int TEMPERATURE;
int HUMIDITY;

DHT dht(SENSOR, DHT11);

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

void loop() {
TEMPERATURE = dht.readTemperature();
HUMIDITY = dht.readHumidity();
Serial.print("Temperature: ");
Serial.print(TEMPERATURE);
Serial.print(" Humidity: ");
Serial.println(HUMIDITY);
delay(1000);
}

This is the circuit scheme:

This is a photo of the circuit and the sensor (probably damaged):

Thanks for your time and sorry for my bad english.

Caution! Always inspect components before hooking up! I got a DHT11 sensor in a Kuman kit. I hooked it up per standard and ran the sketch. Getting 0s reported back I grabbed the sensor to check it was in the board properly and it was burning hot. On closer inspection the were marked ground-data-VCC. Sensor is pooched.

Finally I was able to solve the problem by not using the resistor and connecting it directly, I also had a problem with the sensor pins since some were badly connected, but it was also solved. Now both sensors are working well including the melted one. Thanks!.

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