text:
ESPAsyncWebServer code not compiling
Error messages
    Arduino: 1.8.14 Hourly Build 2020/12/15 11:33 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Disabled (new aborts on oom), Disabled, All SSL ciphers (most compatible), 32KB cache + 32KB IRAM (balanced), Use pgm_read macros for IRAM/PROGMEM, dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:62:18: error: 'HTTP_GET' conflicts with a previous declaration

       62 |   HTTP_GET     = 0b00000001,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:29: note: previous declaration 'HTTPMethod HTTP_GET'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                             ^~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:63:18: error: 'HTTP_POST' conflicts with a previous declaration

       63 |   HTTP_POST    = 0b00000010,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:50: note: previous declaration 'HTTPMethod HTTP_POST'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                                                  ^~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:64:18: error: 'HTTP_DELETE' conflicts with a previous declaration

       64 |   HTTP_DELETE  = 0b00000100,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:83: note: previous declaration 'HTTPMethod HTTP_DELETE'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                                                                                ^~~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:65:18: error: 'HTTP_PUT' conflicts with a previous declaration

       65 |   HTTP_PUT     = 0b00001000,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:61: note: previous declaration 'HTTPMethod HTTP_PUT'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                                                             ^~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:66:18: error: 'HTTP_PATCH' conflicts with a previous declaration

       66 |   HTTP_PATCH   = 0b00010000,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:71: note: previous declaration 'HTTPMethod HTTP_PATCH'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                                                                       ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:67:18: error: 'HTTP_HEAD' conflicts with a previous declaration

       67 |   HTTP_HEAD    = 0b00100000,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:39: note: previous declaration 'HTTPMethod HTTP_HEAD'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                                       ^~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:68:18: error: 'HTTP_OPTIONS' conflicts with a previous declaration

       68 |   HTTP_OPTIONS = 0b01000000,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:96: note: previous declaration 'HTTPMethod HTTP_OPTIONS'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                                                                                ^~~~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:4:

    C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncWebServer-master\src/ESPAsyncWebServer.h:69:18: error: 'HTTP_ANY' conflicts with a previous declaration

       69 |   HTTP_ANY     = 0b01111111,

          |                  ^~~~~~~~~~

    In file included from C:\Users\JUNAID\Documents\Arduino\iot_project_4\iot_project_4.ino:2:

    C:\Users\JUNAID\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:47:19: note: previous declaration 'HTTPMethod HTTP_ANY'

       47 | enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };

          |                   ^~~~~~~~

    Multiple libraries were found for "ESPAsyncTCP.h"

     Used: C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncTCP

     Not used: C:\Users\JUNAID\Documents\Arduino\libraries\ESPAsyncTCP-master

    exit status 1

    Error compiling for board Generic ESP8266 Module.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

Code
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
int Wifiled = 15;

ESP8266WebServer esp(80);

String HTML = "";

String FORM = "testing the second website";

void setup()
{
       HTML +="";
       HTML +=  "";
       HTML +=    "<title>MY SMART HOME</title>";
       HTML +="";

       HTML +=  "";
       HTML +=  "";
       HTML +=  "
";
       HTML +=    "
WELCOME TO MY SMART SENSOR DATA
";
       HTML +=    "
PH SENSOR DATA
";
       HTML +=    "Serial.monitor";
       HTML +=    "
EC SENSOR DATA
";
       HTML +=  "
";
       HTML +=  "";
       HTML +="";
    pinMode(Wifiled,OUTPUT);
    delay(1000);
    Serial.begin(115200);
    WiFi.begin("LAPTOP","123456789");
    while(WiFi.status() != WL_CONNECTED)
    {
          Serial.print(".");
          digitalWrite(Wifiled,HIGH);
          delay(250);
          digitalWrite(Wifiled,LOW);
          delay(250);
    }
        digitalWrite(Wifiled,HIGH);
        Serial.println("wifi connected");
        Serial.println(WiFi.localIP());

        esp.on("/",sendHtml);
        esp.on("/process",sendform);
        esp.begin();
}
void sendform()
{
  esp.send(200,"text/html;",FORM);
}

void sendHtml()
{
  esp.send(200,"text/html;",HTML);

}

void loop()
{
   esp.handleClient();
   delay(200);
   char buffer[20]="";
   if(Serial.available()>0){
  //  char data=Serial.read();
   Serial.readBytesUntil('\n',buffer,20);
   Serial.println(buffer);
   }
}

ESP8266WebServer conflicts with ESPAsyncWebServer. Both cannot be used in the same program. Your code does not seem to use make use ESPAsyncWebServer or its features, so you could remove the lines #include <ESPAsyncTCP.h> and #include <ESPAsyncWebServer.h> from your code.

please add a clear, answerable question to your post

You've included <ESP8266WebServer.h> and <ESPAsyncWebServer.h>, it's one or the other, you can't have both. Hence you're getting error: 'HTTP_GET' conflicts with a previous declaration

having checked <ElegantOTA.h> src it does include all the mentioned libs in your .ino.
You should remove them and replace with  #include <ElegantOTA.h>. Then it works fine

it includes one of them based on a macro ELEGANTOTA_USE_ASYNC_WEBSERVER. so your answer doesn't solve anything


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?

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?

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)

source: Stack Exchange

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

sort: votes


text:
Arduino signed int can't fire timer > 15 seconds
I have tried to use different libraries like TimeAlarms , SimpleTimer, Timer and others. My goal is to call function periodically every minute or so. Each library works fine when repeat time is less than 15 seconds ( maybe greater) but 30seconds,45seconds, 60seconds doesn't work at all.
It seems something with internal timer.
I also use NRF24l01 Mesh library.
Please help to solve the problem
SOLVED
The issue was that I used int type instead of long. but I don't understand why 60 000 cannot be stored in int type which is 4 bytes (2^32)

Please post code, links to libraries, and any projects that you might have copied code from. Even better is to isolate the issue to a test sketch that others can run and understand the issue. If this is an issue with any of the libraries it will have to be solved there.

Thank you for the help. but the issue was that I used int type instead of long. but I don't understand why 60 000 cannot be stored in int type which is 4 bytes (2^32)

A code snippet had shown that. The take-away is that you should provide more info. BW: int is only 2 bytes on Arduino/AVR. Remember this is an 8-bit MCU.

And here is a link for more info on the AVR ABI https://gcc.gnu.org/wiki/avr-gcc.

An int on Arduino is only 16-bits (2 byte). It's also signed. So the maximum value is 2^15-1.

Please post an answer explaining this, I will accept it

Since you found out the solution yourself, you should add the answer yourself.

You could summarize what people told you, and then post your complete solution. You are allowed to answer your own questions. The maximum in an int on the Arduino is 32767 so I am a bit surprised 30 seconds didn't work.

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


text:
Serial communication doesn't work right after upload
I'm trying to communicate between a program on the Arduino Uno and a program on the PC via USB. I got it more or less working. Only problem is that it doesn't work when I run my PC program the first time after I upload the Arduino code via the Arduino IDE (version 2:1.0.5+dfsg2-4). It has some strange behaviour. Of course I could do some workaround, but I hope someone knows what the cause of this problem is and if there is a nice way to solve it.
This program should send back every byte it receives:
void setup () {
    Serial.begin(9600);
    while (!Serial) {}
}

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

This program sends the bytes 0 to 255 to the Arduino twice and outputs every byte it receives. It is written in Scala and uses the Java RXTX library for serial communication. I'm using Debian Linux.
import gnu.io.CommPortIdentifier
import gnu.io.SerialPort

object SerialTest extends App
{
    val portId = CommPortIdentifier.getPortIdentifier("/dev/ttyACM0")
    val port = portId.open(getClass.getName, 0).asInstanceOf[SerialPort]
    port.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE)

    val in = port.getInputStream
    val out = port.getOutputStream

    for (i <- 0 until 512) out.write(i)

    while (true) print(in.read + " ")
}

Instead of the 512 bytes it should receive, only around the last 44 bytes are received. Also, the first bytes the program receives are usually wrong. When I run the program for a second time, I get the desired result.
  Try 1: 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  Try 2: 186 58 93 157 221 29 151 167 183 199 215 231 247 7 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  Try 3: 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  Try 4: 221 29 151 167 183 199 215 231 247 7 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
Desired: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

If I let the program wait for 2 seconds anywhere between val portId = ... and writing to the output stream, it works. But there is be a better way, right?
(related question)

If you say that another question "is more or less the same" then your question should be closed as a duplicate.  To have a new question, you need instead to explain how yours  is different.

It is not clear what exactly your problem is, but you might consider either putting several seconds delay between the opening of the serial port and the attempt to communicate in order to allow the bootloader to time out, or better looking for an echo of test data before real data, or changing the serial port configuration to disable the modem status line manipulation on open which triggers reset, or change the wiring of the board or remove the bootloader.  Also fully configure the advanced serial port settings, rather than merely hoping whatever last used it set what you want.

Why have <while(!Serial)> when you use an UNO??

The only "better way" than a delay is a delay followed by a positive verification of communication and repeate if necessary until success, as already mentioned.   Or else to prevent the reset in the first place, but that is chancy as it depends on a modification that might not be made in every case.

@ChrisStratton How about this "disable the modem status line manipulation"? I have no idea what you're saying and Google isn't my friend on this one. If it might work, how should I do that?

http://arduino.stackexchange.com/questions/4078/why-does-my-arduino-seem-to-reboot-every-time-that-i-open-serial-monitor or http://arduino.stackexchange.com/questions/640/arduino-serial-port-reset-in-serial-monitor-python or http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection

The first time you open the serial port on the PC the Uno resets and enters the bootloader. Two seconds later your sketch starts running.
By then you have already sent a load of your data to the Uno which it ignores because it's not valid bootloader commands.
When your program exits it leaves the port in an different state (RXTX is crap and doesn't clean up after itself when you terminate a program). That state includes the DTR signal being disabled.
With the DTR signal disabled the Uno doesn't reset when you open the port. Thus when you run your program a second time the sketch is already running and everything works fine.
You can toggle the control of the DTR signal in Linux by setting or clearing the hupcl flag on the tty:
Disable DTR control:
$ stty -F /dev/ttyACM0 -hupcl

Enable DTR control:
$ stty -F /dev/ttyACM0 hupcl


text:
DS18B20 - Thermometer and Sensor discrepancy (varying)
This is a follow-up question from this other question
I followed of the user Jot (get the sensor away from the sun and use a delay in arduino program)
But the results are still varying.
I recorded the temperature measured in the sensor, the temperature measured using a mercury thermometer and calculated the difference. The data was collected within 8 days
Here's the data (sorted):
SENSOR  THERM   DIFF
32.69   31.25   1.44
32.00   30.25   1.75
31.94   30.50   1.44
31.87   30.50   1.37
31.44   29.50   1.94
31.00   29.00   2.00
30.75   29.00   1.75
30.50   29.00   1.50
30.44   28.80   1.64
30.31   28.90   1.41
30.25   28.75   1.50
29.87   28.00   1.87
29.81   28.00   1.81
29.81   28.00   1.81
29.81   28.25   1.56
29.75   28.20   1.55
29.69   28.00   1.69
29.56   27.00   2.56
28.75   27.25   1.50
28.69   27.00   1.69
28.56   27.00   1.56
28.44   27.00   1.44
28.25   26.80   1.45
28.00   26.50   1.50
28.00   25.50   2.50
28.00   25.00   3.00
27.75   25.50   2.25

The average difference is around +1.76°C but that's not linear, and as you can see there are fluctuation in the same sensor value, 28.00 has three associated temperatures(25.0, 25.5, 26.5).
I'm not sure what to do, if the difference was regular I could simply subtract that from the sensor readings, but it seems that it varies a lot(Min: 1.37°C, Max: 3.00°C)
Any ideas?

good use of data! it's actually not that far off for a $1 sensor. If you subtract 1-2C from the sensor, you'll be pretty close on almost every sample. try a DHT22 for more precision.

The best fit linear model would be THERM_HAT=SENSOR*1.10237- 4.81422 per  summary(fit<-lm(THERM ~ SENSOR,x)) in R.

Most readings are pretty consistent. There are only a few that are way of. But there could be some other factor that was influencing the reading. Maybe there was a draft.  Maybe you made multiple reading in a row which would slightly warm up the part....

This isn't so much an Arduino question, but you are asking how to do better than a simple offset.  The next level of complexity is to do an offset and scale.
If this is the best data you can get from your setup, a better calibration than just an offset would be finding the best offset and scale.  You can do this with your data in R with:
> x<- read.table(header=TRUE,text="SENSOR  THERM   DIFF
 32.69   31.25   1.44
 32.00   30.25   1.75
 31.94   30.50   1.44
 31.87   30.50   1.37
 31.44   29.50   1.94
 31.00   29.00   2.00
 30.75   29.00   1.75
 30.50   29.00   1.50
 30.44   28.80   1.64
 30.31   28.90   1.41
 30.25   28.75   1.50
 29.87   28.00   1.87
 29.81   28.00   1.81
 29.81   28.00   1.81
 29.81   28.25   1.56
 29.75   28.20   1.55
 29.69   28.00   1.69
 29.56   27.00   2.56
 28.75   27.25   1.50
 28.69   27.00   1.69
 28.56   27.00   1.56
 28.44   27.00   1.44
 28.25   26.80   1.45
 28.00   26.50   1.50
 28.00   25.50   2.50
 28.00   25.00   3.00
 27.75   25.50   2.25
 ")

summary(lm(THERM ~ SENSOR,x))

... to get:
Call:
lm(formula = THERM ~ SENSOR, data = x)

Residuals:
     Min       1Q   Median       3Q      Max
-1.05217 -0.16263  0.08482  0.21809  0.47224

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -4.81422    1.60425  -3.001  0.00602 **
SENSOR       1.10237    0.05369  20.533  < 2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.3816 on 25 degrees of freedom
Multiple R-squared:  0.944, Adjusted R-squared:  0.9418
F-statistic: 421.6 on 1 and 25 DF,  p-value: < 2.2e-16

... from which you can use the intercept and SENSOR parameters as an intercept and scale like:
therm_estimate = -4.81422 + 1.10237 * sensor;

You could plot the data in R like:
library(ggplot2)
ggplot(x,aes(x=SENSOR,y=THERM))+geom_point() +geom_smooth(method='lm')

Looking at the graph and data, your mercury thermometer is reading sometimes to the nearest 0.1th, and sometime to the 0.25th, and that is causing patterns in your data.  Maybe use a better, high-accuracy, calibrated lab thermometer if you want to be sure you aren't calibrating against something unreliable.

Can you buy a few more from other (more reliable) sellers ? Perhaps it is damaged. Did you accidently connect it wrong and it got very hot ?
There has been counterfeit DS18B20 sensors, but they were transistors that were re-labeled as DS18B20. Those didn't work at all.
You have not convinced me that you are only measuring the air temperature. Maybe there is still something nearby that causes it to get warmer. The 3 degrees difference is a lot. There must be a good reason for that, or else the DS18B20 is broken. How accurate is that mercury thermometer ?
I wrote before: "To be sure you can put it in distilled water at sea level at 0°C (water and ice cubes) and 100°C (boiling water)". That is what I did, out of curiosity. It turned out to be accurate.

Yes, I did the distilled water test. The mercury sensor is spot on on those temperatures. I was about to buy some others sensors but I can't be sure if those will be good either, buying from the internet is always a risk, I haven't damaged the sensor as far as I know.

Make sure there they are measuring the exact same physical temperature  -- pack the thermometer and sensor together in a little box or something to minimize air currents and stabilize the transients.   The mercury thermometer could also be non-linear in the range of interest, even it it matches at the 0,100C.  Lab-grade thermometers are graduated to the nearest 0.1C, rather than the 0.25C you are reporting.

Buy a few more to compare. The DS18B20 can return a temperature that is maximum 0.5°C below up to 0.5°C above the actual temperature. As far as I know every single one of them meets that specification.

The DS18B20s would be easy to automatically test and cull during production.   Much easier than consumer-grade liquid thermometers.


text:
Why does Arduino round off some integers but not others when my desktop PC does not do this?
I am writing (in C) some low level digit manipulation routines that convert int to float and vice versa for Arduino. I came across some puzzling behaviour with Arduino rounding some numbers but not others. So I located and extracted the offending code into a simple program which I compiled on desktop Linux PC with GCC and on Arduino - they give different results. Why?
Here are the programs. The goal is to take the float number 1.3140 and the float number 2.3140 and split them into two integers. In the first case I expect '1' and '3140' and in the second case I expect '2' and '3140' (the terminal '0' is important for my application).
The Arduino code:
void setup() {
double dnum,x,y;
uint16_t intpart,fracpart;

Serial.begin(9600);

dnum = 1.3140;

 x=modf(dnum,&y);
 intpart = (uint16_t)y;
 fracpart = (uint16_t)(10000.0*x);

Serial.println(dnum,4);
Serial.println(intpart);
Serial.println(fracpart);

}

and the output I get is:
1.3140
1
3140

Fantastic! Success. But hold on. If I change the hard-coded number to dnum = 2.3140 I get this:
2.3140
2
3139

What? Why did it round the second part down? Am I doing something fundamentally wrong? So I wrote a little C program for my PC (compiled with gcc). Here is the code:
#include<stdint.h>
#include<stdio.h>
#include<math.h>

int main (int argc, char *argv[])
{
 double dnum,x,y;
 uint16_t intpart,fracpart;

 dnum = 2.3140;

  x=modf(dnum,&y);
  intpart = (uint16_t)y;
  fracpart = (uint16_t)(10000.0*x);

 printf("Int_part = %u\nFrac_Part = %u\n",intpart,fracpart);

 return 0;
}

When run I get this result:
Int_part = 2
Frac_Part = 3140

Now that's what I expect - and to be thorough I also did the above C program with dnum = 1.3140; and I again got the 'correct' expected result:
Int_part = 1
Frac_Part = 3140

So why does the Arduino round the fractional part down when I convert it to an integer sometimes and not others?
I tried this on a genuine Arduino Uno, a clone Arduino uno and a clone Arduino nano and all give the same results. In 'theory' it could be some difference in the compiler tolerance to some coding impropriety I have done (gcc is more tolerant) but can anyone tell me what I did wrong and how to get the Arduino to behave (the way I want it to)? Thanks.

When you cast a floating point number to an integer, it always gets
rounded towards zero. If you want round-to-nearest behavior, you should
use the Arduino round() function.
As to the origin of the discrepancy you see, it comes from two facts:

The numbers you use are not exactly representable as floating point
numbers.
The double on an Arduino Uno is actually equivalent to a float
(32 bits only).

When you write a statement such as dnum = 1.3140;, the compiler stores
in dnum the floating point number that is closest to the decimal
number 1.3140.
Compare:
float32(1.3140) = 1.31400001049041748046875
float64(1.3140) = 1.31400000000000005684341886080801486968994140625
float32(2.3140) = 2.3139998912811279296875
float64(2.3140) = 2.31400000000000005684341886080801486968994140625

Out of these 4 examples, only float32(2.3140) is rounded down.

Very clear - thanks. I was unaware of the Arduino 32 bit limit but you educated me. I confirmed your answer also by making 'dnum' a float on my desktop PC program and it gives the same answers as my Arduino so practice and theory agree. I don't think round() will help me here, I just need to accept I can't get the precision I want on the Arduino (without additional 'arbitrary precision' code that will overflow my PROGMEM in my application).

@WildCat: If you only need 1+4 decimal digits or so, like in the example you give, a float should suffice, provided you get the factional digits with round(1e4*x). A float is worth about 7 decimal digits (FLT_EPSILON ≈ 1.19e-7).

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


text:
Modbus rtu server library which logs the requests
Kindly seek help. In my project I want to ‘fake’ a smart meter via Modbus rtu server for a solis inverter.
Somehow the solis realizes that I am faking him, so I am wondering which Modbus rtu server library you can recommend to allow me seeing what registers the solis is querying?
As of now I am using Emilianov Modbus-8266 library to run the rtu server/slave and platform is an esp32 with max3485.

So let me elaborate. Mine Solis simply sucks during low-light conditions. It can not decide if it shall charge or discharge, resulting in heavy oscialltion, jumping from feeding to much into grid and then taking to much from grid - peaks are ranging from +800Watt to -800Watt when it starts oscillating.
On the com-port you are true - here the solis acts as slave. But on its RS485 meter-port I understand the Solis acts as master and the smart meter is the slave.
My goal is to fake the smart-meter.
So topology would be:
Solis(master)-----(slave)ESP32(master)-----(slave)smartmeter
So I am looking for a solution that any read-request from the Solis is transparently passed-through to the smart-meter. But I want one register intercpeted (most likely total-active-power, which to mine understanding is the only value the solis want to bring back to zero in its control-loop).
As of now I can read the Solis and ther Seplos BMS via ESP32/RS485 successfully. I even have a running slave which I thought shall be good enough to get accpeted as fake-smart-meter, but it is not. The solis is asking for more register then my fake-solution is providing. hence mine ask, which ESP32 slave/server modbus library can print any request its arriving.
If my view is incorrect, kindly get me corrected.

What are you really trying to do? You need to read up on Modbus. First of all, you are confusing what is acting as a client and what is acting as a server. If you look at the general Modbus manual for Solis inverters, they act as slaves, or, in modern-speak, as servers. You need to setup a master - nowadays a 'client' - to query - poll - the server, not vice versa. You need to provide the code, the manual and the model of your specific inverter, and, possibly, the hardware setup. Why don't you try polling the inverter with something like a USB-RS485 dongle first with ComTest or Modbus Poll?

Try looking at this as a starting point
https://github.com/straga/Smart-Meter-Gateway
My approach has been different but will come back to this if my current approach fails.

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

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


text:
I'm using nRF2401 and in my transmitter and receiver the Rx is not blinking and Tx is blinking; why does Rx not blink?
I did a search on the meaning of RX and TX and it seems TX means sending data and RX means receiving data.
So when my transmitter is turned off, my receiver looks like this and it works with a battery:

and when I turn on the transmitter my receiver looks like this:

So Tx is blinking and I'm confused, because Rx is not blinking and I think I receive nothing.
receiver code:
#include <RF24.h>
#include <SPI.h>

int speedpin1=5;
int dir11=3;
int dir12=7;

int speedpin2=A4;
int dir21=8;
int dir22=A3;

int speedpin3=A2;
int dir31=A1;
int dir32=A0;

int speedpin4=2;
int dir41=4;
int dir42=6;

int mspeed;

const byte CE = 9;
const byte CS = 10;

int data[1];

RF24 Radio(CE,CS);
const byte address[6]="00001";

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

pinMode(speedpin2,OUTPUT);
pinMode(dir21,OUTPUT);
pinMode(dir22,OUTPUT);

pinMode(speedpin3,OUTPUT);
pinMode(dir31,OUTPUT);
pinMode(dir32,OUTPUT);

pinMode(speedpin4,OUTPUT);
pinMode(dir41,OUTPUT);
pinMode(dir42,OUTPUT);

Radio.begin();
Radio.openReadingPipe(1,address);
Radio.startListening();
}

void loop() {
  // put your main code here, to run repeatedly:
if(Radio.available()){
  Radio.read(data,sizeof(data));
  if (data[0]>131){

    digitalWrite(dir41,LOW);
    digitalWrite(dir42,HIGH);

    analogWrite(dir31,0);
    analogWrite(dir32,255);

    digitalWrite(dir21,HIGH);
    analogWrite(dir22,0);

    digitalWrite(dir11,HIGH);
    digitalWrite(dir12,LOW);

    mspeed=255;

    analogWrite(speedpin1,mspeed);
    analogWrite(speedpin2,mspeed);
    analogWrite(speedpin3,mspeed);
    analogWrite(speedpin4,mspeed);
    Serial.println(mspeed);

  }
  if (data[0]<131){

    digitalWrite(dir41,HIGH);
    digitalWrite(dir42,LOW);

    analogWrite(dir31,255);
    analogWrite(dir32,0);

    digitalWrite(dir21,LOW);
    analogWrite(dir22,255);

    digitalWrite(dir11,LOW);
    digitalWrite(dir12,HIGH);

    mspeed=255;

    analogWrite(speedpin1,mspeed);
    analogWrite(speedpin2,mspeed);
    analogWrite(speedpin3,mspeed);
    analogWrite(speedpin4,mspeed);
    Serial.println(mspeed);

  }
  if (data[0]==131){

    mspeed=0;
    analogWrite(speedpin1,mspeed);
    analogWrite(speedpin2,mspeed);
    analogWrite(speedpin3,mspeed);
    analogWrite(speedpin4,mspeed);
    Serial.println(mspeed);

  }

}

transmitter code:
#include <RF24.h>
#include <SPI.h>
const byte CE = 9;
const byte CS = 10;
int jpin=A0;
int datax;
int data[1];

RF24 Radio(CE,CS);
const byte address[6]="00001";
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
Radio.begin();
Radio.setRetries(5,10);
Radio.openWritingPipe(address);
}

void loop() {
  // put your main code here, to run repeatedly:
datax=analogRead(jpin);
datax=map(datax, 0, 1023, 0, 255);
data[0]=datax;
Serial.print("data x: ");
Serial.println(data[0]);
Radio.write(data,sizeof(data));

}

I'm using nRF2401 and in my transmitter and my receiver the Rx is not blinking and Tx is blinking; why does Rx not blinking?
I also don't know that why does Tx in my receiver not blinking when I move the joystick in my transmitter.
I can control my motors only a few times with a Joystick and after that the Tx in my receiver does not blink and then my motors are keep working or they stop and I can't control them.

Edit

don't pay attention to lights ... examine the transmitted data and examine the received data ... if the data is the same, then your devices are operational

why did you delete your previous question and added this one? ... the two are almost the same ... if you want to make changes then edit your question instead

you are making things difficult for yourself ... add debugging code, so that you know what is being transmitted, what is being received, and how the received data is being decoded

How do you connect your nRF2401 and Arduino Nano? A circuit diagram would help to confirm whether the connection is correct or not as the first step of debugging.

@hcheung
I added the information you asked for to my question.

The wiring looks good. So your question is related to why RX not light-up or you can't receive the data? The RX is not light-up because the TX/RX pins are related to Serial port, has nothing to do with the communication between Arduino and nRF24L21 is via SPI, not via Serial port. TX light-up because you had Serial.print(). If you question is not receiving data (not receive correctly), add Serial.println(data) before if (data[0]>131){` to find out what have been received.

@hcheung
Yes, I can't receive data; I mean I receive the position of the joystick and then I can't receive it after I move the joystick multiple times; I mean the serial monitor does not show me the current position of the joystick.
SO I can't loop what I achieved. To solve this I should reopen the serial monitor and again after a while I receive nothing (because I moved the joystick multiple times) and then again I should close the serial monitor and open it again to receive data.

We've got multiple questions here, so:
Why is TX/RX blinking weirdly?
The RX and TX LEDs on the Arduino Nano are connected to the RX0 and TX1 pins: they show activity on the Serial-over-USB port that connects your Arduino to the PC.
So, every time you receive data, you do a Serial.print(), transmitting text to the PC (where you can see that text in the Serial monitor). And that is what's showing up in the RX/TX LEDs: the text you send over the serial line to the PC. If you want to get RX blinking in this setup, just enter some text in the Serial monitor's input box and send it. The TX LED should blink shortly, then (maybe too short to be noticeable).
Reusing those LEDs to show activity on the wireless transceiver by writing to the RX0/TX1 pins would mean that you'll lose the Serial monitor, i.e. Serial.print() would no longer be possible. Not recommended.
Your best option would be to introduce your own LEDs as an activity monitor. Just add an LED in series with an 1K resistor to pins D11 and D12 each (which are the MOSI and MISO lines of the SPI interface, i.e. the equivalent of RX and TX of a serial interface).
In other words, add these components:
  D11 --> -LED+ --> 1K resistor --> 5V
  D12 --> -LED+ --> 1K resistor --> 5V

Why does my transmission stop?
That's harder to see, but: I think you're using the RF24 library interface wrong.
According to the code example "Transmitter Lv2" on this page, Radio.read() and Radio.write() expect a reference to the data array, so you'd need to use Radio.read(&data, sizeof(data)) and Radio.write(&data, sizeof(data)) (note the ampersands).
It also may be that your transmitter is transmitting faster than your receiver can accept data, so you could try and add a delay(5) in the loop() of your transmitter.

I used this video for coding.
https://youtu.be/fbR_j3y_TC4?t=245

@dagh You also could try and use some of the code here: https://www.deviceplus.com/arduino/nrf24l01-rf-module-tutorial/ -- especially the RF24 configuration (l.50..72) and failure detection and reinitialization (l.91..105). That might give you additional insight.


text:
Turning off a LED
I am trying to make 2 alarms for 2 different times using 2 LED's which should turn on when the time corresponds to the set time and then if a pushbutton is pressed, the LED should turn off. For the first alarm, the first LED can be turn off with the pushbutton, instead for the second alarm, the second LED is turning on, but if the pushbutton is pressed is will not turn off, even though is the same code. What can I do to turn off the second LED?
#include <RTClib.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
int nowHr, nowMin, nowSec;
RTC_DS3231 rtc;

int h1 = 15;
int m1 = 51;
int h2 = 15;
int m2 = 52 ;
int pin_buton1 = 8;
int stop_buton =9;
int state_stop_buton = 0;

int led1_pin = 6;
int state_led = LOW;
int pushpressed = 0;

int led2_pin = 7;
int state_led2 = LOW;

void setup()
{

  Wire.begin();
  //rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  rtc.adjust(DateTime(2021, 03, 27, 15, 50, 50));

  lcd.backlight();
  lcd.begin(16, 2);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Welcome To Our");
  lcd.setCursor(0, 1);
  lcd.print("device");

  pinMode(pin_buton1, INPUT);
  pinMode(stop_buton, INPUT);
  pinMode(led1_pin, OUTPUT);
  pinMode(led2_pin, OUTPUT);
  delay(2000);
  Serial.begin(9600);
}

void loop() {
  timeScreen();
  first_alarm();
  stopPins();
  second_alarm();
  stopPins2();

  state_stop_buton = digitalRead(stop_buton);

}

void timeScreen() {

  DateTime now = rtc.now();
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Time:");
  lcd.setCursor(6, 0);
  lcd.print(nowHr = now.hour(), DEC);
  lcd.print(":");
  lcd.print(nowMin = now.minute(), DEC);
  lcd.print(":");
  lcd.print(nowSec = now.second(), DEC);
  lcd.setCursor(0, 1);
  lcd.print("Date: ");
  lcd.print(now.day(), DEC);
  lcd.print("/");
  lcd.print(now.month(), DEC);
  lcd.print("/");
  lcd.print(now.year(), DEC);
  delay(500);

}

void stopPins() {
  if (state_stop_buton == 1) {

    pushpressed =1;
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("first message ");
    lcd.setCursor(0, 1);
    lcd.print("was read");
    delay(1200);
    lcd.clear();
  }
}

void startBuzz() {

  if (pushpressed == 0) {

    if (state_led == LOW) {
      state_led = HIGH;
      digitalWrite(led1_pin, state_led);

    }
  }
  else if (pushpressed == 1) {

    state_led = LOW;
    digitalWrite(led1_pin, state_led);
  }
}

void first_alarm() {
  DateTime t = rtc.now();
  if (int(t.hour()) == h1 && int(t.minute()) == m1) {

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("first ");
    lcd.setCursor(0, 1);
    lcd.print("text");
    startBuzz();
    delay(5000);

  }
}

//

void stopPins2() {
  if (state_stop_buton == 1) {

    pushpressed = 1;
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("second message ");
    lcd.setCursor(0, 1);
    lcd.print("was read ");
    delay(1200);
    lcd.clear();
  }
}

void startBuzz2() {

  if (pushpressed == 1) {

    if (state_led2 == LOW) {
      state_led2 = HIGH;
      digitalWrite(led2_pin, state_led2);

    }
  }
  else  if (pushpressed == 0 ) {
    state_led2 = LOW;
   digitalWrite(led2_pin, state_led2);
 }
}

void second_alarm() {
  DateTime t = rtc.now();
  if (int(t.hour()) == h2 && int(t.minute()) == m2   ) {

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("second");
    lcd.setCursor(0, 1);
    lcd.print("text");
    startBuzz2();
    delay(5000);

  }
}

1. pushpressed gets set, but never reset.
It's set in stopPins() and stopPins2() if the input is HIGH. Since it's never reset back to zero, once it's been set, the logic in startBuzz and startBuzz2 will follow a single pass. You've created a latched switch.

General Stuff

2. Inconsistent naming: makes reading code harder
Pick snake_case or camelCase or smashitalltogether (not recommended) and stick with it :) Same goes for the "types" of variables: some things are named xxx pin xxx, some are named xxx state xxx, some aren't. It's clearer when same-things are named-same.
3. Duplication: makes understanding code harder
Along with the naming, the (essentially) duplicated code makes tracking down problems harder, as you've noticed trying to debug this problem. There are a ton of ways to go about shrinking the code down to make it understandable. The nutshells are to identify the differences in similar code, and to do less at once.
(And if you want to take it to its logical conclusion, wrapping up each alarm in a class would eliminate all duplication and most function parameters :)

Annoying Diversion of Explanation

Let's look at startBuzz and startBuzz2.
void startBuzz() {
  if (pushpressed == 0) {
    if (state_led == LOW) {
      state_led = HIGH;
      digitalWrite(led1_pin, state_led);
    }
  } else if (pushpressed == 1) {
    state_led = LOW;
    digitalWrite(led1_pin, state_led);
  }
}

void startBuzz2() {
  if (pushpressed == 1) {
    if (state_led2 == LOW) {
      state_led2 = HIGH;
      digitalWrite(led2_pin, state_led2);
    }
  } else if (pushpressed == 0) {
    state_led2 = LOW;
    digitalWrite(led2_pin, state_led2);
  }
}

The only things different here are the LED pin, and the LED state. Let's normalize our naming so things become clear, using startBuzz as the example. We'll also assume pushPressed can only be 0 or 1 (HIGH or LOW):
void startBuzz() {
  if (pushPressed == LOW) {
    if (led1State == LOW) {
      led1State = HIGH;
      digitalWrite(led1Pin, led1State);
    }
  } else {
    led1State = LOW;
    digitalWrite(led1Pin, led1State);
  }
}

We can make this work for either LED by doing two things: taking in the pin and current state, and returning the new state. Why return the new state instead of setting it here? It makes the mainline code easier (and avoids passing a reference).
void startBuzz(int ledPin, int ledState) {
  int newLedState = ledState;

  if (pushPressed == LOW) {
    if (ledState == LOW) {
      newLedState = HIGH;
      digitalWrite(ledPin, newLedState);
    }
  } else {
    newLedState = LOW;
    digitalWrite(ledPin, newLedState);
  }

  return newLedState;
}

Then when we call startBuzz or startBuzz2 we replace the current code with:
led1State = startBuzz(led1Pin, led1State);

We're not done.
Since we keep the original ledState we can remove the duplicated calls to digitalWrite; at worst we'll have a superfluous write when pushPressed != LOW && ledState != HIGH.
Since all conditions except one lead to a LOW value we don't even need to keep the original state. And since it's two conditions to flip it HIGH we can combine those. And if we pull out the digitalWrite we're really just calculating the next state--that doesn't rely on the LED pin.
void getNextLedState(int ledState) {
  return (pushPressed == LOW && ledState == LOW) ? HIGH : LOW;
}

And the callsites look like this:
led1State = getNextLedState(led1State);
digitalWrite(led1Pin, led1State);

Similarly for the alarms: create a function called checkAlarm that takes in hrs and mins and returns a boolean. In the loop call checkAlarm(h1, m1) and if true, call runAlarm1(). (Even that could be shrunk further, but you get the idea.) stopPins differs only in the strings written to the LCD. And so on.

Well that turned into a lot of words. This is what happens when I'm in the middle of writing book.

thank you very much for you response, I think I have to read several times your instructions and then apply them. Good luck with you book!

@biancaaa I'll make a similar circuit and post my code somewhere and post a link. Not soon enough to help you, bit hey :)

sorry if i bother you , but i followed your advice about reseting the stop button, but i can't handle it. Before the end of void startBuzz i wrote "pushpressed = 0;", but it is still not working @Dave Newton

@Biancaaa Maybe post your current code in a gist or here; I can take a look in an hour or two.

'
void startBuzz() {
if (pushpressed == 0) {
if (ledState == LOW) {
  ledState = HIGH;
}
digitalWrite(ledPin, ledState);

}
else if (pushpressed == 1) {
ledState = LOW;
digitalWrite(ledPin, ledState);

}
pushpressed = 0;
}
'

so, this is the edit which i made in the code. I am new in this domain (arduino), but I will pay attention to the advices you explained above about the functions. If i set pushpressed to 0 in function startBuzz, the led for the first alarm will not turn off definitive when the pushbutton is pressed, instead, the second led for the second alarm can be turn off when the same pushbutton is pressed.


text:
Arduino water pump not working and beeping
I’m new to Arduino and am trying to build a plant watering system without much knowledge on the subject. But my water pump is not working as I expected it to.
I wanted to keep it simple so I bought a Arduino Motor Shield for my Arduino Uno R3. I’m using a motor rated at 3-9V (motor is shown below), I’ve tried two different DC adaptors plugged into the power supply port on the arduino, 12V 1.5A and 12V 2A, even though the motor is rated at 9V, I’ve read that I need a 12V adapter to power the motor shield.
http://www.mabuchi-motor.co.jp/cgi-bin/catalog/e_catalog.cgi?CAT_ID=rs_360sh
The first problem is If I run the motor at full speed, analogWrite(3, 255), it sounds like its going to explode, so I’m trying to run it at a lower speed. But If use values anywhere below 170 the motor will not run and will only make a beeping sound.
Secondly, regardless of the PWM value I run the motor at, the chip gets very hot very quickly.
My question is, why can’t I run the pump at lower PWM values, and why is it getting so hot?
If I bought a 12V water pump and used the same setup, would I not have any of these problems?
EDIT:
an update...
it seems to basically work now. i have a feeling it wasn't working great because I was previously using a powerbar
It will run on max power PWM(255) for about a minute, and then stop working, which is okay. It will stop and then the motor shield lights will start blinking. Does anybody have any guesses what is happening? The motorshield chip is a little hot, so overheating is a possibility. Or is there not enough current ?
video
https://www.youtube.com/watch?v=xdxf3f_Svqs
void setup() {

//  //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin
}

void loop(){
  //forward @ full speed, A
  digitalWrite(12, HIGH); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 170);   //Spins the motor on Channel A at a speed. approx 90 is min

  delay(3000);

  digitalWrite(9, HIGH); //Engage the Brake for Channel A

  delay(1000);

}

I’ve read that I need a 12V adapter to power the motor shield. That's incorrect; the product page says 5V to 12V.

the chip gets very hot very quickly - which chip?

Would that be the voltage regulator chip by any chance?

@NickGammon it is the main L298P chip

Of course it sounds like it's going to explode if you're powering a 9V motor with 12V. This could cause a much greater current draw than you would expect as the relationship between voltage and current is unlikely to be linear once you go out of the manufacturer's specifications, which is why the driver gets hot.

@CharlieHanson okay that makes sense, i kind of ignored that. Is there a way I can limit the voltage to my motor, like a sort of resistor before my motor

Yes you can use a resistor, but that will get hot instead. The 'unrequired' energy that is supplied by the power supply has to go somewhere - either as heat in the driver or heat in a voltage-limiting resistor. Your best solution is to change to a 9V supply.

Regarding your motor just making high pitched noise (beeping) I would say that you are not supplying enough power to your motor for it to pull in the load and get rotating, you might try to first get it started by a higher power setting (PWM) and then when it's running see how far down you can set it before it stalls (stops).
I don't belive a 12V pump would work any different.
As to the motor and L298 chip getting hot, this is sort of normal and in some cases would require som way of dissipating this heat. A heatsink might be an option.
If you were to overheat the L298 it will shut down before being destroyed (it should).

Okay thanks, does that mean I should supply more voltage or current ? It just seems strange considering the water pump is rated at 3-9V

Neither, By power you have to take into considerment that you are using PWM. That means that if your motor at 12V would draw lets say for ease of calculation 1A at 100% pwm it would draw 12W (Watt) by lowering your PWM ratio to 50%, your motor will still draw 1A at 12V but only half the time.

The motor runs smoothly and reliably when I connect it straight into the VIN pin using a 9V adapter. But when I drive it through the motor shield problems occur.
Ideally I would want to drive the motor shield/motor with a 9V power adapter so that I can run the motor at max PWM (255), but there isn't enough power if I do that because the motor shield also needs power.

I thought to myself, maybe I'll just run the motor at max power (12V) for the project, I don't need it to be on that long so it's ok. But as I was trying to test that out, the motor stopped responding, the lights on motor shield were blinking and I could hear a ticking sound.
So…… is there any solution to this apparent "electrical noise" ?

Check voltages at 100%, you might have burned the motor.

@HansNever no it's not burnt, it just stops responding after about a minute. if i wait 10 minutes, the motor will run for another minute and then stop


text:
How to break out of a loop if it is contained in a function
I am trying to figure out how to break out of a loop if it is being called from a function.  I have a similar post, here, that I've decided to do something with the Arduino onboard LED, to isolate it from the NeoPixels Library and it is giving me the same issue.  The answers I have received there have been helpful but something is still puzzling me.
Using serial from the Arduino to my PC, the below "Example 1" code, can break out of a local loop successfully (and immediately) when the Arduino received keyboard input with key "2".
//Example 1
int ledPIN = 13; // sets up onboard LED on Arduino located near PIN13
char rx_byte = 0; // variable to hold serial input from console;
int count = 0; // placeholder for incrementing during debugging of loops

void setup() {

  Serial.begin(115200);

  pinMode (ledPIN, OUTPUT);

}

void loop() {

  if (Serial.available() > 0) {    // is a character available?
    rx_byte = Serial.read();       // get the character

    // check if a number was received
    if ((rx_byte >= '0') && (rx_byte <= '9')) {
      switch(rx_byte) {
        case '1':
          Serial.println("You've entered: 1");
          for (int i; i <=5000; i++) {
            rx_byte = Serial.read(); // must read character again
            if (rx_byte == '2') {
              Serial.println("Quitting...");
              digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
              break;
            }
            else {
              Serial.println(i);
              digitalWrite(ledPIN, HIGH); // turn LED pin 13 on
            }
          }
          digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
          break;

      }
    } // end: if (Serial.available() > 0)
  }
}

From what I've been told, you shouldn't necessarily perform a "serial.read()" inside of a loop.  However, if I do not include that in the for loop, it does not allow for any further input.
Since "Example 1" works, I am now trying to accomplish the same principle, but, this time, when calling a function which contains its own independent loop of course.  I've spent countless hours trying to resolve this.
I was under the impression that I could use a while loop within "void loop()" and call in a function which also contains a loop, then be able to break it from the while loop.  When attempting this various ways, the for loop within the function seems to blink the LED 10+ times and totally ignores my keystroke "2" to break the loop and is now infinite.  I know I could just put the for loop up in "void loop()" and it would work to break out similar to Example 1, but I'm sure it can be broken from a function as well.  I will eventually have similar functions that will contain parameters.
How would I go about doing this the correct way?
Below is "Example 2" that I am trying to break from the function.  I'm assuming it's an issue with doing it from the while loop?
Again, any assistance is greatly appreciated.
//Example 2
int ledPIN = 13; // sets up onboard LED on Arduino located near PIN13
char rx_byte = 0; // variable to hold serial input from console;
int count = 0; // placeholder for incrementing during debugging of loops

void setup() {

  Serial.begin(115200);

  pinMode (ledPIN, OUTPUT);

}

void loop() {

  if (Serial.available() > 0) {    // is a character available?

    rx_byte = Serial.read();       // get the character
    boolean forceTerminate = false;

    // check if a number was received
    if ((rx_byte >= '0') && (rx_byte <= '9')) {

      switch(rx_byte) {
        case '1':
          Serial.println("You've entered: 1");
          while(forceTerminate == false) {
            rx_byte = Serial.read(); // must read character again
            if (rx_byte == '2') {
              Serial.println("Quitting...");
              digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
              forceTerminate = true;
              break;
            }
            else {
              //count = count+1;
              //Serial.println(count);
              blinkPIN13(); // FUNCTION: blinkPIN13
            }
          }
          digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
          break;

      } // end: switch(rx_byte)

    }

  } // end: if (Serial.available() > 0)

}

/************************************************************************************
 * FUNCTION for blinking LED located on PIN 13 to the state of ON(1)/OFF(0)
 ************************************************************************************/
void blinkPIN13() {

  for (int i; i <=10; i++) {
    digitalWrite(ledPIN, HIGH);
    delay(1000);
    digitalWrite(ledPIN,LOW);
    delay(1000);
  }

}

To tell a function-caller what to do when the function exits, have the function return a status value.  You can do this at multiple levels.  For example:
byte doOtherStuff(int howLong) {
  digitalWrite(ledPIN, HIGH);
  delay(howLong);
  if (doneDoing()) return false;
  digitalWrite(ledPIN,LOW);
  delay(howLong);
  return !doneDoing();
}

void loop() {
  while(doMore) {
    doStuff();
    for (byte i=0; i<9 && doMore; ++i) {
      doMore = doOtherStuff(1234);
    }
    if (doMore) {
      doMoreOtherStuffInWhile();
    }
  }
}


text:
How to get and interpret digital accelerometer data?
I am trying to connect an Arduino to a digital accelerometer. The Arduino receives commands from a mobile app and transmits over Bluetooth through hardware serial.
I also posted this question here.
Code:
 #include < SPI.h >

const int X8 = 0x06;
const int Y8 = 0x07;
const int Z8 = 0x08;

/*
bits
1 0  mode 00: standby, 01: measurement
5     1: spi 3 wire, 0: 4 wire
4      self test
3     2 glevel: 01 2g
1 0  mode, 00 standby, 01 measurement
*/
const int MODE = 0x16;

const int STATUS = 0x09;

//7 digital filter band width, 0 62.5 Hz, 1 125 Hz
const int CONTROL = 0x18;

bool isTesting = false;

const int chipSelectPin = 7;

void setup() {
    Serial.begin(9600);
    SPI.begin();
    pinMode(chipSelectPin, OUTPUT);

    //set up standby, spi 4 wire, 2g range,
    writeRegister(MODE, 0x04);

    //set up speed
    writeRegister(CONTROL, 0x00);

    delay(100);
}
void loop() {
    if (getSerial() == 't') {
        isTesting = true;
        writeRegister(MODE, 0x05); // 0000 0101- 0001 0101 0x15
        testing();

    }

}
void testing() {
    while (isTesting) {
        if ((readRegister(STATUS) & 1) == 1) {
            Serial.print((char) readRegister(X8), DEC);
            Serial.print("x");
            Serial.print((char) readRegister(Y8), DEC);
            Serial.print("y");
            Serial.print((char) readRegisterChar(Z8), DEC);
            Serial.print("z");
        }

        if (getSerial() == 'u') {
            isTesting = false;
            writeRegister(MODE, 0x04);
        }
    }
}
char getSerial() {
    if (Serial.available()) {
        char c = Serial.read();
        return c;
    }
    return 'x';
}
byte readRegister(byte thisRegister) {
    byte inByte = 0;
    SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(thisRegister << 1);
    inByte = SPI.transfer(0x00);
    digitalWrite(chipSelectPin, HIGH);
    return inByte;
}
char readRegisterChar(byte thisRegister) {
    char inChar = 0;
    SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(thisRegister << 1);
    inChar = SPI.transfer(0x00);
    digitalWrite(chipSelectPin, HIGH);
    return inChar;
}
void writeRegister(byte thisRegister, byte value) {
    SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(128 | thisRegister << 1);
    SPI.transfer(value);
    digitalWrite(chipSelectPin, HIGH);
}

The sensor allows for data values of 10 bits but for simplicity I am getting only the 8 bit data. The data received when the sensor is on a flat surface is:

x  y   z
5 -11 74
4 -19 74
2 -9 69
0 -8 68
7 -16 68
7 -11 73

When the self test is run, the results are:

-5 -20 122
-4 -22 122
-1 -20 123
-4 -20 123
-5 -21 121
-3 -18 123
-8 -22 127

From the data sheet: "When the self-test function is initiated through the mode control register ($16),
accessing the "self-test" bit, an electrostatic force is applied to each axis to cause it to deflect. The Z-axis is trimmed to deflect
1g."

Is the data correct? How is it interpreted? If the z data during self test is 1g, shouldn't it have the same magnitude as when it is on a flat surface?
I adapted to code to get the 10 bits of data:
const int X10_LSB = 0x00;
const int X10_MSB = 0x01;
const int Y10_LSB = 0x02;
const int Y10_MSB = 0x03;
const int Z10_LSB = 0x04;
const int Z10_MSB = 0x05;

//[...]

void testing() {
        while (isTesting) {
            if ((readRegister(STATUS) & 1) == 1) {

                int xData = (readRegister(X10_MSB) << 8) | readRegister(X10_LSB);

                // checks if bit 9 is 1 and sign extends
                if ((xData & 512) == 512)
                    xData = (0b1111110000000000 | xData);
                int yData = (readRegister(Y10_MSB) << 8) | readRegister(Y10_LSB);
                if ((yData & 512) == 512)
                    yData = (0b1111110000000000 | yData);
                int zData = (readRegister(Z10_MSB) << 8) | readRegister(Z10_LSB);
                if ((zData & 512) == 512)
                    zData = (0b1111110000000000 | zData);

                Serial.print(xData);
                Serial.print("x");
                Serial.print(yData);
                Serial.print("y");
                Serial.print(zData);
                Serial.print("z");

            }

The outputs for 2g measurement is:

4 246 -183
5 245 -183
5 245 -182
6 245 -181

For the self test:

252 -20 -134
253 -21 -133
253 -21 -135
253 -20 -135

the values for 8 and 10 bits of data don't correspond. What am I doing wrong?
Update: I rewrote the code to get the 10 bits of data with the LSB bits fisrt as per a comment:
Code:
     int xData =(readRegister (X10_LSB));
        xData = xData | (readRegister (X10_MSB)<<8);
        xData = xData << 6;
        int yData =(readRegister (Y10_LSB));
        yData = yData | (readRegister (Y10_MSB)<<8);
        yData = yData << 6;
        int zData = (readRegister (Z10_LSB));
        zData = zData | (readRegister (Z10_MSB)<<8);
        zData = zData << 6;

        xData /= 64;
        yData /= 64;
        zData /= 64;

The results for the sensor when on a flat surface:

0 -4 71
4 -11 70
5 -13 70
2 -12 70

The results when self-test is applied:

-2 -19 123
-2 -19 122
-4 -20 122
-3 -21 122

Why would the 8 bit and 10 bit results return similar values during a self test (around 128)? Should the 10 bit value be 4X greater?

Why didn't you tell us that it is about a MMA7455L sensor and that you are also asking the question here: http://forum.arduino.cc/index.php?topic=465471.0
Have you tried a library that is known to be working well ? You could try to shift the 10 bits 6 bits to the left for a 2's complement 16 bit integer. You read MSB first, but according to the datasheet: "XOUTH should be read directly following XOUTL read".

Have you tried this link sketch from the Arduino Playground?

The sensor allows for data values of 10 bits but for simplicity I am getting only the 8 bit data

you are using it in 2g mode, so you have only 8bit of data.

The data received when the sensor is on a flat surface is:

this is correct. You have a 8bit range (256 value, from -128 to +128) that map a range from +2g to -2g. So we have 256lsb/4g = 64lsb/g.
Motionless, the lenght of the gravity vector (sqrt(xx+yy+z*z)) must be close to 64. Of corse you need some offset and non-linearity calibration but the data seems fine.
Also if you look at the piece of datasheet you posted in table "Sensitivity", you will see they call the LSB "count", and they are in the range we calculated!

When the self test is run, the results are:

again this is correct, if your sensor is flat in way the Gravity apply on the Z; what you see is the normal gravity (64) summing up to the self-test offset (64), giving you a nice ~128

I adapted to code to get the 10 bits of data:
Why would the 8 bit and 10 bit results return similar values during a self test (around 128)? Should the 10 bit value be 4X greater?

to use 10bit, you must set the full scale range to +-8g. If you look at the piece of datasheet you posted, table "Output Signal", you see how many bit are avaiable for each range.
If you think about it, how does the sensor know if you want to read 8 or 10bit? (remeber the DS say you must read the low register BEFORE high register!) if you read only 8bit, you would be loosing the 2msb, one rapresenting the sign and the other the most important bit that can change your result by 2^9=512
btw also you first 10 bit conversion is wrong as you flip the bit for 2's complement, but does nothing to the value bit.
The solution with bit shitf of 6 follow by divising is working but a bit strange to see. I would go for something more "standard" like
int xData = readRegister (X10_LSB) | (readRegister (X10_MSB) << 8);
if (xData | 0b0000 0010 0000 0000){ //if negative
    //keep 9 bit raspresenting the value and multiply by -1 to keep the sign
    xData = (xData & 0b0000 0001 1111 1111) * -1;
}


text:
How to fix compilation error for tone() using same timer as other function
I am trying to integrate tone() with the open source program for the Amped heart rate monitor. The error:

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `__vector_7'
sketch\PulseSensorAmped_Arduino_1dot4.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

The program comes in three files. PulseSensorAmped_Arduino_1dot4.cpp I don't think references any timers but references a function in another file with this code:
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED

This uses timer 2; but isn't the error for timer 1? The tone() reference page says that tone interferes with pins 3 and 11. Is there any way to fix this?
references:
https://www.arduino.cc/en/Reference/Tone
https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino

In  my case, IR library was conflicting with Tone. Nick's solution works perfectly.

It looks like the Tone library uses Timer 2, and it looks like your other code also uses Timer 2, hence the error message. Vector 7 would be the TIMER2_COMPA_vect (Timer 2 compare "a").
Pins 3 and 11 are from Timer 2.
I wrote a small library that generates tones using the hardware PWM and not interrupts. You can read about it here.
Example code:
#include <TonePlayer.h>

TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

void setup()
  {
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  tone1.tone (220);  // 220 Hz
  delay (500);
  tone1.noTone ();

  tone1.tone (440);
  delay (500);
  tone1.noTone ();

  tone1.tone (880);
  delay (500);
  tone1.noTone ();
  }

void loop() { }

Library can be downloaded from http://www.gammon.com.au/Arduino/TonePlayer.zip
This uses Timer 1 (so that won't interfere with Timer 2) and no interrupts.

For anyone wondering, when defining a tone, all those codes seem to be the address of the single workable pin on Uno/Mega (pin 9). For Mega 2560 there are 3 different pins and TonePlayer.cpp file has the examples.

That's true, thanks for the clarification. In the source are examples of choosing between 3 pins (which are the outputs of the three hardware timers).


text:
How to skip the first line and output the second?
My question is related to my previous question.
These encoder programs outputs two line per pule/tick.
Here is the part of the code I want to use:
void loop()
{
    // Read the status of the inputs
    debouncerA.update();
    debouncerB.update();

    int8_t EncVariation = 0;

    if (debouncerA.rose())
    { // if input A changed from low to high, it was CW if B is high too
        EncVariation = (debouncerB.read()) ? 1 : -1;
    }
    else if (debouncerA.fell())
    { // if input A changed from high to low, it was CW if B is low too
        EncVariation = (debouncerB.read()) ? -1 : 1;
    }
    else if (debouncerB.rose())
    { // if input B changed from low to high, it was CCW if A is high too
        EncVariation = (debouncerA.read()) ? -1 : 1;
    }
    else if (debouncerB.fell())
    { // if input B changed from high to low, it was CCW if B is low too
        EncVariation = (debouncerA.read()) ? 1 : -1;
    }
//
  if (EncVariation != 0) {

        encoder0Pos = encoder0Pos + EncVariation;

        int degs = (encoder0Pos * 6) % 360 ;

        if(degs<0){ degs = 360 + degs; }

        Serial.println (degs);
   }
}

For three inputs/ticks this outputs like:
6
12
18
24
30
36
But I only need the second ones like:
12
24
36
How can I do that?
(I need it to send the relevant data do a PC.)
I spend so long time on it couldnt find any solution.

This line looks like its a mistake if(degrees<0){ deg = 360 + degs; } is it correct?  You do the calculation of degrees and then start using degs.

was a mistype now i corrected

IF and only IF you want exactly what you have asked for which is alternate lines not to be output then this is a very crude and quick solution.
Outside of loop() add this declaration:
bool skipNextLine = true;  // true skips the odd lines, false skips even lines

And change the end of your code like this:
  if (EncVariation != 0) {
    encoder0Pos = encoder0Pos + EncVariation;
    int degrees = (encoder0Pos * 6) % 360 ;
    if(degrees<0){ deg = 360 + degs; }
    if (!skipNextLine)
    {  // This will skip alternate lines
        Serial.println (deg);
        skipNextLine = true;
    }
    else
    {
        skipNextLine = false;
    }
  }

Just tried it didnt work. It doesnt output anything

Can it be there maybe another   Serial.println (deg); needed before the last if?

should skipNextLine be false at some place?

Blush Whoops.  Thanks Mark for editing it.

Use a static variable to count loop execution and only prohibit the very first of every 3 counts.

I tried to use a variable and odd number selection but couldnt achive.


text:
for loop crashes program
Just started out with tinyduino(tinycircuits) and I am trying to develop a hangman game. I have this chunk of code that randomly picks a word from my array. I've omitted some code for readability.
char* words[] = {"Fortran", "Cobol", "Python", "Java", "Javascript", "Kotlin", "Swift", "Golang", "Typescript"};
long word1;
char* generatedWord1;
int k;
int i;
int wordLength;

void setup(void) {
  randomSeed(analogRead(5));
  hangman();

void hangman(){
  word1 = random(sizeof(words)/sizeof(char*));
  k = 1;

  if (k == 1) {
    display.setCursor(10, 50);
    generatedWord1 = words[word1];

    for (i = 0; generatedWord1[i]; i++) {
      generatedWord1[i] = "_";
    }
}

When I upload this to my board, it would not display the underscores based on the randomly chosen word's length. Re-uploading it does not work and usually requires me to reboot the tinyduino after that. Hence, I concluded my code crashes it. But, when I replace the generatedWord1[i] = "_"; in the for loop with display.print("_"); the program carries on and it prints the correct amount of underscores.
However, this does not fit my purpose of replacing the letters with underscores, as display.print("_"); just prints underscores based on the random word's length instead. I need it to be in a manner where I can still compare a user input against the random word and replace the underscore if the letter input matches any letters in the word.
What and how do I modify my code to work as such?
Note: For the context of this whole sketch, I am trying to use get an input from a user through bluetooth and compare whether or not the input matches any of the letters from the random word and then replace the underscore with the input letter. Completing the word means winning the game as per hangman.
EDIT: I've added the whole sketch below for reference just in case I missed out something important for my question.
#include <SPI.h>
#include <STBLE.h>
#include <Wire.h>
#include <SPI.h>
#include <TinyScreen.h>
#include <string.h>

//Debug output adds extra flash and memory requirements!
#ifndef BLE_DEBUG
#define BLE_DEBUG true
#endif

#if defined (ARDUINO_ARCH_AVR)
#define SerialMonitorInterface Serial
#elif defined(ARDUINO_ARCH_SAMD)
#define SerialMonitorInterface SerialUSB
#endif

uint8_t ble_rx_buffer[21];
uint8_t ble_rx_buffer_len = 0;
uint8_t ble_connection_state = false;
#define PIPE_UART_OVER_BTLE_UART_TX_TX 0

TinyScreen display = TinyScreen(TinyScreenDefault);

// declarations
const char* words[] = {"Fortran", "Cobol", "Python", "Java", "Javascript", "Kotlin", "Swift", "Golang", "Typescript"};
long word1;
const char* generatedWord1;
int k;
int i;
int length;

void setup(void) {
  Serial.begin(9600);
  randomSeed(analogRead(5));
  BLEsetup();

  Wire.begin();
  display.begin();
  display.setBrightness(10);
  hangman();
}

void hangman(){
  display.clearScreen();
  display.setFont(thinPixel7_10ptFontInfo);
  display.setCursor(10,20);

  display.print("Ready to hang?");
  delay(2000);

  display.setCursor(5,20);
  display.print("generating word...");
  delay(1000);

  display.clearScreen();

  // word1 is my index, so printing out word1 will give you a random index from the array
  word1 = random(sizeof(words)/sizeof(char*));
  k = 1;

  if (k == 1) {

    display.setCursor(10, 50);
    generatedWord1 = words[word1];

    length = strlen(generatedWord1);
    char user_input[length+1] = "";

    for (i=0; i < length; i++) {
      user_input[i] = "";
      user_input[length] = 0;
    }

    display.setCursor(30, 30);
    display.print("|");

    display.setCursor(30, 20);
    display.print("|");

    display.setCursor(30, 10);
    display.print("|");

    display.setCursor(30, 0);
    display.print("____");

    // remember to move this away from the if statement
    // If user guesses wrong letter (1)
    display.setCursor(50, 10);
    display.print("|");

    // If user guesses wrong letter (2)
    display.setCursor(49, 15);
    display.print("o");

    // If user guesses wrong letter (3)
    display.setCursor(50, 25);
    display.print("|");

    // If user guesses wrong letter (4)
    display.setCursor(43, 21);
    display.print("-");

    // If user guesses wrong letter (5)
    display.setCursor(54, 21);
    display.print("-");

    // IF user guesses wrong letter (6)
    display.setCursor(43, 30);
    display.print("/");

    // If user guesses wrong letter (7)
    display.setCursor(52, 30);
    display.print("\\");
  }

}

void displayScreen(char phone_input[21]) {

  display.clearScreen();

  int width=display.getPrintWidth(phone_input);
  display.setFont(thinPixel7_10ptFontInfo);
  display.setCursor(48-(width/2),32);
  display.fontColor(TS_8b_White,TS_8b_Black);
  display.print(phone_input);
}

void loop() {
  aci_loop();//Process any ACI commands or events from the NRF8001- main BLE handler, must run often. Keep main loop short.
  if (ble_rx_buffer_len) {//Check if data is available
    delay(10);
    displayScreen((char*)ble_rx_buffer);
    ble_rx_buffer_len = 0;//clear afer reading
  }

}

Funny, I just wrote an answer about the problem, that you have here, about 45min ago. And the problem is, that you are trying to modify a string literal. That is undefined behavior in C++.
When you declare your words array with
char* words[] = {"Fortran", "Cobol", "Python", "Java", "Javascript", "Kotlin", "Swift", "Golang", "Typescript"};

you are actually defining an array of pointers. The compiler will place these strings in the RAM and place their memory addresses in the array. Then you are declaring another char pointer and set it to one of the words:
char* generatedWord1;
generatedWord1 = words[word1];

So now generatedWord1 will also point to one of the string literals. And then you are trying to write to this string literal:
generatedWord1[i] = "_";

But - as already mentioned - string literals are not meant to be changed. Trying so is undefined behavior and yes, it can lead crashes.
What to do now? You can define an array of char (not char pointers) as a buffer and fill it with the number of underscores that equals the length of the string literal. When defining the array you can choose the length of the string literal (plus 1 to accommodate the null character) as size, though - depending on your program flow, that you didn't show - it might be better to just declare a buffer with a fixed size bigger than the longest of your words.
You can get the length of the string literal with the strlen() function:
int length = strlen(generatedWord1);

Defining the char buffer:
char user_input[length+1] = "";

Filling it with underscores
for(int i=0;i<length;i++){
    user_input[i] = '_';
}
user_input[length] = 0; // terminating null character

I still can't get the desired output I would like. Also it keeps throwing me an error of invalid conversion from 'const char*' to 'char'.

The following part is wrong:
for (i=0; i < length; i++) {
    user_input[i] = "";
    user_input[length] = 0;
}

First: You misunderstood what is in the loop and what not. I changed my snipped above to use curly braces. Terminating the string with the null character can be done outside of the loop.
Second: You wanted to fill the buffer with underscores. If you look at my code snippet I assigned an underscore here.
The warning that you are getting from the compiler also lies in this line. You have used double quotes. Those mark a string literal. But here we are assigning a single character, so you need to use single quotes, which mark single characters.
The message invalid conversion from const char* to char means, that you used a string literal (which is a pointer to a constant character) and assigned it to a single character variable (one element of the char array).

Hi @chrisl, after trying out the code you've provided, I still can't get the desired output I would like. Also it keeps throwing me an error of invalid conversion from 'const char*' to 'char'.

You can add your new code to the end of your question. Then I will have a look at it.

@IsaacAgatep: 1. chrisl's code works for me. If it doesn't work for you, show us how you integrated it into your program. 2. The “invalid conversion” message is a warning, not an error. You can fix it by using the type const char * (meaning: “pointer to immutable characters”) for all pointers meant to point to string literals. In this program, both words and generatedWord1 need the const qualifier.

Hello @Edgar Bonet, I've tried both of your suggestions but to no avail. I've added my whole sketch at the bottom of the question just in case I missed out anything important that might be causing my mistakes.

@IsaacAgatep I have added a paragraph to my answer to address this.

@chrisl much thanks to your help and explanations. I can't confidently say I understand it but I will now take the time to digest. Will accept your answer!

@IsaacAgatep It might help to do a tutorial on pointers, so that you understand what the * means in this code.


text:
why is "if" slow?
I am new to the Arduino world and I hope I can find a solution here. The code below functionally works ok. The problem I have is, at line 45 I've inserted an if statement to change dac_value. It is very slow while serial and all that is outside if works fast/fine... What would be a solution to make it fast? Tried if - else if and also while... result is the same. Hope someone can help. Thank you.
{
#include <Arduino.h>
#include <Wire.h>
// #include <LiquidCrystal_I2C.h>
#define MCP4725 0x61
#define MCP4725B 0x60
unsigned int val;
byte buffer[3];
byte buff[3];

int ClockPinV = PB1;
int ClockPinA = PA6;
const int currsensPin = PA3;
const int voltsensPin = PA2;

void setup()
{
  Serial.begin(115200);
  pinMode(currsensPin , INPUT_ANALOG);
  pinMode(voltsensPin , INPUT_ANALOG);
  pinMode(ClockPinV , INPUT);
  pinMode(ClockPinA , INPUT);
  Wire.begin();
}

int val0 = 1024;
int val1 = 4096;
volatile int dac_value = 0;

void loop()
{
  analogReadResolution(12);

  volatile int svolt = analogRead(ClockPinV);
  volatile int scurr = analogRead(ClockPinA);
  volatile int set_voltage = (3.3/4096)*svolt;
  volatile int set_curr =  (3.3/4096)*scurr;
  volatile int securr = analogRead(currsensPin);
  volatile int real_curr = (3.3/4096)*securr;
  volatile int sevolt= analogRead(voltsensPin);
  volatile int real_output2 = (3.3/4096)*sevolt;

if(real_curr < set_curr){
    if(set_voltage > real_output2)
    {
      dac_value = dac_value + 1;
    }
    if(set_voltage < real_output2)
    {
      dac_value = dac_value - 1;
    }
  }
  else if(real_curr > set_curr)
  {
    dac_value --;
  }

  dac_value = constrain(dac_value, 0, 2673);
  buffer[0] = 0b01000000; //control byte
  buffer[1] = dac_value >> 4; //MSB 11-4 shift right 4 places
  buffer[2] = dac_value << 4; //LSB 3-0 shift left 4 places

  Wire.beginTransmission(MCP4725); //address device
  Wire.write(buffer[0]); //pointer
  Wire.write(buffer[1]); //8 MSB
  Wire.write(buffer[2]); //4 LSB
  Wire.endTransmission();

  // val1 = constrain(val1, 0, 2673);
  buff[0] = 0b01000000; //control byte
  buff[1] = svolt >> 4; //MSB 11-4 shift right 4 places
  buff[2] = svolt << 4; //LSB 3-0 shift left 4 places

  Wire.beginTransmission(MCP4725B); //address device
  Wire.write(buff[0]); //pointer
  Wire.write(buff[1]); //8 MSB
  Wire.write(buff[2]); //4 LSB
  Wire.endTransmission();

  Serial.println("=============================");
  Serial.println("=============================");
  Serial.println("========= Volt Test =========");
  Serial.println("test: " + String(set_voltage));
  Serial.println("      " + String(real_output2));
  Serial.println("======== Current Test =======");
  Serial.println("test: " + String(set_curr));
  Serial.println("      " + String(real_curr));
  Serial.println("=============================");
  Serial.println("=============================");
}
}

How do you see, that its the if statements, which is slow? Are you sure, that your problem doesn't lie at another place? And what means "slow" in this case?

I asume that... tride a pot connected to a analog pin and output directly to dac - it was working fast...

Why are you using volatile everywhere? What do you mean by "slow" and "fast"? How have you measured that?

"if" isn't slow, just for your info. The things you do inside the "if" will be affecting what the rest of the code is doing. For example, if you say "if it is Monday, sleep for 4 hours" then the "if" isn't the problem, it is "sleep for 4 hours" that is.

It's not the if statement itself that makes your code slow. But it may well be the sketch behaving differently than you expect which makes you believe it was slow. Compare and print timestamps to determine how long the execution of certain parts takes.

if I read a pot on a analog pin and write to dac in serial print i can see it changing the dac value as i spin the pot. In the same time if the conditions in the if are met and i increase the voltage i can see dac_value incrementing very slow. it takes seconds until it reaches the set value...

as I said... new here so pleas don't jump at me. I agree that my problem could be  something else - that is why i posted. hopefully to find a solution and to learn something new :P

No-one is attacking you. We are just curious as to some things about your code. If you can explain, we can better advise you.

if the conditions in the if are met and i increase the voltage i can see dac_value incrementing very slow. - you mean, the serial prints are slower?

yes, but just the dac reading dac_value. If I print anything else + dac_value everything updates fast except the dac_value...

I didn't understand that.

From your code it seems, that you are trying to do a control loop (outputting a control signal via DAC, reading correlated values back and change the control signal based on that. The behavior of such control loops are not always obvious. I'm rather sure this is one of these cases. So please describe, how everything is connected, what you are trying to control and what exactly you expect to happen. A schematic or wiring diagram (and maybe a good image of your real circuit) would also help here

try if (real_curr <= set_curr){

int ClockPinV = PB1;  int ClockPinA = PA6;  is nonsense, BTW. pinMode and analogRead do work with Arduino pin numbers.

@DataFiddler: made it with rotary enc first. Removed and now using pot but did not change pin name... also board is stm32f103

added full main.cpp to github. https://github.com/mariusdp/psu_test.git

The if statements (plural) you posted on GitHub are a lot different to the one you posted above. They contain a lot of of print commands to the LCD, so I think this is what is slowing your code down. It's a fair effort at nicely formatting the output on the display, but is rather convoluted.
Here is a simplified version which writes to the LCD as little as possible (2 cursor moves and 2 prints). The formatting of the string is done in Arduino memory before sending it out to the LCD as one complete string.
I couldn't understand your variable names, so I've renamed them.
setup()
I moved the analogReadResolution(12) from loop() to setup() for a slight performance gain.
void setup()
{
  pinMode(currsensPin , INPUT_ANALOG);
  pinMode(voltsensPin , INPUT_ANALOG);
  pinMode(voltPin, INPUT_ANALOG);
  pinMode(currPin, INPUT_ANALOG);
  Wire.begin();
  lcd0.begin(20, 4);
  lcd0.backlight();

  analogReadResolution(12);  // Moved from loop(). Only need to call it once.

  Serial.begin(115200);
}

loop()
I've grouped the analogue reads together to give a smaller sampling window. Since it's for a control loop, these values should ideally be sampled at exactly the same time and synchronised to a clock (e.g. in hardware).
float real_current_offset = 0;

void loop()
{
  //
  // Obtain data samples as close together as possible with no interrupts.
  //
  cli();  // Disable interrupts.
  int svolt = analogRead(voltPin);
  int scurr = analogRead(currPin);
  int raw_voltage = analogRead(voltsensPin);
  int raw_current = analogRead(currsensPin);
  sei();  // Enable interrupts.

  // Calculate set voltage and current.
  float set_voltage = (3.3 / 4096) * svolt;
  float set_current =  (3.3 / 4096) * scurr;

  // Calculate real voltage and current.
  float real_voltage = (3.3 / 4096) * raw_voltage;
  float real_current = raw_current * (3.3 / 4096) - real_current_offset;
  float real_current_ma = real_current * 1000.0;

  int dac_value = dac_value
              + (real_current <= set_current) * (set_voltage > real_voltage)
              - (real_current < set_current) * (set_voltage < real_voltage)
              - (real_current > set_current);

  buffer[0] = 0b01000000;
  buffer[1] = dac_value >> 4;
  buffer[2] = dac_value << 4;
  Wire.beginTransmission(MCP4725);
  Wire.write(buffer[0]);
  Wire.write(buffer[1]);
  Wire.write(buffer[2]);
  Wire.endTransmission();

  DisplayDataOnLcd(set_voltage, set_current, real_voltage, real_current);
}

DisplayDataOnLcd()
I created a new function for displaying the data on the LCD. It's good practice to break the code down into smaller functional blocks.
void DisplayDataOnLcd(const int set_voltage, const int set_current, const int real_voltage, const int real_current)
{
  Serial.println("\nLCD Data Display");

  // Define the formats for printing to the LCD.
  const char *data_format_set  = "Set : %s V %s mA";
  const char *data_format_real = "Real: %s V %s mA";
  char voltage_str[10];
  char current_str[10];
  char data_str[30];

  // Format the set voltage and current, and display on the LCD.
  dtostrf(set_voltage, 6, 3, voltage_str);
  dtostrf(set_current, 6, 3, current_str);
  sprintf(data_str, data_format_set, voltage_str, current_str);
  lcd0.setCursor(0, 0);
  lcd0.println(data_str);
  Serial.println(data_str);

  // Format the real voltage and current, and display on the LCD.
  dtostrf(real_voltage, 6, 3, voltage_str);
  dtostrf(real_current, 6, 3, current_str);
  sprintf(data_str, data_format_real, voltage_str, current_str);
  lcd0.setCursor(0, 1);
  lcd0.println(data_str);
  Serial.println(data_str);
}

Thank you. Will try later today. Q: I do not know lot of things so be patient with me please. On the LCD the only value that updates slow is the reading from dac (dac_value), all else updates fast... That is why I assumed I am doing something wrong... . The test I made was - pot on a analog input and the reading sent over i2c to dac converter - output from converter to another adc pin as feedback and feedback to LCD trough i2c ==> this setup was updating in real time (or fast enough to perceive as real time and be able to work with it)...

I'm struggling to understand your control loop. Could you post a full schematic of it please? Edit your original post to add an image. I can't see how writing 3 bytes to the MCP4725 DAC at the standard 100 kbps is drastically slowing down the loop. Try adding debug statements to the loop to Serial.println() the time of each iteration.

DAC connected to analog pin controlled by pot or enc and "if" conditionals... the DAC controls a mosfet driver IC. Divider for voltage monitor (real_voltage) and made low side current sensor from LM358 and shunt for "real_current". The way has to work is if set_volt < real_volt the DAC output should get lower... it does that but is to slow. In a short would smoke (output is up to 100VDC 20Amp LINEAR) Before u ask - linear is less noisy and a lot cheaper to build than buy + using trafo I see it silly to make it switch mode. :P THANK YOU!

Nice answer guy, I think your assumption was right. Every I2C liquid crystal display I have used with arduino are dreadfully slow for w.e reason. +1


text:
Get a LED to fade out
I want to light an LED in a sketch and then have it fade out.
I tried to use analogWrite and have it decrease from a value of 255 to 0 using a for() loop, but I can't seem to get it to work.
Using digitalWrite I can turn it on and off but cant get it to fade out.
Can anyone help please.
const int ledPin1 = 2;
const int ledPin2 = 3;
const int ledPin3 = 9;
int j = 0;

void setup() {
    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);
}

void loop() {
    j = 255;
    delay(1000);
    if (j >= 5);
    {
        analogWrite(ledPin3,j);
        delay(10);
        j = j - 5;
    }
    delay(1000);
}

Please show what code you have, along with your wiring. There is an example in the IDE that fades an LED. Did you get that to work?

Yes I did get that sketch to work. I am using pin 9

So please show us your code and better define "can't seem to get it to work".

What sketch did you get to work?

Yes my complaint is a bit vague. The LED comes on and stays on. It is in my code. I am missing what I doing wrong. Some sort of mental block. Wiring is just a LED and resistor from pin 9 to gnd.

Not all output pins are able to perform PWM ("AnalogWrite").

On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.

https://www.arduino.cc/en/Reference/AnalogWrite
Note that the PWM-enabled ports are marked by a "~" on the board.
If you try analogWrite, e.g., on port 4, you'll get your observed switch behaviour.

I am using pin 9

Well - if that's not the problem, I'm totally with @Majenko. Post code, wiring and tell us what boards you are using.

const int ledPin1 = 2;
const int ledPin2 = 3;
const int ledPin3 = 9;
int j = 0;
void setup() {
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
}
void loop() {
j = 255;
delay(1000);
if (j >= 5);{ analogWrite(ledPin3,j);
delay(10);
j = j - 5;
}
delay(1000);
}

New at this so my posts may be a mess. I am using an UNO.

Problems noted in comments:
void loop() {
    j = 255;             // Resets j EVERYTIME
    delay(1000);
    if (j >= 5);         // Semi-colon here makes this a null statement
    {
        analogWrite(ledPin3,j);  // j is always 255 (see line 1)
        delay(10);
        j = j - 5;       // No effect as j is reset in line 1
    }
    delay(1000);
}

Here's a simple fix:
int j = 255;   // Start at 255

void loop() {
    analogWrite(ledPin3, j);   // Set the brightness
    delay(10);
    j -= 5;
    if (j <= 0) j = 255;       // Reset j?
}

of course. Thank you very much. Works like a charm. I must be getting old.

How about we double what we are paying you.