text:
The Ultrasonic sensor just detects the same distance
int tPin = 11;
int ePin = 12;
long duration, inches, cm;

void setup()
{
    Serial.begin(9600);
    pinMode(tPin, OUTPUT);
    pinMode(ePin, INPUT);
    pinMode(2, OUTPUT);
}

void loop()
{
    digitalWrite(tPin, LOW);
    delayMicroseconds(5);
    digitalWrite(tPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(tPin, LOW);
    duration = pulseIn(ePin, HIGH);
    cm = (duration / 2) / 29.1;
    inches = (duration / 2) / 74;
    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();
    delay(100);

    if (inches <= 10) {
        digitalWrite(2, HIGH);
        delay(50);
        digitalWrite(2, LOW);
        delay(50);
    }
    else {
        digitalWrite(2, HIGH);
        delay(500);
        digitalWrite(2, LOW);
        delay(500);
    }
}

The serial print displays the same distance that it first detects. How can I fix this?

What number does it constantly output? Also be aware that you do integer divisions when you do / 2 and / 74, you should change them to float values and also make cm and inches float.

Are you sure it detects the same distance? How far did you try to move the object from the sensor?

First of all you need to make cm, inches and duration float to be more precise. Second, you need to make the delay 2 and 10 microseconds between triggers. Overall, if I'm not wrong you can use the code below without changing your circuit.
int tPin = 11;
int ePin = 12;
float duration, inches, cm; //floating numbers to make the result more precise

void setup()
{
    Serial.begin(9600);
    pinMode(tPin, OUTPUT);
    pinMode(ePin, INPUT);
    pinMode(2, OUTPUT);
}

void loop()
{
    digitalWrite(tPin, LOW);
    delayMicroseconds(2);         //Delay 2 microseconds
    digitalWrite(tPin, HIGH);
    delayMicroseconds(10);        //Delay 10 microseconds
    digitalWrite(tPin, LOW);
    duration = pulseIn(ePin, HIGH);
    cm = duration / 58.2;          //Instead of duration/2/28.1
    inches = cm / 2.54;            //You can use cm that was created before for conversion
    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();
    delay(100);

    if (inches <= 10) {
        digitalWrite(2, HIGH);
        delay(50);
        digitalWrite(2, LOW);
        delay(50);
    }
    else {
        digitalWrite(2, HIGH);
        delay(500);
        digitalWrite(2, LOW);
        delay(500);
    }
}


text:
making a digital dice
i'm trying to make a digital dice to play catan with, here's what i have so far
#include <LiquidCrystal.h>
#include <DFR_LCD_Keypad.h>

// this is factory config shield initialisation
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// initialise the keypad
DFR_LCD_Keypad keypad(A0, &lcd);
int lcd_key     = 0;
int abc_key_in;
int read_LCD_buttons;
int  diceOne;
int  diceTwo;
#define btnSELECT 4
int read_LCD_buttons()
{
  abc_key_in = analogRead(0);
if (abc_key_in < 790) return btnSELECT;}
const int button = 4;
const int BUTTON4LOW = 400;
const int BUTTON4HIGH = 650;

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Press to dice");
  pinMode (A0, INPUT);
  i
}

void loop() {
  int reading =  analogRead (A0);

  lcd_key = read_LCD_buttons();

 if (reading<BUTTON4LOW && reading<BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

  if (diceOne + diceTwo == 7) {
    lcd.clear();
    lcd.setCursor(7, 0);
    lcd.print("7");
    lcd.setCursor(3, 1);
    lcd.print("The pirate");

      if (diceOne + diceTwo == 3,2,1,5,4,6) {
          lcd.clear();
          lcd.setCursor(7, 0);
          lcd.print("fish");
      }
      }
  }
}
}

and im running into a error code saying
Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"

demo_simple:15: error: 'int read_LCD_buttons()' redeclared as different kind of symbol
 int read_LCD_buttons()
                      ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino:11:5: note: previous declaration 'int read_LCD_buttons'
 int read_LCD_buttons;
     ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'int read_LCD_buttons()':
demo_simple:15: error: 'int read_LCD_buttons()' redeclared as different kind of symbol
 int read_LCD_buttons()
                      ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino:11:5: note: previous declaration 'int read_LCD_buttons
 int read_LCD_buttons;
     ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'void setup()':
demo_simple:28: error: 'i' was not declared in this scope
   i
   ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'void loop()':
demo_simple:34: error: 'read_LCD_buttons' cannot be used as a function
   lcd_key = read_LCD_buttons();
                              ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: At global scope:
demo_simple:58: error: expected declaration before '}' token
 }
 ^
exit status 1
'int read_LCD_buttons()' redeclared as different kind of symbol

name your children, like int x read_LCD_buttons(). also, that will play the same game each time, you need to randomize, preferably with micros() after each user input.

You have
int read_LCD_buttons;

int read_LCD_buttons()
{
//..
}

You can't have a variable int read_LCD_buttons at the same time as a function called read_LCD_buttons -- this identifier is already taken. It looks however like you're not assigning or reading anything from this variable, so it probably never should have existed in the first place -- deletion is the solution.
In the case that you wanted to write a function prototype (which you by the way don't have to write in the Arduino IDE because it autogenerates them), the correct form would have been
int read_LCD_buttons();

i.e., the exact same prototype ended by a ;.
In setup() you have a random i which doesn't belong there.
void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Press to dice");
  pinMode (A0, INPUT);
  i //delete this line
}

Finally, you have a mismatch of opening and closing curly braces. Always format your code correctly, so that these errors are more easily spotted! You have one final } too much.
void loop() {
  int reading = analogRead(A0);

  lcd_key = read_LCD_buttons();

  if (reading < BUTTON4LOW && reading < BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

    if (diceOne + diceTwo == 7) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("7");
      lcd.setCursor(3, 1);
      lcd.print("The pirate");

      if (diceOne + diceTwo == 3, 2, 1, 5, 4, 6) {
        lcd.clear();
        lcd.setCursor(7, 0);
        lcd.print("fish");
      }
    }
  }
}
} //This } is too much!

Then you'll also see that the third if statment which checks for a sum is actually within another expression where it was asserted that the sum is already 7. Then the inner if can never become true. You probably meant to move the if to the outer part, i.e. write
void loop() {
  int reading = analogRead(A0);

  lcd_key = read_LCD_buttons();

  if (reading < BUTTON4LOW && reading < BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

    if (diceOne + diceTwo == 7) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("7");
      lcd.setCursor(3, 1);
      lcd.print("The pirate");
    }
    //the line below is still wrong
    if (diceOne + diceTwo == 3, 2, 1, 5, 4, 6) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("fish");
    }
  }
}

Next, this expression makes no sense.
if (diceOne + diceTwo == 3,2,1,5,4,6)

I think you meant that "if the sum of diceOne and diceTwo are equal to either 3, 2, 1, 5, 4, or 6 (i.e. within 1 and 6 inclusive), then do something.
Using multiple or statments this would be expressed as
if ((diceOne + diceTwo == 3) || (diceOne + diceTwo == 2) || (diceOne + diceTwo == 1) || (diceOne + diceTwo == 5) ||(diceOne + diceTwo == 4) || (diceOne + diceTwo == 6))

Or using the simpler interval check, assuming both numbers are positive and greater than 1.
if( diceOne + diceTwo <= 6)

Also this expression is suspect
if (reading<BUTTON4LOW && reading<BUTTON4HIGH)

When you have a LOW and a HIGH boundary and you want to check if reading is between these, you would write it as "if reading is greater than the lower boundary and less than the higher boundary", i.e.,
if (reading > BUTTON4LOW && reading < BUTTON4HIGH)

I fixed my errors but I want to be able to press the select button on the LCD keypad shield to generate random numbers, how would I do that (coding)

and I want to press the select button once for the two dice and again for the 1 die

@user46194 This is not a free coding service. Work it out yourself, and, if you have a particular problem on why something you wrote doesn't work, you can ask another question.

source: Stack Exchange

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

sort: votes


text:
making a LCD dice for catan
when I go to upload the code, I get
 Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"
C:\Users\taran\Documents\Arduino\dice in progress\dice in progress1\diceinprogress\diceinprogress.ino:1:25: fatal error: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino/"DFRkeypad.h": Invalid argument
#include <"DFRkeypad.h">
                     ^
compilation terminated.
exit status 1 Error compiling for board Arduino/Genuino Uno.

and the code is
#include <"DFRkeypad.h">
#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
const char* DFRkeypad::sKEY[]=                          { "---",       "Right",   "Up", "Down", "Left", "Select", "???" };
const int DFRkeypad::iARV_VALUES[DFRkeypad::eNUM_KEYS]= { 1023,        0,         143,  328,    504,     740,      -1   };
int btnSELECT;

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(1, 0);
  lcd.print("Roll the dice!");
}

void loop() {
while (btnSELECT == 0){

  delay (50);
  buttonState = analogRead(btnSELECT);
}

 case btnSELECT:
     {
     lcd.print("Rolling dice");
       diceOne = random(1, 7);
       diceTwo = random(1, 7);
     break;
    }
}

Why have quotation marks around the first library you include and not the second (I believe you shouldn't have quotation marks). That's why it gives "invalid argument "DFRkeypad". Also make sure the library is properly installed and use some proven (library examples or off-the-web) testcode before slapping some code together.

You edit the question to ask a completely different questions. Different questions should be posted as different questions, otherwise the answers do not reflect the answer to the question anymore.

In C/C++ you either use the #include pre-processor statement in the form of
#include "someFile.h"

or
#include <someFile.h>

The form
#include <"someFile.h">

is not legal. You must correct it to one of the two forms above.
The difference between those forms is explained in https://stackoverflow.com/a/77092/5296568.

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


text:
program evaluating if clause incorrectly
As the title says i'm having a problem with an if clause evaluating incorrectly in one particular function
uint16_t    getSleepTime()
{
    volatile uint8_t flag = EEPROM.read(3);

    uint8_t high    = EEPROM.read(0);
    uint8_t low     = EEPROM.read(1);

    if(flag != 0xaa);
    {
        Serial.println(flag);
        Serial.println("ERROR: SLEEP TIME NOT DEFINED, CANNOT CONTINUE.");
        while(true)
        {
            digitalWrite(PIN_LED, true);
            delay(250);
            digitalWrite(PIN_LED, false);
            delay(250);
            wdt_reset();
        }
    }

    return word(high, low);
}

the result is that the if function evaluates as true always
my first thought was, ok the eeprom wasn't written properly, hence i added the println, the returned value was 170 == 0xaa
then i thought well maybe the flag variable is optimized out, hence the volatile
and then, well maybe its a type comparison issue so i also defined a const uint8_t flagv with value 0xaa
same results in every case
13:21:00.991 -> 170
13:21:00.991 -> ERROR: SLEEP TIME NOT DEFINED, CANNOT CONTINUE.
and the corresponding blink

the thing is that being such a trivial code i'm out of ideas right now, as anyone here experienced something like this?

when debugging, put Serial.println(flag); before the if statement

Do not put a ; after an if:
if(flag != 0xaa);

is the same as
if(flag != 0xaa)
{
}

Meaning that the code after the if statement is always executed.

ouch, dumb mistake

No problem, however, I also have to vote for closing, since it's not related to Arduino.

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


text:
Blink only one led in a led strip
I wish to blink only one led (number two in the strip) bit it does not do so, any idea why and how can I do it?
Code:
#include "FastLED.h"

//Number of LEDs
#define NUM_LEDS 9

//Define our clock and data lines
#define DATA_PIN 11
#define CLOCK_PIN 13

//Create the LED array
CRGB leds[NUM_LEDS];

void setup() {
      FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, BGR>(leds, NUM_LEDS);
      FastLED.setBrightness(5);
}

void loop() {
  leds[0] = CRGB::Blue;
  leds[1] = CRGB::Green;

  //Blink this one only
  leds[2] = CRGB::Red;
  leds[2] = CRGB::Black;
  delay(500);
  leds[2] = CRGB::Red;

  leds[3] = CRGB::White;
  leds[4] = CRGB::Purple;
  leds[5] = CRGB::Green;
  leds[6] = CRGB::Blue;
  leds[7] = CRGB::Yellow;
  leds[8] = CRGB::Red;
  FastLED.show();
}

does not do so does not describe what it does ... please describe what you expect to happen, and what you observe happening

Let me translate that for you. The OP want the 2nd LED blink while other LEDs stay the same, but the code he wrote didn't do that. He didn't know how to code and wanted to learn from some experience guy how to do that. Is that clear enough?

Everytime, that you want the LEDs to change, you need to call the FastLED.show() function. You are doing that only once after you set the values multiple times. Also you need 2 delays in total (1 for the LED being on, 1 for it being off).
The workflow for blinking an LED would be:
Set LED to on
Call show function
Delay
Set LED to off
Call show function
Delay

You need to translate that to code.


text:
Temperature is not updated on OLED screen - Grove components
I am using 2 grove components in order to display a temperature. I use an I2C High Accuracy Temperature Sensor - MCP9808 and an OLED Screen using this script:
#include <U8g2lib.h>
#include <SPI.h>
#include <Wire.h>
#include "Seeed_MCP9808.h"

MCP9808 sensor;
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/SCL, /* data=*/SDA, /* reset=*/U8X8_PIN_NONE);  //Software I2C

char strTemp\[16\];
float temp;

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

  if (sensor.init()) {
    Serial.println("sensor init failed!!");
  }
  sensor.set_config(SET_CONFIG_ADDR, 0x0008);
  Serial.println("sensor init!!");
}

void loop() {
  sensor.get_temp(&temp);
  Serial.print("temperature value is: ");
  Serial.println(temp);
  delay(1000);

  dtostrf(temp, 7, 2, strTemp);

  u8g2.clearBuffer();                   // clear the internal memory
  u8g2.setFont(u8g2_font_luBIS08_tf);   // choose a suitable font
  u8g2.drawStr(0, 10, "Hello Seeed!");  // write something to the internal memory
  u8g2.drawStr(0, 30, "Temp. value:");  // write something to the internal memory
  u8g2.drawStr(0, 50, strTemp);         // write something to the internal memory
  u8g2.sendBuffer();                    // transfer internal memory to the display
}

The temperature output is not updated on the screen and I think it might be related to I2C addresses. Is it possible?
I run an I2C scanner and I think that the OLED address is 0x3C and the temp. sensor is 0x18. How can I assign them correctly. I never done something like that so any help is welcome.
Thanks a lot.

Simplify the problem.  Try making a copy of your software w/o the OLED code and simply print the temperature out to the serial monitor already part of the IDE.  If that works, then it may be the I2C addressing.  If it does not then it's likely how you are sampling the temperature sensor.

Thanks for the reply and recommendation. Without the OLED code it prints the temperature out to the serial monitor, Any idea how to proceed?

does "Hello Seeed!" show on the display?

@jsotola: Yes, it does appear on the display

... oh, I see you are already printing out the temperature.  I'd still comment out all the u8g2 lines and maybe even remove the OLED hardware and see if you see new temperature data ever second.

"...Without the OLED code it prints the temperature out to the serial monitor...", yes, but does it print out a new temperature every second?  If so, my guess is that the libraries are not working well w/each other.  Likely they are trying to use the same I2C processor hardware and braking it for the other library.

@st2000: When removing all the u8g2 lines I see in the serial monitor the temp. When  the u8g2 lines are in the code  even the serial monitor is not working

st2000: I suspect as well that there is I2C interference. Any idea how to change one or both of them?

You can look at the MPC9808 and  U8G2 code on github (not sure about if I got the correct U8G2 web page) and try to design a version of code that are compatible w/one another.  But 1st I'd look for other's w/similar problems.  For all we know, maybe the U8G2 libaray has an option to skip I2C initialization already built in.

Or, you could check if your specific Arduino platform has a second I2C port and use it for the U8G2 display.  Or you could buy an Arduino w/2 or more I2C ports (but check to make sure the libraries you are using are compatible with the new Arduino).

You mix software I2C with hardware I2C on the hardware I2C pins.
To use hw I2C with the display use the U8G2_SSD1306_128X64_NONAME_F_HW_I2C constructor.
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE);

Or use a different pair of pins for the software I2C display control.


text:
CIPSEND Shows 404 error using aeduino + esp8266+01
I am trying  to save data in the data base with the get method. my url works fine when used with browser but when tried with esp shows page not found expection.
Arduino Code
SoftwareSerial ESP8266(10, 11); // Rx,  Tx

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

  ESP8266.println("AT+RST");
  delay(1000);
  ESP8266.print("AT+CWQAP\r\n");
  delay(2000);
  unsigned char check_connection=0;
  unsigned char times_check=0;
  Serial.println("Connecting to Wifi");

  while(check_connection==0)
  {
    Serial.print(".");
  ESP8266.print("AT+CWJAP=\"********\",\"*******\"\r\n");
  ESP8266.setTimeout(5000);
 if(ESP8266.find("WIFI CONNECTED\r\n")==1)
 {
 Serial.println("WIFI CONNECTED");
 break;
 }
 times_check++;
 if(times_check>3)
 {
  times_check=0;
   Serial.println("Trying to Reconnect..");
  }
  }
  delay(5000);
}

void loop() {

  // put your main code here, to run repeatedly:
   String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += "homeautomationinternal.xyz"; // api.thingspeak.com
  cmd += "\",80";
  ESP8266.println(cmd);
  if(ESP8266.find("Error")){
    Serial.println("AT+CIPSTART error");
    return;
  }
  String getStr = "GET /auto/addlightvalueuseruno?userid=aravind";
  //getStr += String(temp_f);
  getStr +="&";
  getStr +="value=1";
  //getStr += String(humidity);
  getStr +=" HTTP/1.1\r\nHost: homeautomationinternal.xyz";
  getStr += "\r\n\r\n";
  // send data length
  cmd = "AT+CIPSEND=";
  cmd += String(getStr.length());
  ESP8266.println(cmd);
  ESP8266.setTimeout(2000);
  if(ESP8266.find(">")){
    ESP8266.print(getStr);
   Serial.println(cmd);
  }
  else{
    ESP8266.println("AT+CIPCLOSE");
    // alert user
    Serial.println("AT+CIPCLOSE");
  }
   Serial.println(getStr);
  delay(5000);

}```

and the serial monitor data is

```AT+CIPSTART="TCP","www.homeautomationinternal.xyz",80

CONNECT

OK
 AT+CIPSEND=98

OK
>
busy s...

Recv 98 bytes

SEND OK

+IPD,1245:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>404 - File or directory not found.</title>

Server Error

<fieldset>

404 - File or directory not found.

The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.

 </fieldset>

CLOSED

my website runs on iis server..
please help me with the arduino code and error which I am getting in the serial.monitor and how to resolve it.

As I am send data from Arduino to my website using get method I thought there may be any error with the hosting technicque @jsotola

Just ignore the iis please help me with the error and how to resolve it

how should we help you? the url is not valid for the server. how should we know what is a valid url on your server?

please let me know what all the details you require iwill provide you@Juraj

why this url? does it work from browser?

yes it works for browser . this url www.homeautomationinternal.xyz/auto/addlightvalueuseruno?userid=aravind&value=1 returns a json value 1

this is a home automation project which activates relay.. the arduino sends data to server using get method and we can see the data in website@Juraj

in code I don't see www in hostname

do we need to provide the www in host name...didnt work even after providing www in host name.. i am getting an error that webpage is not found i.e 404 error.

did you add the www in Host header too? 'www' is the name of the server. you can't leave it out

yaa i have added didnt work

You server is set up to redirect everything to https://www.homeautomationinternal.xyz which the ESP-01 doesn't like. You'd be much better off programming the ESP-01 directly with your website interaction code so that then it can handle the connections properly.

can you please help me with it how to do that@Majenko

and how did you came to know that its redirecting to home page

try AT+CIPSTART=\"SSL\", with cmd += "\",443";


text:
Trying to switch a 5v fan with a LiPo and can't figure our what's wrong at full duty cycle
I have a simple project where I want to turn a 5v fan on/off and both the MCU  and fan will powered by a LiPo battery.
I'm powering the ESP and fan directly from the battery in the attached circuit. For now I've decided not to boost the power to 5v for the fan because the fan runs fine at lower voltage. Also using a BJT transistor as a low side switch.
This all seems to work fine except at full duty cycle the voltage to the fan seems to completely collapse. At just below full (like if a do analogWrite(pin 1000) it's humming along fine but when I go to 1023 the voltage drops from around 4 to closer to 2 and the fan stops. Even at lower duty cycles like 50% the fan operates nice and slow.
I put a multimeter on the leads to the fan and observe the voltage drop at full duty.
I'm very new to all this and have done a lot of reading but I haven't been able to solve this. Also this is my first fritzing drawing so I hope it makes sense.
Edit: I made some changes to the circuit and it's working as expected. I have also updated the circuit diagram below.

The 3.3V pin needs to be provided with a regulated 3.3V. When the power input of the ESP gets too low, it will show weird behavior

Oh I need to update the schematic. I’m actually feeding the power from the LiPo to Vin on the MCU. Still unregulated, to your point, but it’s not going to 3v3, it’s going to Vin. Anyway, I can try boosting the LiPo output  to 5v and use that to directly power the MCU and the fan and see if that makes things stable at full duty.

According to specs I found online, the NodeMCU wants 7-12V on Vin. Most LiPo cells put out around 4 volts, which isn't enough. The battery voltage may drop and the MCU's voltage regulator probably fails to keep putting out 3.3V when the fan's average power draw exceeds some threshold.
It might also be that the fan itself is slowing when the duty cycle approaches 100% and the battery voltage drops.
Doesn't the NodeMCU run on 3.3V, not 5V? If you feed 5V into the 3V pin and that's supposed to have 3.3V, it will likely damage or destroy the board.

Looks like you’re right about Vin. I’m still trying to find the datasheet for my exact devkit board to confirm but I can easily put a regulated 7v into Vin and see if it fixes the voltage drop off problem at full cycle. And, sorry, but I don’t understand your last paragraph ... Vin is connected to a voltage regulator so it will regulate to 3.3v for the board which should be safe. Did I misunderstand your comment?

Sorry, that was a typo. I fixed it.

Yes, I would suggest measuring the voltage, both across the motor, and at the Vin to the board, when you're running it at 100% duty cycle. I'm suspecting a voltage drop.

It turns out that the nodemcu dekvit I'm using supports 5v on Vin. And I'm no longer going directly from the Lipo to the Vin but boosting the voltage from the battery to 5v then to Vin and I also changed the transistor to a 2N-2222A and things seem to be working as expected.I don't know enough about transistors to say what fixed it but I'm guessing the one I was using wasn't the right one for my application.


text:
Force TCNT to stay below OCRxA on ATmega328P
I'm using a timer and the TIMERx_COMPA ISR to generate a signal in "the background".
This ISR is triggered when the timer reaches a certain value (OCRxA), which in turn can be changed by the user.
Once the ISR triggers, the timer is reset and the next waiting period occurs.
If the compare value (OCRxA) is changed to a value below the current timer value before having hit the old compare value, the timer keeps running until it overflows back to 0 and hits the new OCRxA value. This results in no signal being generated until the timer has looped around, which can be quite long for the 16-bit TIMER1 timer.
There are multiple way to get around this:

Reset TCNTx to zero whenever OCRxA. Easy, but one signal will always be off-clock
If TCNTx is greater than OCRxA (after changing OCRxA), reset it to just below OCRxA
If TCNTx is greater than OCRxA, trigger the interrupt manually, where the signal is generated and TCNTx is reset

I belive the third option would be the cleanest, both in checking whether the issue has occured as well as for the signal quality.
This is certainly an X -> Y problem, so I'm open for other approaches.
My question, for now, would be:
Can I manually jump to an ISR regardless of its "normal" trigger?

@Juraj True, I suppose the "Electrical Engineering" SE would've been more appropriate?
I am programming an Arduino Uno with the Arduino IDE though.
I've always felt the line between those two SEs is very thin, especially when using the Arduino as nothing but a simple way to program the AVR.

I ask AVR specific questions on https://www.avrfreaks.net/forum/

Can I manually jump to an ISR regardless of its "normal" trigger?

This should be possible, but is probably not the best solution.

This is certainly an X -> Y problem, so I'm open for other
  approaches.

It would seem you are using the timer in CTC mode. In this mode, when
you write to OCRxA, the register is updated immediately, which leads
to the problem you are experiencing. The solution is to instead set the
timer to “fast PWM” mode. In fast PWM mode, the OCRxA register is
double buffered: you will be actually writing to a buffer register, and
OCRxA is automatically updated from that buffer on the same timer
clock cycle that clears the counter.
It may sound counter-intuitive to use a PWM mode when you do not need
the PWM feature. However, as long as the “compare output mode” is set to
“normal port operation” for both channels, the timer will not generate
any PWM output, and you can legitimately use the fast PWM mode only for
its double buffer feature.

That's absolutely gorgeous.
It seems to work perfectly with my test code, without ever checking whether TCNT has reached past OCRxA.
The buffers delay would be irrelevant with OCRxA only being updated once per millisecond.
I'm a bit ashamed to admit I wasn't even using CTC though, the entire code had been in "normal" (mode 0), with me resetting TCNT as the first action in the ISR.
You were refering to "mode 4" where I could have just omitted the TCNT reset, right?

I had some code which would check for how long TCNT was larger than OCRxA and output that over serial.
This now "always" displays some of that "lag".
Am I right in assuming it's comparing my real TCNT value to the buffered OCRxA and not the active OCRxA and that this metric would now be meaningless / expected?
If so, is there any way of reading the "active" OCRxA vs. the  one in the buffer which is not yet "active"?

@TobiasWeiß: Re “the entire code had been in "normal" (mode 0) [...].”: Since the ISR prologue takes some time, and may even be delayed by other interrupts, your interrupt period is likely to be larger than you want. “You were refering to "mode 4" [...], right?” Right. “Am I right in assuming it's comparing my real TCNT value to the buffered OCRxA [...]?” Judging from the section “Output Compare Units” of the datasheet, it would seem this is the case. “Is there any way of reading the "active" OCRxA [...]?” Not that I am aware of.


text:
ESP8266 module doesn't respond to commands and sends garbage to serial on boot
I bought a ESP8266 module (like this).
I connected the module like on the following scheme:

I use a USB to TTL converter (cp2102) that I've connected to RX&TX pins of the module. It works. It successfully transmits data in both ways when I test it with a MCU. I often use it to send debug messages to my PC from a MCU.
I use linux and CuteCom as a program for monitoring the data sent through the serial port.
I supply 3.3V to the module (as required by the manufacturer) from the cp2102 converter (it has both 5V and 3.3V outputs).
The problem
The module does not respond to any command I send to it (AT, AT+GMR, AT+RST, ATE0, etc).
But it sends to the PC some data on boot (when I attach Vcc to CP_PD). Most of the data look like garbage, but at the very end I get meaningful data:
Ai-Thinker Technology Co.,Ltd.

invalid

The baud rate is 115200. No parity, 8-bit characters, 1 stop bit.
The full output from CuteCom:

The red LED on the module is always lightning while the power is supplied.
During the boot process (approximately first 500 milliseconds) also a blue LED blinks a few times (probably due to sending that mostly-garbage data to the PC I mentioned earlier).
What have I tried?
I experimented with the resistor R1, tried: no resistor, 1k, 3k, 10k.
I also tried other baud rates (1200, 2400, 4800, 9600, 19200, 38400, 57600).
And tried using all the parity types, 2 stop bits and other character lengths.
Nothing helped.
Why the module does not respond to any command?
Hope for your help!
Thanks in advance!

The ESP8266 bootloader outputs messages at that 74880 bits per second. At other speeds the bootloader's messages will look like garbage. Set your terminal speed to 74880 to see them.
On the ESP8266 it can be helpful to also use 74880 bits per second for the Serial speed in your program so that you can easily see both your programs output and the boot loader information when your program crashes.


text:
Weird Arduino Code Problem
I'm currently getting started with Arduino, so I do not have very much knowledge.
In this project I have a receiver and a transmitter with 2 buttons.
So, I'd like to switch something to on, when I press the A button. If A is pressed longer I'd like something else to happen.
Same thing goes on with the B button, but for some reasons, when I long press A, then B gets triggered and I have no clue why...
Btw. this code is not purely made by me, but copied and edited for my use.
If anyone could help me I'd be very happy :)
code:
//ButtonAEvents

long prevA = 0;
long prevB = 0;
int buttonStateA = 0; // 0 = not pressed   --- 1 = long pressed --- 2 short pressed
int buttonStateB = 0; // 0 = not pressed   --- 1 = long pressed --- 2 short pressed
int ButtonAPin = 2;
int ButtonBPin = 3;
int DURATION_A_IN_MILLIS = 1000;
int DURATION_B_IN_MILLIS = 1000;

//ONE TIME SETUP

void setup()
{
    pinMode(ButtonAPin, INPUT);
    pinMode(ButtonBPin, INPUT);
    Serial.begin(9600);
}

//LOOP BEGIN

void loop()
{

    //BUTTON A CHECK
    buttonStateA = 0;
    if (digitalRead(ButtonAPin)) {
        prevA = millis();
        buttonStateA = 1;
        while ((millis() - prevA) <= DURATION_A_IN_MILLIS) {
            if (!(digitalRead(ButtonAPin))) {
                buttonStateA = 2;
                break;
            }
        }
    }

    if (!buttonStateA) {
        // Nothin pressed
    }
    else if (buttonStateA == 1) {
        //LONG PRESS

        Serial.println("LongpressA");
        digitalWrite(A1, HIGH);
        delay(100);
    }
    else if (buttonStateA == 2) {
        //SHORT PRESS
        digitalWrite(A1, HIGH);
        Serial.println("ShortpressA");
        delay(100);
    }

    //BUTTON B CHECK
    buttonStateB = 0;
    if (digitalRead(ButtonBPin)) {
        prevB = millis();
        buttonStateB = 1;
        while ((millis() - prevB) <= DURATION_B_IN_MILLIS) {
            if (!(digitalRead(ButtonBPin))) {
                buttonStateB = 2;
                break;
            }
        }
    }

    if (!buttonStateB) {
        // Nothin pressed
    }
    else if (buttonStateB == 1) {
        //SHORT PRESS

        Serial.println("LongpressB");
        delay(100);
    }
    else if (buttonStateB == 2) {
        //LONG PRESS
        digitalWrite(A1, LOW);
        Serial.println("ShortpressB");
        delay(100);
    }
}

All no reasons for your problem, so that's why this is a comment: you switched the words LongpressB and ShortpressB in the serial print statements, also it is adviced not to use the ! operator for integer (use buttonStateB == 0), or even better in your case a switch statement.

upvote for well written question

What are your hardware connections? The button pins are assumed to be HIGH when pressed and LOW when not pressed. You also do not use pullups/downs, so that must be external.

I tested your code on my Arduino Uno with 2 buttons which go LOW when pressed and are pulled up externally, inverted the logic in the digitalRead() in the code and it works as expected. If pressing one button triggers the other one, I'd search for a fault in your hardware setup (crosstalk, accidentally bridged, wrong button polarity,..) Also signal bouncing can be an issue (and can be suppressed with capacitors)

Thanks for your fast answers everyone!
I changed the positions of the pins and made sure, that they are not bridged, sadly the issue still exists. Should I maybe use a resistor between the receiver and the arduino? regards

Could you edit your question and add a circuit diagram drawn on paper or using the circuit tool in the question edit menu so that we can all see your hardware connections without confusion / assuming something?

Hi again, I tried using the circuit diagram function, but I'm not very familiar with the symbols and electronics behind it, so I drew it in Photoshop, I hope it's understandable tho, sorry again...
http://prntscr.com/p7vc8m

Please edit your post to including that picture and the datasheet of RO2A sc2272 chip

Not sure if this is just an academic exercise on your part to learn (which is totally cool), but if you're just trying to move forward and get something working you may consider one of the many excellent button libraries out there for Arduino.
I recently used a library called ButtonKing that allowed me to do some very sophisticated menu interactions on a MKR1010 with a display and single button interface.  There are several other libraries out there as well that take care of debouncing, long clicks, double clicks, etc.


text:
Arduino freezes , how can I convert Arduino String to C string type?
this is my first post, im not an expert but I managed to build an Arduino Mega with an ESP8266 to water my plants inside a tent, unfortunately its freezes/crashes randomly and I have to go and reset it manually all the time. I read that this is because im using string and I should use C string type.
Could you please help me out to find a way to stop reseting manually all the time?
Thanks!
Here is the code:
#include <DHT.h>
#include <DS3231.h>
#define DHTPIN 51 // before it was 53
#define DHTTYPE DHT11
#include <ESP8266_Lib.h>
#define EspSerial Serial1

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

const int AirValue = 820;   // 778
const int WaterValue = 437;  //
int soilmoisturepercentA0=0;
int soilmoisturepercentA1=0;
int soilmoisturepercentA2=0;
int soilmoisturepercentA3=0;

String agAdi = "XXXXXX";
String agSifresi = "XXXXX";
String ip = "184.106.153.149";
float sicaklik, nem;

int led = 38;
int UV_Light = 27;
int Tent_Humid = 29;
int Heater = 26;
//int Free_IN3 = 28;
const int button1 = 53;
int buttonState1 = 0;

DHT dht = DHT(DHTPIN, DHTTYPE);
DS3231  rtc(SDA, SCL);
Time t; // Main time to display

//Schedule R2 UV_Light
const int OnHour_R2 = 6;
const int OnMin_R2 = 00;
const int OffHour_R2 = 1;
const int OffMin_R2 = 00;

int IN1 = 22;
int IN2 = 23;
int IN3 = 24;
int IN4 = 25;

int Pin1 = A0;
int Pin2 = A1;
int Pin3 = A2;
int Pin4 = A3;

float value1 = 0;
float value2 = 0;
float value3 = 0;
float value4 = 0;

void setup() {
  Serial.begin(9600);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);

  pinMode(Pin1, INPUT);
  pinMode(Pin2, INPUT);
  pinMode(Pin3, INPUT);
  pinMode(Pin4, INPUT);

  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, HIGH);

  pinMode(led, OUTPUT);
  pinMode(UV_Light, OUTPUT);
  pinMode(Tent_Humid, OUTPUT);
  pinMode(Heater, OUTPUT);
  pinMode(button1, INPUT_PULLUP);

  digitalWrite(UV_Light, HIGH);
  digitalWrite(Tent_Humid, HIGH);
  digitalWrite(Heater, HIGH);

  dht.begin();
  rtc.begin();

  delay(500);

  Serial.println("Started");
  EspSerial.begin(9600);                                          // We are starting serial communication with ESP8266.
  EspSerial.println("AT");                                         // We do the module control with the AT command.
  Serial.println("AT  sent ");
  while(!EspSerial.find("OK")){                                     // We wait until the module is ready.
    EspSerial.println("AT");
    Serial.println("ESP8266 Not Found.");
  }
  Serial.println("OK Command Received");
  EspSerial.println("AT+CWMODE=1");                                 // We set the ESP8266 module as a client.
  while(!EspSerial.find("OK")){                                     // We wait until the setting is done.
    EspSerial.println("AT+CWMODE=1");
    Serial.println("Setting is ....");
  }
  Serial.println("Set as client");
  Serial.println("Connecting to the Network ...");
  EspSerial.println("AT+CWJAP=\""+agAdi+"\",\""+agSifresi+"\"");    // We are connecting to our network.
  while(!EspSerial.find("OK"));                                     // We wait until it is connected to the network.
  Serial.println("CONNECTED to the Network ");
  delay(500);
//OLED
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3D (for the 128x64)
  display.display(); // show splashscreen
  delay(500);
  display.clearDisplay();   // clears the screen and buffer

}
void loop() {

//  DHT11.read(dht11Pin);
  dht.read(DHTPIN);
  sicaklik = (float)dht.readTemperature();
  nem = (float)dht.readHumidity();
//  value1 = analogRead(Pin1);
  soilmoisturepercentA0 = map(value1, AirValue, WaterValue, 0, 100);
  soilmoisturepercentA1 = map(value2, AirValue, WaterValue, 0, 100);
  soilmoisturepercentA2 = map(value3, AirValue, WaterValue, 0, 100);
  soilmoisturepercentA3 = map(value4, AirValue, WaterValue, 0, 100);
  String veri = "GET https://api.thingspeak.com/update?api_key=123456";   // Thingspeak command. We write our own api key in the key part.
  veri += "&field1=";
  veri += String(sicaklik);// The temperature variable we will send
  veri += "&field2=";
  veri += String(nem);// The moisture variable we will send
  veri += "&field3=";
  veri += String(soilmoisturepercentA0);// Soil A0
  veri += "&field4=";
  veri += String(soilmoisturepercentA1);// Soil A1
  veri += "&field5=";
  veri += String(soilmoisturepercentA2);// Soil A2
  veri += "&field6=";
  veri += String(soilmoisturepercentA3);// Soil A3
  veri += "\r\n\r\n";
  EspSerial.print("AT+CIPSEND=");                                   // We give the length of data that we will send to ESP.
  EspSerial.println(veri.length()+3);
//  delay(500);

  if(EspSerial.find(">")){                                          // The commands in it are running when ESP8266 is ready..
    EspSerial.print(veri);                                          // We send the data.
    Serial.println(veri);
    Serial.println("Data sent.");
    delay(500);
  }
  Serial.println("Connection Closed.");
  EspSerial.println("AT+CIPCLOSE");                                // we close the link
  delay(500);

  Serial. print('\n');
  Serial.print("MOISTURE LEVEL A0:");
  value1 = analogRead(Pin1);
  Serial.println(value1);
  Serial.println(soilmoisturepercentA0);
    if(value1>750)
  //if(soilmoisturepercentA0>35)

  {
      digitalWrite(IN1, LOW);
  }
  else
  {
    digitalWrite(IN1, HIGH);
    }

  Serial.print("MOISTURE LEVEL A1:");
  value2 = analogRead(Pin2);
  Serial.println(value2);
  Serial.println(soilmoisturepercentA1);
  if(value2>750)
 //  if(soilmoisturepercentA1>35)
  {
      digitalWrite(IN2, LOW);
  }
  else
  {
    digitalWrite(IN2, HIGH);
    }

  Serial.print("MOISTURE LEVEL A2:");
  value3 = analogRead(Pin3);
  Serial.println(value3);
  Serial.println(soilmoisturepercentA2);
  if(value3>750)
  //  if(soilmoisturepercentA2>35)
  {
      digitalWrite(IN3, LOW);
  }
  else
  {
    digitalWrite(IN3, HIGH);
    }

  Serial.print("MOISTURE LEVEL A3:");
  value4 = analogRead(Pin4);
  Serial.println(value4);
  Serial.println(soilmoisturepercentA3);
  if(value4>750)
   // if(soilmoisturepercentA3>35)
  {
      digitalWrite(IN4, LOW);
  }
  else
  {
    digitalWrite(IN4, HIGH);
    }
    Serial.println();
  delay(500);

{
    t = rtc.getTime();
  Serial.print(t.hour);
  Serial.print(" hour(s), ");
  Serial.print(t.min);
  Serial.print(" minute(s)");
  Serial.println(" ");
  delay (500);

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(500);
  }
    // Relay UV_Light
  if (t.hour == OnHour_R2 && t.min == OnMin_R2) {
    digitalWrite(UV_Light, LOW);
  }
  else if (t.hour == OffHour_R2 && t.min == OffMin_R2) {
    digitalWrite(UV_Light, HIGH);
  }
   buttonState1 = digitalRead(button1);
   if (buttonState1 == LOW) {
    digitalWrite(UV_Light, LOW);
    delay (100);
  }
  // Read the Humidity in %:
  float h = dht.readHumidity();
  // Read the Temperature as Celsius:
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
   // Display Humidizador
if (h <40)
  {
  digitalWrite(Tent_Humid, LOW);
  Serial.print("Humid ON");
  Serial. print('\n');
  } else{
    digitalWrite(Tent_Humid, HIGH);

    Serial.print("Humid OFF");
    Serial. print('\n');
}

// Display Heater
if (t <18)
  {
  digitalWrite(Heater, LOW);
  Serial.print("Heater ON");
  Serial. print('\n');
  } else{
    digitalWrite(Heater, HIGH);

    Serial.print("Heater OFF");
    Serial. print('\n');
}
    delay (100);
    float hic = dht.computeHeatIndex(t, h, false);
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" % ");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" \xC2\xB0");
  Serial.print("C ");
//  Serial.print("Heat index: ");

   EspSerial.println("AT+CIPSTART=\"TCP\",\""+ip+"\",80");           // We connect to Thingspeak.
  if(EspSerial.find("Error")){                                      // We check the connection error.
    Serial.println("AT+CIPSTART Error");
  }

// OLED
{
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed.
  if (isnan(h) || isnan(t) || isnan(f)) {
    delay(500);
  } else{
    // routine for converting temp/hum floats to char arrays
    char temp_buff[5]; char hum_buff[5];
    char temp_disp_buff[11] = "Tmp:";
    char hum_disp_buff[11] = "Hum:";

    // appending temp/hum to buffers
    dtostrf(t,2,1,temp_buff);
    strcat(temp_disp_buff,temp_buff);
    dtostrf(h,2,1,hum_buff);
    strcat(hum_disp_buff,hum_buff);

    // routine for displaying text for temp/hum readout
    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(0,0);
    display.println(temp_disp_buff);
    display.println(hum_disp_buff);
    display.display();
    delay(500);
{
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(500);

  }
  }
}
}

What means "crashes constantly"? After a few seconds, a few minutes or a few hours? The code above is supposed to run on an Arduino Mega or an ESP8266?

Sometimes after 8 hours, sometimes after 2 hours, its never the same frequency, Im using an Arduino Mega 2560 with an ESP8266 Wifi module.

why don"t you use a proper WiFi library ?

I tried using ESP8266WiFi.h but was not working with the Arduino Mega

Regardless of what the actual answer is, you may want to look into using the watchdog timer.

there is WiFiEsp or my WiFiEspAT for newer AT firmware version

here Majenko writes about C strings in second part: https://majenko.co.uk/blog/evils-arduino-strings


text:
error cannot convert string TO uint_8t
this is the code i am working on for controlling leds
#include <WiFi.h>                                                // esp32 library
#include <IOXhop_FirebaseESP32.h>                                             // firebase library
#define FIREBASE_HOST "mmmmm"                         // the project name address from firebase id
#define FIREBASE_AUTH "mmmmmmm"                    // the secret key generated from firebase
#define WIFI_SSID "mmmmm"                                          // input your home or public wifi name
#define WIFI_PASSWORD "mmmmmm"                                    //password of wifi ssid

String fireStatus ;
String fireStatus1 ;
String fireStatus3 ;
String fireStatus4 ; // led status received from firebase
int relay1 = 15;
int relay2 = 2;
int relay3 = 4;
int relay4 = 5;

void setup() {

Serial.begin(115200);

pinMode(15, OUTPUT);
pinMode(2, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);                                      //try to connect with wifi
Serial.print("Connecting to ");
Serial.print(WIFI_SSID);
  while (WiFi.status() != WL_CONNECTED) {
      Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected to ");
  Serial.println(WIFI_SSID);
  Serial.print("IP Address is : ");
  Serial.println(WiFi.localIP());                                                      //print local IP address
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);                                       // connect to firebase

}
void loop() {

  {
    fireStatus =  Firebase.getString("S1");

    Serial.println("Switch1 Turned ON/OFF");
    digitalWrite(15,fireStatus );
    fireStatus1 =  Firebase.getString("S2");
     Serial.println("Switch2 Turned ON/OFF");
    digitalWrite(2,fireStatus1 );

     fireStatus3 =  Firebase.getString("S3");
     Serial.println("Switch3 Turned ON/OFF");
    digitalWrite(4,fireStatus3));

     fireStatus4 =  Firebase.getString("S4");

     Serial.println("Switch4 Turned ON/OFF");
    digitalWrite(5,fireStatus4 );

}
}

You should always provide the full error message including the line, where the error occurred

You cannot directly cast a String to an uint8 for use with digitalWrite(). What string do you get from Firebase?

fireStatus.toInt() or Firebase.getInt("S1")?


text:
Unable to receive SMS on Android
I have a GSM/GPRS shield for Arduino. It uses a SIM800 from SIMCOM. I've done several projects using it. Previously I used to send SMS from the same module. which were delivered appropriately. Since yesterday, whenever I am sending an SMS to my Android mobile, all what I receive is:
<<Content not supported>>

I also tried sending it to a basic mobile. It displayed:
Content can't be displayed

I tried changing the encoding using the AT command.
AT+CSCS="UCS2"
AT+CSCS="GSM"

It didn't work for any encoding.
The command I use to send SMS is:
---> AT+CMGF=1
<--- OK
---> AT+CMGS="10 digit number"
<--- >
> Hello!
^Z

Can someone please tell me what is going wrong? Thank you in advance!

In the SIM900 is an AT command that let you do a factory reset, your module will restart to the default values. It must be an AT command very similar to the SIM800.
The AT commando that (perhaps) will work for you is the ATZ, in the SIM900 works for me.
You can look over here to see what command is. Look over page 33. And be carefull, the link that I send to you is the AT command list for the SIM900, not the SIM800.
Hope you can find an answer.

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


text:
Need a proper diagram to connect my multiple relays (more than 8) with only a few pins on Arduino Uno Board
Specifically, I want to add multiple relays (approximately 36 to 40) to an Arduino Uno board (using only a few pins). I found a solution using ShiftOut. You can take a look here. But here the example is for testing small LEDs bulbs.
I will control high-voltage electricity like fans, tube lights, washing machine with those relays, so what will be a proper graph or image diagram for that? And if you have any more suggestions for me then you can tell me :) And yes please tell me what I should use for it.
Right now am thinking to use an Arduino, relays, 74HC595 IC only. My diagram for controlling LED is like this:

You can edit it. I just need proper guidance for it and a few good suggestions.

Just replace the led/resistor with a relay... repeat as necessary

Actually am new to arduino. So, Kindly Can You Please tell me with example of 1 relay how to connect it with this bread board properly (just tell me with any 1 relay)

If you want to drive a normal magnetic relay you will need to add a transistor / resistor to the output of the 74HC595 as the current is too high across the magnet of the relay to be driven directly by the 74HC595. If you don't want to use a transistor for every relay, you could you an 8 channel driver chip like the ULN2803A. You should be able to connect your relay coil directly from 12v and to the ULN2803A.
Have a look at this page for an example. http://www.mcmajan.com/mcmajanwpr/blog/2014/04/18/arduino-how-to-connect-many-12v-relays-en/

I would strongly recommend ULN2803. They are designed to drive inductive load (motors, relays and so on). And they are so easy to use. For beginners they are best choice.

What about using an I2C I/O expander like MAX7328 or equal and a ULN28XX as relay driver. and you can connect several I/O expanders to the same I2C buss with different addresses.
This will use minimal amount of pins and minimal amount of components.


text:
My button stays on high if I press it once, what did I do wrong?
If I press my button once, I get characters on all of the 32 character places and I get an infinite tone with my piezo. Can someone help me with this?

#include <LiquidCrystal.h>

const int buttonPin = A0;
int buttonState = 0;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
byte run1c[8] = {
  B00000,
  B01100,
  B01100,
  B00000,
  B01110,
  B11100,
  B01110,
  B10010,
};

byte run2c[8] = {
  B00000,
  B01100,
  B01100,
  B00000,
  B11100,
  B01110,
  B11100,
  B10010,
};

byte jumpc[8] = {
  B01100,
  B01100,
  B00000,
  B11110,
  B01101,
  B11111,
  B10000,
  B00000,
};

byte jumpLowerc[8] = {
  B01110,
  B11100,
  B01110,
  B10000,
  B00000,
  B00000,
  B00000,
  B00000,
};

byte groundc[8] = {
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
};

byte rightGroundc[8] = {
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
};

byte leftGroundc[8] = {
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
};

void setup() {
  lcd.createChar(0, run1c);
  lcd.createChar(1, run2c);
  lcd.createChar(2, jumpc);
  lcd.createChar(3, jumpLowerc);
  lcd.createChar(4, groundc);
  lcd.createChar(5, rightGroundc);
  lcd.createChar(6, leftGroundc);
  Serial.begin(9600);
  lcd.begin(16, 2);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH){
    tone(8, 400);
    lcd.setCursor(1,0);
    lcd.write(byte(2));
    digitalWrite(buttonState, LOW);
  } else {
    lcd.setCursor(1,1);
    lcd.write(byte(0));
  }
}

digitalWrite(buttonState, LOW);  That line is writing either pin 0 or pin 1 low.   Did you mean to just set buttonState = LOW;

@Delta_G yes, I thought that would fix the problem, so i just have to write: buttonState = LOW;

You shouldn't have to write that at all.  It should set buttonState from the digitalRead at the top of loop right before it compares it.  But either way, trying to digitalWrite with another pins state as the pin number is definitely not right.

@Delta_G And if I move that white wire, connected to A0, to pin number 13, and change that in the code. Will that make a difference?

Sure, it will make it so that the code you have is reading the wrong pin.  If you change the pin number in the code as well then you're in the same boat.  Why don't you try an active LOW arrangement for the button like I described in my answer below.

@Delta_G Okay, and the resistor? I wired that one based off the Genuino starter kit book

@Delta_G the resistor is direcly connected to ground, the blue wire is connected to another resistor, wich is connected to the lcd display

If you use the internal pull-up and wire for active low you don't need any resistor.

Also take note that you would normally use the two diagonal pins on the button.  Two sets are normally close and two sets are normally open.  Or try rotating the button 90 degrees.

@Delta_G unfortunately i cant rotate the button, it just would not fit into the breadboard at that moment. And with wire for active low, do i just have to replace the resistor with a normal wire, or am i not understanding you. (My English isn't that good sometimes)

I gave you good instructions in the answer below.  You tie one side of the button to ground and the other side to the pin.  There will be only two wires connected to the button.  One going to ground and the other to the pin.  So when the button is pressed, it connects the pin to ground.

@Delta_G It still gave me the same problem as before

Show the new wiring and the new code.

Where, in your program, do you ever tell it not to play the tone? You start a 400Hz tone on pin 8 but never stop it.

@Majenko I have added the noTone() in else{}

From what I can tell from your drawing, you have both sides of your button tied to 5V.  The green wire on one side and the blue wire through the resistor on the other.  So yes, the button will always read HIGH.
Instead, remove the resistor, tie one side of the button to the pin and the other side to ground.  Use INPUT_PULLUP in your pinMode cal instead of just INPUT.  Now a pressed button will read LOW and not pressed will read HIGH, so you'll have to reverse your logic in your code.  But the wiring will be much nicer.

the blue wire is connected to the lcd display with a 220 ohm resistor, the 10k ohm resistor is connected to ground

In your code you check the button state and if it is high you set the tone.
In the else section you do nothing with the tone.
Hence, once on, it will always stay on.


text:
Arduino Yun V2.0.1 can't configure WiFi
I can't configure at 192.168.240.1. It's giving me this message multiple times:
1- AJAX/HAR Error:0 has not allowed Arduino Configuration Wizard to complete.
Details of my board:
Arduino Yun V2.0.1 anders evinrud

Comments on a non-answer (since deleted) have been moved to chat.

I have this error too when I typed a wrong password to connect to the green 'osjs' interface.
have you changed the password of your board ?
have you tried the 2 possible passwords ( "arduino" or "doghunter" ) depends on the image installed ?
hacve you cleared your browser cache / test with another browser ?

I managed to pass through it...n my project had completed☺

@hydrogen.uranium235 then why don't you answer your question to help out anyone else who may have this issue?

First, u can just ignore the error and check back is ur IP add changed after several times of configuring.

Second, if it is still not working, and u cant enter the site with the new IP address, u just need to hard reset the arduino...mayb cz u did it so many times.

@hydrogen.uranium235 please submit your answer by clicking on the "Answer Your Question" button at the bottom of the page. Once submitted, then accept the answer by clicking on the green tick under the vote area. Please don't post the answer as a comment.


text:
Can I control a Z84 counter timer circuit with Arduino?
Link to pin description and to the Datasheet.
I'm thinking about connecting channel outputs to LEDs and control the clock with IO-Arduino or a 555: I would program it with a 595 register.
Can someone explain me why this is a bad idea?

I wouldn't say it was a "bad" idea - pointless maybe, but not "bad". A good learning experience if nothing else.

can you confirm that the project above could work? i wouldn't like to burn or break something.

I can see no reason why it wouldn't work. As long as you generate the right signals to emulate the Z80 bus it'll be fine. Just remember the resistors on the LEDs.


text:
Weird characters at the end of LCD
I have written a simple sketch that displays temperature and humidity on a 16x2 LCD. Here's its output:
Temp: 28▒▒
Humidity: 68▒▒
The library I used for DHT11 sensor is not from Adafruit. This is the sketch:
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
#include<dht.h>

#define DHT11_PIN 12
#define I2C_ADDR       0x3F
#define BACKLIGHT_PIN  3
#define En_pin         2
#define Rw_pin         1
#define Rs_pin         0
#define D4_pin         4
#define D5_pin         5
#define D6_pin         6
#define D7_pin         7
#define SCL_PIN        12
#define SDO_PIN        11

dht DHT;
LiquidCrystal_I2C  lcd(I2C_ADDR, En_pin, Rw_pin, Rs_pin, D4_pin, D5_pin, D6_pin, D7_pin);

void setup() {
  pinMode(SCL_PIN, OUTPUT);
  pinMode(SDO_PIN, INPUT);
  lcd.begin (16, 2);
  lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.home ();
}

void loop() {
  lcd.setCursor(0, 0);
  int chk = DHT.read11(DHT11_PIN);
  lcd.print("Temp: ");
  lcd.println(DHT.temperature,0);
  lcd.setCursor(0, 1);
  lcd.print("Humidity: ");
  lcd.println(DHT.humidity,0);
  delay(2000);
}

You say “The library... is not from Adafruit”, which is not helpful -- instead, say which DHT11 library you are using.  Without that info, one doesn't know the declarations of DHT.temperature and DHT.humidity, hence doesn't know which println() was invoked and what it does with second param which causes a character in the range 0 to 7, the custom character generator codes, to print.    Please edit your question to include that info

"The library I used for DHT11 sensor is not from Adafruit" - is it also not from Sparkfun? Give us a break and give a link to the library.

@jwpat7 The library is linked here: link

The function println usually appends a carriage-return and linefeed to what it prints. It wouldn't surprise me if those two extra characters are its attempt to "render" that.
Try replacing println with print and see what happens.


text:
How do I write and read internal EEPROM?
I am working on an Arduino Mega 2560. I want to read and write the internal EEPROM.
Can I use EEPROM.get()/EEPROM.put()?
I want to store 3 things in EEPROM:

Boolean status.
String password: length 5 digits.
String Mobile number: length 10 digits.

Yes. Is your question how you can do it?

the easy way to get that working is to simply read/write them all each time, and use a char as a delimter, like "~", to split the loaded values.

How do I write and read internal EEPROM? Can I use EEPROM.get()/EEPROM.put()?

Yes, the Arduino Reference for EEPROM contains an example of what you are asking for. Below is a simple rewrite of the example for EEPROMGet for your info.
struct MyObject{
  bool status;
  char password[6];
  char mobileNumber[11];
};

void setup()
{

  int eeAddress = 0; //EEPROM address to start reading from

  Serial.begin( 9600 );
  while (!Serial) ;

  MyObject customVar; //Variable to store custom object read from EEPROM.
  EEPROM.get(eeAddress, customVar);

  Serial.println(F("Read custom object from EEPROM: "));
  Serial.println(customVar.status);
  Serial.println(customVar.password);
  Serial.println(customVar.mobileNumber);
}

For more details and examples see https://www.arduino.cc/en/Reference/EEPROM.
Cheers!

Avoid the 'String' object, use a character array of fixed length. You might want to add one extra byte for the zero-terminator. Put everything in a 'struct' and then you can use the EEPROM.get() and EEPROM.put() to read and write the complete struct. I prefer a struct to keep the data from EEPROM together. That makes it easier to add a checksum and a version number for the data. When something is wrong with the data from EEPROM then default values could be used.
Instead of a struct, you can also read and write the seperate items. The EEPROM.get() and EEPROM.put() should be able to use a character array of fixed length.


text:
String to char array conversion
In my project I need to convert a string to a char array. From various examples I concluded that toCharArray() will convert a string to a char array. But I failed to do so. The error is:

'a' does not name a type

The code I am using is:
String a = "45317";
char b[6];
a.toCharArray(b,6);

Resources are https://www.arduino.cc/en/Reference/StringToCharArray and http://forum.arduino.cc/index.php?topic=199362.0

maybe this example may help you:
https://stackoverflow.com/questions/68497443/convert-an-arduino-c-string-to-an-ansi-c-string-char-array-using-the-string

If you're trying to use a method of a in the global scope, that's doomed to failure. You can only call methods within functions.
If all you want is a char array with "45317" in it then just use:
char *b = "45317";

If you want to convert a string that is built at runtime into a char array, then your current method is correct - you just have to do it in the right place.


text:
Arduino UNO UART coding in pure C
Below is a simple USART code for ARDUINO written in Pure C.
But due to uknown(in reference to me) reasons, the code is not provicing desired output.
Can someone point out the error in the code.
I cannot use the Arduino built in function Serial.begin as i need to use USART receive interrupts.
#include <avr/io.h>
#define F_CPU 16000000
#define BAUD 9600
#include<util/setbaud.h>

void UART_Init();

void setup()
{
    UART_Init();
}

void loop()
{
    UART_Transmit('c');
}

void UART_Init()
{
   UBRR0H = UBRRH_VALUE;
   UBRR0L = UBRRL_VALUE;
   UCSR0B = (1<<RXEN0) | (1<<TXEN0);
   UCSR0C = (3<<UCSZ00);
}

void UART_Transmit(unsigned char data)
{
    while(!(UCSR0A & (1<<UDRE0)));
    UDR0 = data;
}

Compiled as an Arduino sketch, your code runs like a charm on my Uno. How did you compile it?

@EdgarBonet I did compiled it on Arduino IDE . There was no error in the code. But after uploading to the board the output received is not as expected.

What kind of output did you expect? I see a long stream of "ccccccccccccccccccccccc...", and that's what I expect from reading the code.

@EdgarBonet I too expect that only. But am not getting it.In my serial monitor, I get only square boxes

At 115200 baud rate, the correct output is received. But for 9600, the output is square boxes.

Is this a real Uno clocked at 16 MHz? Could you post the generated elf somewhere?

@EdgarBonet I am using an Arduino clone clocked at 16Mhz. elf file: link

I can't download that without opening a Dropbox account, which I won't do.

suggest a good alternative please.

@EdgarBonet elf file

i am stuck in the same problem...not able to use arduino serial functions .....while using uart receive interrupt.....
have you got the solution?

Finally I figured it out.
The UBRR0 calculation was the mistake
For making the code work for baud rate 9600, we need to set the equation as:

UBRR0 = (F_CPU / 4 / baud - 1) / 2;

and also double the USART speed by setting :

UCSR0A = (1<< U2X0)

I hope someone will find this information helpful.

util/setbaud.h defines USE_2X to 0 or 1 depending on whether the U2X bit is needed. Then you can UCSRA |= (USE_2X << U2X);.

@EdgarBonet Thanks for the help man. It works like a charm.

UBRR0 = (F_CPU / 4 / baud - 1) / 2;

you probably want to check the datasheet for that.
One way to code it is to change it based on the U2X bit, like this:
UxBRR=F_UART / ((UxCSRA & (1<<U2X0))?8:16) / baud - 1;          //generate baud rate register

So the user can change the U2X bit freely and the software will take care of it.
there is one set of uart polling and interrupt-driven routines that I use: https://github.com/dannyf00/My-MCU-Library/tree/master/UART/UARTISR/ATMega328p
they have the same user interface so can be exchanged freely.


text:
Read from analog then cast not showing the correct value
I'm trying to read the analog value of the light sensor and print its percentage but for unknown reasons I'm getting negative values when I'm printing the value.
void setup() {
  Serial.begin(9600);
}

void loop() {

  // Let's say 1002 is the analogValue
  int analogValue = (int) analogRead(0);

  // get the percentage
  int value = 100 * analogValue / 1023;

  Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");
  Serial.println(analogValue); // print the analog value 0...1023
  Serial.println(100 * analogValue); // just for test
  Serial.println(value); // The percentage
  Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");

  delay(500);
}

I don't know what's going in background, but I'm getting negative values when I try to print the percentage:
~~~~~~~~~~~~~~~~~~~~~~~~~
1002
-30772
-30
~~~~~~~~~~~~~~~~~~~~~~~~~

Max value for int is 32,767. But 100 * 1002 = 100,200. You are overflowing the int. Use unsigned long. Or float and cast to int when printing.

Simplest would be to replace 100 by 100L.

Yes, but OP would have to be sure to do that on both lines - the original calculation as well as the Serial.println line (even though it's "just for test").  Either way works, though.


text:
Keep motor moving
I have a problem on how to keep my stepper motor moving when button is released. It should only stop moving if I press the button again.
For now, stepper motor  is only moving IF the button is constantly pressed.
//Constants won't change. They're used here to set pin numbers:
const int buttonPin = 4;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin
const int dirPin = 8;        // the number of the motor direction pin
const int stepPin = 9;         // the number of the motor step pin

//Variables will change:
boolean flag = true;
int buttonState = 0;         // variable for reading the pushbutton status
int distance = 0;

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(dirPin, OUTPUT);  //YELLOW
  pinMode(stepPin, OUTPUT); //ORANGE

  digitalWrite(buttonPin, LOW);
  digitalWrite(dirPin, HIGH);
  digitalWrite(stepPin, HIGH);
}

void loop() {
  buttonState = digitalRead(buttonPin); // Read the state of the pushbutton

  if (digitalRead(buttonPin) == LOW) {  // If pushbutton is pressed, buttonState is HIGH:
    digitalWrite(ledPin, HIGH);
    digitalWrite(dirPin, LOW);          // LOW=FORWARD DIRECTION
    digitalWrite(stepPin, HIGH);        // stepPin = MOTOR ON/OFF
    delayMicroseconds(100);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(100);
    distance++;
    if(distance > 21000){
      distance = 0;
      delay (3000);
      reverse();
    }
  }

  if (digitalRead(buttonPin) == HIGH){ // turn LED off:
    digitalWrite(ledPin, LOW);
    digitalWrite(dirPin, LOW);  //LOW = FORWARD DIRECTION
    digitalWrite(stepPin, LOW); //stepPin = MOTOR ON/OFF
    delayMicroseconds(100);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(100);
  }
}

void reverse() {
  digitalWrite(dirPin,HIGH); //HIGH = REVERSE DIRECTION
  digitalWrite(stepPin,HIGH);
  delayMicroseconds(100);
  digitalWrite(stepPin,LOW);
  delayMicroseconds(100);
  distance++;
    if(distance > 21000){
      distance = 0;
      delay(3000);
      return;
    }
  reverse();
}

1.) Please format your code. Left-aligned code is hard to read. It should be indented properly. That will also make it easier for you to spot problems. 2.) Use variables in order to name pins, e.g. pin 8 and 9. You have already done so for pin 4 and 13. Why not for 8 and 9? With names, people don't have to remember what number has what purpose

3.) if you want two different actions when a button is pressed, then you need to keep records of the current state. So you will need a vaiable like bool isMoving=true and toggle that on each button press.

N.b. your code is unreadable, so I won't attempt to debug your program, but I will present some pseudo-code that could help.

It should only stop moving if I press the button again ... [as of] now, [the] stepper motor is only moving IF the button is constantly pressed.

So what you need to do is save the state of your Motor, (MOVING, STOPPED, etc.) and base your code on that state.
You will also need to de-bounce your switch.
Your loop will have to:

Read & de-bounce the switch
Update the state based on switch
Run the stepper based on state

pseudo-code:
// include libraries etc.
#include <Stepper.h>

// set up your buttons pins etc.
int button = <pin>;
Stepper = step(...); // pins etc.

void setup()
{
   // do setup stuff...
}

enum MOTORSTATES {
  STOPPED = 1,
  FORWARD = 2,
}

MOTORSTATES state = STOPPED;

// forward declare your functions
bool isPressedDebounce(int pin);
void doStep(Stepper&, MOTORSTATES);
MOTORSTATES changeState(MOTORSTATES);

// loop is now simple
void loop()
{
  if(isPressedDebounce(button))
    state = changeState(state);

  doStep(step, state);
}

// because we have broken our problem into pieces
bool isPressedDebounce(int pin)
{
  // proccess and de-bounce the switch
  // implementation left as exercise for reader
}

void doStep(Stepper& step, MOTORSTATES state)
{
  // based on the state move the stepper
  // implementation left as exercise for reader
  switch(state)
  {
    case STOPPED:
      // DO IT
      break;
    case FORWARD:
      // DO IT
      break;
  }
}

MOTORSTATES changeState(MOTORSTATES state)
{
  // n.b. I used this pattern because it is the beginning of a state machine!
  switch(state)
  {
    case STOPPED:
      return FORWARD;
      break;
    case FORWARD:
      return STOPPED;
      break;
  }
}

I structured the pseudo code such that it contains a simple state machine, and can be easily extended. State machine code is very useful for programming Arduinos!

There are two issues:

You SHOULD pull-up or pull-down the input pin when using pushbutton.
You should detect the "press" and "release" event.

Two above issues are mentioned in this tutorial


text:
Difficulties programming Arduino uno for 24 hour cycle
I am trying to program my Arduino Uno board for a 24 hour cycle.
I have the Arduino board and two relays.
The aim is; every 24 hours relay 1 has to switch on for 5 seconds, and 1 second later relay 2 has to switch on for 15 seconds.
I have a sketch for a 12 hour cycle, and that works fine, but when I try for a 24 hour cycle, by changing the const unsigned int totalTime from 43200 seconds to 86400 seconds, everything goes wrong.
24 hour sketch - what is wrong?
//turn relays on and off at certain times.
//when the digital output pin is HIGH, then the relay is off.
//when the digital output pin is LOW, then the relay is on.

enum actioEnum {
  RELAY1_ON,
  RELAY1_OFF,
  RELAY2_ON,
  RELAY2_OFF,
};

struct tableStruct{
  unsigned int time;
  actionEnum action;
}
const table [] = {
  {0,RELAY1_ON},
  {5,RELAY1_OFF},
  // remaining 86395 for a total of 86400.
  {0,RELAY2_OFF}, // not needed, it is already off.
  {6,RELAY2_ON},
  {6+15,RELAY2_OFF},
  // remaining 86379 for a total of 86400.
};

const unsigned int totalTime = 86400; // total amount for sequence
unsigned int seconds;

unsigned long previousMillis;
const unsigned long interval = 1000; // 1000 ms; // 1000 ms is one second

const int relay1Pin = 2;
const int relay2Pin = 3;

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

  // the relay is off when the pin is high.
  // turn output high before setting the pinMode.
  // then the output changes from a floating pin to high,
  // and the relays will not be activated.
  digitalWrite (relay1Pin, HIGH);
  pinMode (relay1Pin, OUTPUT);
  digitalWrite (relay2Pin, HIGH);
  pinMode (relay2Pin, OUTPUT);
}

void loop () {
  // a one second timer with millis
  if (millis() - previousMillis >= interval) {
    previousMillis += interval;
    // scan table
    for ( int i = 0; i < int (sizeof(table) / sizeof (tableStruct)); i++) {
      if (table [i] . time == seconds) {
        switch (table [i] . action) {
          case RELAY1_ON:
            Serial.println("Relay 1 on");
            digitalWrite (relay1Pin, LOW); // low is relay on.
            break;
          case RELAY1_OFF:
            Serial.println("Relay 1 off");
            digitalWrite (relay1Pin, HIGH); // high is relay off.
            break;
          case RELAY2_ON:
            Serial.println("Relay 2 on");
            digitalWrite (relay2Pin, LOW); // low is relay on.
            break;
          case RELAY2_OFF:
            Serial.println ("Relay 2 off");
            digitalWrite (relay2Pin, HIGH); // high is relay off.
            break;
          default:
            Serial.println ("Error, a bug in the scketch");
        }
      }
    }
    seconds++;
    if (seconds >= totalTime) {
      seconds = 0;
    }
  }
}

Why you are not using a RTC module?

The Uno isn't the most accurate in time keeping, and can drift by a few minutes every day. Depending on your application this might not matter. However, if it does, use an RTC like newbie suggested.

On the Uno unsigned int is a 16 bit number. That means, that it can hold values between (and including) 0 and 65535. If you try to write a bigger value to this variable, it will cut of the higher bits, so that the rest fits into 16 bits. That gives you a totally different value, which is significantly small than 24h.
The solution is to use a bigger variable type for totalTime.
 You can use unsigned long, which has 32 bits and can hold way bigger values ( 0 to 4,294,967,295 (2^32 - 1)). That should be plenty enough for all your cases.

Hi, your solution is to use unsigned long instead of totalTime. how do I change this in my sketch? Regards, Martinus.

No, not instead of totalTime, but as the type of it. In your sketch you wrote const unsigned int totalTime = 86400;, but instead you should write const unsigned long totalTime = 86400;. That changes the type of the variable totalTime from unsigned int to unsigned long.


text:
Fixing Error function 'long int map

Arduino: 1.8.5 (Windows 8.1), Board: "Arduino/Genuino Uno"

C:\Users\julie_000\Documents\Arduino\BIO_199\BIO_199.ino: In function 'void loop()':

BIO_199:19: error: too few arguments to function 'long int map(long int, long int, long int, long int, long int)'

   t1 = map(2, 0, 1023, 2);

                         ^

In file included from sketch\BIO_199.ino.cpp:1:0:

C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:253:6: note: declared here

 long map(long, long, long, long, long);

      ^

exit status 1
too few arguments to function 'long int map(long int, long int, long int, long int, long int)'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
How do I fix this error?

Use formatting! And don't post pictures of code!

map takes 5 parameters, not 4.  You have the original lower and upper bounds, the desired lower and upper bounds, but you forgot the actual value you want to map:
map(value, fromLow, fromHigh, toLow, toHigh)

So
t1 = map(t2, 2, 0, 1023, 2);

(assuming those numbers are actually meaningful...)