body:
i am new in arduino and ESP8266 module. I am still learning about AT command. But i found this problem:

1.My website code (index.html)-http://nyalalampu.atwebpages.com:
```
<html>
<body>
<?php
        ECHO $_GET['subject'];
?>
</body>
</html>
```

2.My AT commands (In Arduino IDE Serial Monitor)
```
AT+CIPSTART="TCP","nyalalampu.atwebpages.com",80

CONNECT

OK
AT+CIPSEND=29

OK
>
Recv 29 bytes

SEND OK

+IPD,391:HTTP/1.1 408 Request Timeout
Date: Sat, 10 Oct 2020 17:00:24 GMT
Server: Apache
Content-Length: 221
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>408 Request Timeout</title>
</head><body>
<h1>Request Timeout</h1>
<p>Server timeout waiting for the HTTP request from the client.</p>
</body></html>
CLOSED
```

After > i put
```
GET /?subject=anis HTTP/1.0
```

My question is why it not print **anis** in Arduino IDE Serial Monitor? It just show 408 Request Timeout

I hope someone can tell me what's wrong with my code.TQ

title: AT Commands ESP8266 Arduino IDE serial monitor not print any data from server. It say 408 request timeout

Answers: 0


body:
I found this Haptic Headband project on YouTube (link below) and I am trying to verify the code that was given in the instructions with the Arduino IDE. However, I keep getting the message below and am not too sure what I need to do to fix it. I'd appreciate any help I could get to solve this issue.

I have also attached a pdf of the instructions with the code to use for the headband.

PDF: https://cdn-learn.adafruit.com/downloads/pdf/haptic-headband.pdf?timestamp=1602887165

https://www.youtube.com/watch?v=xD7bfBx5D9M&ab_channel=AdafruitIndustries

```

libraries\Adafruit_DRV2605_Library\Adafruit_DRV2605.cpp.o (symbol from plugin): In function `Adafruit_DRV2605::Adafruit_DRV2605()':
(.text+0x0): multiple definition of `Adafruit_DRV2605::setRealtimeValue(unsigned char)'
sketch\Adafruit_DRV2605.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries\Adafruit_DRV2605_Library\Adafruit_DRV2605.cpp.o (symbol from plugin): In function `Adafruit_DRV2605::Adafruit_DRV2605()':
(.text+0x0): multiple definition of `Adafruit_DRV2605::useERM()'
sketch\Adafruit_DRV2605.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries\Adafruit_DRV2605_Library\Adafruit_DRV2605.cpp.o (symbol from plugin): In function `Adafruit_DRV2605::Adafruit_DRV2605()':
(.text+0x0): multiple definition of `Adafruit_DRV2605::useLRA()'
sketch\Adafruit_DRV2605.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino Uno.
```

title: Error message - Need help

Answers: 1

body:
“Multiple definition” means that you have something defined more than
once. According to the error message, some methods are defined both in
libraries\\Adafruit\_DRV2605\_Library and in your sketch folder.

It looks to me like you are trying to use two copies of the
Adafruit\_DRV2605 library. One of them is properly installed as a
library, and the other is within your sketch folder. You don't need two
copies. If the library is properly installed, there is no point in
copying its source files to your sketch folder. Get rid of that extra
copy and try recompiling.


body: I'am asking this question, because in my ESP-01 OTA upload always fail. In fact update won't even start. When update was triggered esp wifi led(build in blue) indicates "working" , but after cca one second esp reset itself. And The original program remains and starts again...

title: Is 1MB flash enough for OTA upload in ESP-01?

Answers: 2

body:
Yes, 1MB is fine for OTA. There are, though, a few caveats when working with OTA that you must observe regardless of the flash size:

1. The maximum OTA program size is less than half the available flash size. Typically it is about 500kB. Two copies need to be stored in flash, plus the partition table and NVRAM. The rest of the flash on larger chips is most often dedicated to FS storage.
2. The device must first be programmed through USB with an OTA-compatible partition layout.
3. After programming through USB it must be manually reset or power cycled to set the boot mode correctly.
4. You can not change the partition layout over OTA programming. You need to make sure you have the same partition layout selected as when you originally programmed through USB.
5. `ArduinoOTA.handle();` has to be called very regularly to handle the programming request. You can't have any blocking code in your sketch that might stop that from being called.

Observe all those and you should be able to program over WiFi with no problems.

body:
For OTA uploads, the size of the compiled (old sketch + new sketch) should not exceed the flash size.

Due to this, large sketches (more than 500KB with 1MB flash) cannot be OTA uploaded directly if the sketch size exceeds half of the flash size.

However, this restriction can be circumvented by first uploading a sketch only with OTA features as given below:

------------------------------------------------------------------

    #include <ESP8266WiFi.h>
    #include <ESP8266mDNS.h>
    #include <WiFiUdp.h>
    #include <ArduinoOTA.h>

    char ssid[] = "xxxxxxxx"; //WiFI user id
    char pass[] = "yyyyyy";   //WiFi password

    #define OTA_Host_Name "ESP01S-EMPTY-OTA"

    void setup()  {
      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, pass);

      while (WiFi.waitForConnectResult() != WL_CONNECTED) {
        delay(5000);
        ESP.restart();
      }
      ArduinoOTA.setHostname(OTA_Host_Name);
      ArduinoOTA.begin();
    }

    void loop() {
      ArduinoOTA.handle();
    }

------------------------------------------------------------------

This script will compile to around 300KB. Once this script is uploaded in flash, a script with upto 700KB can be uploaded through OTA to a 1MB flash!

Upload this script first. Then restart the controller and choose "ESP01S-EMPTY-OTA" as the port and upload the new updated script that you wish to upload!

IMPORTANT: Firewall must be turned OFF during OTA uploads.


body: I am using ESP-12e as a controller for my garden lights. I am using pins 1 (TX), 3 (RX) and 5 as an analog output (PWM signal with mosfets) for three separate light sets. ESP is powered on when wall switch is turned on (wall switch turns on power adapter). When I turn the switch on, for short period of time lights connected to pin 1 and 3 work at full power and after that they are set according to PWM signal. Lights on pin 5 works just as expected. I am not using Serial communication, just elegantOTA library for OTA updates and async web server. Is it possible to somehow disable RX/TX functionality at all/before they are set to high, or I am forced to solder lights on pins 1 and 3 to another ones? I tried some software tricks I found online, but without success.

title: ESP-12e - RX/TX pins flickering on boot when used as GPIO pins

Answers: 2

body:
[According to this reference][1], GPIOs 1 and 3 have dedicated behaviour during boot (debug output or pulled high) which can not be disabled in your sketch.
You have to either choose different pins or implement an additional circuitry.

  [1]: https://randomnerdtutorials.com/esp8266-pinout-reference-gpios/

body:
> I am not using Serial communication,

You might not be, but the bootloader sure is.

> Is it possible to somehow disable RX/TX functionality at all/before they are set to high

No. It's hard coded in ROM. There's nothing you can do.

> or I am forced to solder lights on pins 1 and 3 to another ones?

You could use one IO pin to control a buffer the other IO pins. Something like an AND gate (74HC08) would do the job:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/rILD9.png)

<!-- End schematic -->

Only when `CTL` is `HIGH` will the `L0`-`L2` signals be mirrored on the outputs to the LEDs. That way you ignore whatever is going on with those pins until you actively drive the `CTL` signal high. Choose one pin that has no boot noise for `CTL` and the other pins then don't matter.

For more detail on what pins do what at boot time [read this](https://randomnerdtutorials.com/esp8266-pinout-reference-gpios/).


body:
I have a project which, to save on battery, is put to sleep until an interrupt pin is rising from LOW to HIGH.

This works well on Arduino Nano, however the translation doesn't on the ATTiny.

    #include <avr/sleep.h>
    void setup(){
        pinMode(2,INPUT);
        noInterrupts();
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        attachInterrupt(INT0,wakeUp,RISING);
        //Yadada
        Interrupts();
    }
    void wakeUp(){
       //Something Something
       sleep_mode();
    }

Both on the Arduino Nano and the AtTiny, the interrupt Pin 0 is equivalent to Pin 2.

 - The Arduino is set to ISP
 - I have run the Bootloader (with internal clock as 8MHz if that makes a difference)
 - The program loads on the AtTiny45.

Yet, the interrupt pin does not interrupt.

**Does the INT0 act differently on a ATTiny than on the Arduino, and if so, how can I wake up my AtTiny?**

title: Arduino to AtTiny change of pin interrupt behaviour?

Answers: 1

body:
After going through a lot of documentation, it seemed best and more efficient to attach the interrupt without functions.

    EIMSK  |=  (1<< INT0);//Attaches the interrupt
    MCUCR  |=  (1<< SM1)  //Power-down mode
             | (1<<ISC01) //The rising edge of INT0
             | (1<<ISC00);// generates an interrupt request


body:
I'm trying to implement a stopwatch with an LCD display, and I'm supposed to be using the `attachInterrupt` command to catch the button press. The clock runs perfectly, but the button input isn't caught or acted upon at all.

In `void setup()`, I have set it up this way: `attachInterrupt(digitalPinToInterrupt(buttonPin), buttonInterrupt, RISING);`.

And the buttonInterrupt function only does `start = !start`, so in a sense just flipping the start variable.

This is the updated version of the code:
```
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int buttonPin = 7;
volatile int buttonState;
int lastButtonState;
long sec;
long startTime;

void setup() {
  lcd.begin(16, 2);
  pinMode(buttonPin, INPUT_PULLUP);
  lcd.setCursor(0,0);
  lcd.print("Push the button!");
  attachInterrupt(digitalPinToInterrupt(buttonPin),buttonInterrupt,HIGH);
}

void loop() {

  buttonState = digitalRead(buttonPin);
  if(buttonState == LOW){
    startTime = millis();
  }

  while(buttonState == HIGH){
    long time = millis();
    long z = (time - startTime);
    sec = (z/1000);
    long ms = z00;
    lcd.setCursor(0,1);
    lcd.print(sec);
    lcd.print(".");
    lcd.print(ms);
    lcd.setCursor(8,1);
    lcd.print("Secs");

    if(buttonState == LOW){
      break;
    }
  }
}

void buttonInterrupt() {
  if(buttonState == LOW){
    buttonState = HIGH;
  }else{
    buttonState = LOW;
  }
}
```
The loop function works as far as time counting is concerned, but doesn't work to stop the time with the button. Any help is appreciated, I'm extremely new to Arduino (literally started yesterday). My circuit looks like this: https://i.stack.imgur.com/XHHy5.png

If there is any other way to print the numbers other than printString, more than happy to hear them!

Thanks!

title: Button to stop a stopwatch not working correctly!

Answers: 1

body:
There are several issues here. First and foremost, your button is wired
incorrectly. If you connect one end of the button to +5V, then the other
end should have a pushdown to GND, like here:

![Wiring of a button][img]

(Image from the [Arduino Button example][button]).

The second issue is the lack of debouncing. You should ignore the rising
edges you sense for a few milliseconds after you record one.

The third issue is the timekeeping. As explained by Sim Son, your
seconds will not be very accurate. It's better to just count the
milliseconds elapsed since the button press, and then break the count
into full seconds and remaining milliseconds.

[img]: https://www.arduino.cc/wiki/static/875a01f9d20a576acd5b7974e6339339/b2982/button.png
[button]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/Button


body:
I am trying to use the *u8g2* library and an Arduino Mega to control an LCD display. Adapting `HelloWorld` from the examples included in the library to use the SPI ports of the Mega (50-52), I have the code below.

This gives a bit of a disappointing greeting as in the picture below. It seems that the Arduino is not accessing all the pixels, and only able to change the states of three blocks (the top one with "Hello V", and the two darker regions at the bottom).

[![That's supposed to say "Hello World"][1]][1]

[![Wired up][2]][2]

The display is a `128X64ZW-10` salvaged from a 3D printer which was working when connected to the printer's motherboard. Pin-out deduced by some kind folk [here][3] and [here][4] [(translation)][5]. I briefly saw random Pinyin characters flash across the whole display while I was switching wires. These two facts, and the fact that the regions of pixels that are working are not arranged at random, makes me suspect it is a wiring or coding issue, and that the pixels are not dead.

Here is the code:

    #include <Arduino.h>
    #include <U8g2lib.h>

    #ifdef U8X8_HAVE_HW_SPI
    #include <SPI.h>
    #endif
    #ifdef U8X8_HAVE_HW_I2C
    #include <Wire.h>
    #endif

    int LCD_CLK_PIN = 52; //Clock (white)
    int LCD_RW_PIN = 50; //Read-Write (blue)
    int LCD_RS_PIN = 51;  //Register Select (green)
    U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, LCD_CLK_PIN, LCD_RW_PIN, LCD_RS_PIN,U8X8_PIN_NONE);

    void setup(void) {

      /* U8g2 Project: SSD1306 Test Board */
      //pinMode(10, OUTPUT);
      //pinMode(9, OUTPUT);
      //digitalWrite(10, 0);
      //digitalWrite(9, 0);

      /* U8g2 Project: T6963 Test Board */
      //pinMode(18, OUTPUT);
      //digitalWrite(18, 1);

      /* U8g2 Project: KS0108 Test Board */
      //pinMode(16, OUTPUT);
      //digitalWrite(16, 0);

      /* U8g2 Project: LC7981 Test Board, connect RW to GND */
      //pinMode(17, OUTPUT);
      //digitalWrite(17, 0);

      /* U8g2 Project: Pax Instruments Shield: Enable Backlight */
      //pinMode(6, OUTPUT);
      //digitalWrite(6, 0);

      u8g2.begin();
    }

    void loop(void) {
      u8g2.firstPage();
      do {
        u8g2.setFont(u8g2_font_ncenB10_tr);
        u8g2.drawStr(1,18,"Hello World!");
      } while ( u8g2.nextPage() );
      //delay(1000);
    }

I have spent a couple of days on this, but no luck. Any ideas?

  [1]: https://i.stack.imgur.com/GFME3.jpg
  [2]: https://i.stack.imgur.com/NPasP.jpg
  [3]: https://imgur.com/Slwgbcu
  [4]: https://fabrizio.zellini.org/come-connettere-lcd-12864-per-anet-a8-su-creality-v1-1-4
  [5]: https://www.translatetheweb.com/?ref=TVert&from=&to=en&a=https://fabrizio.zellini.org/come-connettere-lcd-12864-per-anet-a8-su-creality-v1-1-4

title: ST7920 and u8g2 only using some of a 128x64 display

Answers: 1

body:
Many thanks for your photos.

Test carried out with the motherboard of an Ender3 V1.1.3

PIN configuration: U8g2lib library

    #include <U8g2lib.h>

    #ifdef U8X8_HAVE_HW_SPI
    #include <SPI.h>
    #endif
    #ifdef U8X8_HAVE_HW_I2C
    #include <Wire.h>
    #endif

    int LCD_CLK_PIN = 30; //Clock (white)
    int LCD_RW_PIN = 17; //Read-Write (blue)
    int LCD_RS_PIN = 28;  //Register Select (green)
    U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, LCD_CLK_PIN, LCD_RW_PIN, LCD_RS_PIN,U8X8_PIN_NONE);

configuration PIN: library U8glib

    #include "U8glib.h"
    U8GLIB_ST7920_128X64_1X u8g(30, 17, 28);  // SPI Com: SCK = en = 18, MOSI = rw = 16, CS = di = 17

Your program is working properly.


body:
I have purchased XH-M131 Photoresistor Relay Module to automatically light my outdoor yard at sunset and turn it off at sunrise. I'ts working as it is supposed to, However, if I power off the relay, the light goes off.

I want this to be a closed circuit in such way if the relay malfunction or loose power, the outdoor light stays on which I can manually switch off if I want to.

BTW, I tried connecting the light wires to the otherside, but the whole thing reversed, light goes on when light detected which defies the purpose. Any suggestion or modifications.
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/e8N7k.png

title: XH-M131 Photoresistor Relay Module NC position

Answers: 1

body:
If you put an additional relay (Relay B) between the XH-M131 and the light and connect the light to the mains via the Normally Closed pole of Relay B, the light will be ON unless Relay B is activated or you turn off the light switch.
Then, connect the coil of Relay B (instead of the light) to the "other side" as you say, of the XH-M131, the logic will be such that when the sensor is exposed to light (daytime) the XH-M131 turns on. That will activate Relay B, switching it from Closed to Open and turn the light OFF.
If the XH-M131 fails, the light will be ON.


body:
I use a double called delta and use that to turn off an LCD if delta is larger than the timeout threshold. Once that happens, delta is supposed to set to 0 and then other parts of the program run. However, delta continues to increment and I'm not sure why.

This is causing a problem because delta is used to determine if the device should "sleep". So when I try to wake up the device via button click, delta is always way past the timeout threshold and the device immediately goes back to sleep.

Any thoughts as to why? Thanks in advance.

```
#include <M5StickC.h>

double BUTTON_PRESS_NEXT_PRESS_TIME= .5; //Time in seconds
double MINIMUM_BUTTON_PRESS_TIME = .05; //Time in seconds
int BUTTON_PRESS_SLEEP = 3; //Time in seconds
int SCREEN_TIMEOUT = 5;
int count;

static int pressCount = 1;
static int nextPress= 1;

static bool buttonIsPressed;

void setup(void) {
  buttonIsPressed = false;
  M5.begin();
  M5.Lcd.setRotation(0);
  M5.Lcd.fillScreen(TFT_BLACK);
  M5.Lcd.setTextColor(TFT_WHITE, TFT_BLACK);

  // Datum is middle centre
  M5.Lcd.setTextDatum(MC_DATUM);
  M5.Axp.ScreenBreath(100);

  updateScreen();
}

void updateScreen() {
   char tmp[12];

  // Datum is middle centre
  M5.Lcd.setTextDatum(MC_DATUM);
  M5.Lcd.drawString(dtostrf(pressCount,4,0,tmp), 80,60,6);
  M5.Lcd.drawString(dtostrf(nextPress,3,0,tmp), 80,100,6);
}

static void evaluatePress(double d) {
   // Evaluate press
  if (d >= BUTTON_PRESS_NEXT_PRESS_TIME) {
    nextPress++;
    pressCount = 1;

    if (nextPress == 19) {
      nextPress= 1;
    }
  }
  else if (d >= MINIMUM_BUTTON_PRESS_TIME && d < BUTTON_PRESS_NEXT_PRESS_TIME) {
    pressCount++;
  }

  updateScreen();
}

void sleepLoop() {
  bool bIsPressed = false;
  Serial.println("Sleep 1");
  while(1) {
    Serial.println("Sleep 2");
    if (digitalRead(M5_BUTTON_HOME) == LOW && !bIsPressed) {
      bIsPressed = true;
    }

    if (digitalRead(M5_BUTTON_HOME) == HIGH && bIsPressed){
      Serial.println("BREAKY BREAKY");
      M5.Axp.ScreenBreath(100);

      break;
    }
  }
}

void awakeLoop() {
  double delta;
  double old_time;
  double current_time;

  Serial.println("Awake 1");

  while(1) {
    Serial.println("Awake 2");
     //Calculate delta time
    old_time = current_time;
    current_time =  millis();
    delta = delta + (current_time - old_time)/1000;

    if (digitalRead(M5_BUTTON_HOME) == LOW && !buttonIsPressed) {
      buttonIsPressed = true;
      delta = 0;
    }

    if(digitalRead(M5_BUTTON_HOME) == HIGH && buttonIsPressed) {
      buttonIsPressed = false;
      evaluatePress(delta);
      delta=0;
    }

    if(delta > SCREEN_TIMEOUT && !buttonIsPressed) {
      Serial.println(delta);
      Serial.print("BREAK AWAKE");
      Serial.println(M5.Axp.ScreenBreath(0));
      count = 0;
      break;
    }
    else {
      count++;
    }
  }

  delta = 0;
}

void loop() {
  awakeLoop();
  sleepLoop();
}

title: Value keeps incrementing even though loop has terminated, why?

Answers: 1

body:
Here:

```c++
void awakeLoop(){
  double delta;
  // The rest of the function body...
  delta = 0;
}
```

delta is being defined as a variable local to the function `awakeLoop()`
and with automatic storage. This means the variable is created whenever
the program enters the function, is _not_ implicitly initialized, and is
destroyed when the function returns.

The last statement `delta = 0;` has no effect, as it is setting a
variable that is going to be destroyed right away. The compiler most
likely got rid of it.

You most likely want the variable to retain its value across invocations
of the function. For this to be the case, it has to be either global
(defined outside the function) or local with the `static` qualifier. In
both cases, it will have static storage, i.e. its lifetime will be the
whole program run. Also, if you fail to explicitly initialize it, the
compiler will implicitly initialize it to zero.


body:
I wrote a code to move linear actuator and lights up and down using timer. But its not getting Sensor input please help me in this.

#include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes
#define interruptPin 2 //Pin we are going to use to wake up the Arduino

int uv1 = 7; //light
int uv2 = 8; // light
int mot1 = 5; //motion down
int mot2 = 6; // motion up
int buzz=39;
const int speaker = 27;
int led = 9;
int ledState = LOW;
int inputPin = 10;               // choose the input pin (for PIR sensor)
int pirState = 0;            // variable for reading the pin status, we start, assuming no motion detected
long previousMillis = 0;
long interval = 2000;
long OnTime = 30000;
long SenseDel = 8000;           // milliseconds of on-time
long OffTime = 8000;
unsigned long timestart = 0;

const int ply = 23; // relay to reset the sound
const int stp = 35; //relay to puase sound
bool sound = false;

long time_taken = 0;
int start_delay = 3000;
int audio_time = 8000;
int audio_time1 = 8000;
int audio_time3 = 8000;
void setup()
{
  pinMode(led, OUTPUT);
  pinMode(uv1, OUTPUT);
  pinMode(uv2, OUTPUT);
  pinMode(mot1, OUTPUT);
  pinMode(mot2, OUTPUT);
  pinMode(led, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input
  digitalWrite(mot1, HIGH);
  digitalWrite(mot2, LOW);
  digitalWrite(led, LOW);
  pinMode(interruptPin,INPUT_PULLUP);//Set pin d2 to input using the buildin pullup resistor
  Serial.begin(9600);

  pinMode(ply, OUTPUT);
  pinMode(stp, OUTPUT);
  pinMode(speaker, OUTPUT);

  // TIMER 1 for interrupt frequency 300.0018750117188 Hz:
  cli(); // stop interrupts
  TCCR1A = 0; // set entire TCCR1A register to 0
  TCCR1B = 0; // same for TCCR1B
  TCNT1  = 0; // initialize counter value to 0
  // set compare match register for 300.0018750117188 Hz increments
  OCR1A = 53332; // = 16000000 / (1 * 300.0018750117188) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12, CS11 and CS10 bits for 1 prescaler
  TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);
  sei(); // allow interrupts
  digitalWrite(speaker,LOW);
  audio_message();
  delay(200);

}

ISR(TIMER1_COMPA_vect)
{ //interrupt commands for TIMER 1 here
  pirState = digitalRead(inputPin);
}

void loop()
{

unsigned long currentMillis = millis();
while ((pirState == HIGH) && (currentMillis-previousMillis >=SenseDel))

  {
    //previousMillis = currentMillis;
    Serial.println("Motion detected!");
    digitalWrite(mot2, LOW);
    digitalWrite(mot1, LOW);
    digitalWrite(uv1, HIGH);
    digitalWrite(uv2, HIGH);
    //delay(SenseDel);
    //Go_To_Sleep();

  }
  // We only want to print on the output change, not state
  //pirState = HIGH;

  while ((pirState == LOW) && (currentMillis-previousMillis >= OnTime))
  {

    previousMillis = currentMillis;
    Serial.println("Moving Down");
    digitalWrite(mot2, HIGH);
    digitalWrite(mot1, HIGH);
    digitalWrite(uv1, LOW);
    digitalWrite(uv2, LOW);
    pirState = HIGH;
  }

  while ((pirState == LOW) && (currentMillis-previousMillis >=  OffTime))
  {

    //previousMillis = currentMillis;
    Serial.println("Stay There!");
    digitalWrite(mot2, HIGH);
    digitalWrite(mot1, LOW);
    digitalWrite(uv1, LOW);
    digitalWrite(uv2, LOW);
    pirState = HIGH;
  }

  while ((pirState == LOW) && (currentMillis-previousMillis >=  OnTime))
  {

    //previousMillis = currentMillis;
    Serial.println("Moving Up!");
    digitalWrite(mot2, LOW);
    digitalWrite(mot1, LOW);
    digitalWrite(uv1, LOW);
    digitalWrite(uv2, LOW);
    tone(buzz,2000);
    delay(1000);
    noTone(buzz);
    delay(1000);
     pirState = HIGH;

  }
}

void Go_To_Sleep()
{
    sleep_enable();//Enabling sleep mode
    attachInterrupt(0, wakeUp, LOW);//attaching a interrupt to pin d2
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);//Setting the sleep mode, in our case full sleep
    sleep_cpu();//activating sleep mode
    Serial.println("just woke up!");//next line of code executed after the interrupt
    audio_message();
}

void wakeUp()
{
  Serial.println("Interrrupt Fired");//Print message to serial monitor
  sleep_disable();//Disable sleep mode
  detachInterrupt(0); //Removes the interrupt from pin 2;
}

void stop_button()    // func to act as stop sound
{
  digitalWrite(stp, LOW);
  delay(200); //100
  digitalWrite(stp, HIGH);
}

void play_button()  // // func to act as play sound
{
  digitalWrite(ply, LOW);
  delay(140);//100
  digitalWrite(ply, HIGH);
}

void audio_message()
{
      digitalWrite(speaker, HIGH);
      play_button();
      sound = true;
      delay(100);
      //digitalWrite(speaker, LOW);
      Serial.println("Speaker On");
      play_button();
      //time_taken = millis();
      delay(audio_time1);
      delay(audio_time);
      //delay(audio_time3);
      //Do something.....
      play_button();
      stop_button();
      sound = false;
    digitalWrite(speaker, HIGH);
    Serial.println("Speaker Closed");
    delay(1000);
}

title: Not getting input from sensor using timer

Answers: 0


body:
When pushing a button I want to read the value...once.
If I push(hold) the button I get a continuous print of button1Pushed

        if(button1State == LOW) {
         Serial.println("button1Pushed");
      }

But if I try to solve it like this, nothing happens, not a single print. What am I missing?

     int button1State = digitalRead(button1);
      int lastButton1State;

      if(button1State != lastButton1State){
          if(button1State == LOW){
            Serial.println("button1Pushed");
                   }
            }

      lastButton1State = button1State;

title: continuous print of button Pushed

Answers: 1

body:
`lastButton1State` is not initialized and therefore has no strictly defined value. In your case, it appears to have a value of `0` (which is random, it's not due to implicit initialization, which is only done for global variables). The condition `if(button1State != lastButton1State)` becomes true only if the button is released.

You can check that by changing

    if(button1State == LOW){
      Serial.println("button1Pushed");
    }

to

    if(button1State == HIGH){
      Serial.println("button1 released");
    }

The following should work:

    int last_button_state=HIGH; // initialize to HIGH, so the button does not teigger on very first iteration
    void setup () {
      // whatever you want to do here
    }
    void loop() {
      int button_state=digitalRead(button1);
      if (button_state!=last_button_state && button_state==LOW) {
        Serial.println("button pressed");
      }
      else if (button_state!=last_button_state && button_state==HIGH) {
        Serial.println("button released");
      }
      last_button_state=button_state;
    }


body:
I have ESP32 connected to TZT servo SG90.
This is the code

    #include <ESP32Servo.h>
    #define TURN_TIME 175

    Servo myservo;  // create servo object to control a servo
    // 16 servo objects can be created on the ESP32

    int pos = 0;    // variable to store the servo position
    // Recommended PWM GPIO pins on the ESP32 include 2,4,12-19,21-23,25-27,32-33
    #define servoPin  17
    #define MOTOR_1_PIN 22

    void setup() {
      pinMode(servoPin, OUTPUT);
      Serial.begin(9600);
     // Allow allocation of all timers
     ESP32PWM::allocateTimer(0);
     ESP32PWM::allocateTimer(1);
     ESP32PWM::allocateTimer(2);
     ESP32PWM::allocateTimer(3);
     myservo.setPeriodHertz(50);    // standard 50 hz servo
     // using default min/max of 1000us and 2000us
     // different servos may require different min/max settings
     // for an accurate 0 to 180 sweep
    }

    void loop() {

      myservo.attach(servoPin, 700, 2500); // attaches the servo on pin 18 to the servo object
      myservo.write(0);
      delay(TURN_TIME);
      for(int i =0; i<180; i++)
      {
        myservo.write(i);
        delay(TURN_TIME);
      }
      delay(3000);
      for(int i =180; i>0; i--)
      {
        myservo.write(i);
        delay(TURN_TIME);
      }
      myservo.detach();
      delay(3000);

    }

My servo starts rotating one way and reverse for few degrees, then after 5 seconds the servo starts rotating at one way forever..

I had no problems with arduino and nodemcu board. What should I change in the code?

EDIT: I have connected the servo with battery, they have common ground.
The pin on esp32 that I am using is G17. "#define servoPin 17" in the code

title: ESP32 servo runs continuous

Answers: 1

body:
I used other servo library and it worked.. Then i changed the pulse width with this line of code.
The default is 1000-2000. But it rotates only 95 degrees. When it's pushed to around ~2850us the servo rotates up to 181-185 degrees.
`servo1.attach(servoPin,CHANNEL_NOT_ATTACHED, 0,180,544,2840/);`

    #include <Servo_ESP32.h>

    static const int servoPin = 16; //printed G14 on the board
    int delayTime = 20;
    Servo_ESP32 servo1;

    int angle =0;
    int angleStep = 5;

    int angleMin =0;
    int angleMax = 180;
    #define CHANNEL_NOT_ATTACHED -1
    void setup() {
        Serial.begin(115200);
        servo1.attach(servoPin,CHANNEL_NOT_ATTACHED, 0,180,544,2840/);

    }

    void loop() {
        for(int angle = 0; angle <= angleMax; angle +=angleStep) {
            servo1.write(angle);
            Serial.println(angle);
            delay(delayTime);
        }

        for(int angle = 180; angle >= angleMin; angle -=angleStep) {
            servo1.write(angle);
            Serial.println(angle);
            delay(delayTime);
        }
    }


body:
I am currently using an esp32 with Wifi. I need at least 15kByte/s constant throughout. This works fine but I am not happy with the range.

I came across the RFM69HCW 915MHz module. It is stated with 300 kbps.

Now what is confusing me are duty cycle regulations. Various countries have a 1% limit.
Is this limit considered in the 300 kbps? Or do I effectively only get 3 kbps because I cannot constantly send?

title: 915Mhz vs Wifi (speed impact of duty cycle limitations)

Answers: 1

body:
300kbps is the data transmission rate. Not the throughput rate.

That means that yes, if you only transmit for 1% of the time then for 1% of the time you are getting 300kbps - i.e., 3kbps as you correctly surmised.


body:
This is not a code error I have been using DS3231 RTC module with battery. When I bought this module It worked perfectly now when I get it to use, The time is running perfectly. when I set the current time of my location, it has been running along with that time but the problem is when I unplug the power of my Arduino Nano and again when I give the power I can see the time is running from its start, I could not see any current time value my location but I have attached CR2032 battery along with DS3231 module? what is the problem with this? I changed another battery too but It shows same problem my DS32321 haven't kept the time when I unplug and re-plug the power

This is the code I'm using for set the time

    #include <DS3231.h>

    // Init the DS3231 using the hardware interface
    DS3231  rtc(SDA, SCL);

    void setup()
    {
      // Setup Serial connection
      Serial.begin(115200);
      // Uncomment the next line if you are using an Arduino Leonardo
      //while (!Serial) {}

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

      // The following lines can be uncommented to set the date and time
      rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
      rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
      rtc.setDate(1, 1, 2014);   // Set the date to January 1st, 2014
    }

    void loop()
    {
      // Send Day-of-Week
      Serial.print(rtc.getDOWStr());
      Serial.print(" ");

      // Send date
      Serial.print(rtc.getDateStr());
      Serial.print(" -- ");

      // Send time
      Serial.println(rtc.getTimeStr());

      // Wait one second before repeating :)
      delay (1000);
    }

This is the code I'm using to make Interrupt

     #include <DS3231.h>

    int Relay = 4;

    DS3231  rtc(SDA, SCL);
    Time t;

    const int OnHour = 21;
    const int OnMin = 46;
    const int OffHour = 21;
    const int OffMin = 48;

    const int On2Hour = 14;
    const int On2Min = 54;
    const int Off2Hour = 21;
    const int Off2Min = 48;

    void setup() {
      Serial.begin(115200);
      rtc.begin();
      pinMode(Relay, OUTPUT);
      digitalWrite(Relay, LOW);
    }

    void loop() {
      Serial.println("Time:  ");
      Serial.print(rtc.getTimeStr());
      Serial.print('\n');

      Serial.println("Date: ");
      Serial.print(rtc.getDateStr());
      Serial.print('\n');

      t = rtc.getTime();
      Serial.print(t.hour);
      Serial.print(" hour(s), ");
      Serial.print(t.min);
      Serial.print(" minute(s)");
      Serial.println(" ");
      delay (1000);
      //can be set lcd display alspo
      if(t.hour == OnHour && t.min == OnMin){
        digitalWrite(Relay,HIGH);
        Serial.println("LIGHT ON");
        }

        else if(t.hour == OffHour && t.min == OffMin){
          digitalWrite(Relay,LOW);
          Serial.println("LIGHT OFF");
        }
      if(t.hour == On2Hour && t.min == On2Min){
        digitalWrite(Relay,HIGH);
        Serial.println("LIGHT ON");
        }

        else if(t.hour == Off2Hour && t.min == Off2Min){
          digitalWrite(Relay,LOW);
          Serial.println("LIGHT OFF");
        }
    }

title: Real Time clock module error-DS3231

Answers: 2

body:
I am posting a code please try it may be it can help you

        #include "RTClib.h"

    RTC_DS3231 rtc;

    char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

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

    #ifndef ESP8266
      while (!Serial); // wait for serial port to connect. Needed for native USB
    #endif

      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        Serial.flush();
        abort();
      }

      if (rtc.lostPower()) {
        Serial.println("RTC lost power, let's set the time!");
        // When time needs to be set on a new device, or after a power loss, the
        // following line sets the RTC to the date & time this sketch was compiled
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
         rtc.adjust(DateTime(2020, 10, 19, 10, 13, 0));
      }

      // When time needs to be re-set on a previously configured device, the
      // following line sets the RTC to the date & time this sketch was compiled
      // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
      // This line sets the RTC with an explicit date & time, for example to set
      // January 21, 2014 at 3am you would call:
      // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
    }

    void loop () {
        DateTime now = rtc.now();

        Serial.print(now.year(), DEC);
        Serial.print('/');
        Serial.print(now.month(), DEC);
        Serial.print('/');
        Serial.print(now.day(), DEC);
        Serial.print(" (");
        Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
        Serial.print(") ");
        Serial.print(now.hour(), DEC);
        Serial.print(':');
        Serial.print(now.minute(), DEC);
        Serial.print(':');
        Serial.print(now.second(), DEC);
        Serial.println();

        Serial.print(" since midnight 1/1/1970 = ");
        Serial.print(now.unixtime());
        Serial.print("s = ");
        Serial.print(now.unixtime() / 86400L);
        Serial.println("d");

        // calculate a date which is 7 days and 30 seconds into the future
        DateTime future (now + TimeSpan(7,12,30,6));

        Serial.print(" now + 7d + 30s: ");
        Serial.print(future.year(), DEC);
        Serial.print('/');
        Serial.print(future.month(), DEC);
        Serial.print('/');
        Serial.print(future.day(), DEC);
        Serial.print(' ');
        Serial.print(future.hour(), DEC);
        Serial.print(':');
        Serial.print(future.minute(), DEC);
        Serial.print(':');
        Serial.print(future.second(), DEC);
        Serial.println();

        Serial.print("Temperature: ");
        Serial.print(rtc.getTemperature());
        Serial.println(" C");

        Serial.println();
        delay(3000);
    }

Upload the above code and then upload the same code just comment the following part

    if (rtc.lostPower()) {
            Serial.println("RTC lost power, let's set the time!");
            // When time needs to be set on a new device, or after a power loss, the
            // following line sets the RTC to the date & time this sketch was compiled
            rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
            // This line sets the RTC with an explicit date & time, for example to set
            // January 21, 2014 at 3am you would call:
             rtc.adjust(DateTime(2020, 10, 19, 10, 13, 0));
          }

This will work and even if you plug and unplug it from power the RTC time will not reset

body: I will take a SWAG as I do not know what module you are having problems. Remove the battery, power it up and measure the voltage at the battery terminals. If you have about 3.2V the module is designed to charge the battery (thought you might like to know). Power down the module insert the battery, do not power it up, and measure the battery voltage at the chip. Be sure to also check the ground side. I believe you will find the same thing I did, the solder connection to the battery holder was open, just added some solder and that solved it. I also found the SCL line was  broken on the board so if I connected the other side it would not work. I added a jumper to fix it. I purchased several from azon but only the first one was bad.


body:
I am wondering can I use this bicks camera switcher with the arduino since it uses a PWM signal.[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/i9atQ.jpg
If i can do I just put it on one of the PWM outputs or do I need to wire I add something to make it work.
**You can find the user manual here under attachments.**https://store.bicks.us/multiview/20-bicks-s-multiview-duo-fpv-camera-switcher.html

title: Can I use this camera switcher?

Answers: 1

body: The pwm output of an RC receiver is the same signal used to control a servo. So if you used the servo library with Arduino to control the pwm of this device it should work fine.


body:
I am trying to make a Bluetooth controlled 4WD robot. i was following a tutorial i found online (https://howtomechatronics.com/tutorials/arduino/arduino-robot-car-wireless-control-using-hc-05-bluetooth-nrf24l01-and-hc-12-transceiver-modules/). After successfully connecting my 2 HC 05 Bluetooth module i used the script from the tutorial and modified it slightly so it would work for my set up.
The code for the robot:

    //Code for Slave
    #define enA 9
    #define in1 8
    #define in2 7
    #define enB 10
    #define in3 6
    #define in4 5
    int xAxis, yAxis;
    unsigned int  x = 0;
    unsigned int  y = 0;
    int motorSpeedA = 0;
    int motorSpeedB = 0;
    void setup() {
      pinMode(enA, OUTPUT);
      pinMode(enB, OUTPUT);
      pinMode(in1, OUTPUT);
      pinMode(in2, OUTPUT);
      pinMode(in3, OUTPUT);
      pinMode(in4, OUTPUT);
      Serial.begin(9600); // Default communication rate of the Bluetooth module
    }
    void loop() {
      // Default value - no movement when the Joystick stays in the center
      x = 510 / 4;
      y = 510 / 4;
      // Read the incoming data from the Joystick, or the master Bluetooth device
      while (Serial.available() >= 2) {
        x = Serial.read();
        Serial.print("X: ");
        Serial.println(x);
        delay(10);
        y = Serial.read();
        Serial.print("Y: ");
        Serial.println(y);
      }
      delay(10);
      // Convert back the 0 - 255 range to 0 - 1023, suitable for motor control code below
      xAxis = x*4;
      yAxis = y*4;
      // Y-axis used for forward and backward control
      if (yAxis < 470) {
        backMov;
        // Convert the declining Y-axis readings for going backward from 470 to 0 into 0 to 255 value for the PWM signal for increasing the motor speed
        motorSpeedA = map(yAxis, 470, 0, 0, 255);
        motorSpeedB = map(yAxis, 470, 0, 0, 255);
      }
      else if (yAxis > 550) {
        fowardMov;
        // Convert the increasing Y-axis readings for going forward from 550 to 1023 into 0 to 255 value for the PWM signal for increasing the motor speed
        motorSpeedA = map(yAxis, 550, 1023, 0, 255);
        motorSpeedB = map(yAxis, 550, 1023, 0, 255);
      }
      // If joystick stays in middle the motors are not moving
      else {
        motorSpeedA = 0;
        motorSpeedB = 0;
      }
      // X-axis used for left and right control
      if (xAxis < 470) {
        // Convert the declining X-axis readings from 470 to 0 into increasing 0 to 255 value
        int xMapped = map(xAxis, 470, 0, 0, 255);
        // Move to left - decrease left motor speed, increase right motor speed
        motorSpeedA = motorSpeedA + xMapped;
        motorSpeedB = motorSpeedB - xMapped;
        // Confine the range from 0 to 255
        if (motorSpeedA > 255) {
          motorSpeedA = 255;
        }
        if (motorSpeedB < 0) {
          motorSpeedB = 0;
        }
      }
      if (xAxis > 550) {
        // Convert the increasing X-axis readings from 550 to 1023 into 0 to 255 value
        int xMapped = map(xAxis, 550, 1023, 0, 255);
        // Move right - decrease right motor speed, increase left motor speed
        motorSpeedA = motorSpeedA - xMapped;
        motorSpeedB = motorSpeedB + xMapped;
        // Confine the range from 0 to 255
        if (motorSpeedA < 0) {
          motorSpeedA = 0;
        }
        if (motorSpeedB > 255) {
          motorSpeedB = 255;
        }
      }
      // Prevent buzzing at low speeds (Adjust according to your motors. My motors couldn't start moving if PWM value was below value of 70)
      if (motorSpeedA < 70) {
        motorSpeedA = 0;
      }
      if (motorSpeedB < 70) {
        motorSpeedB = 0;
      }
      analogWrite(enA, motorSpeedA); // Send PWM signal to motor A
      analogWrite(enB, motorSpeedB); // Send PWM signal to motor B
    }
    void fowardMov(){
      digitalWrite(in2,HIGH);
      digitalWrite(in4,HIGH);
      digitalWrite(in1, LOW);
      digitalWrite(in3, LOW);
    }

    void backMov(){
      digitalWrite(in1,HIGH);
      digitalWrite(in3,HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(in4, LOW);
    }

The code for the Controller:

    #define Xaxis A0
    #define Yaxis A1

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

    void loop() {
      // put your main code here, to run repeatedly:
     Serial.write(analogRead(Xaxis)/4);
     Serial.write(analogRead(Yaxis)/4);
     delay(20);
    }
After uploading the code i tried to move it but it wasn't working so i put print statements to see the value of X and Y. initially it didn't work so i swapped the Bluetooth modules i had and reconnected them. i also changed this line.

     while (Serial.available() >= 2)
To this

     if (Serial.available() > 0)
i started to receive values from the master to the slave but  i noticed the values were the same for x and y so i searched for another tutorial on the internet and found this (https://create.arduino.cc/projecthub/andriy-baranov/arduino-4wd-rc-car-639953?ref=similar&ref_id=18369&offset=3) reading his code i wondered how did the slave work. According to the official Arduino documentation Serial.read() does not take in any arguments but i still tried it and it didn't work. I decided to retry the code from the first tutorial i checked this time it looked like it was working so i tried moving the joystick and the serial monitor printed correct values for both at first then it swaps their values then freezes. How can i stop it from freezing and swapping the values? Also why doesn't the while loop run forever isn't the amount of data in the serial buffer always higher than 2? Thank you.[![diagram of slave][1]][1]

[![diagram of master][2]][2]

  [1]: https://i.stack.imgur.com/1CY82.png
  [2]: https://i.stack.imgur.com/xfp1I.png

title: Bluetooth module(HC 05) issues

Answers: 2

body: Your setup is WAY too complex!  Simplify your setup to the point where it only deals with just the piece that is giving you problems; in your case serial port comms between master and slave.  Solve JUST THAT problem, and then move on

body:
There is an issue with the way in which the data is sent and received because it assumes the transmission will remain perfectly synchronised for the lifetime of the programme. Consider what would happen if one byte were to be dropped due to a communication error – the x and y data would be swapped for further transmissions.

**Original Sender**

```cpp
void loop() {
  // put your main code here, to run repeatedly:
 Serial.write(analogRead(Xaxis)/4);
 Serial.write(analogRead(Yaxis)/4);
 delay(20);
}
```

**Original Receiver**

```cpp
void loop() {
  // Default value - no movement when the Joystick stays in the center
  x = 510 / 4;
  y = 510 / 4;
  // Read the incoming data from the Joystick, or the master Bluetooth device
  while (Serial.available() >= 2) {
    x = Serial.read();
    Serial.print("X: ");
    Serial.println(x);
    delay(10);
    y = Serial.read();
    Serial.print("Y: ");
    Serial.println(y);
  }
  delay(10);
  . . .
}
```

Therefore, there needs to be a way to synchronise to the first byte of the message. This can be achieved by using message packets where the start and end of the message are delimited with unique characters, e.g. `{` and `}`, similar to the [JSON format][1].

As another example, the [NMEA GPS][2] standard uses `$` and `\n` to delimit messages, and `,` to delimit fields. It also has a checksum at the end.

Here is a non-blocking algorithm which builds upon [Majenko's `readline()` example][3] and the [Blink Without Delay example][4] to read a packet. `ReadPacket()` returns true when incoming data has been accumulated into a valid packet. The LED is flashed to indicate that the MCU hasn't frozen.

**New Sender**

```cpp
void loop()
{
    Serial.print("{");                  // First character delimiter.
    Serial.print(analogRead(Xaxis));    // Full resolution. No need to divide by 4.
    Serial.print(",");                  // Field delimiter.
    Serial.print(analogRead(Yaxis));    // Full resolution. No need to divide by 4.
    Serial.print("}");                  // Last character delimiter.
    delay(20);
}
```

**New Receiver**

```cpp
void loop()
{
    //
    // TASK 1: Blink without delay to indicate that MCU hasn't frozen.
    //
    const unsigned int INTERVAL = 250;
    unsigned long current_timestamp = millis();
    static unsigned long previous_timestamp = current_timestamp;
    static bool led_state = false;
    if (current_timestamp - previous_timestamp >= INTERVAL)
    {
        led_state = !led_state;
        digitalWrite(LED_BUILTIN, led_state);
        previous_timestamp += INTERVAL;
    }

    //
    // TASK 2: Read and parse data packet.
    //
    static char packet[100];
    const byte NUM_FIELDS = 2;
    unsigned int fields[NUM_FIELDS];
    static unsigned int x = 512;   // Full resolution. No need to divide by 4.
    static unsigned int y = 512;   // Full resolution. No need to divide by 4.
    bool new_x = false;
    bool new_y = false;
    if (ReadPacket(Serial, packet, sizeof(packet)))
    {
        Serial.print(F("Received packet >"));
        Serial.print(packet);
        Serial.println(F("<"));

        // Parse the packet for x and y values at full resolution.
        const char delimiters[] = "{,}";
        char* field;
        int i = 0;
        field = strtok(packet, delimiters);
        while (field != NULL && i < NUM_FIELDS)
        {
            Serial.print("field = ");
            Serial.println(field);
            fields[i] = atoi(field);
            Serial.print("fields[");
            Serial.print(i);
            Serial.print("] = ");
            Serial.println(fields[i]);
            field = strtok(NULL, delimiters);
            i++;
        }
        if (i == NUM_FIELDS)
        {
            if (x != fields[0])
            {
                new_x = true;
                x = fields[0];  // Full resolution. No need to multiply by 4.
                Serial.print("New x = ");
                Serial.println(x);
            }
            if (y != fields[1])
            {
                new_y = true;
                y = fields[1];  // Full resolution. No need to multiply by 4.
                Serial.print("New y = ");
                Serial.println(y);
            }
        }
    }

    Serial.print("x = ");
    Serial.println(x);
    Serial.print("y = ");
    Serial.println(y);

    //
    // TASK 3: Process x and y values.
    //
    if (new_x || new_y)
    {
        Serial.println("Processing new values.");

        . . .
    }
}

bool ReadPacket(Stream& stream, char *const packet, const unsigned int SIZE)
{
    const char FIRST = '{';
    const char LAST = '}';
    static bool read_until_last = false;
    static unsigned int i = 0;
    char ch;

    if (stream.available())
    {
        ch = stream.read();

        if (ch == FIRST)
        {
            Serial.println(F("Received FIRST."));
            i = 0;
            packet[0] = ch;
            read_until_last = true;
            return false;
        }
        if (read_until_last)
        {
            i++;
            if (i > SIZE - 2)
            {
                Serial.println(F("Buffer overrun. Resetting to look for next packet."));
                i = 0;
                read_until_last = false;
                return false;
            }
            if (ch == LAST)
            {
                Serial.println(F("Received LAST."));
                packet[i++] = ch;
                packet[i] = 0;
                read_until_last = false;
                return true;
            }
            else
            {
                Serial.print(F("Received char >"));
                Serial.print(ch);
                Serial.println("<");
                packet[i] = ch;
                return false;
            }
        }
    }
    return false;
}
```

  [1]: https://en.wikipedia.org/wiki/JSON
  [2]: https://www.gpsworld.com/what-exactly-is-gps-nmea-data/
  [3]: https://majenko.co.uk/blog/reading-serial-arduino
  [4]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay/


body: I am relatively new to Arduino and I am looking to use flexinol or muscle wire to control flower petals. I think I will need to control 4 sets of the wire. I have totally no idea of how to wire the components together, if I will need to get additional parts like a transistor or battery, and what type/thickness of wire I should get.

title: Using Flexinol Or Muscle Wire To Control Paper Flower Petal With Arduino

Answers: 0


body:
I am having problems while writing custom bootloader, so that it uploads code from EEPROM (for now internal, as I have no external memory in my hands) and writes into flash. After ~2 weeks of struggling I encountered these [question and answers][1]. After that, I realized that I made a mistake not checking the possibility of it. However, I am still confused about several things:

1. If Harvard Architecture limits what I want, how come optiboot can flash the memory from incoming UART data, which is not even a memory?

2. If UART reads and flashes memory accordingly, cant I do the same with EEPROM? Read bytes, erase flash, write bytes.

3. If it is not possible, given two answers in above link, then how does [this][2] work? I guess, it is the same logic as I want, using external memory and rewriting flash. Does it mean Harvard Architecture limits only internal memory exchange?

**UPDATE:** Here is what I have done for now:

In separate sketch, EEPROM is filled with binary code. Bootloader (edited optiboot v8):

```
  // Set up watchdog to trigger after desired timeout
  watchdogConfig(WDTPERIOD);
#if BIGBOOT

  if ((eeprom_read(0x000) == 0x0C) && (eeprom_read(0x001) == 0x94))
  {
    //while (EECR & (1 << EEPE)); //wait if previous data is still being written
    uint8_t i, j;

    for (i = 0; i < 8; ++i) // 8 pages total
    {
      uint8_t *code;
      code = buff.bptr;
      address.word = (i * 128);

      for (j = 0; j < 128; ++j)  // 128 words at a time
      {
        if (j % 64 == 0)
          LED_PORT ^= _BV(LED);

        *code++ = eeprom_read(address.word + j);
      }

#ifdef VIRTUAL_BOOT_PARTITION
      virtualBootPartition(buff, address);
#endif

      writebuffer(0x46, buff, address, 128);
    }

    while(1); // wait for WDT
  }
#endif

#if (LED_START_FLASHES > 0) || LED_DATA_FLASH || LED_START_ON
  /* Set LED pin as output */
  LED_DDR |= _BV(LED);
#endif
```

while my function looks like this:

```
#if BIGBOOT
static uint8_t eeprom_read(uint16_t addr)
{
  EEAR = addr; //read from that address
  EECR |= (1 << EERE); //enable reading

  return EEDR;
}
#endif
```

I use `make atmega328 BIGBOOT=1` to generate hex file. It does not work + UART uploading also fails. If I set `BIGBOOT` to 0 and generate, UART uploading works fine.

P.S. `virtualBootPartition` is function which is called in `STK_PROG_PAGE` case. In order to not repeat the same piece of code, I collected that part into the function.

```
#ifdef VIRTUAL_BOOT_PARTITION
/*
 *              How the Virtual Boot Partition works:
 * At the beginning of a normal AVR program are a set of vectors that
 * implement the interrupt mechanism.  Each vector is usually a single
 * instruction that dispatches to the appropriate ISR.
 * The instruction is normally an rjmp (on AVRs with 8k or less of flash)
 * or jmp instruction, and the 0th vector is executed on reset and jumps
 * to the start of the user program:
 * vectors: jmp startup
 *          jmp ISR1
 *          jmp ISR2
 *             :      ;; etc
 *          jmp lastvector
 * To implement the "Virtual Boot Partition", Optiboot detects when the
 * flash page containing the vectors is being programmed, and replaces the
 * startup vector with a jump to te beginning of Optiboot.  Then it saves
 * the applications's startup vector in another (must be unused by the
 * application), and finally programs the page with the changed vectors.
 * Thereafter, on reset, the vector will dispatch to the beginning of
 * Optiboot.  When Optiboot decides that it will run the user application,
 * it fetches the saved start address from the unused vector, and jumps
 * there.
 * The logic is dependent on size of flash, and whether the reset vector is
 * on the same flash page as the saved start address.
 */

#if FLASHEND > 8192
/*
 * AVR with 4-byte ISR Vectors and "jmp"
 * WARNING: this works only up to 128KB flash!
 */
#if FLASHEND > (128*1024)
#error "Can't use VIRTUAL_BOOT_PARTITION with more than 128k of Flash"
#endif
  if (address.word == RSTVEC_ADDRESS) {
 // This is the reset vector page. We need to live-patch the
 // code so the bootloader runs first.
 //
 // Save jmp targets (for "Verify")
    rstVect0_sav = buff.bptr[rstVect0];
    rstVect1_sav = buff.bptr[rstVect1];

        // Add "jump to Optiboot" at RESET vector
        // WARNING: this works as long as 'main' is in first section
    buff.bptr[rstVect0] = ((uint16_t)pre_main) & 0xFF;
    buff.bptr[rstVect1] = ((uint16_t)pre_main) >> 8;

#if (SAVVEC_ADDRESS != RSTVEC_ADDRESS)
// the save_vector is not necessarilly on the same flash page as the reset
//  vector.  If it isn't, we've waiting to actually write it.
  }
  else if (address.word == SAVVEC_ADDRESS) {
   // Save old values for Verify
   saveVect0_sav = buff.bptr[saveVect0 - SAVVEC_ADDRESS];
   saveVect1_sav = buff.bptr[saveVect1 - SAVVEC_ADDRESS];

   // Move RESET jmp target to 'save' vector
   buff.bptr[saveVect0 - SAVVEC_ADDRESS] = rstVect0_sav;
   buff.bptr[saveVect1 - SAVVEC_ADDRESS] = rstVect1_sav;
  }
#else
        // Save old values for Verify
        saveVect0_sav = buff.bptr[saveVect0];
 saveVect1_sav = buff.bptr[saveVect1];

        // Move RESET jmp target to 'save' vector
        buff.bptr[saveVect0] = rstVect0_sav;
        buff.bptr[saveVect1] = rstVect1_sav;
}
#endif

#else
/*
 * AVR with 2-byte ISR Vectors and rjmp
 */
  if (address.word == rstVect0) {
    // This is the reset vector page. We need to live-patch
    // the code so the bootloader runs first.
    //
    // Move RESET vector to 'save' vector
   // Save jmp targets (for "Verify")
    rstVect0_sav = buff.bptr[rstVect0];
    rstVect1_sav = buff.bptr[rstVect1];
    addr16_t vect;
    vect.word = ((uint16_t)pre_main-1);
    // Instruction is a relative jump (rjmp), so recalculate.
    // an RJMP instruction is 0b1100xxxx xxxxxxxx, so we should be able to
    // do math on the offsets without masking it off first.
    // Note that rjmp is relative to the already incremented PC, so the
    //  offset is one less than you might expect.
    buff.bptr[0] = vect.bytes[0]; // rjmp to start of bootloader
    buff.bptr[1] = vect.bytes[1] | 0xC0;  // make an "rjmp"
#if (SAVVEC_ADDRESS != RSTVEC_ADDRESS)
  }
  else if (address.word == SAVVEC_ADDRESS) {
 addr16_t vect;
 vect.bytes[0] = rstVect0_sav;
 vect.bytes[1] = rstVect1_sav;
 // Save old values for Verify
 saveVect0_sav = buff.bptr[saveVect0 - SAVVEC_ADDRESS];
 saveVect1_sav = buff.bptr[saveVect1 - SAVVEC_ADDRESS];

 vect.word = (vect.word-save_vect_num); //substract 'save' interrupt position
  // Move RESET jmp target to 'save' vector
  buff.bptr[saveVect0 - SAVVEC_ADDRESS] = vect.bytes[0];
  buff.bptr[saveVect1 - SAVVEC_ADDRESS] = (vect.bytes[1] & 0x0F)| 0xC0;  // make an "rjmp"
  }
#else

  // Save old values for Verify
  saveVect0_sav = buff.bptr[saveVect0];
  saveVect1_sav = buff.bptr[saveVect1];

  vect.bytes[0] = rstVect0_sav;
  vect.bytes[1] = rstVect1_sav;
  vect.word = (vect.word-save_vect_num); //substract 'save' interrupt position
  // Move RESET jmp target to 'save' vector
  buff.bptr[saveVect0] = vect.bytes[0];
  buff.bptr[saveVect1] = (vect.bytes[1] & 0x0F)| 0xC0;  // make an "rjmp"
  // Add rjmp to bootloader at RESET vector
  vect.word = ((uint16_t)pre_main-1); // (main) is always <= 0x0FFF; no masking needed.
  buff.bptr[0] = vect.bytes[0]; // rjmp 0x1c00 instruction
}

#endif
#endif // FLASHEND
#endif // VBP
```

  [1]: https://arduino.stackexchange.com/questions/3828/is-it-possible-to-run-a-binary-from-eeprom
  [2]: https://github.com/FleetProbe/MicroBridge-Arduino-ATMega2560/

title: Is it possible to upload and run code from EEPROM during boot time?

Answers: 1

body:
If you have a sketch which can write its updated version into EEPROM of ATmega328p and then boootload from the EEPROM, then you can use the flash for the same purpose. The ATmega328p has 32kB of flash and only 1kB EEPROM.

For my ArduinoOTA library I developed a way to store the uploaded binary in upper half of the flash and then let the bootloader copy the binary to address 0 and reset the MCU.

The Optiboot 8 has do_spm() function. This function can be called from the sketch to write to flash memory.

To copy the binary stored in upper half of the flash to address 0, I wrote a new function for the Optiboot. It is called copy_flash_pages and has an extra boolean parameter to request a reset of MCU after copying the pages.

For network upload the sketch size is larger then half of the flash of 328p because of the networking library. So ArduinoOTA is only for ATmega with more then 64kB flash.

If you have a way how to get the binary of size less then half of the 328p flash, then you can write it to the upper half of the flash and then use my copy_flash_pages function to bootload it.

Resources:

* [header file][1] to access the Optiboot functions from sketch
* boards definition and bootloader for 328p with Optiboot with copy_flash_pages function in [my_boards][2] (note the changed fuses in boards.txt for Uno/Nano/Mini)
* the [InternalStorageAVR][3] class in ArduinoOTA library as example how to store and apply the binary

Example of InternalStorage use:
```
  if (!InternalStorage.open(length)) {
    Serial.println("There is not enough space to store the update. Can't continue with update.");
    return;
  }
  byte b;
  while (length > 0) {
    if (!source.readBytes(&b, 1)) // reading a byte with timeout
      break;
    InternalStorage.write(b);
    length--;
  }
  InternalStorage.close();
  if (length > 0) {
    Serial.print("Timeout downloading update file at ");
    Serial.print(length);
    Serial.println(" bytes. Can't continue with update.");
    return;
  }
  Serial.println("Sketch update apply and reset.");
  InternalStorage.apply(); // this doesn't return
```

  [1]: https://github.com/jandrassy/ArduinoOTA/blob/master/src/utility/optiboot.h
  [2]: https://github.com/jandrassy/my_boards
  [3]: https://github.com/jandrassy/ArduinoOTA/blob/master/src/InternalStorageAVR.cpp


body:
I am doing a project where, for troubleshooting reasons, I find myself often swapping components to different serial ports. Maybe one time it's in Serial, then in Serial1, maybe I need to try if software serial works.

But changing every line where Serial.print or Serial.write is written for the new port is a hassle and easy to screw up.

Would it be possible to either create a definition at the beginning of the code that lets me rename Serial to SensorSerial so just by changing that definition I am sure it will use the correct port?

title: Can you use Serial Port as a variable?

Answers: 2

body:
Yes. The simplest way is with a preprocessor macro. Macros get replaced verbatim before compilation happens, so you can do something like:

```
#define MY_SERIAL Serial

void setup() {
    MY_SERIAL.begin(115200);
}

void loop() {
    MY_SERIAL.println(millis());
    delay(1000);
}
```

body:
Majenko's answer is the right answer for your question. But to answer the title of the question, if you ever need to use different Arduino outputs and inputs as variable, most of them have common type Stream or Print. So it would be:
```
Stream& SensorSerial = Serial;
```
 or
```
Stream* SensorSerial;
SensorSerial = &Serial;
```
The Arduino Stream classes hierachy:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/3OV45.png


body:
am trying to completly turn off ra-01 radio and esp8266 and turn it on by external trigger but i have issues getting the lora radio to turn off

```#include <SPI.h>
#include <LoRa.h>
#include <ESP8266WiFi.h>

void setup() {
  Serial.begin(115200);
  // while (!Serial);

  // disable wifi
  WiFi.mode( WIFI_OFF );
  WiFi.forceSleepBegin();

  // LoRa
  #define dio0 2
  #define ss 15
  #define rst 16
  //#define rst 32

  LoRa.setPins(ss, rst, dio0);
  LoRa.setSyncWord(0xF3);

  Serial.println("LoRa: OK");

  if (!LoRa.begin(433E6)) {
    Serial.println("LoRa: Fail!");
    while (1);
  }
  Serial.println("Sending packet: ");

  // send packet
  LoRa.beginPacket();
  LoRa.print("c");
  LoRa.endPacket();
  LoRa.end();

  // shutdown spi
  SPI.end();
  digitalWrite(dio0, HIGH);
  digitalWrite(ss, HIGH);
  digitalWrite(rst, HIGH);

  // deep sleep
  ESP.deepSleep(0);
}

void loop() {

}``

title: RA-01 Lora Radio not turning off

Answers: 0


body:
I know this is Arduino Forum but I think this question is related to programming, I am using ESP8266 for the project. I need to convert the  string incoming on the serial through UART lines and receiving those using the below code. Also I am converting the received string to char array as i need to insert some more characters in between hence I need the conversion.
I have used 3 different commands to convert the above string into char array as you can see below
```

#include <SoftwareSerial.h>
#include <Arduino.h>

#include <stdio.h>

#include <string.h>

SoftwareSerial s; //RX TX
using namespace std;
String str= "";
String str_tx;

const char* c;
double buff[24];
unsigned long int str_len = 0;
double val;
char* token;
//char* rest = char_array;
int i=0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  s.begin(115200, SWSERIAL_8N1, 13, 15, false, 256); //115200, SWSERIAL_8N1, 13, 15, false, 512
  pinMode(13, INPUT);
  pinMode(15, OUTPUT);

  Serial.println("in setup 1");
  Serial.println("in setup 2");
  Serial.println("in setup 3");

}

void loop() {
  // put your main code here, to run repeatedly:2
 while(s.available() >0)
 {

  char ch=s.read();
  str.concat(ch);
  if( ch =='\n' )
  { str.trim();
    Serial.println(str);
    str_tx = str;
    Serial.println(str_tx);

    str_len = str_tx.length()+1;
    Serial.println(str_len);
    //char char_array[sizeof(str_tx)];
    char char_array[str_len];
    //strcpy(char_array, str_tx.c_str());
    //str_tx.toCharArray(char_array, str_len);
    std:copy(str_tx.begin(),str_tx.end(),char_array);
    Serial.println(char_array);
    char_array[sizeof(str_tx)] = '\0';
    //char_array[65] = 0;
    str="";
    str_tx = "";
    Serial.println("------------------------------------");
  }
  /*
  str = "";
  str = s.readStringUntil('\n');
  str.trim();
  Serial.println(str);
  str_tx = str;
  Serial.println(str_tx);

  str_tx = str;
  str_tx.replace("\n","");

  str_len = str_tx.length();
  Serial.println(str_len);
  Serial.println(str_tx.c_str());*/

}

}

```
The output of the above code comes as below, you can see the first time conversion occurs but the next time only empty string shows up, in all the 3 cases its showing the same hence I need to find out what exactly this issue is caused by, would appreciate if anyone could thro some light on it.
Thankyou
[![ESP8266 serial output][1]][1]

  [1]: https://i.stack.imgur.com/SKfqE.png

title: Conversion from string to char array

Answers: 0


body:
Module light is blinking/working but it's not showing for pairing in my smart phone.I have supplied it 3.3 volts and have tried different phones.[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/RUeQy.jpg

title: Hc-05 bluetooth module pairing issue

Answers: 2

body:
It won't pair directly you will need other apps for pairing the modules. Try using this [app][1]. It will solve your issue for sure

  [1]: https://play.google.com/store/apps/details?id=de.kai_morich.serial_bluetooth_terminal&hl=en&gl=US

body:
I put together a complete tutorial on using the HC-05 in the Arduino environment for remote programming.  You can see it [here][1]

  [1]: https://www.fpaynter.com/2019/06/arduino-remote-programming-using-a-hc-05-bluetooth-module/


body:
Help needed! I am using an Arduino Nano and a general purpose npn (2n2222a) transistor to provide a 12v signal to a low current 12vdc load in an automobile. The Arudino code is set to pulse D2 at bootup/startup for .5 second. The PWM output setting was 255 (since switched to digitalWrite). However, the switched output measures only 4.5v (expected close to 12v). What am i doing wrong?
Applying 12v+ directly to the black box works. The purpose is to simulate a temporary button push in the car so an auto function is enabled.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/6gJ8K.jpg

title: Why is my transistor switched output so low?

Answers: 4

body:
The 2N2222 is an [*NPN*](https://www.electronics-tutorials.ws/transistor/tran_2.html) device. Skipping all of the physics involved, that means that (in your application) it will ***sink*** current as a *low-side switch*, but not ***source*** current as a *high-side switch*.

If you want a *high-side switch*, you should find a *PNP* transistor. In this case your Nano pin will **sink** current from the transistor's base terminal.

I would recommend you stick with the 2N2222, but make two changes:

1. Connect your "black box" between the positive terminal (+) of your 12V supply, and the **collector** terminal of the 2N2222.

2. Reduce the size of your base resistor from 10Kohms to 1Kohms

body:
What I have thought about is using an opto-coupler
[![enter image description here][1]][1]

Connect the Arduino pin output to pin 1 through 330 ohms resistor, pin 2 to ground of Arduino, connect pin 4 to Vcc of 12 V and finally connect pin 3 to the black box load.

Try this configuration

Since black box only needs few milliamps as you said
May be the transistor is not ***saturated*** since base current has to go through the black box load opto-coupler s have ***no base current instead they use photons***

Here is the circuit diagram

 [![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/Y9PY3.png
  [2]: https://i.stack.imgur.com/dB2Rp.png

5 V supply looks like the Arduino pin D2 and lamp is the black box load.
This is 4N35 example

body:
The problem is that you are using an NPN transistor as a high side switch.

The voltage at the emitter of the transistor will always be about 0.7V below the voltage at the base.  The "high" output from the Arduino is 5V.  The emitter will be at about 4.3V.

Have a look at the Wikipedia ["emitter follower"](https://en.wikipedia.org/wiki/Common_collector) page.  The emitter follower is also called a common collector circuit. That explains the "problem" in more detail.  It is only a problem in so far as it is not the correct solution for your task.

You need to use a ["common emitter"](https://en.wikipedia.org/wiki/Common_emitter) circuit.

This usage is commonly called a "low side switch."

That would look like this:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/FoH9v.png)

<!-- End schematic -->

If your black box really needs its input pulled up to 12V, then you would do something like this:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/DcNCM.png)

<!-- End schematic -->

The resistor values and transistor part numbers are place holders.  The values of resistors you will need depends on the transistors you use.  The transistor selection will depend on how much current you need to deliver to the black box.

I see in a comment that your black box only needs a few milliamperes.  In that case, the shown transistors should work just fine.  The resistor values may be a little too high, but I think they'll be OK.

------

A couple of additional points:

1. The Arduino has PWM outputs, not PCM.
2. The output voltage for your black box will be pulsing if you use any PWM value lower than 255.  Your black box probably won't like that, and your voltmeter won't read a correct voltage.

You should use D2 as a digital output rather than PWM.  Just turn it on or off rather than fiddling with the PWM duty cycle.  Use ["digitalWrite"](https://www.arduino.cc/reference/en/language/functions/digital-io/digitalwrite/) instead of ["analogWrite"](https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/) on pin D2.

body:
[![enter image description here][1]][1]ok, so i chose the 2 transistor high side circuit as i had the needed pnp transistor laying around. Works great, thanks everyone for your help. The trace (5v/div) shows the Arduino signal at 5v and the circuit output at 12v - perfect!
[![enter image description here][2]][2]
[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/ReotF.jpg
  [2]: https://i.stack.imgur.com/TPelO.jpg
  [3]: https://i.stack.imgur.com/U1ZEK.jpg


body:
I have a doubt in the AD7705 library [AD7705 Library Link](http://www.kerrywong.com/2012/04/18/ad7705ad7706-library-revisited/comment-page-1/?unapproved=1271018&moderation-hash=8b80f04a3200d58d64eb86a598fc3c24#comment-1271018) when I am declaring a reference voltage of 5 V and giving a reference voltage of 5 V to IN1+. On the serial monitor, I can see ADC conversion from 2.5V to 5 V when I vary the potentiometer.

whatever reference voltage I am giving it is divided by 2.

What parameter should I change to get full-scale voltage reading?

Thanks in Advance!

title: Receiving half the value of Reference Voltage in AD7705?

Answers: 0


body:
I have been using ds3231 rtc module for keep tracking and make alarm along with backup battery. when I used it for first time it worked fine. but now it doesn't keep track my time when the power lose it from main power but I have checked that my battrey is in safe. So I search in lot of forums they said EOSC bit was set high that would be stoped the clock as it stops the internal oscillator. also want to set it into low then only rtc keep track of the time

but in another some forums they instructed that put this following code for set it to low

    DS3231 RTC;

      Wire.beginTransmission(0x68);
      Wire.write(0xF);                            // Address the Status register
      Wire.write(0x00);                           //  Zero the Status register
      Wire.endTransmission();
      Wire.beginTransmission(0x68);
      Wire.write(0xE);                            // Address the Status register
      Wire.write(0x00);                           //  Zero the Status register
      Wire.endTransmission();

      RTC.setA2Time( ADay, AHour, AMin, 0x00, true, false, false);
      delay(100);
      RTC.turnOnAlarm( 2 );

in another place showed the following code

    // clear /EOSC bit to ensure that the clock runs on battery power
      Wire.beginTransmission(0x68); // address DS3231
      Wire.write(0x0E); // select register
      Wire.write(0b00011100); // write register bitmap, bit 7 is /EOSC
      Wire.endTransmission();

but now problem is that where should I want to place this code and how  to past it in proper manner for keep tracking the time when ds3231 loses power too? please any know about this problem because I finded so many people are strugling with this issue when they come forward to use this ds3231 rtc module. if any body know about how to solve this issue plese consider to share your idea this will definately help full for evryone because there is no one properly answer for this issue

title: Set control register to low in ds3231 rtc

Answers: 2

body:
I also have a DS3231 RTC in my robot project.  Here's my complete setup code.  This can be placed anywhere in setup():  I don't think you have to mess with individual registers to get what you want.

     if (rtc.begin()) //02/19/19 this now returns FALSE if RTC doesn't respond
     {
      Serial.println("Found RTC...");
      delay(100);
      bRTCLostPower = rtc.lostPower(); //added 10/17/18
      mySerial.printf("rtc.lostPower() reports %d\n", bRTCLostPower);

      if (rtc.lostPower())
      {
       Serial.println("RTC lost power.  Setting RTC to last compile time");
       rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));// sets RTC to last compile date/time
      }

    #ifdef FORCE_RTC_TO_LAST_COMPILE_TIME
      Serial.println("Forcing RTC to last compile time");
      rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));// sets RTC to last compile date/time
    #endif

      DateTime now = rtc.now();
      char buffer[100];
      memset(buffer, '\0', 100);
      mySerial.printf("Retrieving Date/Time from RTC with rtc.now() =  %ld\n", now.unixtime());
      GetDayDateTimeStringFromDateTime(now, buffer);
      Serial.print("Date/Time: "); Serial.println(buffer);
      RTC_Avail = true;
     }
     else
     {
      Serial.println("Couldn't find RTC. Real-time clock functions won't be available");
      RTC_Avail = false; //use this instead
     }

     if (RTC_Avail && rtc.lostPower())
     {
      DateTime Comp_dt = DateTime(F(__DATE__), F(__TIME__)); //__DATE__ & __TIME__ are environment variables)
      uint8_t mydayofweek = Comp_dt.dayOfTheWeek();  //returns 0 for Sunday, 6 for Saturday dayOfTheWeek
      int mymonth = Comp_dt.month();
      int myday = Comp_dt.day();
      int myyear = Comp_dt.year();
      int myhour = Comp_dt.hour();
      int mymin = Comp_dt.minute();
      int mysec = Comp_dt.second();
      long unixtime = Comp_dt.unixtime();
      char* dayofweek = (char*)daysOfTheWeek[mydayofweek];

      Serial.print("day of week value = "); Serial.println(mydayofweek);
      Serial.print("day of week value = "); Serial.println(Comp_dt.dayOfTheWeek());

      mySerial.printf("RTC lost power - setting to datetime of last compile %ld (%s M/d/d at d:d:d)\n",
       unixtime, dayofweek, myyear, mymonth, myday, myhour, mymin, mysec);

      rtc.adjust(Comp_dt);
     }

body:
From the DS3231 data sheet:

**Control Register (0Eh)**

Bit 7: Enable Oscillator (EOSC). When set to logic 0, the oscillator is started. When set to logic 1, the oscillator is stopped when the DS3231 switches to VBAT. This bit is clear (logic 0) when power is first applied. When the DS3231 is powered by VCC, the oscillator is always on regardless of the status of the EOSC bit. When EOSC is disabled, all register data is static.

**Status Register (0Fh)**

Bit 7: Oscillator Stop Flag (OSF). A logic 1 in this bit indicates that the oscillator either is stopped or was stopped for some period and may be used to judge the validity of the timekeeping data. This bit is set to logic 1 any time that the oscillator stops. The following are examples of conditions that can cause the OSF bit to be set:
1) The first time power is applied.
2) The voltages present on both VCC and VBAT are insufficient to support oscillation.
3) The EOSC bit is turned off in battery-backed mode.
4) External influences on the crystal (i.e., noise, leakage,etc.).
This bit remains at logic 1 until written to logic 0.

I dug out an old D3231 board. It had a battery in it but was last set ~3 years ago and I am not sure how old the battery was when I first put it in the board. The battery cannot keep the clock running. When I attached it to an Arduino UNO and booted up, the clock’s registers read as follows (just pay attention to the time and the EOSC bit and the OSF flag):

CLOCK: 00:01:15 (24h clock) Sunday, 01/01/2000  Temperature=21C  Aging offset=0

Alarm #1: 00:00:00 (24h clock) DY/DT=18[DoM mode]   Alarm selection: when date, hours, minutes and seconds match

Alarm #2: 00:00 (24h clock) DY/DT=20[DoM mode]  Alarm selection: when date, hours, minutes match

CONTROL byte=00011100 /EOSC is ON /BBSQW is Disabled /CONV is clear /INTCN mode is Match /Alarm 1 is Disabled /Alarm 2 is Disabled

STATUS byte=10000000 /OSF is ON /EN32KHZ Disabled /BSY is OFF /A1F is OFF /A2F is OFF

The clock is now running because with VCC supplied by the Arduino, the oscillator will always run. When I read the clock, I can see the time advancing, but it started from 00:00:00

Now, I remove power and after a minute or so, power up the UNO and the clock, and read the clock. It is again running, but the time had not advanced – it simply restarted from 00:00:00. EOSC is ON. OSF is ON.

With no VBAT, the time was not preserved.

A fresh battery is inserted and I power up. The clock is again running, again, restarted at 00:00:00. EOSC is ON. OSF is ON.

After a couple of minutes, I power down (with the fresh battery still in the clock). When I boot up and read the clock, it is running AND it kept running on battery power, so the current time is accurate. EOSC is ON. OSF is ON.

EOSC was always enabled (read as 0) – that is the POR value. Unless your program explicitly sets the bit to 1, EOSC will reliably be enabled. If you do disable EOSC (set to 1), the oscillator will NOT run off of the battery backup (VCC off and VBAT on). With EOSC disabled, and if there is enough juice in the battery, it will hold the time (and other registers) when VCC is switched off and VBAT is on. When VCC is on, the oscillator will always run.

But, what about the OSF flag?

Reading the data sheet, you can see that the OSF flag gets set when the oscillator stops, which can occur from a number of conditions.

It is designed so that the software can legitimately suspect that the time is not accurate, But, OSF is set as the POR value.

**You need to enable EOSC AND CLEAR OSF**, every time you do a clean power up and every time OSF got set because you unplugged (no VCC) and changed batteries. Also, remember, that with VCC, the oscillator will run regardless of the state of the EOSC bit.

Do not ignore OSF, it is an important flag and it should not be getting set regularly. In fact, once you insert a battery and clear OSF, it should not be set again until the battery drains. If it is getting set regularly, you have problems elsewhere.

Some software reads OSF and if it is set, the software will balk and tell you as much, as it should. Since OSF is set on POR, it will be set whenever you remove VCC and VBAT and then power up again.

**You need to explicitly clear OSF AND know why it got set.**

This code snippet, enables EOSC AND clears OSF.

     // enable EOSC and clear OSF flag
     // *** The other bits in these two registers are writtten
     // with POR Values or '0' if POR value=X.
      Wire.beginTransmission(0x68); // address DS3231
      Wire.write(0x0E); // select CONTROL register
      Wire.write(0b000011100); // write register (bit 7 is EOSC)
      Wire.endTransmission();
      Wire.beginTransmission(0x68);
      Wire.write(0x0F); // select STATUS register
      Wire.write(0b00001000); // write register (bit 7 is OSF)
      Wire.endTransmission();

Hope it helps.


body:
I am making a line follower robot. The issue is trying to make the motors run.

The L239D module has 4 input pins (to control two motors), 4 output pins (to drive motors), and 6 power pins (5V, 5V, GND, GND, 9/12V, and 9/12V).

I have used one 5V pin to connect it to an Arduino's 5V supply and one of the 9/12V pins to two 9V batteries in series.

The motors are barely running and when the robot is on the ground it is not able to move. I even tried three 9V batteries in series to get the voltage up to 27V but it doesn't help.

title: L239D motor driver not able to drive motors

Answers: 3

body:
9 V batteries, assuming you mean the little PP3-size ones, can't supply the current needed for driving robot motors; they are intended for low-current applications.

Putting them in series will give you a higher voltage, not more current, and the higher voltage could damage something else in the circuit.

*Assuming you connected everything correctly, including ground:* you need bigger batteries. Even 6 AAs in series would be much better than using a 9V battery for getting your robot to move.

body: On your next try use a different H-Bridge, one with MOSFET outputs, you can have a voltage drop across the L239D of 2.4V. Measure the voltage at the motor and at your batteries you will see what I am getting at. You might want to try connecting the motors directly to the battery first to see if it will do what you want.

body: I guess using 9 Volt battery in parallel will do your work because if the motor is moving as you quoted above means it is getting the voltage but not enough current to drive it, please connect the 9 volt battery in parallel and it will work for you


body:
From what I read about duty cycles in the EU there is a 10% limitation (even less in some sub bands).
The modules I found have a max. rate of 300 kbps. Even if you max out the duty cycle that would only be 30kbps.

How do consumer devices like a digital walkie talkie operate here legally in the EU?
What am I missing?

Is there a frequency where I can legally stream constantly at more than 70kbps (not Wifi) ?

title: legality of streaming data on 868 or 915 Mhz in EU/US

Answers: 0


body: I want to make any 2 Arduino module from different places to communicate over wifi. I really need to know if it possible? If yes, advice me more about it. I want send data from sensor module from one Arduino to another and vice versa. That's the basic idea. Do I need a third party services such as cloud services to make it happen? Or simply can send ovee wifi with the help of Ip adress. Sorry, I have less knowledge on this. Help me out. Thank you in advance.

title: I want to make two arduino to communicate over different wifi. Is that possible?

Answers: 1

body:
If they are on the same (wifi) network; then yes.

If you are on a different network, it would be more difficult. You would have to setup port forwarding on your router. Then you would have to somehow know the public IP address of the other router. These addresses can change from time to time with certain ISPs. I wouldn't advice doing this.

Instead I'd go with an third party service. For example Adafruits offers an MQTT server. I'd probably use this even if they are on the same network.


body:
I know I can make the motor move backwards and forwards with buttons but I don't want it to move at full speed. I want it to increment in very small amounts to where it can be adjusted very small amounts at a time. I should also be able to hold the button so it moves continuously. I also have a motor with an encoder on it. Maybe there is a way to use the numbers on the encoder to increment? so press the CW button and now the motor wants to move till the encoder reaches +10 from where it was at? I understand what I want to do, just need help getting there. Thanks

HERE IS THE CODE I FIGURED OUT THAT MAKES MY DC MOTOR INCREMENT CW AND CCW

```

#define MOTOR_DIRECTION_PIN   2
#define MOTOR_SPEED_PIN       3

#define MOTOR_DIRECTION_CW    LOW
#define MOTOR_DIRECTION_CCW   HIGH

void setup()
{
  //button inputs
  //pullup so we do not need to include a physical resistor
  pinMode(12, INPUT_PULLUP);
  pinMode(13, INPUT_PULLUP);

  pinMode(MOTOR_DIRECTION_PIN, OUTPUT);
  pinMode(MOTOR_SPEED_PIN, OUTPUT);

  Serial.begin(9600);

  Serial.println("test");
}

void loop()
{
  int pushedButtonOne = digitalRead(12);
  int pushedButtonTwo = digitalRead(13);

  if(pushedButtonOne == LOW)
  {
    Serial.println("Button number 1 has been pushed");
    digitalWrite(MOTOR_DIRECTION_PIN, MOTOR_DIRECTION_CCW);
    analogWrite(MOTOR_SPEED_PIN, 50);
    delay(7);
    analogWrite(MOTOR_SPEED_PIN, 0);
  }

  else if(pushedButtonTwo == LOW)
  {
    Serial.println("Button number 2 has been pushed");
    digitalWrite(MOTOR_DIRECTION_PIN, MOTOR_DIRECTION_CW);
    analogWrite(MOTOR_SPEED_PIN, 50);
    delay(7);
    analogWrite(MOTOR_SPEED_PIN, 0);
  }
  else
  {
    Serial.println("nothing has been pushed");
  }

  //delay(100);

}

title: I need help creating a code that moves a DC motor CW or CCW based off of 2 different buttons

Answers: 2

body:
To formulate the comments into an answer:

In principle it is of course possible to put an encoder onto a DC motor shaft and then drive the motor, until you reach the desired position. But you won't get good precision or accuracy with this. You wrote

> till the encoder reaches +10 from where it was at

Since most encoders have more than 10 tics per full rotation (you didn't specifiy how much yours has), this can mean  rotating only a fraction of a full rotation. Let's assume, that the encoder has 40 tics per full rotation. With 10 tics you have a quarter rotation. It seems you want precision in the range of about 1 tic.

DC motors are made for spinning relatively fast. They don't give you control over the position with steps. They mostly have very few coil/magnet combinations (for example just 2 coils, which are switched internally). Thus you have just an inert motor shaft, which is driven by the motor. It will need time to accelerate and to decelerate. With most motors, you may even get a half or full rotation, when you wanted only a quarter rotation (the 10 tics). Calculating the correct timings to get it any better will be not easy for relatively small reward. DC motors are not made for rotations below a small number of full rotations.

You could tackle that problem by using a geared DC motor. The shaft after the gears will run slower and thus have the explained problem not so badly. Then you have to live with the smaller speed.

**Or you could go a more proper way and just use a stepper motor**, which is made for small steps in the range of sub-full-rotation. It is a bit more difficult to drive (also depending on the driver circuit), but it gives you the position control, that you want. And to rotate continuously: A continuous rotation on a stepper motor is nothing else but step after step taken in fast succession (much like running is a fast succession of steps with your feet).

---

Note: The stepper motor does not have a feedback like an encoder on it. The motor driver will just drive the coils to step the motor. If the motor is stalled or if it is overloaded, you might loose some steps (meaning that the coils are driven for the steps, but the motor doesn't actually move). You could sense that with an additional encoder on the motor shaft. But in most cases that is not necessary. If you just make sure, that the motor is not overloaded at any time, you will be fine. Or you might not worry about some steps being lost sometimes, if the overall precision is good enough. That is your decision.

body:
Here is the code i eventually figured out. It increments my DC Motor basically by activating it for a small amount of time in the direction of whichever button was pushed.

```
#define MOTOR_DIRECTION_PIN   2
#define MOTOR_SPEED_PIN       3

#define MOTOR_DIRECTION_CW    LOW
#define MOTOR_DIRECTION_CCW   HIGH

void setup()
{
  //button inputs
  //pullup so we do not need to include a physical resistor
  pinMode(12, INPUT_PULLUP);
  pinMode(13, INPUT_PULLUP);

  pinMode(MOTOR_DIRECTION_PIN, OUTPUT);
  pinMode(MOTOR_SPEED_PIN, OUTPUT);

  Serial.begin(9600);

  Serial.println("test");
}

void loop()
{
  int pushedButtonOne = digitalRead(12);
  int pushedButtonTwo = digitalRead(13);

  if(pushedButtonOne == LOW)
  {
    Serial.println("Button number 1 has been pushed");
    digitalWrite(MOTOR_DIRECTION_PIN, MOTOR_DIRECTION_CCW);
    analogWrite(MOTOR_SPEED_PIN, 50);
    delay(7);
    analogWrite(MOTOR_SPEED_PIN, 0);
  }

  else if(pushedButtonTwo == LOW)
  {
    Serial.println("Button number 2 has been pushed");
    digitalWrite(MOTOR_DIRECTION_PIN, MOTOR_DIRECTION_CW);
    analogWrite(MOTOR_SPEED_PIN, 50);
    delay(7);
    analogWrite(MOTOR_SPEED_PIN, 0);
  }
  else
  {
    Serial.println("nothing has been pushed");
  }

}


body:
Hello dear StackExchange users,

i want to develop an Infrared blaster which i can plug into the headphone jack of a phone or console of choice. In order to communicate what frequency to modulate the diode with and how long to send pulses, i simply generate tones for the Arduino to read and interpret.

My problem is that i can't reliably measure the frequency with it. In order to measure the frequency i use an Analog Comparator Interrupt and trigger at falling edge, thus getting always the interrupt after a full pulse occured. I called micros() at every interrupt in order to get the pulse duration, but it was too imprecise. Then i tried using Timer0 with a prescaler of 8 to measure the frequency, but it only counts to 255.

Now i switched over to Timer1 because of it's bigger TCNT register. However for some reason it already overflows at 255 even though i didn't set the OCR1 registers.

This is my current code. Please note that the actual frequency calculation happens in the main loop to not mess with the measurements gained in the ISR.

    const int setFrequencySound = 1000;
    const int receiveDataSound = 2000;
    const int receiveDataEndSound = 3000;

    const int readyMode = 0;
    const int setFrequencyMode = 1;
    const int receiveDataMode = 2;
    const int sendDataMode = 3;

    volatile unsigned long timeBefore;
    volatile unsigned long timeNow;
    volatile unsigned long delta;
    volatile float audioFrequencyBefore;
    volatile float audioFrequency;

    volatile float irFrequency;
    volatile int irData[100];
    volatile int irDataIndex;

    volatile int mode = 0;

    ISR (ANALOG_COMP_vect)
    {
    timeNow = TCNT1;
    Serial.print (timeNow);
    Serial.println (" TCNT1");
    //TCNT1 = 0; //reset timer register
    }

    void setup ()
    {
    Serial.begin (115200);
    Serial.println ("Started.");
    ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
    ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
          | bit (ACIE)    // Analog Comparator Interrupt Enable
          | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)

    TCCR1B |= (0 << CS12) | (1 << CS11) | (0 >> CS10); //Activate timer and set prescaler to 8
    TCNT1 = 0; //Reset timer register
    }  // end of setup

    void loop ()
    {
    //Calculate frequency by using the period duration
    //determined through the timestamps captured in
    //ISR method.
    //delta = timeNow - timeBefore;
    audioFrequency = 1000000000.0 / (float(timeNow) * 2.0);

    if (millis() % 1000 == 0)
    {
      Serial.print (audioFrequency, 5);
      Serial.print (" Hz, ");
      Serial.print (timeNow);
      Serial.println (" TCNT0");
    }

    //Do not process the same frequency multiple times
    if (audioFrequency != audioFrequencyBefore)
    {
      switch (mode)
      {
        case readyMode:
          if (audioFrequency == setFrequencySound)
          {
            mode = 1;

            Serial.println ("Start setting IR frequency.");
          }
          else if (audioFrequency == receiveDataSound)
          {
            mode = 2;

            Serial.println ("Start receiving IR data.");
          }
          break;
        case setFrequencyMode:
          irFrequency = audioFrequency + 25000;

          Serial.print ("IR frequency set to ");
          Serial.print (irFrequency, 10);
          Serial.println (" Hz.");

          mode = readyMode;
          break;
        case receiveDataMode:
          if (audioFrequency == receiveDataEndSound)
          {
            Serial.println ("Stop receiving IR data.");

            mode = readyMode;
            irDataIndex = 0;
          }
          else
          {
            irData[irDataIndex] = audioFrequency;

            irDataIndex++;

            Serial.print ("IR pulse received: ");
            Serial.print (irData[irDataIndex]);
            Serial.println (" microsecs.");
          }
          break;
        case sendDataMode:
          Serial.println ("Sending IR data...");
          break;
      }
    }

    audioFrequencyBefore = audioFrequency;

    }  // end of loop

title: Measure audio frequency through pulse duration

Answers: 1

body:
Timer 1 overflows at 255 because that's how it has been configured by
the Arduino core, as it is intended to provide 8-bit PWM. If you want
to use the timer in normal mode, you should undo the Arduino's
initialization by setting `TCCR1A` to zero.

Two comments on the ISR:

```c++
ISR (ANALOG_COMP_vect)
  {
    timeNow = TCNT1;
    Serial.print (timeNow);
    Serial.println (" TCNT1");
    //TCNT1 = 0; //reset timer register
  }
```

First, as has been stated in a previous comment, you should not print
from within an ISR. Also, if you want consistent timing, you should
never reset the timer. Just keep it freely running and use time
differences to get the signal period. Do not worry about the timer
overflowing: if you do the computation with unsigned 16-bit integers
(`uint16_t`), you will be immune to the overflows. If you reset the
timer you will likely loose some ticks, as you can not read it and reset
it in the same clock cycle.

Lastly, I recommend you read about the “input capture” capability of
Timer 1. This is a feature of the timer designed for solving the exact
kind of problem you have here: the timer will automatically record a
timestamp on an external event. You can have this triggered by a rising
or falling edge on input pin 8, or by the analog comparator if you
prefer. This method gives you zero jitter, which cannot be achieved with
code, even running within an interrupt.

------------------------------------------------------------------------

**Edit**: Answering an extra question in the comment.

> Could i connect the audio wire [...] directly to pin 8 and use the
> input capture functionality?

It depends on the shape of the signal that comes out of this wire.
First, you have to make sure the signal always stays between the
electric potentials of GND and Vcc (i.e. 0 – 5 V), otherwise you risk
damaging the Arduino.

Note that if the signal comes from a high impedance source, it can
safely go somewhat beyond this range, as the Arduino has all of its
inputs protected by diodes. You just have to limit the current in the
diodes to less than 1 mA. In other words, for each kΩ of output
impedance, you can extend the (unloaded) acceptable voltage range by 1 V
on each side. If the source is low impedance, you can make it high
impedance simply by adding a 10 kΩ resistor in series.

Second point is, you have to make sure the signal has a large enough
voltage span to make the digital input switch between LOW and HIGH.
According to the datasheet of the ATmega328P, when powered at 5 V the
input thresholds are typically around 2.1 V for switching LOW and 2.6 V
for switching HIGH. The difference between those thresholds provides
some hysteresis, which can help cancelling noise. Note that those are
typical values. If you want _guaranteed_ switching, the signal should go
below 1.5 V to get a guaranteed LOW reading (this is VIL) and
above 3 V to get a guaranteed HIGH reading (VIH).

Note also that, if the input thresholds of the digital pin do not fit
your needs, you can use the analog comparator as a trigger for the input
capture.