text:
Bluetooth Modules not communicating correctly
I plug in BT rx to digital 11, BT tx to digital 10 and then 5v and ground from the HC-05 to the arduino. I then upload this code to the HC-05 that is set as a master.
#include <SoftwareSerial.h>

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

void setup() {
  Serial.begin(57600);
  mySerial.begin(9600);
}

void loop() { // run over and over
  Serial.println(mySerial.read());
  delay(2000);
}

I then upload this code to the arduino with the HC-05 that is set as a slave:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX , TX

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

void loop() {
  // put your main code here, to run repeatedly:
  mySerial.write("100");
  delay(2000);
}

The issue is that I never receive "100" on the serial monitor, I only ever receive 49 and occasionally 48. When I changed it from "100" to "10" same thing happened. Any help would be appreciated.

UPDATE: I changed "100" to "hello" and now I'm getting values like 104, 101, 111, 108. I read something that the bytes may be getting mixed up because of how long or short a delay is.

49 is the decimal ASCII value of string 1 .... 48 is the decimal ASCII value of string 0 .... 104=h, 101=e, 108=l`  etc. etc.  ........... http://www.asciichart.com/ascii_decimal.html

Guessing I can't send strings over bluetooth then

you already are, the data being transmitted is always a binary value which has a decimal equivalent and an ASCII equivalent ..... just convert the ASCII values to string .... lot of places on web show you how

SoftwareSerial.read() returns a single character as an integer. When you print an integer the print() functions convert it to a human readable format.
You want to covert (cast) the output of read() to the char type. Either:
void loop() {
  char c;
  c = mySerial.read(); // store the result in a temporary variable c
  Serial.println(c);
  delay(2000);
}

or
void loop() {
  Serial.println((char)mySerial.read()); // cast the type to char befor printing.
  delay(2000);
}

However since only one character at a time is being read your output will be one character per line (assuming no data loss due to the delay):
1
0
0

"You are getting 49 and 48 occasionally"?
I would expect you to get 49, 48, 48, 49, 48, 48 ...
49 is '1' in ASCII and guess what 48 means :)
This is because you are writing and reading bytes not characters.  There is a very subtle difference.
change you receiver to this and it should make more sense.
void loop() { // run over and over
  const char letter = (char)mySerial.read(); // Turn the byte into an ASCII letter.
  Serial.println(letter);
  delay(2000);
}

It may all still go wrong, if you read <32 or >126 but ...
Here is an ASCII table to help:
ASCII Table

You should change the TX and the RX pins on the arduino board and pin it on to another pin other than the TXD and RXD as the are hardware pins....

The OP says they are using 10 and 11.


text:
Read both battery voltage and analog sensor value with NodeMCU ESP8266
I have a soil sensor that reports value once every 5 minutes, deepsleep in between.
Is there a way to also report battery voltage (with ESP.getVcc())?
To get the battery voltage reading to work I need to set ADC_MODE(ADC_VCC); but that disables the reading of the sensor.

does the ADC_VCC use the same channel on the ADC that your sensor is using? Can you use another channel?

can you set the mode to vcc after you take a sample and before you sleep?

that disables the reading of the sensor ... so enable it after you read the voltage ... what is the problem?

@ChadG esp8266 has only one analog pin

you can use a digital pin and RC circuit to precisely
measure voltage as a function of time

to read VCC voltage, ADC pin must be kept unconnected. Additionally, the following line has to be added to the sketch:
  ADC_MODE(ADC_VCC);

The setting of a purpose of the analog pin of esp8266 is at low level and must be projected into the compiled binary. It can't be changed at runtime.
On esp8266 if you want to use the power sensing or to have more ADC you must use an external I2C ADC.
reference

Was afraid of that, but thanks for confirming.

I found a solution that I believe works great.
Although the ADC_MODE macro cannot be modified after the board is started, we can actually set its integer input as the output of a function and then use RTC memory to trigger different modes, depending for example on how many times the board has been started.
#include "ESP8266WiFi.h"
#define QUERY_VCC_INTERVAL  10

int adc_selection;
ADC_MODE(get_adc());

int get_adc(){

  typedef struct {
  uint32_t adc_mode;
  uint32_t count;
  } rtcStore;

  rtcStore rtcMem;

  system_rtc_mem_read(100, &rtcMem, sizeof(rtcMem));

  if ((rtcMem.adc_mode != ADC_VCC) && (rtcMem.adc_mode != ADC_TOUT)) return ADC_TOUT;

  return rtcMem.adc_mode;
}

int get_adc_and_write_change(){

  typedef struct {
  uint32_t adc_mode;
  uint32_t count;
  } rtcStore;

  int a;
  rtcStore rtcMem;

  system_rtc_mem_read(100, &rtcMem, sizeof(rtcMem));
  a = rtcMem.adc_mode;

  Serial.print("CYCLE NUMBER: ");
  Serial.println(rtcMem.count);

  if (rtcMem.count > QUERY_VCC_INTERVAL){
        rtcMem.adc_mode = ADC_VCC;
        rtcMem.count = 0;
  } else {
        rtcMem.adc_mode = ADC_TOUT;
        rtcMem.count++;
  }

  system_rtc_mem_write(100, &rtcMem, sizeof(rtcMem));

  return a;

}

void setup() {

  int vcc;

  Serial.begin(9600);
  Serial.println(" ---------- ");
  delay(1000);

  adc_selection = get_adc_and_write_change();
  Serial.print("VALUE FOR ADC MODE WAS: ");
  Serial.println(adc_selection);

  vcc = ESP.getVcc();
  Serial.print("VALUE WHEN READING VCC: ");
  Serial.println(vcc);

  if (adc_selection == ADC_TOUT){
    Serial.println("VCC SHOULD BE 65535");
   } else {
    Serial.println("VCC SHOULD NOT BE 65535");
   }

  Serial.println("RESET BOARD TO CONTINUE");
  delay(1000);

}

void loop() {
}

Note that the function gets executed very early on the board startup, so we cannot even count on using or writing to global variable definitions of the script's code. This is why all structures are defined within the get_adc function.
The above code triggers ADC_MODE(ADC_VCC) for every 10 times that ADC_MODE(ADC_TOUT) is triggered. This allows me to read analogue sensors for 10 times after the board is woken up from deep sleep and then read the VCC level to gauge the battery voltage once every 10 times.
Note also that to have VCC readings work correctly I need to connect analogue sensor power to a digital pin and use that to power the sensors ON/OFF as needed.
I have tested the above code with a NodeMCU v3, on the Arduino IDE.

source: Stack Exchange

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

sort: votes


text:
Need help with an Arduino project using a RTC and LEDs
I need some help with a project I am doing involving the DS1307 RTC. I am trying to make what is essentially a way to mins quickly check the time which involves nine LEDs slowly lighting up every 10 so that I can quickly check time but looking at it. : So far I've tried TimeAlarms but I can't figure out how to do this. I have a Arduino Uno by the way.
Can someone possibly help?

start by learning how to light up the LEDs .... then learn how to use the  DS1307 RTC .... tutorials can be found on the web

please explain what slowly lighting up actually means

Use the SQW pin on the DS3231 or DS1307 to create 1sec pulse, read it on your Arduino. There are very good libraries are available (like RTClib from adafruit).

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


text:
Watchdog problem
I am using Maniacbug Mighyty-1284p 16MHz in my project.
Here I used watchdog for safety.I used three command for watchdog.
1. wdt_enable(WDTO_8S);
2. wdt_reset();
3. wdt_disable();

Is it create any problem if I use "wdt_enable(WDTO_8S);" command two times (one after another without using wdt_disable();)

no. it only sets the registers. and the reason for setting it twice is?

@Juraj besides setting the registers, it also resets the watchdog timer if it is running. Still not an issue for the OP. Calling it twice is fine.


text:
Arduino Modbus Master code to read data using arduino uno from EB meter
I am using DC energy meter as slave.When I am testing DC energy meter using Modbus tester tool,its showing value from 1 to 24 register.I am using my own atmega328P with on board RS485 as a master device.I have connected A,B from slave to mater board.Now,I want to read slave outputs using my master.For that I have written below mentioned code.when I am serially printing array,its showing 00000000000000000000000000000000769.I am not getting full data on my master.
#include <ModbusRtu.h>

// data array for modbus network sharing
uint16_t au16data[64];
uint8_t u8state;

int i;

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus master(0,0,1); // this is master and RS-232 or USB-FTDI

/**
 * This is an structe which contains a query to an slave device
 */
modbus_t telegram;

unsigned long u32wait;

void setup() {
  master.begin( 9600 ); // baud-rate at 19200
  master.setTimeOut( 2000 ); // if there is no answer in 2000 ms, roll over
  u32wait = millis() + 1000;
  u8state = 0;
}

void loop() {
  switch( u8state ) {
  case 0:
    if (millis() > u32wait) u8state++; // wait state
    break;
  case 1:
    telegram.u8id = 1; // slave address
    telegram.u8fct = 3; // function code (this one is registers read)
    telegram.u16RegAdd = 1; // start address in slave
    telegram.u16CoilsNo = 24; // number of elements (coils or registers) to read
    telegram.au16reg = au16data; // pointer to a memory array in the Arduino

    master.query( telegram ); // send query (only once)
    u8state++;
    break;
  case 2:
    master.poll(); // check incoming messages
    if (master.getState() == COM_IDLE) {
      u8state = 0;
      u32wait = millis() + 100;
    }
    break;
  }
 //au16data[4] = analogRead( 0 );

 for(i=0;i<=64;i++)
 {
  Serial.print(au16data[i]);
 }
 Serial.println("\n");
 Serial.println("\n");
 delay(1000);
 }

source of the library? shouldn't you print the data only if it is received in case 2?

source of the library means #include <ModbusRtu.h> right?.So how to receive the polling data on master.

there is no ModbusRtu library in Library Manager. so from where do you have the library?

I have downloaded this source code with library from Github .I have mentioned URL on below. https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino/blob/master/examples/advanced_master/advanced_master.ino

Modbus (0,0,0)  last argument I have changed as 1,because we are usin RS485 and My slave device of A,B is connected on my Master controller of MAX485 and Max is communicated with Atmega328P with the help of software serial.Pin is 8,9

when I am measuring voltage on my MAX485 IC on pin A ,it giving 1.09V and B its showing 3.89 V

in simple_master example the author forgot to print the received data, but in the software serial example he prints them in if (master.getState() == COM_IDLE) {

Now I have uploaded software serial master example code on my master controller.I am using external Rs485(D+,D-,Gnd) to TTL board(RX,Tx) for communicating the slave device.I have changed only the software serial pins 8(Rx),9(Tx).I have connected my TTL output on software serial pins (rx-rx,tx-rx viceversa).Even though its printing  '0' on serial terminal.I have tested RS485 to TTL its working fine and when I am testing the salve device in Mtester ,it contains 5453 value on 40001.So how to resolve

can you check the function code on software serial master example.They have mentioned 4 instead of 3.

I have changed the function code as 3,software serial pins,no of register need to read .I can able to read all slave response serially on my modbus master controller.Thank you

The response is received when ModbusRtu library object is again in the IDLE state after a request was sent. In your code based on the example from the library, the response is ready in state 2 which follows state 1 where the request was sent. If in state 2 when the master object state changes to IDLE, you can use the response in array au16data.


text:
ESP8266 based wifi IR Universal Remote for A/Cs
I have been working on a prototype for a wifi based universal remote controller and i have been using the IR-Remote library for the same. But i have a couple of questions which google couldn't help with.
So, the problem is that there are some remotes like hitachi or some other brands that aren't recognised by the library and the coding type shows "UNKNOWN". The raw dump shows an array of 211 integers like such:
Timestamp : 012012.059
Encoding  : UNKNOWN
Code      : 794B7E67 (106 bits)
Library   : v2.4.0

Raw Timing[211]:
   +  3424, -  3352,    +   378, -  1336,    +   376, -   454,    +   458, -  1254,
   +   378, -  1334,    +   378, -   454,    +   460, -   352,    +   396, -  1336,
   +   460, -   356,    +   394, -  1334,    +   458, -   364,    +   466, -  1256,
   +   458, -   356,    +   392, -  1336,    +   458, -  1258,    +   456, -  1254,
   +   378, -   452,    +   460, -   360,    +   470, -  1256,    +   458, -   298,
   +   532, -   366,    +   466, -  1256,    +   458, -  1256,    +   458, -   358,
   +   472, -  1256,    +   458, -  1254,    +   458, -   358,    +   472, -   304,
   +   526, -  1258,    +   456, -   298,    +   532, -   362,    +   466, -   368,
   +   464, -  1256,    +   456, -  1258,    +   456, -  1258,    +   456, -  1256,
   +   378, -  1336,    +   458, -   360,    +   470, -   304,    +   524, -   364,
   +   466, -   364,    +   464, -   310,    +   522, -  1232,    +   482, -  1256,
   +   456, -   304,    +   526, -   310,    +   520, -   306,    +   524, -   370,
   +   462, -  1256,    +   456, -  1260,    +   454, -  1232,    +   480, -   306,
   +   524, -   366,    +   464, -   312,    +   516, -  1236,    +   478, -   368,
   +   462, -   368,    +   462, -   368,    +   386, -   454,    +   454, -   372,
   +   456, -   374,    +   458, -   372,    +   460, -   306,    +   524, -   372,
   +   458, -   370,    +   460, -   308,    +   520, -   312,    +   444, -   452,
   +   376, -   454,    +   452, -   308,    +   524, -   368,    +   462, -   372,
   +   458, -   306,    +   522, -   374,    +   458, -   368,    +   460, -   306,
   +   524, -   374,    +   458, -   308,    +   522, -   372,    +   460, -   370,
   +   458, -   374,    +   460, -   364,    +   464, -   370,    +   460, -   304,
   +   450, -   454,    +   452, -   308,    +   522, -   370,    +   460, -   368,
   +   386, -   452,    +   452, -   374,    +   456, -   312,    +   520, -  1260,
   +   452, -  1262,    +   452, -   376,    +   456, -   372,    +   458, -   376,
   +   454, -   378,    +   380, -  1334,    +   452, -  1260,    +   452, -  1264,
   +   378, -  1336,    +   378, -  1310,    +   476, -   320,    +   438, -   452,
   +   378, -   428,    +   402

uint16_t rawData[211] = {3424, 3352,  378, 1336,  376, 454,  458, 1254,  378, 1334,  378, 454,  460, 352,  396, 1336,  460, 356,  394, 1334,  458, 364,  466, 1256,  458, 356,  392, 1336,  458, 1258,  456, 1254,  378, 452,  460, 360,  470, 1256,  458, 298,  532, 366,  466, 1256,  458, 1256,  458, 358,  472, 1256,  458, 1254,  458, 358,  472, 304,  526, 1258,  456, 298,  532, 362,  466, 368,  464, 1256,  456, 1258,  456, 1258,  456, 1256,  378, 1336,  458, 360,  470, 304,  524, 364,  466, 364,  464, 310,  522, 1232,  482, 1256,  456, 304,  526, 310,  520, 306,  524, 370,  462, 1256,  456, 1260,  454, 1232,  480, 306,  524, 366,  464, 312,  516, 1236,  478, 368,  462, 368,  462, 368,  386, 454,  454, 372,  456, 374,  458, 372,  460, 306,  524, 372,  458, 370,  460, 308,  520, 312,  444, 452,  376, 454,  452, 308,  524, 368,  462, 372,  458, 306,  522, 374,  458, 368,  460, 306,  524, 374,  458, 308,  522, 372,  460, 370,  458, 374,  460, 364,  464, 370,  460, 304,  450, 454,  452, 308,  522, 370,  460, 368,  386, 452,  452, 374,  456, 312,  520, 1260,  452, 1262,  452, 376,  456, 372,  458, 376,  454, 378,  380, 1334,  452, 1260,  452, 1264,  378, 1336,  378, 1310,  476, 320,  438, 452,  378, 428,  402};  // UNKNOWN 794B7E67

Now for such AC remotes which are unknown, which are more common than i thought would be, it is a matter of best implementation. I know I can save these arrays in variables and send them using .sendRaw(array, sizeof(array, freq) but then I will have to store about 15 such arrays for multiple brands. Even if I save ir codes for five different protocols, i'll be making a table of 5 * 15 = 75 huge arrays. i don't think that is a good practice nor the ESP8266 will be able to store all that.
What can be the best way to do this? What am I missing? Is there a better way to do this?

the SPIFFS file system on flash of the esp8266 can be 3 MB big if the flash has 4MB

By this i think you are suggesting that i can store that huge data without problem, is that it? But is it the best practice? Won't I have to store raw data arrays for all remotes like this?

Also, if i occupy a lot of space, wont that create problem when update the device using OTA?

SPIFFS and sketch are ota updated separate. SPIFFS with IDE plugin from data subfolder

"Best practice" would be to implement the protocol in the library properly. Just because it's not supported doesn't mean it can't be supported.


text:
Program an Arduino Uno with an Atmel ICE
When I connected my atmel ice to my arduino uno everything went okay.
Then I tried debugWIRE and since then I can't connect to my ATMEGA328p.
I get the error
Failed to enter programming mode. ispEnterProgMode: Error status received: Got 0xc0, expected 0x00 (Command has failed to execute on the tool)
I think one of the fuse bits is wrong but can't connect to the ATMEGA328p to change them. Does anyone have a idea what to do?

I can't connect to my ATMEGA328p - connect using what? If you try to connect it using the "regular" USB, then it won't work until you flash the bootloader using ICE. You have probably overwritten it.

Have you looked up the problem with Atmel? It's like I always tell people on here... You're not discovering new problems when you encounter a problem. The chances of an error happening to you and someone else having the same problem is extremely high... But this looks like a physical connection problem (i.e. a lose wire, bad connection between components, clock frequencies etc).

@EugeneSh. The poster is asking how to program the Arduino with the Atmel Ice programmer after debugging with debugWIRE. No bootloader required.

Your Ardunino is stuck in debugWIRE (The debug wire fuse is set). Here is a tutorial on how to get it back to programming mode.
In the tutorial I am using the AVR Dragon with AS6, but the process is the same with Atmel ICE and AS7.
You have to be in Debug Mode to disable debugWIRE. While in debug, Click Debug>Disable Debug Wire and Close.


text:
Serial.write(buf, len) error. How to remove an error and pass an array of bytes?
int angleServo1,angleServo2 = 0;
const int axisX=A0; // ось Х подключена к A0
const int axisY=A1; // ось Y подключена к A1
int valX, valY = 0; // переменные для хранения значений осей
int datos[3];
#include <SPI.h>

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

void loop()
 {
      valX = analogRead(axisX); // значение оси Х
      valY = analogRead(axisY); // значение оси Y
      // масштабируем значение к интервалу 0-180
      angleServo1=map(valX,0,800,100,-100);
      angleServo2=map(valY,0,810,100,-100);

       datos[0] = angleServo1;
       datos[1] = angleServo2;
       Serial.write(datos, sizeof(datos));
       delay(100);
}

error: no matching function for call to 'HardwareSerial::write(int [3], unsigned int)'
how to remove an error and pass an array of bytes?

byte datos[3]; changed, I will test the code. I'm not sure that it will work. Because the byte of small value.

it is telling you that HardwareSerial::write() does not have a function that will accept two arguments where the first one is an array of integers and the second one is an unsigned integer ..... i think that HardwareSerial::write() only has a function that accepts one argument that is an integer, not an array

try this: Serial.print(datos);

See: https://github.com/arduino/ArduinoCore-avr/blob/3d09a51bd20f095e1354243e6d8addedfcb6001e/cores/arduino/Print.h#L56-L59

@jsotola, what? write(int)? there is write(byte) and write(buff[], size)

did not word that correctly ... i think that the brain was in neutral ... the serial.write() accepts an array of bytes, not an array of integers

You want to send data to computer processing or print them for user to read? Functions write send raw data. To print the data to Serial monitor print and println functions are used.
There are two write functions. First sends one byte. Second sends array of bytes. There is no write function to send array of ints. You could cast the array of ints to array of bytes to send the array as raw bytes for processing on the receiving side. But then you first should perhaps send to the receiving side some control data about the data package.
  Serial.write((byte*) datos, sizeof(datos));

If you want to print numbers to Serial Monitor, the print functions have variants which take a number and convert it to string. But there is no print function to print an array of numbers. You must print them one by one in a for loop. And put some separator between them (coma, space, new line).

note: sizeof returns the size of the array in bytes


text:
DS18B20 flaky with LOLIN32 ESP32 board, rock-solid with Uno
I'm trying to read 4 DS18B20 sensor probes (https://amazon.com/gp/product/B00Q9YBIJI and https://amazon.com/gp/product/B008HODWBU) with a "Wemos" LOLIN32 ESP-32 board (https://amazon.com/gp/product/B072HBW53G).
Wiring:

The probes' Vcc wires are connected to the ESP32 board's "3.3" pin
the probes' ground wires are connected to one of the ESP32 board's "Gnd" pins
the probes' data wires are connected together at the end of their furnished meter-long cable, and the wire carrying the combined data is connected to GPIO 16 on the ESP32 board.
Additionally, there's a 4.7k resistor between GPIO16 and the 3.3v pin on the Lolin32 board to pull the 1-wire bus high.

I'm using the stock Arduino  and  libraries.
Sometimes, the sensors work. Often, they don't.
Possibly noteworthy is the fact that I purchased 1 probe a few years ago, and a 3-pack of probes this week. Probes from the 3-pack ONLY work if the probe I purchased earlier is ALSO connected. Put another way...
Original probe connected: sometimes works, sometimes doesn't.
1-3 of new probes connected: never works.
1-3 of new probes connected along with original probe: sometimes works, sometimes doesn't.
Wiring should theoretically be a total non-issue... I'm using only the original ~meter-long wires, with short (~3-4") AWG20 solid hookup wire soldered to the end and connected through a breadboard.
If I unplug the wires connected to the ESP32 board's GPIO16, 3.3, and Gnd pins and connect them instead to an old Arduino Uno's D2, 5v, and Gnd pins (and change the port in the code), all tested permutations of the sensors work perfectly and reliably.
Any ideas for troubleshooting this?
At the moment, these are my top theories:

GPIO16 is unsuitable for some unknown reason.
There's at least one software bug somewhere between the ESP32's low-level firmware, the firmware that enables an ESP32 to act like it's an Arduino, the two Arduino libraries themselves, or some combination of them all. Knowing that something like this is almost certainly the problem would at least spare me from going in circles for the next few days trying to solve a problem that can't be solved.
The 3 new sensors really don't like 3.3v, but the older one semi-tolerates 3.3v (theory fails to explain why adding a fourth sensor -- the original one -- would occasionally enable the 3 new ones to work)
The ESP32 board can't supply enough current from the 3.3v pin to properly power the sensors (flaws in theory: if it were purely lack of current capacity, adding the fourth sensor on top of the first 3 should make matters worse, not better. And in any case, the DS18B20 sensors don't use much power, and almost by definition MUST be able to work with unstable & intermittent power for parasitic powering to be capable of working. Just to emphasize, I am NOT using parasitic power, though).

I considered trying to feed the sensors 5v, but I'm not entirely sure how to deal with the level translation between their data bus and the ESP32 board.

I know Espressif has officially stated that the ESP8266 has 5v-tolerant i/o
I could swear I also read somewhere that the ESP32 is unambiguously NOT 5v-tolerant.
I have a hunch that level-shifting Dallas 1-wire is more complicated than it seems, and that there's probably at least one "gotcha" lurking that will cause problems if I try blindly using something like a TXB0104 or MAX3378 between the sensors' data wire and the ESP32 board.

Here's the relevant code (when it works, it works for the original sensor or the original sensor + one or more of the new sensors... when it doesn't work, it fails to detect any sensors & just outputs "Temp:   " to Serial when running in loop().
#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 16
#define TEMPERATURE_PRECISION 12

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature dallasTempSensor(&oneWire);
int totalOneWireDevices = 0;
DeviceAddress tempDeviceAddress;

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

    dallasTempSensor.begin();
    totalOneWireDevices = dallasTempSensor.getDeviceCount();
    Serial.print("Locating devices...");
    Serial.print(totalOneWireDevices, DEC);
    Serial.println(" devices.");

    Serial.print("Parasite power is: ");
    if (dallasTempSensor.isParasitePowerMode())
        Serial.println("ON");
    else
        Serial.println("off");

    for (int x=0; x<totalOneWireDevices; x++) {
        if (dallasTempSensor.getAddress(tempDeviceAddress, x)) {
            Serial.print("Found device ");
            Serial.print(x, DEC);
            Serial.print(" with address: ");
            printAddress(tempDeviceAddress);
            Serial.println();
            Serial.print("Setting resolution to ");
            Serial.println(TEMPERATURE_PRECISION, DEC);
            Serial.print("Resolution actually set to: ");
            Serial.print(dallasTempSensor.getResolution(tempDeviceAddress), DEC);
            Serial.println();
        }
        else {
            Serial.print("Found ghost device at ");
            Serial.print(x, DEC);
            Serial.print(" but could not detect address. Check power and cabling.");
        }
    }
}

// function to print the temperature for a device

void printTemperature(DeviceAddress deviceAddress)

{
  float tempC = dallasTempSensor.getTempC(deviceAddress);
  //Serial.print("Temp C: ");
  //Serial.println(tempC);
  //Serial.print("Temp F: ");
  //Serial.print("    ");
  Serial.print(DallasTemperature::toFahrenheit(tempC)); // Converts tempC to Fahrenheit
}

void loop() {
  // put your main code here, to run repeatedly
    //Serial.print("Requesting temperatures...");
    dallasTempSensor.requestTemperatures();
    //Serial.println("DONE");
    Serial.print("Temp:   ");
    for (int x=0; x < totalOneWireDevices; x++) {
        if (dallasTempSensor.getAddress(tempDeviceAddress, x)) {
            //Serial.print("Temperature for device: ");
            //Serial.println(x, DEC);

            printAddress(tempDeviceAddress);
            Serial.print(" = ");
            printTemperature(tempDeviceAddress);
            Serial.print("    ");
        }
    }
    Serial.println("");
    delay(5000);
}

void printAddress(DeviceAddress deviceAddress) {
    for (uint8_t x=6; x < 8; x++) {
        if (deviceAddress[x] < 16)
            Serial.print("0");
        Serial.print(deviceAddress[x], HEX);
    }
}

trying to read 4 DS18B20 sensor probes .... what about only one?

The original one sometimes works if it's the only one connected. The new ones never work if they're the only one(s) connected. The new ones sometimes work if they're connected along with the original one.

stop trying to run all four until you get one working rock solid ...... you either have a wiring problem or software problem or power supply problem or a combination of the three ..... please post your code, if you can

Code added. As noted, the only factor that seems to influence whether it works "sometime" or "not at all" is the presence of the original sensor... present, alone or with the others, the sketch sometimes works. Without the older sensor present, it never works.


text:
Data transfer to and from Arduino to Raspberry Pi
I am trying to transmit MPU6050 accelerometer data + data from 3 potentiometers from Arduino to Raspberry Pi. I do post processing here (on Raspberry Pi) and then transfer the data back to Arduino to move actuators. However my problem is that when I try to write the processed data back to Arduino, I see that even the stream of incoming data from Arduino starts getting corrupted and everything becomes really slow . Even If I just read serial data from Arduino, things are slower if than if I do the processing on Arduino directly. Also, the accelerometer data seems to become unresponsive i.e. its value doesn't change if I move the accelerometer. Everything just works fine if all the processing is done on Arduino. I don't know what is going wrong. Below are my Arduino and Python functions / codes.
Arduino Code:
void send_rec_data(){

    Serial.print(Kp);
    Serial.print(",");
    Serial.print(Kd);
    Serial.print(",");
    Serial.print(Ki);
    Serial.print(",");
    Serial.println(Theta_x);

    delay(20);

  if (Serial.available()>0){ // Read data sent by Raspberry Pi / Piserial

    str_data = Serial.readString();

    int firstCommaIndex = str_data.indexOf(',');

    cmd = str_data.substring(0, firstCommaIndex); // This stores the Scaled output from the Raspberry Pi

    param1 = str_data.substring(firstCommaIndex+1); // This stores the error from the Raspberry Pi to decide motor roattion direction

    Output = cmd.toFloat(); my_error = param1.toFloat(); // Change the outputs from string to float

    blink_led(); // Blink LEDS if data is received from Raspberry Pi

  }

}

Python Code:
while 1:

    data = cont.get_serial_data(arduino)

    time.sleep(0.02)

    if data is not None:

        Kp, Kd, Ki, Theta_x = data

        print(" \n Arduino sent Kp = ", Kp , "Kd = ",Kd , "Ki = ", Ki, "Theta_x = ", Theta_x)

        cont.set_tunings(Kp, Kd, 0)

        Output_scaled = cont.Compute_PID_Output(Input = Theta_x) # Compute the output of PID Algorithm

        ff = str(Output_scaled)+','+str(cont.error)

        arduino.write(ff.encode())

        print("\n Computed data sent TO ARDUINO Output_scaled = ", Output_scaled, "Error = ", cont.error)

arduino.close()

I have spent quiet sometime to resolve the issue byputting delays, flushing buffer but nothing has worked so far. Can someone please help.
Thanks.

You should start by seriously thinking about your required communication timings: How many bytes do you want to send in each direction? At what baud rate? How often? Then read Blink without delay, just to learn how to write non-blocking code, then Reading Serial on the Arduino.

Thank you every one. I read through this forum and it also says the same things which you guys also suggested. I did the same thing and now everything is fast.
Serial.readString()

is indeed the problem.

Ok, without rewriting all your code, one thing I'm seeing here is a lot of sloooow string functions.
Pythons print function is extremely slow, for example. You should insert some timers in your code and see how long everything's taking. I think you will be surprised.
For a real-time application, which it sounds like this is, you need to be very careful and use timeouts and non-blocking code to make sure that everything doesn't grind to a halt unexpectedly.
You really need to re-write all this code, but I'll point out a few specific problems.
delay(20);
if (Serial.available()>0){
   ...
}

This is sloppy. If your python code does not process and return data before the 20ms elapses everything is going to go out of sync.
str_data = Serial.readString();

A look at the documentation reveals that this will only return on timeout, so this is guaranteed to block for 1s (I think that's the default), so there's another show-stopper problem. See this question for more info.
cmd = str_data.substring(0, firstCommaIndex);

This is also not sufficient. There is no synchronization between the pi and the arduino, so you have no guarantee that you won't get half of a previous transmission tacked onto the front of your data string (or worse). You need to make your own buffer and parse for the datastring. Or do some careful buffer clearing and use generous timeouts.
So TLDR; here's what you want to do (assuming you want to block while this exchange happens)

Clear the arduino receive buffer.
Send data packet from arduino.
Start receiving. Add received bytes to a char buffer.
Continuously search that buffer for your complete data packet.
Timeout after x ms. Handle the lack of returned data somehow.
If you do find the complete data packet, then process it.

On the Pi:

Poll for serial data. Add it to a buffer as it comes in.
Start deleting the oldest characters from the buffer if it's longer than 2x the longest data packet
Continuously search the buffer for your data packet. If you find it then continue below.
delete the data packet from the receive buffer.
process the data.
Send out return data packet to arduino.


text:
Arduino Mega RS485
I am following the instructions from this page to set up RS485 communication between two Arduinos.
https://arduino-info.wikispaces.com/SoftwareSerialRS485Example
My wiring varies slightly from the demo in that;
DI (data in)is Pin 18 (11 in the example)
RO (receive out) is pin 19 (10 in the example)
DE (data enable) and RE (receive enable) jumpered together and to pin 5
When I use the script, I can see the built in LED go dark when sending, but I don't get the echo back, nor do I see the LED on the remote blink for the receive.
Is there a fundamental problem with the pins I am using on the MEGA, or am I having difficulty with the script?
Thanks!

it is not possible to comment on your script for obvious reasons

Have you connected ground correctly?

I don't know what is wrong with your setup, but I suggest you start by
testing with a simpler program.
Below is a program that simply copies bytes from the USB link (the bytes
coming from the Arduino's serial monitor) to the RS-485 bus, or the
other way around depending on a #define. Both Arduinos should be
connected as follows:
Arduino     transceiver
--------------------------------
GND         GND
5V          VCC
TX1 (18)    DI (driver input)
RX1 (19)    RO (receiver output)

Additionally, connect:

on the sending side:

the USB plug to your computer
the transceiver's DE (driver output enable) and RE (receiver output
enable) to the Arduino 5V

on the receiving side:

the transceiver's DE and RE to the Arduino GND

Make sure both Arduinos are powered and share a common ground.
Optionally, you can connect the receiving Arduino to your computer, if
you can manage to tell the USB links apart.
Then load the program below to both of them. Make sure you comment-out
the line #define SENDER before programming the receiver.
// The "sender" copies bytes from the USB link (Serial) to the RS-485
// bus (Serial1). The receiver copies them the other way around.
// Comment-out this line for the receiver.
#define SENDER

#ifdef SENDER
HardwareSerial &inputStream  = Serial;
HardwareSerial &outputStream = Serial1;
#else
HardwareSerial &inputStream  = Serial1;
HardwareSerial &outputStream = Serial;
#endif

void setup()
{
    inputStream.begin(9600);
    outputStream.begin(9600);
    pinMode(LED_BUILTIN, OUTPUT);  // used to show activity
}

void loop()
{
    // Copy input stream to output stream.
    if (inputStream.available()) {
        digitalWrite(LED_BUILTIN, HIGH);
        outputStream.write(inputStream.read());
        outputStream.flush();
        digitalWrite(LED_BUILTIN, LOW);
    }
}

Now you can test sending strings through the serial monitor and
seeing whether both LEDs blink. If you connect both Arduinos to your
computer, you could use a terminal emulator (screen, putty, minicom...
depending on your OS) to get the characters back from the receiving
Arduino.
If all that fails, get a scope and look at all the signals along the
path.

Thanks! I can't tell you how much of a huge help that was! The part I had missed was setting up the transceiver's DE (driver output enable) and RE (receiver output enable) to the Arduino 5V
and on the receiving side:
the transceiver's DE and RE to the Arduino GND. Works a treat now!


text:
How to transmit string data using the rc-switch library?
I am using the rc-switch library for sending and receiving data. In rcswitch library, there is no method to send string data. I am using below method to send the string message in char buffer.
send_string("Hello World!");
---------------------------

void send_string(const char *str)
{
int i = 0;

for (char *p = str; *p; p++ ) {
mySwitch.send((i<<8) + *p, 16);
i++;
}
mySwitch.send((i<<8) + 255, 16);
}

And I am receiving is using this Serial.print((char)mySwitch.getReceivedValue()); build in method. But I am getting this message.
H
H
H
e
e
e
l
l
l
l
l
l
o
o
o

W
W
W
o
o
o
l
l
l
d
d
d
!
!
!

Now how can I get my original message?

stop sending characters multiple times

I need to send string. How can I do this?

check your code and remove the duplicate transmit code .... the problem may also be on the receiving end ... you may be printing each received character three times

I need something like this https://stackoverflow.com/a/44749986/5280371

The communication protocol used by this library is unreliable. Thus,
each code word is sent multiple times, 10 times by
default. One solution around this problem is to send
a “byte number” along with each byte you transmit. You would then
transmit 16-bit words, where the MSB (most significant byte) is the byte
number, and the LSB is the actual byte you want to transmit. Something
like this:
int i = 0;
for (char *p = str; *p; p++) {
    mySwitch.send((i<<8) + *p, 16);
    i++;
}

Oh, wait! That's exactly what you are already doing! So it appears that
you are already aware of this issue and you have even implemented a
solution. How come you are asking this question then?
OK, I'll assume in the following that you just forgot to tells us that
the code snippet above is not from you, and that you didn't even
understand what it is doing. And you also forgot to provide a link to
the source of that code. Please, next time read How do I ask a good
question? before asking, and provide all the relevant
information right in the question.
So now the problem is in the reading side. You have to use those byte
numbers to remove the duplicates. One (untested) solution could look
like this:
// Return a received byte, or -1 if none is available.
int receivedValue()
{
    if (!mySwitch.available())  // no byte available
        return -1;
    static uint8_t last_byte_number = 0xff;
    uint16_t code = mySwitch.getReceivedValue();
    uint8_t this_byte_number = code >> 8;
    if (last_byte_number == this_byte_number)  // this is a duplicate
        return -1;
    last_byte_number = this_byte_number;
    return code & 0xff;  // LSB is the byte to return
}

And you could use it to print the data on the serial monitor like this:
int c = receivedValue();
if (c != -1)  // if we really got a new byte
    Serial.write(c);

Many thanks. It's working but when I using Serial.print((char)c); it's not working properly. And how I convert it to String would you help, please?

@ChayanMistry: Don't use String objects. You can get a C string in the same manner as when reading from a serial port.


text:
Voltmeter using Arduino mega 2560 giving unexpected result after some time
I have been trying to construct a smart energy meter that can observe readings of 220v household. For now i am working on voltmeter. I have been following the circuit I attached. Transformer step down 220V to 6V. Zener diode is of 5V.
The output from the circuit( 5v max) is fed to arduino Mega 2560 A0 pin.
* I am powering arduino using a USB cable *
Arduino takes this voltage as input from pin A0 in form of analog values between 0 to 1023. 0 being 0 volt and 1023 being 5v.So any random analog value corresponds to X=(5/1023)*Y where Y is obtained analog value. X is then multiplied by a value obtained by hit and try method (165 in my case) to reach the exact reading of voltage in line observed via multimeter.
Now the problem is that, everything works fine when i calibrate it, but after some time when i switch circuit on the value is inaccurate by margin, and i have to calibrate it again and again every time I turn circuit on after some time.If i switch circuit on soon after switching it off, it gives almost accurate value. I guess this issue is due to the capacitor, but i don't know anything about it or how to solve it I have constructed the same circuit more than 5 times, soldering it 3 times and 2 times on bread board and i am sure there is no problem with my implementation, verified it many times.
this is my code:
float V; // Voltage samples
float V0;

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

void loop() {
  for(int i=0; i<=20000; i++){
    V = V + analogRead(A0);
  }
  V = V / 20000;
  V = round(V);

  float V0 = V * (5.0 / 1023.0);
  I0 = I0 * 165; // has to be callibrated again and again each time circuit is switched on after a while

  Serial.print("Voltage = ");
  Serial.print(V0);
  Serial.println(" -------------- ");
  delay(1500);
}

this is the link i am following
http://engineerexperiences.com/3-phase-smart-energy-meter-using-arduino.html
Any help would be appreciated, Thanks!

you monitor the household or only some appliance or device?

thank you for asking Mr. Edgar Bonet, my aim is to monitor electrical consumption of a household.

With that circuit you can expect a roughly 10% variance in the output voltage depending on the exact moment at which you sample the voltage.
The basic circuit you have, and the waveforms generated, are like this:

That green waveform is the one you are reading. As you can see, exactly where you sample defines what the result will be.
Since you're trying to average over an undefined period (20,000 samples of how long per sample exactly?) you're not going to get a particularly well defined output.
You should change your sampling strategy to perform multiple samples over a well defined period to find the maximum value. That is the value you should then use in your calculations.
Ideally, you want to repeatedly sample for at least one entire waveform cycle. At 50Hz that's a period of 20ms (17ms for 60Hz).
For example:
uint16_t maxval = 0;
uint32_t ts = millis();
while (millis() - ts < 20) {
    uint16_t val = analogRead(0);
    if (val > maxval) {
       maxval = val;
    }
}

// Use "maxval" in your calculations.

With this strategy, because you're looking for the peak value, you don't care about the impact that the capacitor has on the circuit (except that it will remain artificially high for a period if the voltage drops), so you could actually simplify the circuit and remove that capacitor completely.

he uses average of 20000 A0 readings

Yeah, now the post is formatted I see that. That's not really ideal though, since you're dependent on a) how fast the ADC reads, and b) how fast the capacitor discharges. By finding the max over at least 1 wave period you don't care about either of those.

Re-worded it to fit that existing method a little more.

Honorable Majenko, first of all thank you for sparing some time and communicating amazing knowledge to me.
Earlier i was using this approach
for (int i=0; i<=39; i++){
adc_int[i] = analogRead(A0);
}
int max = adc_int[0];
for(int i=0; i<=39; i++){
if(max < adc_int[i])
max = adc_int[i];
}
and i used this peak value in my calculations the results were unpredictable after time as i explained in my question, anyway I will follow what you have instructed and get back to you soon after implementing your teachings

I just wanted to add some points to what Majenko already said.
You are making a measurement device, so you need a precise reference. So why are you using the 5V reference?
Your 5V in your circuit is assumed to be stable. But is it? Maybe some time you are using the PC to power it, then you attach a lot of loads to the USB ports, then you use a wall USB power supply. Every time the 5V can change (see here for instance). A variation in the supply of +/-5% will be translated in a +/- 12V for a 240V input (I don't know if this is above or below your expected accuracy).
The solution is to use the internal reference, which is an internal peripheral used explicitely for measuring analog sources.
In your case (Arduino MEGA 2560) you have a 1.1V or a 2.56V internal references. Your transformer is a 240->6V transformer, which means the value you should read after it is around 8.5V (6Vrms has a peak of 6*1.415 = 8.5V). After the voltage divider, this becomes 1.53 V. Consequently you can use the 2.56V reference in this case. To do so write, in your setup function, analogReference(INTERNAL2V56);. Then your readings will be relative to 2.56V rather than 5.0V (so float V0 = V * 2.56 / 1023.0;).
(Note: the way to implement this was taken from the arduino reference manual; I never implemented it, so it may require tweaking)


text:
minimal code for multiple buttons de-bouncing
i have 4 buttons attached to 4 pins configured as inputs with internal pull-up activated...
is this function sufficient to get a debounced state of the pressed button?
byte buttonPressed(){
  byte btn = 0;
  if (digitalRead(30)==LOW) btn = 1; else
  if (digitalRead(9)==LOW) btn = 2; else
  if (digitalRead(31)==LOW) btn = 3; else
  if (digitalRead(8)==LOW) btn = 4;
  delay(20);
  return btn;
}

any strictly necessary improvements are welcome...

i write the code a-la-va-vite, thanks Edgar.

Currently there is no debouncing present in your code. The delay is completely useless.

Oops! I deleted my previous comment, which was wrong: I didn't notice your elses due to your very unconventional indent style.

Yes, your code should work as the most basic debouncing, although the
debouncing time may be a little bit short. Note however that, in many
instances, one would like to have a little more that the most basic. One
may also want:

deglitching: when the button is held down, your hand may make the
contacts move a little bit, making spikes in the reading that are not
associated with a real change in the button position; you don't want
those spikes to read as "released and pressed again"
edge detection: many times you are more interested in the button
press event than in knowing whether the button is down or up; this can
be handled by another function, but it can be convenient to integrate
it with the debouncing
non blocking operation: your program may have better things to do
than wasting CPU cycles inside delay().

Those are the reasons most debouncing codes are significantly more
complex. But it's often worth it.

Edit 1: In view of the comments, some clarification seems to be
needed. There are two kinds of glitches a mechanical button can
experience:

when the button is mechanically changing position, i.e. it is being
depressed or released; this is called a bounce
when the button is being held down, especially if the pressure on the
button is low and the finger applying that pressure is somewhat
shaky.

Most debouncing libraries you can find actually address both kinds of
glitches. Thus, they do more than just debouncing, they do what I
called “deglitching”. The previous answers implicitly assume that a
proper debouncing code must address both kinds.
The code posted in the question only addresses the first kind of
glitches, i.e. the bounces in the strict sense. That's why I wrote
that it does the “most basic debouncing”. It is however susceptible to
the second kind of glitches. So yes, with this code glitches can persist
even after debouncing.
Edit 2: As an example, consider the Bounce 2 library. It
provides edge detection, non blocking operation and, in the default
configuration, full deglitching. However, it can be configured to use
an alternative debounce algorithm called “Lock-out
interval”, which is more responsive but does not protect against the
“type 2” glitches mentioned above: it “does not cancel noise”, as the
documentation puts it.

is there any relation between deglitching and debouncing?...

@moyoumos: A bounce is just a specific kind of glitch that happens while the button is being depressed or released. If you do deglitching, e.g. by waiting until a level is stable, you are also debouncing. The converse is not true: the code you posted removes bounces but it does not properly clean glitches that happen while the button is held down.

according to what you say glitchs can exist or persist even after debouncing!!!

@moyoumos: Yes, see amended answer.

i think that any debouncing algorithm based on a time interval can't do de-glitching since bounces (or glitchs) persist after this time interval!!! am i wrong?

@moyoumos: Time-based deglitching is based on the premise that if the button has been giving a consistent reading throughout a given time interval, then that reading is not a glitch (glitches are short).

No. Actually it just checks each button one by one. In addition only the last button is checked since it overwrites the btn variable.
The simplest way to use debouncing button 1 is:
byte buttonPressed()
{
    byte btn = 0;

    byte btn1Before = digitalRead(30);
    delay(50); // Wait 50 ms, or 100 depending on your debouncing time
    byte btn1After = digitalRead(30);

    if ((btn1Before == LOW) && (btn1After == LOW))
    {
        btn = 1;
    }
}

You have to do similar as the others. You can use only one delay (just add 4 before and after variables and check them.
byte buttonPressed()
{
    byte btn = 0;

    byte btn1Before = digitalRead(30);
    byte btn2Before = digitalRead( 9);
    byte btn3Before = digitalRead(31);
    byte btn4Before = digitalRead( 8);

    delay(50); // Wait 50 ms, or 100 depending on your debouncing time

    byte btn1After = digitalRead(30);
    byte btn2After = digitalRead( 9);
    byte btn3After = digitalRead(31);
    byte btn4After = digitalRead( 8);

    if ((btn1Before == LOW) && (btn1After == LOW))
    {
       btn = 1;
    }
    else if ((btn2Before == LOW) && (btn2After == LOW))
    {
       btn = 2;
    }
    else if ((btn3Before == LOW) && (btn3After == LOW))
    {
       btn = 3;
    }
    else if ((btn4Before == LOW) && (btn4After == LOW))
    {
       btn = 4;
    }

    return btn;
}

Note that this way the program will be unresponsive for 50 ms. If you do not want this, you have to use millis, but this makes it more complex. Check the debouncing example on the Arduino site.

why check the before and after state of the button?...

By checking that the state again after the debounce time (I chose 50 ms). If the debouncing is finished, it will show twice LOW.

i think that if the hardware detects the first LOW it's because the button is Pressed, then a delay (20 or 50ms..) is sufficient to ignore all bounces!!...

I wanted to stick to the original program. If no interrupts are used, this way the priority can be changed by software.

No - simply delay()ing after reading the button doesn't tell you whether the button is still bouncing or, more importantly, what its final state is. Debouncing requires you to know that the button

changed state;
has stopped changing state;
what state it has settled into.

You'll need to notice the current state doesn't match the last debounced state you saw; then either test it frequently until it doesn't change state again for some number of tests, or simply wait the known maximum time it takes to settle; then read, store, and return the final state.

While @MichelKeijzers answer is a nice solution for simple querying in the main loop. This is not practicable for interrupts. Interrupts can block the entire MCU and interrupting an interrupt routinte can cause serious problems.
Depending on your requirements I'd suggest to take a look at using capacitors and resistors for debouncing. With that you achieve simpler code and no need for dealing with hardware issues in software. Of course at the expense of additional parts in your hardware setup.
If your MCU for example is using a pin as interrupt, that interrupt would be called only once as opposed to bouncing one.


text:
Minimum value of a pull-down resistor
I've just started working with the Arduino UNO SMD edition and I'm also quiet new to electronics in general. Recently I wanted to try out this tutorial https://www.arduino.cc/en/Tutorial/Button and I ran into a problem with the pull-down resistor. In the tutorial they recommend a 10kOhm resistor but I've got only 460Ohms laying around. Obviously I could link dozens of them in series but I was wondering if it is possible to replace this 10k resistor with 460 Ohms. Would that be enough? I'm assuming, that the 5V Output can supply up to 500mA (datasheet) and the ground can take up to 500mA. Following Ohms Law I = U/R given 460Ohms there should be a current of 11mA flowing. Is it correct that the ground can take this amount of current?
Hope you can answer my question and may point out mistakes i made.
Greetings Tmirror

11mA is within the limits of an Arduino pin (which is 20mA). The only problem is that it wastes more electricity while the button is pressed. This is more of a issue when running of a battery.

You are talking about an I/O pin I think. I'm talking about the 5V power supply pin, which is directly connected to the power source. This one can supply up to 500mA not 20mA. Or do I missunderstood something?

Sorry, you’re right. Disregard my first sentence. Second part is still valid. An alternative would be to use internal pull-up resistor that is in the ATMega328. That way you don’t need to add any resistor.

Thank you for your answer. So my assumption and math was correct? It's not dangerous for the Arduino (or me laugh) to only use 460 Ohms?

Your calculation was correct. No danger. Power dissipation is 50mW, so assuming you are using a regular quarter watt throughhole resistor, there is also no danger of the resistor overheating.

Why are you messing with pulldown resistors at all? Use the internal pullup resistor instead.  Connect your button between the pin and Gnd so the pin goes low when pressed.
Here's a simple code example:
byte inputPin = 2;

void setup(){
    pinMode (inputPin, INPUT_PULLUP); // turns on internal pullup
    Serial.begin(9600);
}

void loop(){
    if (digitalRead(inputPin) == LOW){
        Serial.print ("button pressed");
    }

    else {
        Serial.print ("button open");
    }

    delay(200);  // limits reading to 5 times a second to avoid flooding the PC with messages

}

i corrected the formatting of your example code .... please do not post improperly formatted code. .... correct indentation is the first thing that beginners need to learn.

How do you get the code box? When I edit the post, I don't what was added to create the code box.


text:
DLHR differential pressure sensor SPI
I am new to using SPI with an Arduino. But I'm trying to wrap my head around the "coding protocols"/syntax of the Arduino IDE code. I understand the basics of how SPI works conceptually, just not how to actually use it with an Arduino Mega 2560. Most examples on YouTube are about how to play with LEDs and the examples on the Arduino blogs are very specific for two specific examples.
Analog reading is incredibly easy (which is what I am used to doing).
I have an AllSensors DLHR-L05D 18 bit differential pressure sensor (SPI, not I2C) [Datasheet: https://www.allsensors.com/cad/DS-0350_Rev_B.PDF]. Page 5 has the commands needed. From my understanding, I need to somehow send from the Arduino to the sensor a "start" sequence (0xAA) and a "read" (0xF0 and 0x00) sequence, but I'm not sure what that looks like when coding it.
Any and all advice/direction on how to "code up" this SPI device would be greatly appreciated!

I’d suggest finding one of the Adafruit sensors that uses SPI, and read source code of the library they provide for that sensor.

By any chance, are you planning to use this to measure static pressure between the return and supply of a HVAC system? If you are, I'm curious... do you just connect a few feet of plastic tubing (like you'd use for an aquarium air hose) to each barb, drill a small hole in the two ducts, shove a tube into each, and seal up around the tubes? Or do you need something specific on the duct side of the tube, like a metal tube of some kind? I know that for measuring atmospheric pressure, almost anything will do... but suspect distinguishing between 0.5" WC and 0.6" WC is a bit more demanding...

I'm using this sensor to measure atmospheric pressure differences in a moving object (i.e., using it for a pseudo-pitot-static system), so I am using plastic pitot tubes typically used in remote control aircraft. The data sheet says that this sensor is typically used in HVACs, but I haven't tried it in my HVAC per se.

Turns out, someone actually has a specific library to handle the I2C for this sensor, which helps tremendously: https://github.com/jeremycole/AllSensors_DLHR


text:
Using attachInterrupt() to make a reset button for my code?
I have used attachInterrupt() to reset my program to the beginning. It actually interrupts while running the 3 states as shown below inside of the if statement but when I press the actual button it does not exit, it goes to the function and continuing to the next state. It only works (means exiting/resetting) after all three states have executed completely.
if(buttoncount<2){
  originalstate();
  alertstate();
  evacuationstate();

I would like to make a button to stop the program while running in the middle and start again.
Code:
// Declaring pins

// Input pins
const int sensor1button_pin = 6;
const int sensor2button_pin = 3;
const int sensor3button_pin = 4;
const int sensor4button_pin = 5;
const int sensor5button_pin = 2;
const int sensor6button_pin = 15;
const int sensor7button_pin = 15;

// Output pins
const int led1_pin = 8;
const int led2_pin = 9;
const int led3_pin = 10;
const int led4_pin = 11;
const int buzzerpin = 15;

// Initialy buzzer at false mode
boolean flag1;
boolean flag2;
int flag3 ;

// for leds
int ledState1 = LOW;   // Original
int ledState2 = LOW;   // Alert
int ledState3 = LOW;   // Evacuate
int ledState4 = LOW;   // Isolate

// Buttons
int button1_state = LOW;
int button2_state = LOW;
int button3_state = LOW;
int button4_state = LOW;
int button6_state = LOW;
int button7_state = LOW;
int button5_state = LOW;

// Other variables
int buttoncount = 0;
int reset_switch=0;

void setup() {
  // INPUT pins
  pinMode(sensor1button_pin, INPUT);
  pinMode(sensor2button_pin, INPUT);
  pinMode(sensor3button_pin, INPUT);
  pinMode(sensor4button_pin, INPUT);

  pinMode(sensor5button_pin, INPUT_PULLUP);

  attachInterrupt(digitalPinToInterrupt(sensor5button_pin), clearreset, CHANGE);

  pinMode(sensor6button_pin, INPUT);
  pinMode(sensor7button_pin, INPUT);

  // OUTPUT pins
  pinMode(buzzerpin, OUTPUT);
  pinMode(led1_pin, OUTPUT);
  pinMode(led2_pin, OUTPUT);
  pinMode(led3_pin, OUTPUT);
  pinMode(led4_pin, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  button1_state = digitalRead (sensor1button_pin);
  button2_state = digitalRead (sensor2button_pin);
  button3_state = digitalRead (sensor3button_pin);
  button4_state = digitalRead (sensor4button_pin);
  button5_state = digitalRead (sensor5button_pin);
  button6_state = digitalRead (sensor6button_pin);
  button7_state = digitalRead (sensor7button_pin);

  Serial.println(digitalRead (sensor5button_pin));

  if( button1_state == HIGH || button2_state == HIGH || button3_state == HIGH || button4_state == HIGH) {
    delay(280);
    buttoncount = buttoncount + 1;
  }

  if (button1_state == HIGH || button2_state == HIGH || button3_state == HIGH || button4_state == HIGH) {
    if(buttoncount<2){
      originalstate();
      alertstate();
      evacuationstate();
    }
  }
}

// LED lighting arrangements
void originalstate() {
  digitalWrite(led1_pin, HIGH);
  digitalWrite(led2_pin, LOW);
  digitalWrite(led3_pin, LOW);
  digitalWrite(led4_pin, LOW);
  delay(1500);
}

void alertstate() {
  digitalWrite(led1_pin, LOW);
  digitalWrite(led2_pin, HIGH);
  digitalWrite(led3_pin, LOW);
  digitalWrite(led4_pin, LOW);
  delay(1500);
}

void evacuationstate() {
  digitalWrite(led1_pin, LOW);
  digitalWrite(led2_pin, LOW);
  digitalWrite(led3_pin, HIGH);
  digitalWrite(led4_pin, LOW);
  delay(1500);
}

void isolatestate() {
  digitalWrite(led1_pin, LOW);
  digitalWrite(led2_pin, LOW);
  digitalWrite(led3_pin, LOW);
  digitalWrite(led4_pin, HIGH);
}

// Clear or reset back to the begin

void clearreset() {
 button1_state = LOW;
 button2_state = LOW;
 button3_state = LOW;
 button4_state = LOW;
 button5_state = LOW;
 button6_state = LOW;
 button7_state = LOW;

 digitalWrite(led1_pin, LOW);
 digitalWrite(led2_pin, LOW);
 digitalWrite(led3_pin, LOW);

 buttoncount = 0;
 exit;
}

The arduino has a reset pin,   pull it to ground with switch,and it will reset from the beginning.

i tried your one but it completely reset the arduino , but that's fine for the reset button  .any way ,i can interrupt the program while running and change to any other function  of the program . such as when we press the reset button it goes to reset, if we press a push button it goes to some any other function.

set a flag variable in the interrupt service function ... check the flag at the beginning of each state function and skip digitalWrite() and delay() commands if the flag is set

you could also use a state variable and call the state functions depending on its value .... use the interrupt to set the state variable to a specific value

you have two identical if statements one after another .... merge the contents into one

You need non-blocking code in combination with a finite state machine:
 1. Non-blocking code: You should not use delay(), since it is just busy waiting. Instead use the millis() function to measure the time distance between the last execution of the code part and the current time. If it has reached a certain level (like 1500ms), execute the code and save the current time in a timestamp as a reference for the next execution. Refer to the BlinkWithoutDelay example of the Arduino IDE. There are also many tutorials for that on the internet, so I will not explain this further here.
 2. Finite state machine: Here your loop() function contains of a switch statement with a (mostly numerical) state variable as parameter. Every case contains only the code for its special case. To get from one state to another you would just change the state variable to the corresponding value. You can also do this in an ISR (if you set the state variable as volatile). If you non-blocking code as described above, the loop() function is executed very fast, so that the change of the state variable inside the ISR takes effect almost immediately (delay will not be sensable by a human). Something like this:
volatile int state=0;

void isr_function(){
    state++;
    if(state>1) state=0;
}

void loop(){
    switch(state){
        case 0: // state 0
            do_something();
            break;
        case 1: // state 1
            do_another_thing();
            break;
    }
}

Note: Depending in your target you may want to add code for button debouncing, so that one button press is really sensed as one press, not more. This is relevant most times you have non-blocking code. Debouncing has been described many times in the internet, so just Google it

You should enable verbose compilation in the IDE. You will then have a
chance to see this compiler warning:
warning: statement is a reference, not call, to function ‘exit’
  exit;
      ^
warning: statement has no effect

Naming a function without calling it is a way to get a pointer to the
function. It's equivalent to &exit. But since you do nothing with that
pointer, the statement has no effect, and that's exactly what the
compiler is warning you about.
You presumably want to call the exit() function, like in:
exit(0);

Edit: That being said, exit() is probably not what you want.
This function just stops your program by putting it in an infinite loop.
If you want it to restart from scratch, you can first declare
extern "C" void __init();

then, instead of exit(0); call __init();. This will send your
program to the beginning of the initialization code from the C runtime,
which is responsible of resetting the stack and initializing the memory
(.data and .bss sections). Note that this is not equivalent to a
hardware reset because:

doing this does not run the bootloader
more importantly, it doesn't reset the IO registers of the peripherals
to their default reset state.

... .any way, I can interrupt the program while running and change to any other function of the program. such as when we press the reset button it goes to reset, if we press a push button it goes to some any other function.

Interrupt will not help you achieve your requirement. You want to 'reset the state' of your running sketch. But after the interrupt the MCU returns in the code where it was before interrupt and continues.
You should implement the 'reset of the state' in your algorithm. In a loop of a non-blocking sketch you can check the button and if it is pressed, then 'reset the state' of the sketch.

Did you read my answer? __init() completely resets the state of the program. There is no “after the interrupt”: since __init() does not return, the following reti (return from interrupt) instruction will never be executed. And there is no “state where it was before interrupt”: that state was on the stack, and the stack is reset by __init().

@EdgarBonet, I did read your answer and it is correct. I answer other point of view, not what he coded, but what he wants to achieve (second comment). He doesn't want to reset the program, only the 'state of the program'.

Then you should clarify your answer, say that you are proposing a different approach (the OP specifically asked to “stop the program [...] and start again”), adjust the wording accordingly (“must” → “should”), tell if/how the proposed approach is better, and maybe explain how resetting the “state of the program” (whatever you mean by that) is different from resetting the program itself.


text:
Error compiling to teensy 3.6
Problem:
In short, the Arduino IDE won't compile a sketch for the Teensy 3.6. It gives the error:
exec: "A:\\arduino-1.8.5\\hardware\\teensy/../tools/teensy_post_compile": file does not exist
Error compiling for board Teensy 3.6.

What I have tried
-Re-installing teensyduino (And yes, I have it installed, along with a compatible Arduino IDE (version 1.8.5))
-completely wiping the IDE and re-installing
-using a different USB cable
Other information
The OS I'm using is Windows 10
A broken Teensy is not out of the question, as I have been doing some soldering on it and I may have slipped or something, although I don't think that's the problem
Thanks in advance.

are you running the IDE from a floppy disk? .... A: is the disk name for the floppy disk

It's my USB stick, I assigned it the letter A: so that it's easy to remember

Also so other programs that reference it (e.g. my python programs) don't have to be changed on the whim of windows

I found a fix, it's not elegant or easy to use, but it works.
Steps to take
-Install a fresh version of teensyduino
-Make a copy of [arduino directory]/hardware/tools and save it anywhere as a backup (sometimes weird, buggy things happen)
-Make a copy of teensy.exe from the tools folder, and put it in the same directory as arduino.exe
-every time you run arduino.exe (don't double-click on a .ino file), first start teensy.exe and everything should work.
Sometimes, the tools directory gets deleted (It just seems a bit buggy), if that happens copy the backup and paste it where it should be ([arduino directory]/hardware/tools)
Also occasionally teensy.exe gets deleted, so make sure to have a backup of that as well.


text:
How to stop sending the last received char of UART echo function?
I developed a code for uart based ISR with linear buffers, the problem is that it keep sending the last received char in Arduino IDE.
Here's the application code:
#include "uart_new.h"

void setup() {
uart_init_new(103);
DDRB = 0xff;
}

void loop() {
uint16_t c;
c = get_char();
if (c & NO_DATA)
{
  PORTB |= (1<<PB5);
  _delay_ms(500);
  PORTB &= ~(1<<PB5);
  _delay_ms(500);
}
else
{
  put_char(c);
}
}

The header file:
#ifndef uart_new_H_
#define uart_new_H_

#define NO_DATA     0x0100
#define Buf_OF      0x0200
#define FR_Er       0x0400
#define DOR_Er      0x0800
#define PARTY_Er    0x1000

#define buf_s 32
#define buf_mask Buf_s - 1
#define baud_rate 9600

void uart_init_new(uint16_t ubrr);
void put_char(uint8_t data);
uint16_t get_char(void);
void put_s(uint8_t *str);

#endif // uart_new_H_

The source code:
#include <avr/io.h>
#include <Arduino.h>
#include "uart_new.h"

/*******************************************
If you want to prevent reading a string
backwards then you need FIFO implementation
*******************************************/

static volatile uint8_t rx_buf[32],tx_buf[32];
static volatile uint8_t rx_p,tx_p,rx_cnt,tx_cnt;
static volatile uint8_t rx_errors,tx_sBuf,rx_sBuf;

void uart_init_new(uint16_t ubrr)
{
    rx_p=0,tx_p=0,rx_cnt=0,tx_cnt=0;
    UBRR0H = (uint8_t)(ubrr>>8);
    UBRR0L = (uint8_t)ubrr;
    UCSR0B = (1<<RXEN0)|(1<<TXEN0)|(1<<RXCIE0); //Enable Rx and Tx & Receive interrupt
    UCSR0C = (1<<USBS0)|(3<<UCSZ00);            //Set frame format: 8data, 2stop bit
}

uint16_t get_char(void)
{
    if (rx_cnt == 0)
        return NO_DATA;
    else if (rx_p < rx_cnt)
        return rx_buf[rx_p++];
}

void put_char(uint8_t data)
{
    if (tx_cnt < 32)                        // start count the input data
        tx_buf[tx_cnt++] = data;            // 1st input location tx_cnt

        UCSR0B |= (1<<UDRIE0);
}

void put_s(uint8_t *str)
{
    while (*str)
        put_char(*str++);
}

ISR(USART_RX_vect)
{
    if (rx_cnt < 32)                        // start count the received data
        rx_buf[rx_cnt++]=UDR0;              // 1st output location rx_cnt
    else
        rx_cnt = 0;                         // when the counter reached max value, reset it, overwrite everything

if (!(UCSR0A & (1<<RXC0)))
        UCSR0B &= ~(1<<UDRIE0);
}
ISR(USART_UDRE_vect)
{
    uint8_t i;
    if (tx_p < tx_cnt)                      // check if pointer < counted data
        UDR0 = tx_buf[tx_p++];
        else
        {
            for (i=0;i<tx_cnt;i++)
                tx_buf[i]=0;
            tx_p = 0;                       // when the pointer reach max value, reset it
            tx_cnt= 0;                      // also reset counter for new transmission
            UCSR0B &= ~(1<<UDRIE0);         // disable empty data register interrupt
        }
}

If the there's a received char, then ISR is executed, the function exit the LED blink loop, but when the receive stops and there're no more data it doesn't return the blink state and keeps sending the last received char. How to solve this problem?

We cannot see the code inside your UART functions. You have to show us. Also: are you sure, that the buffer is emptied correctly? It seems as the last byte is not deleted after the read, hence getting read over and over again

Post updated, added the main source code.

How is the NO_DATA const defined?  Are you sure, that you have to use the bitwise & in the if statement? Shouldn't you check for equality with ==? Please also include the corresponding header file

The Arduino core library provides the Serial object, which is a perfectly good driver for the UART. Why would you want to replace it with your broken implementation? 2. If you really want to reimplement it, start by learning how a ring buffer works.

Well, I want to learn how to program microcontroller peripherals so I get more skills in programming, if I'm having problems now then it means I'm still at a low level in programming. I know Serial and I know other ready pre-written codes but I have to be good at programming core peripherals so I'm good to go with larger projects.

Post updated with header file.

There are many, many problems with this code. The most fundamental flaw
is that it uses linear buffers, where you should be using circular
buffers instead. I'll come to this later. Now, if we look
at the details, in the header file:
#define Buf_OF      0x0200

This, and a few other macros, serve no purpose. Do not put "TODO" items
in the code: put them in a TODO file, or as comments. Strive to always
have your code in a clean state. More so when you post it in a public
place.
#define buf_mask Buf_s - 1

This is presumably intended to be used as a bit mask, but it will not
work reliably. For example, if you try to complement the mask as
~buf_mask, the preprocessor will expand that to ~Buf_s - 1, and the
compiler will interpret it as (~Buf_s) - 1, which is not what you
want. You should always parenthesize any expression you use in a macro,
as
#define buf_mask (Buf_s - 1)

Later,
void put_s(uint8_t *str);

If you want to be able to issue calls like put_s("Hello!");, then you
should declare the function as:
void put_s(const char *str);

Now, in the implementation, you have:
static volatile uint8_t rx_errors,tx_sBuf,rx_sBuf;

All those are unused. Remove them. Again, this is supposed to be a
program, not a TODO list.
Later,
uint16_t get_char(void)
{
    if (rx_cnt == 0)
        return NO_DATA;
    else if (rx_p < rx_cnt)
        return rx_buf[rx_p++];
}

The compiler should have warned you about this: what if both conditions
are false? In this case the function will return by reaching its end,
with no specified return value. This is undefined behavior. You should
probably return NO_DATA in this case. But then, that's what you should
return every time you are not returning valid data, so the function can
be simply written as:
uint16_t get_char(void)
{
    if (rx_p < rx_cnt)
        return rx_buf[rx_p++];
    else
        return NO_DATA;
}

Later, in ISR(USART_RX_vect),
if (rx_cnt < 32)
    rx_buf[rx_cnt++]=UDR0;
else
    rx_cnt = 0;

If you set rx_cnt to zero without updating rx_p, then the subsequent
characters that you will put in the buffer will be ignored by
get_char() until you fill the buffer up to rx_p. Thus you presumably
want to set rx_p to zero also. And if you do this at the start if the
ISR, you ensure that at least the current character is not lost:
// when the counter reached max value, reset the buffer
if (rx_cnt >= 32) {
    rx_p = 0;
    rx_cnt = 0;
}
rx_buf[rx_cnt++]=UDR0;

Further in the ISR:
if (!(UCSR0A & (1<<RXC0)))
    UCSR0B &= ~(1<<UDRIE0);

This makes no sense: if you have no pending character in the receive
register (which you should not have, as you have just read that
register), then you disable the ISR that serves the transmitter. The
transmitter and the receiver should be able to work independently:
remove those lines.
Then, in ISR(USART_UDRE_vect):
for (i=0;i<tx_cnt;i++)
    tx_buf[i]=0;

This serves no purpose. If you handle your buffers properly, you should
never access uninitialized data in them. Thus you will never read the
zeroes you are writing here. Again, remove those lines.
If you implement all the fixes above, you should end up with a code that
“kind of” works. There are still a couple of issues though:
Race conditions
If get_char() gets interrupted by ISR(USART_RX_vect), you can get
what is known as a “race condition”, which can lead to incoherent
behavior or data corruption. For example, testing rx_p<rx_cnt is not
atomic: the CPU has to read rx_cnt from RAM, then read rx_p, then
compare them. If the interrupt fires between the two memory reads, the
ISR can set both values to zero, then the test will compare the old
rx_cnt with the new rx_p (which is now zero) and incorrectly assume
there is valid data to be returned.
There are other places where this can byte you. For example, rx_p++ is
not atomic either, it's a read-modify-write sequence that can very well
be interrupted in the middle. And there are similar issues if
put_char() gets interrupted by ISR(USART_UDRE_vect).
The fix for these issues is to disable interrupts while you are in the
“critical sections” that access data shared with the ISRs. This can be
done using noInterrupts()/interrupts() pairs or, if you prefer the
avr-libc style, with atomically executed code blocks. For
example:
#include <util/atomic.h>

uint16_t get_char(void)
{
    uint16_t result = NO_DATA;
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
        if (rx_p < rx_cnt)
            result = rx_buf[rx_p++];
    }
    return result;
}

A similar protection is needed in put_char().
Linear buffers
This is the main flaw, because it will require you to rethink a
significant part of your code. Imagine what can happen if the UART
transmitter lags slightly behind your program calling put_char(). Say
you reach tx_p = 30 and tx_cnt = 32. Then your
buffer has 30 “empty” cells (from 0 to 29 the space is available, as
that data has already been sent) and two cells with bytes pending to be
sent (at positions 30 and 31). If you call now put_char() to send an
extra byte, that byte will be lost (because tx_cnt<32 is false). This
is unacceptable: you should not loose data when the buffer is almost
empty!
The solution is to put the extra byte at position 0, the next one at
position 1, etc. But this creates a complication: now the pending bytes
are at positions 30, 31, 0, 1... At this point your buffer becomes a
circular buffer. It's not a big deal, but you must
read about the subject before you try to implement it.
Note that the same issue applies to the receive buffer: both buffers
should be made circular.

Thank you very much for the explanations and declaring my mistakes, now I'm trying to improve the code with linear buffers until I get the code to work with very minimal errors, then I move to circular buffers. My question is that can linear buffers be very efficient as circular buffers?

Again, thank you very much, I actually tweaked the code little more this morning. I would like you to provide me with your opinion. But where should I post the new code?

Also, I want you to know that I want to do more testing on uart and I want to test my skills in C and how I can solve problems. I know that circular buffers are the best option for uart, but even so I'm trying to do the best code with linear buffers, then I move to circular buffers.


text:
const char* to double
I'm trying to use an if statement to check when the time goes past a specific point and run a specific function. To do this I'm looking to convert time into a double and running something along the lines of if(timeCurrent >= 8.30). I seem to however have an issue with the conversion part, normally I'm aware the standard practice in C++ would be to do the following:
DateTime now = rtc.now();
static char buffer[80];

sprintf(buffer, "%02d.%02d", now.hour(), now.minute());
String str(buffer);
double timeCurrent = strtod(str);

However, this doesn't work for Arduino. What can be done to create the same desired function?

this may help ... you made no mention of any research that you may have done ... https://playground.arduino.cc/Code/Time

convert buffer to float, not String. but there are more elegant end efficient solutions. if you really want float then 0.01 * m + h

There is really no need to take the extra effort in converting first to char buffer, then String and then double. Just convert the ints from the RTC directly to a float like juraj wrote. And I doubt, that your code is a good practice in C++ either

I'm aware the standard practice in C++ would be to do the following... Umm... no, it certainly would not. What would give you that impression?

Don't do that. Converting a time to double is highly inefficient.
Moreover, your approach suffers from a rollover issue every 24h.
If you just want to compare the time of day with 8:30, you can do it in
a very straightforward way:
if (now.hour() > 8 || (now.hour() == 8 && now.minute() >= 30))

If the long if annoys you, you can put the comparison logic inside a
static inline function. If you really want to combine hour and minute
into a single number, then convert to an integer rather than a double:
if (now.hour() * 100 + now.minute() >= 830)

This can be made more efficient if you think in binary rather than
decimal: you can build a 16-bit number with one byte holding the hours
and the other byte holding the minutes:
if ((now.hour() << 8) | now.minute() >= (8 << 8) | 30)

Again, you may encapsulate the ((a)<<8|(b)) in a macro or static
inline function if it helps with readability. If you want to compare to
an absolute time, your best option is to build a DateTime object
representing the deadline, and compare with now as:
// Assume timeout should be today at 8:30.
DateTime timeout(now.year(), now.month(), now.day(), 8, 30, 0);
if (now.secondstime() >= timeout.secondstime())

Here the secondstime() method is used to convert the DateTime into a
scalar number (a 32-bit integer of type time_t) that can be easily
compared and is far more efficient than using floats.


text:
DC Motor Not Braking
I have a brushed motor hooked up to a NodeMCU that moves a plate left (moveLeft) and right (moveRight). When a button (buttonOpen) is pressed, it turns to the left until the plate hits a limit switch (limit1), then the system stops and the motor driver goes to sleep. Then when a different button (buttonClose) is pressed, it moves the plate to the right, until a different limit switch (limit2) is pressed.
Now the thing is that I need the DC motor to brake once the limit switch is triggered, otherwise it will slowly roll over the switch (which is bad).
I noticed that I needed to apply the brake for at least a fraction of a second to get the motor to stop. If the brake is too short, the motor will continue to spin. That is why I created a loop that lasts 0.8 seconds (stopMotor)
The problem is that the brake is only being applied when the motor moves right. But when it moves left, it does not get applied and coasts to a stop. I can't figure this out for the life of me. I really need to to brake and stop in either direction.
Here's the code.
const int IN1 = 13;
const int IN2 = 12;
const int Enable1 = 14;
const int buttonOpen = 2; // Yellow
const int buttonClose = 0; // Black
const int limit1 = 5;
const int limit2 = 4;

void setup()
{
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(Enable1, OUTPUT);
  pinMode(buttonOpen, INPUT);
  pinMode(buttonClose, INPUT);
  pinMode(limit1, INPUT);
  pinMode(limit2, INPUT);
}

void moveLeft()
{
  digitalWrite(Enable1, HIGH); // wakes up driver
  digitalWrite(IN1, LOW); //
  digitalWrite(IN2, HIGH); // spins counter-clockwise
}

void moveRight()
{
  digitalWrite(Enable1, HIGH); // wakes up driver
  digitalWrite(IN1, HIGH); //
  digitalWrite(IN2, LOW); // spins clockwise
}

void stopMotor() //brake motor for 0.1 seconds to avoid coasting then place             driver to sleep
{
  int period = 80L;       // 0.08 seconds
  for( int tStart = millis();  (millis()-tStart) < period;  ){
    digitalWrite(IN1, HIGH); // brake
    digitalWrite(IN2, HIGH); // brake
  }
  digitalWrite(Enable1, LOW); // Sleep driver
}

void loop(){
  // Move motor right
  if (digitalRead(buttonOpen) == LOW){
    while(digitalRead(limit2) == HIGH){
      moveRight();
      yield();
    }
  }
  else
    (stopMotor());

  // Move motor left
  if (digitalRead(buttonClose) == LOW){
    while(digitalRead(limit1) == HIGH){
      moveLeft();
      yield();
    }
  }
  else
    (stopMotor());
}

I'm not sure, if this has to do with your problem, but the logic in your loop() is weird. When you hit a limit switch the code does not go directly to the stop function, because its in the else statement of the control button, which will not be evaluated, when you are inside its if statement. Insteat the stop Funktion will be executed in the next if statement ( for the other direction). Instead stop the Motor directly after it hit the limit switch

And the yield() function does WLAN stuff in the ESP, right? As I remember this has to be executed often enough or the webserver, you may want to use in future, will be unresponsive. Since it may take relatively long time for the motor to hit the limit switch, you can execute it inside the while() loop. Or rewrite your code to be completely non-blocking

Your whole methodology belies a complete misunderstanding of how the Arduino works. You do not need to constantly tell it "Go right!Go right!Go right!Go right!Go right!Go right!Go right!". You only need to do it once and it will keep going right until you tell it otherwise. What you need is a finite state machine to switch between different modes depending on the various external stimulii.

Thanks guys. Yes the     yield() function keeps the ESP from resetting since I have blocking code which times the ESP out.

And I found this code that uses a state machine in almost my exact same situation link. But I was very confused about this methodology so thanks for the link to that tutorial, I'll be sure to dive into it


text:
Code throwing errors after an IDE update
I'm really new to coding for arduino.  My current project is a monitor for my terrarium using an arduino UNO board, a DHT11 and a DS3231 RTC, displaying Temperature(from both DHT (in the terrarium) and the RTC (outside)) as well as time and humidity.
The code was functional, but recently the IDE said there were some updates (which I ran) and now it won't verify. All this code was basically obtained through examples for the hardware I'm using.   Can someone please point me to what I need to correct?
The code as is ....
#include <DS3231.h>

#include <dht11.h>

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
DS3231  rtc(SDA, SCL);
dht11 DHT;                        //Note:DHT on behalf of the temperature         and humidity sensor
const int dht11_data = 6;
int temp=0;
int hum=0;

#include "Wire.h"
#define DS3231_I2C_ADDRESS 0x68
                              // Convert normal decimal numbers to binary   coded decimal
byte decToBcd(byte val)
{
  return( (val/10*16) + (val%10) );
}
                              // Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)

{
  return( (val/16*10) + (val%16) );
}

void setup()
{
  Wire.begin();
                              // set the initial time here:
  // DS3231 seconds, minutes, hours, day, date, month, year
  // setDS3231time(30,42,21,4,26,11,14);
  rtc.begin();                    //Initialize the rtc object
  lcd.begin(16,2);                //Initialize LCD display
  lcd.print("Terrarium ");        //Splash Screen text line 1
  lcd.setCursor(0,1);             //Set Cursor Position for second line of Splash screen
  lcd.print("Monitor 1.3");       //Splash screen text line 2
  delay(3000);                    //Delay 3 seconds on Splash screen
  lcd.clear();                    //Clear LCD
}

void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte
dayOfMonth, byte month, byte year)

{
  // sets time and date data to DS3231
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0);                  // set next input to start at the seconds register
  Wire.write(decToBcd(second));   // set seconds
  Wire.write(decToBcd(minute));   // set minutes
  Wire.write(decToBcd(hour));     // set hours
  Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
  Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
  Wire.write(decToBcd(month));    // set month
  Wire.write(decToBcd(year));     // set year (0 to 99)
  Wire.endTransmission();
}

void readDS3231time(byte *second,byte *minute,byte *hour,byte     *dayOfWeek,byte *dayOfMonth,byte *month,byte *year)

{
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
                              // request seven bytes of data from DS3231       starting from register 00h
  *second = bcdToDec(Wire.read() & 0x7f);
  *minute = bcdToDec(Wire.read());
  *hour = bcdToDec(Wire.read() & 0x3f);
  *dayOfWeek = bcdToDec(Wire.read());
  *dayOfMonth = bcdToDec(Wire.read());
  *month = bcdToDec(Wire.read());
  *year = bcdToDec(Wire.read());
}
void displayTime()
{
  DHT.read(dht11_data);
  temp=DHT.temperature;
  hum=DHT.humidity;

  lcd.clear();                    //clear display

  lcd.print("rH=");               //Display text rH= on LCD
  lcd.print(hum);                 //Display relative humidiy reading from    DHT11
  lcd.print("%");                 //Display Percent sign

  lcd.setCursor(9,0) ;            //set cursor position
  lcd.print("Ti=");               //display"Ti="
  lcd.print(temp);                //Displays temperature reading from     DHT11, designated is Internal Temperature
  lcd.write(0xDF);                //Display custom characters '°'
  lcd.print("C");                 //Display text "C" to designate Celsius     units

  byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

                              // retrieve data from DS3231
  readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month,  &year);
                              // send it to the serial monitor

  lcd.setCursor(0,1);
  lcd.print(hour, DEC);           //Displays hours value on LCD
                               // convert the byte variable to a decimal number when displayed
  lcd.print(":");                 //Displays ":" between hours and minutes
  if (minute<10)
  {
    lcd.print("0");
  }
  lcd.print(minute, DEC);         //Displays Minutes value on the LCD
  lcd.setCursor(9,1);
  lcd.print ("Te:");              //Displays text "Te:" on LCD
  lcd.print(rtc.getTemp());       //Displays Temperature from DS3231 designated as "External Temperature"

}
void loop()
{
  displayTime();                  // display the real-time clock data on the Serial Monitor,
  delay(1000);                    // every second
}

and the errors it is throwing are:
> > Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Uno"
>
> Terrarium_Monitor_1.3:8: error: no matching function for call to
> 'DS3231::DS3231(const uint8_t&, const uint8_t&)'
>
>  DS3231  rtc(SDA, SCL);
>
>                      ^
>
> F:\Arduino Kit Stuff\my
> sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino:8:21: note:
> candidates are:
>
> In file included from F:\Arduino Kit Stuff\my
> sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino:1:0:
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:64:3:
> note: DS3231::DS3231()
>
>    DS3231();
>
>    ^
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:64:3:
> note:   candidate expects 0 arguments, 2 provided
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
> note: constexpr DS3231::DS3231(const DS3231&)
>
>  class DS3231 {
>
>        ^
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
> note:   candidate expects 1 argument, 2 provided
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
> note: constexpr DS3231::DS3231(DS3231&&)
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
> note:   candidate expects 1 argument, 2 provided
>
> F:\Arduino Kit Stuff\my
> sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino: In function
>    'void setup()':
>
> Terrarium_Monitor_1.3:34: error: 'class DS3231' has no member named
> 'begin'
>
>    rtc.begin();                    //Initialize the rtc object
>
>        ^
>
> F:\Arduino Kit Stuff\my
> sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino: In function
> 'void displayTime()':
>
> Terrarium_Monitor_1.3:112: error: 'class DS3231' has no member named
> 'getTemp'
>
>    lcd.print(rtc.getTemp());       //Displays Temperature from DS3231
> designated as "External Temperature"
>
>                  ^
>
> Multiple libraries were found for "LiquidCrystal.h"  Used: E:\Program
> Files (x86)\Arduino\libraries\LiquidCrystal  Not used:
> C:\Users\Ursinos\Documents\Arduino\libraries\arduino_136712 exit
> status 1 no matching function for call to 'DS3231::DS3231(const
> uint8_t&, const uint8_t&)'
>
> This report would have more information with "Show verbose output
> during compilation" option enabled in File -> Preferences.

As I said, I was working when I uploaded it to my arduino on last changes a week ago (and it's still running on the board right now), but after doing the updates to the libraries and whatnot, it's now throwing all these errors.   I know the code isn't very elegant, I'm still learning.  Please help
edit:  After altering the line as advised in the answers, I now get the following errors.
Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Uno"

F:\Arduino Kit Stuff\my sketches\Terrarium_Monitor_1.3  \Terrarium_Monitor_1.3.ino: In function 'void setup()':

Terrarium_Monitor_1.3:34: error: 'class DS3231' has no member named 'begin'

   rtc.begin();                    //Initialize the rtc object

       ^

F:\Arduino Kit Stuff\my sketches\Terrarium_Monitor_1.3  \Terrarium_Monitor_1.3.ino: In function 'void displayTime()':

Terrarium_Monitor_1.3:112: error: 'class DS3231' has no member named 'getTemp'

 lcd.print(rtc.getTemp());       //Displays Temperature from DS3231 designated as "External Temperature"

             ^

Multiple libraries were found for "LiquidCrystal.h"
 Used: E:\Program Files (x86)\Arduino\libraries\LiquidCrystal
 Not used: C:\Users\Ursinos\Documents\Arduino\libraries   \arduino_136712
exit status 1
'class DS3231' has no member named 'begin'

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

Could this have anything to do with my Arduino IDE being version 1.8.3 instead of the newest version?

the I2C (Wire) pins SDA and SCL are constant on Uno. no need to give them into the constructor. change DS3231  rtc(SDA, SCL); to DS3231  rtc;

huh, that's pretty weird since so many of the code examples I've come across have it entered like I had it.

because the libraries are cross platform and on some platforms you can choose the pins. and in new version they disabled for AVR the constructor with parameters

I found this online but I can not verify it.
http://www.instructables.com/topics/no-matching-function-for-call-to-DS3231DS3231const/
The relevant part for you I think is:

I don't know where you get the syntax
DS3231 rtc (SDA, SCL);
My copy of the DS3231 library says you need only DS3231 rtc; //no
  arguments. BUT you need the Wire library.

So change your code and make sure you have the Wire library.

I have the wire library installed and included.  I tried changing that segment of code and it did not help

actually, I figured out what I did wrong the first time I tried changing it.  It cleared the error for that one segment, Editing original post to show new errors.

so why did you accept the answer?

because it was part of the problem

Alright, so I figured it out by gasp going and reading the documentation for the DS3231 library I'm using.
It seems when the library updated, one of the keywords changed.
so, after removing the (SDA, SCL) from the one line, I had to remove the line
rtc.begin();

and change
lcd.print(rtc.getTemp());

to
lcd.print(rtc.getTemperature());

thanks for the help :D

Thanks for advising us of that. Personally I don't update the IDE very often. What is the point? I currently use 1.6.9. It works, and there is a danger if you upgrade then things stop working. It's not as if your Arduino has to connect to some new-fangled printer that was only released last week.