text:
Brownout with Arduino Nano

I'm making an RC car with the Arduino Nano. I'm using RF433 as  wireless communication with 2 motors and L293D as the motor driver. I use 4 1.5V batteries to power the Arduin and another 6V battery pack to power the motors, and a joystick with an Arduino Mega to send commands through the RF433 to the Arduino Nano.
I've written a program that sends specific digits when the joystick is in a certain position, i.e. when the joystick is "bent" to the front it sends a "1", a "2" is sent when the joystick is bent towards the back, and so on.
My problem is this:
When I bend the joystick towards a certain direction, the RC car moves accordingly without problem; However, when I bend the joystick towards another direction the RC car doesn't respond.
I took a look at what the RC car was receiving, and I've noticed that after the first command was sent (when I bend the joystick towards a certain direction), no more commands get to the RC car (in other words the Arduino Nano), and this occurs occasionally. I think this means the Arduino Nano "froze" after the first command.

Does the problem occur or not occur when you unhook power to the motors?

@jwpat7 Sorry, but what do you mean by "unhook power to the motors"? If I unhook the batteries powering the motors, It'll stop rotating in the first place, no?

You can run tests with an LED+resistor in place of each motor.  The idea is to have a low-current non-inductive load in place of the motors.  If problem still occurs, look for wiring or software errors.  If it doesn't, look for battery supply problem or electrical noise problem.

@jwpat7 Ok. I'll look into that and comment if things go awry again. Thanks for the help.

Nice drawing, bub.

You have at least three problems here:
1) First and most critically, a nominal 6v pack does not meet the input voltage requirements of the regulator used an Arduino even before it gets loaded down by a motor, and it only gets worse under load
2) L293/L297 and similar bipolar bridges have absurdly high internal losses, so are unsuited to low voltage systems - effectively one of your cells goes just to feeding the wasteful driver chip.  Use a modern and efficient FET driver like a TB6612FNG, or else add another cell to the pack.
3) The 433 MHz RF modules are notoriously low fidelity, and in many places not permitted for the control of RC models anyway.  You'll have much better results with the sophisticated digital radio modules sold at comparable prices for 2.4 GHz, which are incidentally the functional equivelent of what most RC toys now use (and actually in many cases can be made interoperable with them).
Granted, you may well have other issues as well, such as errors in your software.


text:
Metal pushbutton voltage drops only to 3.15V when OFF
I'm trying to detect a press of a 5-terminal LED button using the tutorial here: https://newbiely.com/tutorials/esp8266/esp8266-button-long-press-short-press
Works with no issue with standard pushbutton (4 legs, wired to ground and input IN pin), however, it doesn't work with 5 terminal self-resetting halo button. I did notice that when I pressed the button the voltage drops only to ~3.15V instead of 0V. Do you know why that might be caused?

Thanks!

In all the codes in that tutorial the digital pin is configured as INPUT_PULLUP, so the internal pullup resistor will pull it to 3.3V.
Since you connected to pin to NC (normally connected), the button is connected to 3.3V when not pressed, and to nothing when pressed - and in that case the pullup resistor pulls it towards 3.3V. Depending on your supply and your measurement method that might be a bit lower (like your 3.15V), though comfortably inside the HIGH range.
Either connect the common pin (C) to ground, or use INPUT_PULLDOWN (if your board supports that) or an external pulldown resistor (from the digital pin to ground, value like 1kOhm should be good)

Thank you @chrisl, connecting common to the ground and switching the signal to NC worked like a charm :)

source: Stack Exchange

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

sort: votes


text:
Arduino TFT Touch Screen Interface Only Returns One Button Option
I'm trying to create an arduino code that returns a value for the button that was pressed as the user choice. However, whichever button I press the only return is 2. Also, whenever pressing other buttons, button 2 is the one that seems to have been pressed.
What could it be? Any ideas on how to solve this issue?
This is the current code I have.
#include <MCUFRIEND_kbv.h>
#include <TouchScreen.h>

#define MINPRESSURE 500
#define MAXPRESSURE 2000
#define PRETO   0x0000
#define VERMELHO     0xF800
#define VERDE   0x07E0
#define BRANCO   0xFFFF

#define XP 6
#define XM A2
#define YP A1
#define YM 7

#define TS_LEFT 945
#define TS_RT 221
#define TS_TOP 916
#define TS_BOT 201

TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);
Adafruit_GFX_Button botoes[4];
MCUFRIEND_kbv tft;

int posX, posY;
int escolha = 0;

bool obterToque(void) {
    TSPoint p = ts.getPoint();
    pinMode(YP, OUTPUT);
    pinMode(XM, OUTPUT);
    digitalWrite(YP, HIGH);
    digitalWrite(XM, HIGH);
    bool pressed = (p.z > MINPRESSURE && p.z < MAXPRESSURE);
    if (pressed) {
        posX = map(p.x, TS_LEFT, TS_RT, 0, 320);
        posY = map(p.y, TS_TOP, TS_BOT, 0, 240);
        // Debugging: Print the raw and mapped touch coordinates
        //Serial.print("Raw X: "); Serial.print(p.x); Serial.print(", Raw Y: "); Serial.println(p.y);
        //Serial.print("Mapped X: "); Serial.print(posX); Serial.print(", Mapped Y: "); Serial.println(posY);
        return true;
    }
    return false;
}

void setup() {
  Serial.begin(9600);
  uint16_t ID = tft.readID();
  tft.begin(ID);
  tft.setRotation(3);
  telaInicial();
}

void telaInicial(){
  tft.fillScreen(PRETO);
  botoes[0].initButton(&tft,  160, 40, 250, 40, BRANCO, VERDE, PRETO, "1. Normal Sinus", 2);
  botoes[1].initButton(&tft, 160, 95, 250, 40, BRANCO, VERDE, PRETO, "2. Atrial Fibrillation", 2);
  botoes[2].initButton(&tft, 160, 150, 250, 40, BRANCO, VERDE, PRETO, "3. Ventricular Ectopy", 2);
  botoes[3].initButton(&tft, 160, 205, 250, 40, BRANCO, VERDE, PRETO, "4. SV Arrhythmia", 2);

  for (int i = 0; i < 4; i++) {
    botoes[i].drawButton(false);
  }
}

void TeclaPressionada(bool teclaTocada) {
  for (int i = 0; i < 4; i++) {
    botoes[i].press(teclaTocada && botoes[i].contains(posX, posY));
  }
  checkPressedButton();
}

void checkPressedButton() {
  for (int i = 0; i < 4; i++) {
    if (botoes[i].justPressed()) {
      checkPressed(i);
    }
  }
}

void esperaSoltar() {
  while (obterToque()) {
    delayMicroseconds(50);
  }
}

void checkPressed(int button) {
    botoes[button].drawButton(true);
    esperaSoltar();
    botoes[button].drawButton();

    if (button == 0) {
        escolha = 1;
    } else if (button == 1) {
        escolha = 2;
    } else if (button == 2) {
        escolha = 3;
    } else if (button == 3) {
        escolha = 4;
    }

    Serial.print("Escolha: ");
    Serial.println(escolha);
}

void loop() {
  bool toque = obterToque();
  TeclaPressionada(toque);
}

Thanks for reading.

why is the debugging code disabled?

Hi everyone, eventually I found a tutorial that solves this issue: https://www.youtube.com/watch?v=wn-1hHjRyjo

I managed to find an answer on this video tutorial: https://www.youtube.com/watch?v=wn-1hHjRyjo
Here's the screen project I'm working on.
#include <MCUFRIEND_kbv.h>
#include <Adafruit_GFX.h>
#include <TouchScreen.h>

MCUFRIEND_kbv tft;

#define XP 6
#define XM A2
#define YP A1
#define YM 7

#define TS_LEFT 945
#define TS_RT 221
#define TS_TOP 916
#define TS_BOT 201

TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

// Definição de cores
#define BLACK 0x0000
#define BLUE 0x2015
#define BLUE2 0x0DDE
#define RED 0xF800
#define GREEN 0x07E0
#define CYAN 0x07FF
#define MAGENTA 0xF81F
#define YELLOW 0xFFE0
#define WHITE 0xFFFF
#define GREY 0xC639

// Variáveis Globais
uint32_t startRead = 0;
int page = 0;
int posX;
int posY;

// Variables for ECG data
float ecgValue = 0.0; // Current ECG value received from serial
int scale = 75;      // Scale factor for voltage values
int startY;          // Vertical center for the waveform
int ecgIndex = 0;    // Current index for plotting
int xPos = 0;        // Horizontal position to draw the next data point
int choice = 0;       // User rhythm selection variable to lead to desired rhythm

#define MINPRESSURE 10
#define MAXPRESSURE 1000

void setup(void) {
  Serial.begin(115200);
  Serial.println("TFT Test");
  tft.reset();
  delay(500);
  uint16_t identifier = tft.readID();
  tft.begin(identifier);
  tft.setRotation(1);
  tft.setCursor(0, 0);
  tft.setTextColor(BLACK);
  tft.setTextSize(2);

  tft.println("Programa feito por: ");
  tft.println("Giovanne Lucas");
  tft.println("Barreto");
  tft.println("giovanne.pinto@medicina.uniceplac.edu.br");

  delay(2000);
  tft.fillScreen(BLACK);

  displayBootScreen();
  delay(5000);

  telainicial();
  page = 0;

  startY = tft.height() / 2; // Calculate vertical center for ECG plotting
}

void displayBootScreen() {
    int screenWidth = tft.width();
    int screenHeight = tft.height();
    tft.drawBitmap(0, 0, bootImage, screenWidth, screenHeight, WHITE);
    delay(5000);
    tft.fillScreen(0x0000); // Placeholder: Fill screen with black
    tft.setTextColor(0xFFFF);
    tft.setTextSize(2);
    //tft.setCursor(10, screenHeight / 2 - 10);
    //tft.print("Booting...");
}

void telainicial() {
  tft.fillScreen(WHITE);
  tft.fillRoundRect(5, 5, 310, 30, 0, BLACK);
  tft.fillRoundRect(7, 7, 306, 26, 0, BLUE);
  tft.setCursor(120, 10);
  tft.setTextColor(WHITE);
  tft.setTextSize(3);
  tft.print("MENU");

  tft.fillRoundRect(50, 55, 220, 40, 0, BLACK);
  tft.fillRoundRect(52, 57, 216, 36, 0, GREY);
  tft.setCursor(60, 65);
  tft.setTextColor(BLACK);
  tft.setTextSize(1);
  tft.print("1. Ritmo Sinusal");

  tft.fillRoundRect(50, 115, 220, 40, 0, BLACK);
  tft.fillRoundRect(52, 117, 216, 36, 0, GREY);
  tft.setCursor(60, 124);
  tft.setTextColor(BLACK);
  tft.setTextSize(1);
  tft.print("2. Fibrilacao Atrial");

  tft.fillRoundRect(50, 175, 220, 40, 0, BLACK);
  tft.fillRoundRect(52, 177, 216, 36, 0, GREY);
  tft.setCursor(60, 185);
  tft.setTextColor(BLACK);
  tft.setTextSize(1);
  tft.print("3. Ectopia Ventricular");
}

void tela1() {
  tft.fillScreen(WHITE);
  tft.fillRoundRect(5, 5, 310, 30, 0, BLACK);
  tft.fillRoundRect(7, 7, 306, 26, 0, BLUE);
  tft.setCursor(120, 10);
  tft.setTextColor(WHITE);
  tft.setTextSize(1);
  tft.print("Ritmo Sinusal");

  tft.fillTriangle(30, 20, 50, 30, 50, 10, GREY); // Botão de voltar
}

void tela2() {
  tft.fillScreen(WHITE);
  tft.fillRoundRect(5, 5, 310, 30, 0, BLACK);
  tft.fillRoundRect(7, 7, 306, 26, 0, BLUE);
  tft.setCursor(90, 10);
  tft.setTextColor(WHITE);
  tft.setTextSize(1);
  tft.print("Fibrilacao Atrial");

  tft.fillTriangle(30, 20, 50, 30, 50, 10, GREY); // Botão de voltar
}

void tela3() {
  tft.fillScreen(WHITE);
  tft.fillRoundRect(5, 5, 310, 30, 0, BLACK);
  tft.fillRoundRect(7, 7, 306, 26, 0, BLUE);
  tft.setCursor(90, 10);
  tft.setTextColor(WHITE);
  tft.setTextSize(1);
  tft.print("Ectopia Ventricular");

  tft.fillTriangle(30, 20, 50, 30, 50, 10, GREY); // Botão de voltar
}

void tela4() {
  tft.fillScreen(WHITE);
  tft.fillRoundRect(5, 5, 310, 30, 0, BLACK);
  tft.fillRoundRect(7, 7, 306, 26, 0, BLUE);
  tft.setCursor(90, 10);
  tft.setTextColor(WHITE);
  tft.setTextSize(1);
  tft.print("Arritmia Supraventricular");

  tft.fillTriangle(30, 20, 50, 30, 50, 10, GREY); // Botão de voltar
}

void plotECG() {
  static int xPos = 0; // horizontal position to draw the next data point
  static int startY = tft.height() / 2; // vertical center for the waveform
  static int lastY = startY; // previous Y coordinate

  if (Serial.available() > 0) {
    float ecgValue = Serial.parseFloat();
    int y1 = startY - (int)(ecgValue * scale); // calculate Y coordinate based on ECG value

    // draw a line from the previous point to the current point
    tft.drawLine(xPos - 1, lastY, xPos, y1, RED);

    // update lastY and xPos for the next loop iteration
    lastY = y1;
    xPos = (xPos + 1) % tft.width(); // wrap xPos around the screen width

    // clear the screen and redraw the grid if necessary
    if (xPos == 0) {
      tft.fillScreen(WHITE); // clear the screen
      drawECGGrid(); // redraw the grid
    }
  }
}

void loop() {
  TSPoint p = ts.getPoint();
  pinMode(XM, OUTPUT);
  digitalWrite(XM, LOW);
  pinMode(YP, OUTPUT);
  digitalWrite(YP, HIGH);
  pinMode(YM, OUTPUT);
  digitalWrite(YM, LOW);
  pinMode(XP, OUTPUT);
  digitalWrite(XP, HIGH);

  if (p.z > MINPRESSURE && p.z < MAXPRESSURE) {
    posX = map(p.y, TS_LEFT, TS_RT, 0, 320);
    posY = map(p.x, TS_TOP, TS_BOT, 0, 240);

    if (page == 0) {
      if (posX > 52 && posX < 268 && posY > 57 && posY < 93)  //RITMO SINUSAL
      {
        page = 1;
        choice = 1;
        tela1();
        delay(50); // debounce
      }
      if (posX > 52 && posX < 268 && posY > 117 && posY < 153)  //FIBRILACAO ATRIAL
      {
        page = 2;
        choice = 2;
        tela2();
        delay(50); // debounce
      }
      if (posX > 52 && posX < 268 && posY > 177 && posY < 213)  //ECTOPIA VENTRICULAR
      {
        page = 3;
        choice = 3;
        tela3();
        delay(50); // debounce
      }
    } else {
      // Verifica o botão de voltar
      if (posX > 30 && posX < 50 && posY > 10 && posY < 30)  //botão voltar
      {
        telainicial();
        page = 0;
      }
    }
  }
  if (page == 1) {
    plotECG(); // Ritmo Sinusal
  } else if (page == 2) {
    plotECG(); // Fibrilação Atrial
  } else if (page == 3) {
    plotECG(); // Ectopia Ventricular
  } else if (page == 4) {
    plotECG(); // Arritmia Supraventricular
  }

  // Always send the choice value to the serial port
  Serial.print("Choice: ");
  Serial.println(choice);

}

// Function to draw the ECG grid
void drawECGGrid() {
    int smallSquareSize = 10; // 10 pixels for small squares
    int largeSquareSize = 50; // 50 pixels for large squares

    uint16_t smallGridColor = GREY; // Light grey color for small squares
    uint16_t largeGridColor = 0x7BEF; // Darker grey color for large squares

    // Draw the small squares
    for (int x = 0; x <= tft.width(); x += smallSquareSize) {
        tft.drawFastVLine(x, 0, tft.height(), smallGridColor);
    }
    for (int y = 0; y <= tft.height(); y += smallSquareSize) {
        tft.drawFastHLine(0, y, tft.width(), smallGridColor);
    }

    // Draw the large squares
    for (int x = 0; x <= tft.width(); x += largeSquareSize) {
        tft.drawFastVLine(x, 0, tft.height(), largeGridColor);
    }
    for (int y = 0; y <= tft.height(); y += largeSquareSize) {
        tft.drawFastHLine(0, y, tft.width(), largeGridColor);
    }
}

what is the answer? ... what caused the problem?

I see that those are two different approaches for the same question. I think the second code example is better as it creates pages and refreshes the screen based on what the user touches. Instead of having multiple functions to handle the page selection.

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


text:
Powering SG90 Servo with 18650 battery
I want to power one SG90 servo with an 18650 3.7v battery. Since the working range for the servo is 4.8v-6v, I used XL6009 boost converter and got a 5.8v output. I have measured it with my multimeter. When I connected everything, it just fried my servo. I tested several of them with my Arduino connected to a 9v battery and they worked fine, but with this setup, they burn.
I tested every component and wire separately for continuity and voltage. The wires I connect to the servo give 5.8v and the PWM wire gives a variable signal as per the "Sweep" example code. The code itself is correct since it works with Arduino connected directly.
What is wrong?
Could anyone suggest an article of book to read regarding this? My distant goal is to create a hexapod with 18 servos powered by 18650.

It is powered by a micro-USB cable from the computer. Schematic is the same as in official docs, except for the XL6009 boost converter - https://docs.arduino.cc/static/9521df5ddacc221dd7560ba80e2acc3e/29114/servo_circuit_knob.png

I tested several of them with my Arduino connected to a 9v battery ... the 9 V battery is not able to provide enough current to burn the servo

I was answering the question that was later deleted. Please, read carefully, with 9v battery it works fine, that's 18650 with boost converter that fried the servo.

read my comment again

As the SG90's maximum voltage rating is 6v, running it at 5.8v can heat it up quite a bit. Even if it worked, running it on 5.8v is not a good long term solution. Your servo probably burned up because of the heat it generated. 5V is pretty much the safe spot for running a SG90 servo.
The servo worked with the arduino and the 9v battery because the arduino has a built-in voltage regulator, and gives a regulated 5v power supply to it's 5v pin (and the I/O) so your servo was getting 5v from the arduino, not anything higher or lower.
I did some research and it says that the lowest output voltage of the xl6009 boost converter is 5v, so see if you could make the voltage lower.
I recommend buying another of the same battery and connecting both together, then using a voltage regulator module to reduce the voltage to 5v.


text:
Sleep and Wake Arduino Nano 33 BLE
I'm trying to figure out how to wake up and put to sleep the Arduino Nano 33 BLE. I have seen a few post about it but absolutely nothing I can understand or implement. I'm attaching a subset of the code below because the whole thing is 20 pages. But the declarations, setup and loop show what I'm trying to do. The first if statement in the loop is where I would like to put the code to wake it up. The second If statement is where I would like to put the Arduino to sleep. I can provide the rest of the code if needed but its really 20 pages of functions that all work without issue.
Any help would be appreciated.
// Note this program uses a watchdog timmer.
// It is required to reset the Arduino by two presses of the reset button and setting available com ports prior to upload.
// After upload the com port needs to be reset.

// Define Global Constants /////////////////////////////////////////////////////////////////

// constants thet are desirable to adjust during debugging.
const bool SerialStatus = true;               // Set to true to hold serial printing until the serial printer is started. Set to false to release hold for stand alone use
const bool WDTStatus = false;                 // Set to true to activate the Watch Dog Timmer, Set to false to deactivate for debugging
const unsigned long WDT = 30;                 // Watch Dog Timer max time seconds This must be greater than the time requird to complete a cycle

// Constant for voltage sensing
const unsigned long Resistor1 = 33000L;       // Voltage divider resistor #1
const unsigned long Resistor2 = 3300L;        // Voltage divider resistor #2
const float BoardV = 3.3;                     // Board operating voltage
const float VMult = BoardV*((Resistor1 + Resistor2)/Resistor2)/1023L;        // Voltage multiplier to get voltage from analogread pin "VsnPin"
const float EngineOnVoltage = 13.2;           // Voltage at which the engine is considered to be running
const float KeyOnVoltage = 12;                // Voltage at which the key is considered to be on
const long PostRunInterval = 30;              // Time the fan will run after engine shut down

// Constanst for program control
const int frequency = 10.0;                   // Set fan frequency
const int NumberOfSamples = 20;               // Sent number of data samples for averaging.
const int BlinkTimeOnTest  = 2000;            // Blink time on period for initial circuit test
const int BlinkTimeOn      = 500;             // Blink time on period
const int BlinkTimeOff     = 500;             // Blink time off period

// Constants for Arduino board configuration
const int VsnPin  = A0;                       // Circuite 15 Voltage level sensing pin
const int RadPin  = A1;                       // Radiator Input Thermister
const int CndPin  = A2;                       // Condenser Input Thermister
const int AuxPin  = A3;                       // Auxilary Input
const int FanPin  = D9;                       // Set Fan pin
const int LED1Pin = D4;                       // Set Cooling Fan LED
const int LED2Pin = D3;                       // Set Condenser Fan LED
const int LED3Pin = D2;                       // Set Aux Fan LED

////////////////////////////////////////////////////////////////////////////////////
void setup()
{
  // put your setup code here, to run once:
  pinMode(VsnPin, INPUT);
  pinMode(RadPin, INPUT);
  pinMode(CndPin, INPUT);
  pinMode(AuxPin, INPUT);
  pinMode(LED1Pin, OUTPUT);
  pinMode(LED2Pin, OUTPUT);
  pinMode(LED3Pin, OUTPUT);
  pinMode(FanPin, OUTPUT);
  pinMode(LED_BUILTIN, OUTPUT);

////////////////////////////////////////////////////////////////////////////////////
void loop()
  {

  if (VMult*analogRead(VsnPin) > EngineOnVoltage)
    {
      // Wake Nano 33 BLE
    }
  if (RunFan() == false)
    {
      //Put Nano 33 BLE to sleep
    }
  if (RunFan() == true)                          // Run the fan if apropriate
    {
    // wait for a Bluetooth® Low Energy central
    BLEDevice central = BLE.central();
    // if a central is connected to the peripheral:

If your MCU is in sleep mode, it won't execute the if statement to read the analog input. You need to either set up a timer to wake up periodically or with a hardware comparator with the analog input as the input and compare to a threshold reference voltage to generate a trigger signal to wake up the MCU.

Also posted in https://forum.arduino.cc/t/putting-the-nano-33-ble-to-sleep-and-waking-it/1320717

your sketch has a lot of irrelevant code lines

I guess my first priority is to figure out how to get it in and out of sleep mode. Then I can look into what runs or doesn't when its asleep. I certainly expect that to be a hurdle.


text:
TX and RX texts on sim800c on a sim that isnt payg
Well I managed to send and receive texts on one of my sims but my smarty sim (three network), doesnt like it and so I followed the right steps to find out why:
(see what networks are available and auto connect or manual connect. I also found from smartys website that there is reception here)
sendCommand("AT+COPS=?");
+COPS: (3,"vodafone","voda UK","23415"),(3,"T-Mobile","TMO UK","23430"),,(0-4),(0-2)
so smarty also uses vodafone so below
sendCommand("AT+COPS=1,2,\"23415\""); //
sendCommand("AT+CREG?"); // Check network registration

The code is fine as it worked with my other sim - is there anything I need to know here that anyone could tell me as you guys have more experience. Please.
#include <SoftwareSerial.h>

// com3
/*
  Check Network Compatibility: Ensure that the SIM800C module supports the frequency
  bands used by Smarty. The SIM800C typically supports quad-band frequencies
  (850/900/1800/1900MHz), which should cover most networks.
  = yes 900

  Manual Network Registration: Try manually registering on the Smarty network using
  the correct MCCMNC (Mobile Country Code and Mobile Network Code). You can find this
  information on Smarty's website or by contacting their customer support.
  = 23415
*/
SoftwareSerial sim800(7, 8); // RX, TX

void setup() {
  Serial.begin(9600);
  sim800.begin(9600);
  delay(1000);

  // Initialize communication
  sendCommand("AT");
  sendCommand("AT&F");  // Factory reset
  sendCommand("AT&W");  // Save settings
  sendCommand("AT+CMGF=1");  // Set SMS mode to text
  sendCommand("AT+CSQ"); // Check signal quality
  // sendCommand("AT+COPS=?");
  // +COPS: (3,"vodafone","voda UK","23415"),(3,"T-Mobile","TMO UK","23430"),,(0-4),(0-2)
  // so smarty also uses vodafone so below
  // sendCommand("AT+COPS=1,2,\"23415\""); //
  sendCommand("AT+CREG?"); // Check network registration

  sendSMS("+1234", "Arduino hobbyist");
}

void sendCommand(const char* command) {
  sim800.println(command);
  delay(1000);
  printResponse();
}

void sendSMS(String number, String message) {
  sendCommand("AT+CMGF=1");  // Ensure text mode
  sim800.print("AT+CMGS=\"");
  sim800.print(number);
  sim800.println("\"");
  delay(2000); // Wait for the > prompt
  printResponse();

  sim800.print(message);
  delay(1000);
  sim800.write(26);  // CTRL+Z to send the message
  delay(5000); // Wait for the message to be sent
  printResponse();
}

void printResponse() {
  while (sim800.available()) {
    Serial.write(sim800.read());
  }
}

void loop() {
  // Only monitor responses, do not send messages in loop
  if (sim800.available()) {
    Serial.write(sim800.read());  // Read from SIM800 and write to Serial Monitor
  }
  if (Serial.available()) {
    sim800.write(Serial.read());  // Read from Serial Monitor and write to SIM800
  }
}

a SIM card does not do any communication ... it is only an authentication key ... which module is the SIM card plugged  into?

It will be more useful to provide the Serial Monitor output data to see how the SIM800 handshake with the network. Also, you don't need the Arduino to test out the SIM800, all you need is a terminal and manually type out the AT commands. Once that work, you can write your code accordingly.

Of course: ```112:57:12.072 -> AT+CMGF=1
12:57:12.072 -> OK
12:57:13.087 -> AT+CSQ
12:57:13.087 -> +CSQ: 20,0
12:57:13.087 ->
12:57:13.087 -> OK
12:57:14.079 -> AT+CREG?
12:57:14.115 -> +CREG: 0,0
12:57:14.115 ->
12:57:14.115 -> OK
12:57:15.094 -> AT+CMGF=1
12:57:15.126 -> OK
12:57:17.120 -> AT+CMGS="+1234"
12:57:17.166 -> > Arduino hobbyist
12:57:29.836 -> ERROR

sorry thats hard to read - i dont know how to format it in comments. is what i put the same as the handshake debug? it would be good to see more like a tcp handshake.

Use AT+CREG? or AT+COPS? to confirm if the SIM800C module successfully registers on the Smarty network.
+CREG: 0,1 or +CREG: 0,5 indicates successful registration.


text:
Problem to store values from Arduino MKR 1010 to mysql?
I have problem to store values to MySQL table from Arduino MKR 1010 Wifi.
I get the following message.
trying
got: 0 retrying
trying
got: 0 retrying
ERROR!

I have also tried to turn off firewall without success.
Is my code wrong? Can someone help me with this issue?
#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
#include <MySQL_Encrypt_Sha1.h>
#include <MySQL_Packet.h>
#include <DHT.h>
#include <DHT_U.h>
#include <dht.h>
#include <WiFiNINA.h>
#include <wifiinfo.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

#define DHT22_PIN 7
#define DHTTYPE 22
DHT deviceMonitor(DHT22_PIN,DHTTYPE) ;

IPAddress server_addr(192,168,86,39);  // IP of the MySQL *server* here
char user[] = "root";              // MySQL user login username
char password2[] = "test1234";        // MySQL user login password

char ssid[] = SECRET_SSID;        // your network SSID (name)
char password[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the Wifi radio's status

float hum;
float temp;
float humError;
float tempError;
int checkTemp;

char INSERT_DATA[] = "INSERT INTO weather (temp, hum) VALUES ('%s','%d')";
char query[128];
char temperature[10];

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to network: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, password);

    // wait 10 seconds for connection:
    delay(10000);
  }

  // you're connected now, so print out the data:
  Serial.println("You're connected to the network");

  Serial.println("----------------------------------------");
  printData();
  Serial.println("----------------------------------------");

  if (conn.connect(server_addr, 3306, user, password))
  {
    delay(1000);
  }
  else
  {
     Serial.println("Mysql connection failed.");
  }
    }

void loop()
{
  delay(5000);
  if (conn.connect(server_addr, 3306, user, password2)) {

    MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
    checkTemp = deviceMonitor.read(DHT22_PIN);
    hum = deviceMonitor.readHumidity();
    temp = deviceMonitor.readTemperature();
    Serial.println((String)"Temperature: " + temp + " Celsius");
    Serial.println((String)"Humidity: " + hum +"%");
    Serial.println();
    sprintf(query, INSERT_DATA, temp, hum);
    cur_mem->execute(query);
    delete cur_mem;
    Serial.println("Data recorded.");
    delay(10000);
 }
 else
 {
   Serial.println("ERROR!");
 }
}

void printData()
{
  Serial.println("Board Information:");
  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  Serial.println();
  Serial.println("Network Information:");
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.println(rssi);

  byte encryption = WiFi.encryptionType();
  Serial.print("Encryption Type:");
  Serial.println(encryption, HEX);
  Serial.println();
}

Your output listing seems to have nothing to do with the the code you're apparently trying to run.

I granted full right to user root in MySQL and now got this error instead.
ERROR: Timeout waiting for client.
Error: -1 = Mysql connection failed.

Can someone help me with this problem?

Not an answer..


text:
Arduino code for thermistor respiratory monitor
I have designed a thermistor-based respiratory monitor which detects changes in temperature during respiration, but I am having problems with the coding part. Can someone help, my code given below is not working.
void setup() {
  Serial.begin(9600);
}
unsigned long timer;
void loop(void)
{
    delay (500)
  int sensorValue = analogRead(A0);
timer=millis ();
    if ( sensorValue<200) {
unsigned long currentTime = millis();
float period_respiration = currentTime-timer;
float breathrate= 60000/period_respiration;
Serial.println("Respirations per minute:");
Serial.println(breathrate);
  }
}

The sensor value is 600-800 during inspiration, and about 100 during expiration.

Do you want to know how long the expiration takes ? Please explain what you want to do. Do you want to count the number of expirations per minute ? Then it would take a minute before the first number can be calculated. The solution is in this: https://www.arduino.cc/en/Tutorial/StateChangeDetection and this: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay I think you want to measure a full cycle of inspriration and expiration and with that calculate the number of respirations per minute that would result into. If that is the case, please edit your question and explain it.

The OP wants to calculate the instantaneous respiratory rate. He's almost there, with a few little problems. See my answer below

may i know the value is set based on what? -Serial.begin(9600) -sensorValue > 300 -breathrate = 60000 -sensorValue < 200

The primary reason your code doesn't work is very simple: every time you go around the loop you set
timer = millis();

and if the reading is greater than 200 you set
currentTime = millis();

but those two statements are executed just a few microseconds apart, so the difference between them (in milliseconds) will almost always be zero (it might occasionally be one if you happened to cross a tick boundary, but it will never be more than that).
There are a few other problems with the logic of your code, which I think you'll understand when you look at some code that will work. Try something like this:
enum respState {
    Inhaling,
    Exhaling
};
unsigned long prevRespTime = 0;
unsigned long currRespTime = 0;
respState currentRespState;
int movingAvgRespRate = 0;

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

void loop()
{
    //delay(500);
    // don't need to delay because we'll only fire once per inhalation and once per exhalation
    int sensorValue = analogRead(A0);

    if ((sensorValue > 300) && (currentRespState == Exhaling))
    {
        currentRespState = Inhaling;
        prevRespTime = currRespTime;  // save time from last cycle
        currRespTime = millis();

        float period_respiration = currRespTime - prevRespTime;
        float breathrate = 60000 / period_respiration;
        Serial.print("Inhaling /tRespirations per minute: ");
        Serial.println(breathrate);
    }
    else if ((currentRespState == Inhaling) && (sensorValue < 200))
    {
        currentRespState = Exhaling;
        Serial.println("Exhaling");
    }
}

The above code will give you the instantaneous respiratory rate, which probably will jump around a bit more than you would like. You probably want to add some dependency on prior history (hysteresis) to smooth it out a bit. One easy way is to put this through a low-pass filter algorithm to get a moving average value for the respiratory rate. That way the rate goes up when you breathe faster and down when you breathe slower but it doesn't instantaneously jump around on every breath.  Here's what that might look like:
// Global variables
enum respState {
    Inhaling,
    Exhaling
};
unsigned long prevRespTime = 0;
unsigned long currRespTime = 0;
respState currentRespState = Exhaling;
float breathrate = 0;
int movingAvgRespRate = 0;

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

void loop()
{
    //delay(500);
    // don't need to delay because we'll only fire once per inhalation and once per exhalation
    int sensorValue = analogRead(A0);

    if ((sensorValue > 300) && (currentRespState == Exhaling))
    {
        currentRespState = Inhaling;
        prevRespTime = currRespTime;  // save time from last cycle
        currRespTime = millis();

        float period_respiration = currRespTime - prevRespTime;

        if (period_respiration == 0)
            breathrate = 0;
        else
            breathrate = 60000 / period_respiration;

        Serial.print("Inhaling /tResp Rate: ");
        Serial.print(breathrate);

        if (movingAvgRespRate == 0)
            movingAvgRespRate = breathrate;
        else
            movingAvgRespRate = (int) ((0.2 * breathrate) + (0.8 * movingAvgRespRate));

        Serial.print("/tAvg Resp Rate: ");
        Serial.println(movingAvgRespRate);
    }
    else if ((currentRespState == Inhaling) && (sensorValue < 200))
    {
        currentRespState = Exhaling;
        Serial.println("Exhaling");
    }
}

This code compiles, but I did not happen to be near an arduino with a sensor, so I didn't run it -- there could be issues, but this should be enough to put you on the right track. Good Luck!

This code is missing 2 critical components.  First, with out some form of hysteresis it is unlikely the program will respond in a dependable manner. Second, it would be best if a finite state machine were utilized to assist in the collection of data and calculation of a reparation rate.  In this case, 4 states to track exhale, transition from exhale to inhale, inhale & transition from inhale to exhale.

Aside from all the useful code provided, here is some additional input for a relatively accurate flow measurement using thermistors. Sage metering provides a useful overview of the most established modes of operation. You'd need an array of two or more thermistors; by heating the central element and measuring the temperature field displacement induced by the flow using the other thermistors you would get a really accurate reading. Google Scholar has a lot of papers on constant temperature and constant current flow meters.
Also, I suppose you are using some short of tubing where you inhale/exhale; there is a critical length for this tube, where you would want to place your sensors to measure a good, steady flow (this is called laminar flow). You can look up Reynolds number and laminar - turbulent flow in pipes; I can say from experience that after approx. 15cm you would measure well, but have a reading, this is really interesting information on setting up a proper measurement setup.

This answer is interesting, but does not address the question of the OP which is explicitly about the code (hence placed on the Arduino stack exchange).

Yeah, I agree, but it's a pitty to write all the code and go measure differently everyday, or have your code spitting out different results for any person breathing on it. I get your comment though, thanks.

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


text:
Arduino Nano + RFID RC522 + Ethernet shield W5100
I have this Arduino Nano, Ethernet shield W5100 and RC522 as card reader. They are sharing pins D13, D12, D11, D10 is SS pin for W5100 D8 is SS pin for RC522. Problem is with pin D12, like it doesn't share it.
For example if I unplug D12 from W5100 RC522 reader works, if I wire it back it doesn't work anymore. W5100 works no matter if RC522 is wired or not, so problem would be somehow with pin D12.
Does anybody have some ideas, what I'm doing wrong right here?

I had almost exactly this situation with one of my projects.
The problem is that some Serial Peripheral Interface (SPI) devices don't properly put the MISO pin into high-impedance when SS is pulled high. I eventually resolved this by placing a tri-state buffer in the MISO line for each of the SPI devices.
I used a 74HC125 (4-channel tri-state buffer).
This is the page on Better SPI Bus Design in 3 steps that finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).

Can you tell me little bit more, because I don't understand it very well. I'm kind a new into Arduino and IoT projects and also in electronic's part.

@noname I'm just looking for the page the got me on the right direction. Bear with me for a few minutes ...

@noname I've added the link. Hope that helps you out.

Does this change contains also any hardware changes?

@noname That depends on whether your RFID & Ethernet shield already have tri-state buffers on the MISO line. Mine didn't, so I had to add the 74HC125.

This doesn't help me really a lot...

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


text:
Arduino Serial Communication Between 2 Uno
I'm trying to get two arduino uno to communicate. The slave reads a temp sensor as an analog value, then converts it to degrees C, then sends that value to the master, the master then prints the value to the serial monitor. This is the code I have thus far.
for the slave
const int tempPin = A0;

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

  void loop() {

   //read sensor data to a variable
   float volt = analogRead(tempPin) * 0.004882814;
   float degC = (volt - 0.5) * 100.0;
   Serial.println(degC);

   delay(2000); //Not to flood serial port
  }

this is the code for the master
float tempC;
void setup(){
  Serial.begin(9600);
  delay(2000);
 }

  void loop() {
 /**  check if data has been sent from the computer: */
 while (Serial.available()) {
 /* read the most recent byte */
    tempC = Serial.read();     //now byteRead will have latest sensor
                              // data sent from Arduino1

    Serial.println(tempC);
  }
}

My issue is that I am reading on the serial monitor 4 different 2 integer values

What exactly are you seeing in the serial monitor? What does "4 different 2 integer values" mean?

The code comes from this: https://arduino.stackexchange.com/questions/16227/sending-a-value-from-one-arduino-to-another That example for sending and receiving a single byte. You want to send a text (a text that shows a floating point number), so you will have to read that complete text.

Your slave is sending an array of characters and your master is reading the ASCII values of those characters.
If you send 25.43, Serial.println will send 7 characters 2, 5, ., 4, 3, carriage return and a newline.
The master will read them as 50, 53, 46, 52, 51, 13 and 10. Your code then prints:
50.00
53.00
46.00
52.00
51.00
13.00
10.00

On your master, the loop() should look like:
void loop() {
  if (Serial.available()) {
    char c = Serial.peek(); // just look at the next character on the serial buffer
    if (c == '\r' || c == '\n') // ignore the carriage return and newline characters
      Serial.read(); // remove the character from serial buffer by reading it
    else {
      tempC = Serial.parseFloat(); // read and parse the string representing the float value
      Serial.println(tempC);
    }
  }
}

The value is floating point, not integer.  Reading the integer part would be a start, though that will truncate rather than round.  Possible solutions are parsing the float, rounding to an integer on the sender, or something like multiplying by 100, rounding, sending that, and then on the receiver copying the multiplied value to a float and dividing it back.

I fixed it, so it properly reads the floating point value.


text:
Arduino Uno synthesizer - Line Level (audio) output to mixer/amplifier
Is using PWM tones from Arduino amplified by a HiFi amplifier safe? Can I damage the amplifier or speakers because the PWM signal is not a "real" audio signal? Taken in consideration that I do not clip the signal and using a RC Low Pass Filter to filter out inaudible frequencies and using a LM386 amplifier chip to amplify and control the volume?
I am developing a synth/sampler project based on the Arduino Uno r3. This is my first electronics project ever and because of that reason I have some questions which I can't find a definite answer for on internet.
The synth has two function. It has a tone generator using the ToneAC library. With code I have mimicked LFO and VCO functions, using potentiometers I can adjust the frequency and LFO speed realtime. The other function is that I can trigger samples stored on a SD card using the TMRpcm library. The lowest frequency which can be played is 100hz and the highest 3100hz.
The device will be used in nightclubs on high end sound-systems and PA. I am afraid I will damage the equipment with my device because I do not send a pure audio (AC?) signal.
Currently the flow is like this:
PWM output (pin 9, 10) -> voltage divider to 2.5v -> RC Low Pass Filter 15Khz -> LM386 amp with volume control -> mono jack output -> mixing desk -> amplifier -> speakers
(the TMRpcm and ToneAC library share the same pin (9), I have fixed this by disabling the TMRpcm when the ToneAC is playing and vice versa. The mono jack is wired as follow. pin 9 goes to plus side of mono jack output, pin 10 to negative side. The TMRpcm pin 9 also needs to go to plus side of mono jack output, and mono jack negative needs to go to ground. Because I disable the ToneAC at that time I consider port 10 grounded because it not generating any sound so there is no signal/voltage running out of it, aka the IO pin is set to LOW)
I am hoping that using the voltage divider I am within range of the Audio Line levels of a default mixers Line-IN (like Pioneer, Behringer, etc). The RC Low Pass Filter is used to filter of inaudible frequencies and clean up the sound a bit, the LM386 audio amp is used to amplify the signal and (hopefully) make it a real audio signal.
Because I lack a lot of knowledge in this field and because I do not own a oscilloscope I can't say for sure if my output signal is harmful for the equipment and was hoping to get some guidance on my project on this forum.

Questions on stack exchange forums get better answers, the more specific you can make your question. Asking for guidance doesn't help someone know how to help you and the responses are likely not to be well focused. Also, this question sounds more about audio electronics than Arduinos, even though you're using an Arduino host. If so, it may be a better fit for the Electrical Engineering stack exchange site.

Point taken, I've redefined the question

In theory, the peak signal accepted from your amplifier should be 0.894V p2p if you want to rescpect the common -10dB signal strength/level. I don't know why you would want to have a 5V to 2.5V "voltage divider" in the first place, but in any case if you use that you already limit the current probably enough, it all depends on the resistor values used.
Using the LM386 amplifier is also simply not required at all, since the Arduino is already providing more than enough power. If you want to tune the volume at that stage, simply combine all functions (volume, low pass and current limit) by connecting the 5V PWM output thru a resistor (eg. 4k7) to a POT (eg. 1k) in parallel with the capacitor (eg.2n2) would give you approximately what you want. Then to remove de DC component, add a series capacitor (eg. 1uF) and you're all set. You may still hear a "click" when you connect it to the amplifier though, so keep the faders low when connecting.
Of course you can adapt the values quite liberally, but these values are both safe and should be close to what is needed (cutoff 15kHz, Vpp 0.88V max).

Thanks for the detailed answer. I already found out that I need to pass the signal through a 10uF capacitor so it looks like the +/-2.5V AC signal. Send that through a resistor divider and bring it down to +/- 1V (line level) for feeding into audio amplifier. LM386 is indeed not necessary. This should do the trick :)


text:
Replace char based on user input
I am developing a hangman game on tinyduino(tinycircuits) and I am currently stuck on how to properly replace a char based on user input within a for loop. My current code does actually replace the correct underscore(blank), if a user inputs a correct letter.
As per the game hangman, it will print out a series of blanks(in my case, underscores) based on number of letters, that serve as placeholders for the correct letter and will reveal the letter only if a user inputs a correct letter.
However, whenever a user inputs another correct letter (after inputting a correct letter prior), my program creates another 'line' and replaces the underscore in that new line instead.
For example, say the word to guess is kotlin. If user inputs 'k', my console shows me:
k_____

The output above is still correct.
But, when the user inputs another letter, say 'o' which is also correct, the result I get is:
k______o____

To further re-emphasize, now if a user inputs 't', I would get:
k______o______t___

What do I need to modify in my code in order to replace the underscores in the original line whenever a user enters a correct letter? Below is my current code.
if (k == 1) { // Str1 is "kotlin"
    display.setCursor(10,50);
    length = strlen(Str1);

    String user_input = String(phone_input);
    String word = String(Str1);

    for (i = 0; i < length; i++) {
      word[i] = '_';

      if (user_input == "k") {
        word[0] = 'k';
      }

      if (user_input == "o") {
        word[1] = 'o';
      }

      if (user_input == "t") {
        word[2] = 't';
      }

      if (user_input == "l") {
        word[3] = 'l';
      }

      if (user_input == "i") {
        word[4] = 'i';
      }

      if (user_input == "n") {
        word[5] = 'n';
      }

      display.print(word[i]);
      SerialMonitorInterface.print(word[i]);
    }
  }

why does it have to be in a for loop?

print your code on paper ... get a pencil ... go through your code step by step ... make notes about values of variables ... it may help you discover why your code does not work as you think that it does

The logic of your code seems confused. The loop doing word[i]='_'; belongs the initialization phase, which is performed only when a new game is started. The tests on user_input belong to the regular “play” phase. I suggest you move the “initialize a new game” logic into its own function, and think carefully about what kind of event should trigger the start of a new game. Also, you print() the current guess without erasing the previously printed ones, and without moving the cursor to the next line. Try println() instead.

@EdgarBonet could you elaborate more about println() and moving the cursor?

@jsotola it is in a for loop because every instance a user inputs a correct character, the for loop should replace the specific index's underscore. Is there a better method to approach this?

Attention  spoiler (If it's ok for you just to enhance it to a playable version by enhancing the shortcuts! )
If you want to replace single characters in a word, String and
std::string is way too much overhead. Use good old char [] instead.
const char* result { "kotlin" }; // shortcut
const size_t size = 6; // shortcut

char guess[size+1]; // The guessed intermediate result

const byte wrongMax = 22;
byte wrong = 0; // number of wrong guesses

void setup() {
  for (char& c : guess) c='_';
  guess[size] = 0;

  Serial.begin(9600);
  Serial.println(guess);
}

void loop() {
  if (strcmp(result,guess)== 0) {
    Serial.println("Got it !"); while (1){} // Stop, reset required
  }
  if (wrong >= wrongMax) {
    Serial.println("Failed !"); while (1){} // Stop, reset required
  }

  int c = Serial.read();
  if (c >= 'a' && c <= 'z') {
    // shortcut: only lower characters allowed
    byte p;
    for (p=0; p < size; p++) {
       if (c == result[p] && guess[p] == '_') {
         // found a new correct one
         guess[p] = c;
         break;
       }
    }
    if (p == size) {Serial.print( ++wrong ); Serial.println( " wrong guesses");}
    Serial.println (guess);
  }
}


text:
I have 2 sketches with same RTC DS1307 but when I combine the 2 sketches it gives errors
I have 2 sketches one is pixel clock with RTC ds 1307 and the other is 7 Segment with DHT 11, I want to merge the two into one but it is giving errors for rtc.
sketch for pixel clock
#include <Wire.h>
#include <RTClib.h>
#include <Adafruit_NeoPixel.h>

#define PIN 6
#define PIXEL 60

Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL, PIN, NEO_GRB + NEO_KHZ800);

RTC_DS1307 RTC; // Establish clock object
DateTime Clock; // Holds current clock time

byte hourval, minuteval, secondval;

void setup() {
 Serial.begin(9600);
  Wire.begin();          // Begin I2C
  RTC.begin();   // begin clock

    if (! RTC.isrunning()) {
//  Serial.println("RTC is NOT running!");
  // following line sets the RTC to the date & time this sketch was compiled

  }

//  RTC.adjust(DateTime(__DATE__, __TIME__));
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
  strip.setBrightness(20);

}

sketch for 7 segment
#include <Time.h>        //Time Library
#include <TimeLib.h>
#include <DS1307RTC.h>   //Real Time Clock Library
#include <Wire.h>        //Auxiliary Library for DS1307RTC (Real-Time Clock) - Pins to Arduino UNO: A4 (SDA), A5 (SCL)
#include <DHT.h>         //Temperature and Humidity Library

#define DHTPIN 8         //Sensor DHT11  conected to the pin 8 on Arduino

// Definition of what DHT sensor type you are using
#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

DHT dht(DHTPIN, DHTTYPE);

int clockPin = 13; // Pin 13 of Arduino connected in the pin 11 of 74HC595 (Clock)
int latchPin = 10; // Pin 10 of Arduino connected in the pin 12 of 74HC595 (Latch)
int dataPin = 11; // Pin 11 of Arduino connected in the pin 14 of 74HC595 (Data)

int hora, minuto, temp, umid;
int unidadeHora, unidadeMinuto, dezenaHora, dezenaMinuto;
int unidadeTemp, dezenaTemp, unidadeUmid, dezenaUmid;
unsigned long ti;
int brightness; // Brightness of display (Min=1 / Max=20)
int k;

//Digits Matrix - 0 a 9
byte num[] = {
  B01111110, // Zero
  B00110000, // One
  B01101101, // Two
  B01111001, // Three
  B00110011, // Four
  B01011011, // Five
  B01011111, // Six
  B01110000, // Seven
  B01111111, // Eight
  B01111011, // Nine
};

void setup() {

  pinMode(latchPin, OUTPUT); // Define the 3 digital pins as output
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

  dht.begin();

  setSyncProvider(RTC.get);   // Update the time with data of RTC (Real Time Clock)
  setSyncInterval(300);       // Set the number of seconds between re-sync

  //setTime(hours, minutes, seconds, days, months, years);
  //setTime(15, 05, 00, 13, 02, 2016);
  //RTC.set(now());           // Set the RTC time

  brightness = 15; // Set the brightness of display (Min=1 / Max=20)

}

error in the
void loop{
a function-definition is not allowed here before '{' token

E:\pixel_clock_with_7_segment\pixel_clock_with_7_segment.ino: In function 'void setup()':

pixel_clock_with_7_segment:86:15: error: a function-definition is not allowed here before '{' token

   void loop() {

E:\pixel_clock_with_7_segment\pixel_clock_with_7_segment.ino: At global scope:

pixel_clock_with_7_segment:257:1: error: expected declaration before '}' token

 }

Can anybody help me in merging the two sketches as I am new to Arduino programming?

you cannot have multiple functions with the same name ... you have two functions named setup() ... change the name of one, or merge them

Does this answer your question? How do you combine 2 different sketches together It describes the general principles to follow for combining 2 sketches (which isn't as easy as just copy&pasting everything in one sketch).


text:
ESP8266 (D1 mini) fails to upload sketches
My Setup: 3.3v LiFePo battery attached to G and 3.3 pins. Serial-USB connected.
Result: During the following code the blue on-board LED blinked rapidly for a few seconds then went off. I unplugged it to see if it was programmed but the Blink Sketch didn't run. Any help would be greatly appreciated.
Sketch uses 222,205 bytes (21%) of program storage space. Maximum is 1,044,464 bytes.
Global variables use 31,572 bytes (38%) of dynamic memory, leaving 50,348 bytes for local variables. Maximum is 81,920 bytes.
C:\Users\jhoxie\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.9/esptool.exe -vv -cd nodemcu -cb 115200 -cp COM3 -ca 0x00000 -cf C:\Users\jhoxie\AppData\Local\Temp\arduino_build_351972/Blink.ino.bin
**(Everything below this line was highlighted in red)**
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 226352 bytes from C:\Users\jhoxie\AppData\Local\Temp\arduino_build_351972/Blink.ino.bin to flash at 0x00000000
    erasing flash
    size: 037430 address: 000000
    first_sector_index: 0
    total_sector_count: 56
    head_sector_count: 16
    adjusted_sector_count: 40
    erase_size: 028000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting serial port timeouts to 15000 ms
    setting serial port timeouts to 1000 ms
    espcomm_send_command: receiving 2 bytes of data
    writing flash
................................................................................ [ 36% ]
................................................................................ [ 72% ]
..............................................................                   [ 100% ]
starting app without reboot
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
closing bootloader
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete

The uploading seems to work. Please post your code and settings in the IDE. It's not a good idea to connect a battery to the 3.3V pin while plugged into USB.

How do you know the code isn't working?  You might want to check the code is using the correct GPIO port. You upload looks OK, the flashing blue light sounds right, so I think you might be using Arduino Blink.

Thank you for your input. Especially the tip on connecting the battery while connected to usb [tttapa] I finally got it to work by changing the baud rate and messing around with the settings(i.e. board in IDE). I believe I got it to work with the "WeMos D1 R2 & Mini" board whereas I was using the generic esp8266 board.


text:
Arduino code works when connected to laptop, not when connected to battery or wall socket
So I have an Arduino nano, and I am using two SG90 servos, and 1 BMP280, and 1 MPU6050. My code works fine when I plug my nano into my computer, but when I connect the battery to my nano, it doesn't run. The servo moves to 90 degrees, but it seems that it is not detecting the sensor data and not moving the servo. I commented out all calls to Serial.
Here is my code:
/***************************************************************************
  This is a library for the BMP280 humidity, temperature & pressure sensor

  Designed specifically to work with the Adafruit BMP280 Breakout
  ----> http://www.adafruit.com/products/2651

  These sensors use I2C or SPI to communicate, 2 or 4 pins are required
  to interface.

  Adafruit invests time and resources providing this open source code,
  please support Adafruit andopen-source hardware by purchasing products
  from Adafruit!

  Written by Limor Fried & Kevin Townsend for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ***************************************************************************/

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_BMP280.h>

// MPU
#include <MPU6050.h>

// Servo
#include <Servo.h>

Servo servoY;
Servo servoX;

MPU6050 mpu;

// Timers
unsigned long timer = 0;
float timeStep = 0.01;

// Pitch, Roll and Yaw values
float pitch = 0;
float roll = 0;
float yaw = 0;

#define BMP_SCK  (13)
#define BMP_MISO (12)
#define BMP_MOSI (11)
#define BMP_CS   (10)

Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

void pitch_roll_yaw(){
  // Serial.print("Pitch: ");
  // Serial.println(pitch);

  // Serial.print("Roll: ");
  // Serial.println(roll);

  // Serial.print("Yaw: ");
  // Serial.println(yaw);
  int thsjsojf = 1;
}

void setup() {
  // Servo
  servoY.attach(8);
  servoY.write(90);

  servoX.attach(9);
  servoX.write(90);

  // Serial.begin(115200);
  // while ( !Serial ) delay(100);   // wait for native usb
  // Serial.println(F("BMP280 test"));
  unsigned status;
  //status = bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID);
  status = bmp.begin();
  if (!status) {
    // Serial.println(F("Could not find a valid BMP280 sensor, check wiring or "
    //                   "try a different address!"));
    // Serial.print("SensorID was: 0x"); Serial.println(bmp.sensorID(),16);
    // Serial.print("        ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n");
    // Serial.print("   ID of 0x56-0x58 represents a BMP 280,\n");
    // Serial.print("        ID of 0x60 represents a BME 280.\n");
    // Serial.print("        ID of 0x61 represents a BME 680.\n");
    while (1) delay(10);
  }

  /* Default settings from datasheet. */
  bmp.setSampling(Adafruit_BMP280::MODE_NORMAL,     /* Operating Mode. */
                  Adafruit_BMP280::SAMPLING_X2,     /* Temp. oversampling */
                  Adafruit_BMP280::SAMPLING_X16,    /* Pressure oversampling */
                  Adafruit_BMP280::FILTER_X16,      /* Filtering. */
                  Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */

  // MPU
  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    // Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  // Calibrate gyroscope. The calibration must be at rest.
  // If you don't want calibrate, comment this line.
  mpu.calibrateGyro();

  // Set threshold sensivty. Default 3.
  // If you don't want use threshold, comment this line or set 0.
  mpu.setThreshold(3);

}

int incrementPitch = 0;
int curAngle = 90;
int incrementPitchDown = 0;

void loop() {
    timer = millis();
    // Read normalized values
    Vector norm = mpu.readNormalizeGyro();

    // Calculate Pitch, Roll and Yaw
    pitch = pitch + norm.YAxis * timeStep;
    roll = roll + norm.XAxis * timeStep;
    yaw = yaw + norm.ZAxis * timeStep;

    float normalY = norm.YAxis;

    // Serial.print(F("Temperature = "));
    // Serial.print(bmp.readTemperature());
    // Serial.println(" *C");

    // Serial.print(F("Pressure = "));
    // Serial.print(bmp.readPressure());
    // Serial.println(" Pa");

    // Serial.print(F("Approx altitude = "));
    // Serial.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */
    // Serial.println(" m");

    // pitch_roll_yaw();

    //TODO: This works, but if pitch > 1 and the servo arm is already at max, it doesn't move. Fix.
    // TODO: If pitch < 1. move the servo in the opposite way by 5 degrees. Need to track current angle.
    if(pitch>1){
      // Serial.println("PITCH IS GREATER++++++THAN 1, MOVING Y SERVO");
      servoY.write(curAngle+incrementPitch);
      curAngle = curAngle+incrementPitch;
      // Serial.print("Pitch: ");Serial.println(pitch);
      if(curAngle>180){
        // This is just so we don't print the current angle if curAngle > 180. This can be antything.
        int something = 1;
      } else {
        // Serial.print("Current Angle of Y servo: ");Serial.println(curAngle);
      }
      incrementPitch+=6;
    } else if(pitch<-1){
      // TODO: If pitch is < -1, then we move the servo in 5 degree increments starting at the current angle. Right now it jumps some degrees, check the if(pitch>1) for errors? MUST FIX.
      // Serial.println("Pitch is LESS---------THAN 1, MOVING Y SERVO");
      servoY.write(curAngle-incrementPitchDown);
      curAngle = curAngle-incrementPitchDown;
      incrementPitchDown+=6;
    }

    // Serial.println();
    delay(200);
}

ALso, none of the other threads solve my problems.

what battery are you using?

@jsotola a 9v battery

do you mean a standard 9 V block battery like these? ... https://duckduckgo.com/?q=9v+battery&iax=images&ia=images

@jsotola yes precisely

those are for powering low current devices like smoke alarms ... it is surprising that there is enough current to move the servo even once

So, what should I use to power it? I am using my Arduino in a model rocket so it can't be too heavy.

the 9 V battery contains six AAAA cells in series ... try six AA cells for testing ... you may have to choose another battery chemistry for higher power density

How long should the circuit work? It's not the capacity, but the current that's limiting you. -- You could look for a rechargeable battery like NiMH or LiIon. Make sure you read the data sheet and check that it can deliver enough current. Of course you need to find the required current, by measuring or reading the data sheets of your Arduino and the other parts like the servo.

If are you powering the servo's via your Nano (and thus the USB port), this will cause problems. The Servo's need need 500/700 mA each (>1 Amp total). My laptop USB is 500mA, so rotating two servo's will cause a power drop (voltage goes down due the draw of current).
in my experience using servo's when connected to a computer/laptop is not reliable. This will happen: the servo rotates, the power drops causing the Microcontroller to restart or cause problems (voltage) for the  sensor.

So how will I power them?

connect an external 5v supply tot the servo's (PowerBank/USB charger/5V LED driver/anything 5V). Connect this power supply to the GND of Servo's AND the board (important!).
Connect the board to the laptop via USB (now the board is powered by your laptop and the servo's via an external supply).
Upload code and test


text:
How many stepper motors can you run on one Arduino Uno? Ideas on how to run 9?
I am in middle school and new to Arduino. I just learned to set up and code a stepper motor on my Arduino Uno from watching YouTube videos.  I want to set up 9 stepper motors to all run at the same time and at the same rotation speed for a science project I am working on. Right now I have the Arduino Uno with a 830 breadboard, ULN2003 stepper motor driver and 28BYJ-48 stepper motor.  I think I will need to use something different because I can see that my driver doesn't have more than one set of plugs for the wires. I got a budget for my science project so I am allowed to buy some new equipment. But I am confused about what I need to run 9. If anyone can help to suggest the best and simplest way to do this, I would be very happy. I feel like once I have the equipment, I can try to figure out how to put it together and figure out the code. Thanks for the help!

Each step motor need 4 phase driving pins, so you will need 4x9 GPIO pins, and you already tag 'arudino-mega', so I think you know what you want already. If you are looking for driver other than ULN2003, you can research on this page, please note that this is not product recommendation, but to give the idea of the variaties available, before you make any decision on your hardware, check the availability of library for a specific driver IC.

9 stepper motors to all run at the same time and at the same rotation speed ... connect them in parallel ... control them same as one motor

You can use 4 N-Channel MOSFETs, get the logic level avalanche rated ones. Get something in the 5A or higher current range (lower RDSon). Your motors draw 240mA each. The higher the amperage rating the of the MOSFET the cooler the MOSFET will run. I am a firm believer silicon in place of heatsinks. In small it is not that expensive and you do not have the hassle of a heatsink.
You can then drive the MOSFETs from four port pins through a 50 Ohm resistor to each of the gates. Then put a 10K pull down resistor on the port pin, not the gate. Putting the pull down on the gate creates a voltage divider for the gate voltage. This is to guarantee the MOSFETs are all off when the system is first turned on and during initialization until your code takes over. I use the low gate resistors one to control oscillation and two to drive it hard so it switches faster keeping it out of the linear range where it will get hot. Be sure the Source of each output is connected to the ground of the motor power supply and that the arduino ground is also connected to this ground.
You then connect all of the motors in parallel and connect them to the drains of the MOSFET. I am assuming 4 leds (Pink, Yellow, Orange and Blue) from the motor to the MOSFETs drain and a common (Red) for +5 power.
This will give you about 1.4V more per phase when operating not dropping across the driver thereby increasing the efficiency. Also the wiring is much simpler.

Since the OP already has drivers for each motor, why not using each motor with its own driver and just connecting the 4 signal lines together?

A 50 Ω / 10 kΩ voltage divider will divide its input voltage by 1.005.


text:
READ 433mhz DEVICES
I have an issue with 433mhz reading. I have two cheap transmitter and receiver boards, the most known ones :
I followed several tutorials, and I'm using the rc switch library.
I'm trying to read the signal sent by a remote control, (stores), as I would like to duplicate it, to control the store. I firstly tried with the basic code to read 433mhz signals, but it didn't work. Assuming that there is an encryption between the two devices, (I'm not sure if that this is the case, but internet didn't help to find if it's usually the cases for those devices, and how to tell if mine has encryption, It would be nice if I can get some help on that too), I decided to upload a code to get raw data, sent by any transmissions.
The problem is that there is absolutely no data coming out from the receptor when I use the rc switch library. I have another Arduino constantly sending float values with a transmitter, and it works if I use virtualwires, but it doesn't show anything on the serial monitor with rc switch. I also tried with my store remote control, and a garage remote control, but nothing is showing up.
Here is the code of the receiver :
/*
  Example for analyzing and proposing unknown new protocols

  https://github.com/Martin-Laclaustra/rc-switch/

  Requires modified rc-switch branch "protocollessreceiver"
  with ReceivedInverted() function exposed.
*/

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
  // Use mySwitch.enableReceive(D2); for ESP8266
  Serial.println("beginned");
}

void loop() {
  if (mySwitch.available()) {

    int value = mySwitch.getReceivedValue();

    if (value == 0) {
      Serial.print("Unknown encoding");
    } else {

      int databuffer[64]; // get a copy of the received timings before they are overwritten
      int numberoftimings = 2 * mySwitch.getReceivedBitlength() + 2;
      if (numberoftimings > 64) numberoftimings = 64;
      for (int i = 0; i < numberoftimings; i++) {
        databuffer[i] = mySwitch.getReceivedRawdata()[i];
      }

      Serial.print("Received ");
      Serial.print( mySwitch.getReceivedValue() );
      Serial.print(" / ");
      Serial.print( mySwitch.getReceivedBitlength() );
      Serial.print("bit ");
      Serial.print("Protocol: ");
      Serial.println( mySwitch.getReceivedProtocol() );

      unsigned int databitsoffset = abs( (int)mySwitch.getReceivedLevelInFirstTiming() - (int)mySwitch.getReceivedInverted());
      //Serial.println( mySwitch.getReceivedLevelInFirstTiming() );
      //Serial.println( mySwitch.getReceivedInverted() );
      //Serial.println( databitsoffset );
      unsigned long dataduration = 0;
      for (unsigned int i = 1 + databitsoffset; i < numberoftimings - 1 + databitsoffset; i++) {
        dataduration += databuffer[i];
      }
      Serial.print("data bits of pulse train duration: ");
      Serial.println( dataduration );
      unsigned int averagebitduration = (int)(0.5 + ((double)dataduration) / mySwitch.getReceivedBitlength());
      unsigned int protocolratio = (unsigned int)(0.5 + ((double)(averagebitduration - mySwitch.getReceivedDelay())) / (double)mySwitch.getReceivedDelay());
      Serial.print("proposed protocol: { ");
      Serial.print(mySwitch.getReceivedDelay());
      Serial.print(", { ");
      Serial.print( (databitsoffset == 0) ?
                    (int) (0.5 + (double)databuffer[2 * mySwitch.getReceivedBitlength() + 1] / (double)mySwitch.getReceivedDelay())
                    :
                    (int) (0.5 + (double)databuffer[0] / (double)mySwitch.getReceivedDelay())
                  );
      Serial.print(", ");
      Serial.print( (databitsoffset == 0) ?
                    (int) (0.5 + (double)databuffer[0] / (double)mySwitch.getReceivedDelay())
                    :
                    (int) (0.5 + (double)databuffer[1] / (double)mySwitch.getReceivedDelay())
                  );
      Serial.print(" }, { ");
      Serial.print("1");
      Serial.print(", ");
      Serial.print(protocolratio);
      Serial.print(" }, { ");
      Serial.print(protocolratio);
      Serial.print(", ");
      Serial.print("1");
      Serial.print(" }, ");
      Serial.print((mySwitch.getReceivedInverted()) ? "true" : "false" );
      Serial.println(" }");

      // raw signal
      Serial.println("====");
      Serial.print("first level ");
      Serial.println((mySwitch.getReceivedLevelInFirstTiming() == 0) ? "down" : "up" );
      for (int i = 0; i < 2 * mySwitch.getReceivedBitlength() + 2 - 1 + databitsoffset; i++) {
        Serial.print(databuffer[i]);
        Serial.print(" ");
        if ((i - databitsoffset) % 16 == 0) Serial.println("");
      }
      if ((2 * mySwitch.getReceivedBitlength() + 2 - 1 + databitsoffset - 1) % 16 != 0) Serial.println("");
      if (databitsoffset != 1) Serial.println(databuffer[2 * mySwitch.getReceivedBitlength() + 1]);
      // plot signal in spreadsheet
      Serial.println("====");

    }

    mySwitch.resetAvailable();
  }
}

I am aware that interruptPin(0) = pin #2 on Arduino
Here is the layout :

Does anyone have an idea of why I can't get anything on my serial monitor ?, I'll take any help !

there is no encryption ... it's just a wireless wire ... connect a switch to the transmitter and an LED to the receiver ... otherwise, connect a GPIO output to the transmitter and a GPIO input to the receiver

For stores i don't think there is, but I read that garage door have that system, but don't know how to check. For the setup this is exactly what i have done : Data is going out from a GPIO to the transmitter, and reversed for the receiver. What's wrong ?

try to read with SimpleScanner, you can find sketch here:
https://github.com/sui77/SimpleRcScanner/blob/master/htdocs/Sketchbook/SimpleRcScanner.ino


text:
Making a menu through serial
I'm working on a project for a robot and I'm trying to make a menu that can run on start up where the user can calibrate the mid-point for the servos (so they're stationary) and the ldrs so it can tell between black lines and white paper. So, I've made the menu a switch case where it calls the calibration when user enters a value, the calibration routines are their own functions.
What I want to know how to do is how to make it so when the user is finished with a calibrator it will go back to the menu function and also how to get the menu to exit on user input. So far when the menu calls a function it will just loop on it.
The menu:
void Menu(){

  Serial.println("|****************************|");
  Serial.println("|**|Ardnoid Configuration |**|");
  Serial.println("|**|        Menu          |**|");
  Serial.println("|****************************|");
  Serial.println("");
  Serial.println("Select one of the following options:");
  Serial.println("1 LDR configuration");
  Serial.println("2 Servo calibration");
  Serial.println("3 Exit configuration menu");

  while(!Serial.available()){}
  int i = Serial.parseInt();

  switch(i){

  case 1:
    break;
  case 2:
    while(srvConOn == true){
      srvConfig();
      }
    break;strong text
  case 3:
    Serial.println("Leaving configuration menu");
    break;
  default:
    Serial.println("Unrecognized command, try again!");
    }
 }

and the servo calibration:
void srvConfig(){

Serial.println("");
Serial.println("Begin servo stop calibration routine");

int x = 0;

  while(x == 0){

    Serial.println("Enter values for servos until both are stationary");
    delay(100);

    Serial.println("Enter value for left servo");
    while (!Serial.available()) {;}
    left = Serial.parseInt();
    Serial.println(left);
    delay(100);

    Serial.println("Enter value for right servo");
    while (!Serial.available()) {;}
    right = Serial.parseInt();
    Serial.println(right);
    delay(100);

    srvR.write(right);
    srvL.write(left);

    Serial.println("have both servos stopped?");
    Serial.println("1 = Yes | 2 = No");

    int j;
    while (!Serial.available()) {;}
    j = Serial.parseInt();

    if (j == 1) {
      Serial.println("Saving calibration");
      EEPROM.write(leftMid, left);
      EEPROM.write(rightMid, right);
      srvConOn == false;
      x == 1;
      } else if (j == 2) {
        Serial.println("Try again");
        Serial.println();
        }
  }
}

You could put your switch/case inside an infinite loop, and return from
the Menu() function when the user presses '3'. E.g.:
void Menu() {
    Serial.println(menu_banner);
    for (;;) {
        switch (Serial.read()) {
            case '1': ldrConfig(); break;
            case '2': srvConfig(); break;
            case '3': return;
            default: continue;  // includes the case 'no input'
        }
    }
}

Good work around for the menu! But how would you suggest getting from the functions back to the menu switch?

@ROff: This is already handled here: when srvConfig() returns, we break out of the switch, then we get into another iteration of the infinite for (;;) loop, then back to switch (Serial.read()). The infinite loop is only broken when the user types '3'.

I just ran it through and it seems like whenever I try to save the srvConfig instead of returning to the menu it will just run srvConfig again

@ROff: In srvConfig(), replace x == 1 with x = 1, or more simply with return (and then get rid of x)..


text:
Can the Blink class be used on a 5v to 240v relay?
I have found the following code and it works fine on a breadboard controlling small LEDs but I want it to work with LED strip lighting with external 240v transformers. We have built the circuit using a 5v to 240v relay and the connections are functional but the code does not seem to translate. Does the built in blink class in Arduino function with relays? As it is either High or Low with no variation in voltage I don't see why it wouldn't work as a switch. Has anyone got any suggestions?
Thank you
class LED
{
  public :

    LED();

    void init( uint8_t pin );

    void update();

    void toggle( bool const on );
    void on()  { toggle( true  ); };
    void off() { toggle( false ); };

    void blink( uint16_t const * const pattern, size_t const length, int8_t const count = -1 );
    void blink( uint16_t const timeOn = 1000, uint16_t const timeOff = 1000, int8_t const count = -1 );
    void flash( uint16_t const timeOn );

  private :

    uint8_t          m_pin;
    bool             m_isOn;
    uint32_t         m_millis;
    uint16_t         m_time;
    int8_t           m_count;
    uint16_t const * m_patternPtr;
    uint16_t         m_pattern[2];
    size_t           m_patternLength;
    size_t           m_patternIndex;

    void write( bool const on );
};

LED::LED()
: m_pin           ( 255 )
, m_isOn          ( false )
, m_millis        ( 0 )
, m_time          ( 0 )
, m_count         ( 0 )
, m_patternPtr    ( nullptr )
, m_pattern       { 0, 0 }
, m_patternLength ( 0 )
, m_patternIndex  ( 0 )
{
}

void LED::init( uint8_t pin )
{
  m_pin = pin;
  pinMode( pin, OUTPUT );
  write( false );
}

void LED::toggle( bool const on )
{
  m_count = 0;
  m_patternPtr = nullptr;
  m_patternIndex = 0;
  m_patternLength = 0;
  write( on );
}

void LED::write( bool const on )
{
  m_isOn = on;
  digitalWrite( m_pin, on ? HIGH : LOW );
}

void LED::blink( uint16_t const * const pattern, size_t const length, int8_t const count )
{
  if ( count != 0 && length > 0 && pattern != nullptr )
  {
    write( true );
    m_millis = millis();
    m_count = count;
    m_patternPtr = pattern;
    m_patternLength = length;
    m_patternIndex = 0;
    m_time = m_patternPtr[0];
  }
}

void LED::blink( uint16_t const timeOn, uint16_t const timeOff, int8_t const count )
{
  m_pattern[0] = timeOn;
  m_pattern[1] = timeOff;
  blink( m_pattern, 2, count );
}

void LED::flash( uint16_t const timeOn )
{
  m_pattern[0] = timeOn;
  blink( m_pattern, 1, 1 );
}

void LED::update()
{
  if ( m_count != 0 && millis() - m_millis >= m_time )
  {
    if ( m_patternLength == 1 )
    {
      toggle( false );
    }
    else if ( ++m_patternIndex < m_patternLength )
    {
      m_time = m_patternPtr[ m_patternIndex ];
    }
    else
    {
      if ( m_count != -1 )
      {
        m_count--;
      }

      if ( m_count == 0 )
      {
        toggle( false );
      }
      else
      {
        m_patternIndex = 0;
        m_time = m_patternPtr[0];
      }
    }

    if ( m_count != 0 )
    {
      m_millis = millis();
      write( !m_isOn );
    }
  }
}

LED led1;
LED led2;
LED led3;

void setup()
{
  led1.init( 10 );
  led2.init( 11 );
  led3.init( 9 );

  // 2 flashs toutes les secondes           on   off    on   off
  static const uint16_t led1_pattern[] = { 100,  100,  2000,  400, 5000, 5000, 1000, 200 };
  led1.blink( led1_pattern, 8 );

  // 2 flashs toutes les deux secondes      on   off    on   off
  static const uint16_t led2_pattern[] = { 2000,  100,  250, 1400, 2000, 400, 800  };
  led2.blink( led2_pattern, 8);

 // 2 flashs toutes les secondes           on   off    on   off
  static const uint16_t led3_pattern[] = { 100,  5000,  2000,  400, 5000, 500, 1000, 2000 };
  led3.blink( led3_pattern, 8 );

}

void loop()
{
  led1.update();
  led2.update();
  led3.update();
}

the whole library reduces to digitalWrite( ) ... that command actually sets the state of a hardware pin ... the library is actually irrelevant to controlling a 250 V light ... build a circuit that allows a GPIO pin to control a light ... test with digitalWrite( ) command ... if that works, then the library should also work

Post a schematic of your 240V circuit. Transformers do not like to be cycled as fast as you appear to be doing.  Not all lights will work either.


text:
Bluetooth Arduino Data Type Error
In my code I want to send some float values from my phone to the Arduino's Bluetooth which I will then split using the substring function. it will then print that split value to the serial monitor.
I don't even know what is wrong but there is no error and it just spits out the ascii code of those numbers (not split). Please help if anyone has any idea.
Here is my code:
#include <Wire.h>
#include<SoftwareSerial.h>
#define TxD 3
#define RxD 2
SoftwareSerial bluetoothSerial(TxD,RxD);

String Sstring;
String arrayOne;

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

void loop()
{

 if(bluetoothSerial.available()>0)
 {

  arrayOne=bluetoothSerial.read();

  Sstring=arrayOne.substring(0);
  Serial.println(Sstring);
 }
}

First thing, you have to decide what data format the phone application
will use for sending the data to the Arduino: define a “language” of
sorts. Then you have to program both the phone and the Arduino to speak
that same language.
Unless the data throughput is critical, I strongly advise you to use a
text-based format, where each “message” is followed by a dedicated
character that signals the end of the message. Popular choices for the
message terminator are '\n' (ASCII line feed, numeric value 0x0a =
10), '\r' (carriage return = 0x0d = 13) and ';' (semicolon = 0x3b =
59). The semicolon is often used as a second-level separator, to split a
message into smaller fields.
Here is a simple example that reads one-line messages, using a line feed
as a delimiter:
void loop() {
    if (bluetoothSerial.available() > 0) {
        String message = bluetoothSerial.readStringUntil('\n');
        Serial.println(message);
    }
}

If you want to send the data as binary, then message framing becomes a
tricky problem. Since every possible byte value can legitimately appear
within the message (any byte can appear within a float), you cannot
simply reserve one byte to serve as a terminator. This is why, unless
you are an advanced programmer, I strongly encourage you to send
whatever data you want to send as text. Text also makes debugging much
easier.
Finally, I have to warn you that the String class is not friendly to
the memory of your Arduino, and can lead to instabilities if used
extensively. If you have time, I encourage you to study the robust way
to read text from the serial port: see the article Reading Serial on
the Arduino, by Majenko.

Hey , Thanks for your reply . I tried out your code and it seemed to show no errors (which is good) but when I tried to send a message from my phone and then used the \n terminator , the IDE didn't care , it just printed the whole message . I saw some logs regarding substring and readstringuntil but found no answer . I probably think its still the data type error .Thanks still !

@CodeStuff: What do you mean by “the IDE didn't care”? The IDE has nothing to do with this. If the Arduino did not find the line feed terminator, that's because you did not send it from the phone. Did you send the two characters '\' and 'n' instead? I do not know what programming environment you are using on the phone side, or whether you really know how to properly use it, but it is essential that you know what you are sending. If line feed is too complicated for that environment, try ';'.

I'm guessing the line arrayOne=bluetoothSerial.read();
is converting the received value to a string (character array of ASCII charachters terminated with the '\0' character).
Then, you copy that string to another string variable. If you want to split the string you should:

define a starting character > 0
and/or: define an ending character < the total string size.

See this link for more info.
You could try the following. I'm sure it's far from perfect but it might get you a bit further.
void setup()
{
    bluetoothSerial.begin(9600);
    Serial.begin(9600);
}

void loop()
{
    if (bluetoothSerial.available)
    {
        delay(100); // wait a little for the serial buffer to saturate. This value should be as short as possible

        // Save the buffer bytes as the float (Big Endian!)
        double received_float = (bluetoothSerial.read() << 24) | (bluetoothSerial.read() << 16) | (bluetoothSerial.read() << 8) | (bluetoothSerial.read());
        Serial.println(received_float);
    }
}

Some conciderations:

The nr of bytes a float occupies may differ on your phone and your Arduino. The example above uses a 32-bit float
If possible you'd want to start the transmission with a sequency of starting characters. That way, you can be sure to read the proper value.

There are multiple issues with this way of building the float from individual bytes: 1. The order of the bytes is not defined: it will be whatever order this version of the compiler decides this day to use. 2. Shifting by 16 or 24 bits will overflow on an Uno. 3. This cannot work for a float: you will get the bits of the original float interpreted as an integer, and that integer represented as a (very different) float.

Hey , I tried using the code , but  there was no message printed itself .


text:
Line following robot problems
I am making line following robot using Arduino Uno but every time I connect everything together and upload the code and put the sensors on the line the motor does not work can anyone help me?
I use an L298n motor and Arduino Uno. This is the circuit diagram i am using:

And this is the code:
// First the line following (IR) sensors
const int irLeft = 2; //Left line sensor is on pin A2
const int irRight = 3; //Right line sensor is on pin A3

//Motor A (Right)
int enableA = 11;
int pinA1 = 10;
int pinA2 = 9;

//Motor B (Left)
int enableB = 7;
int pinB1 = 6;
int pinB2 = 5;
//Define Run variable
boolean run;
void setup() {
pinMode(enableA, OUTPUT);
pinMode(pinA1, OUTPUT);
pinMode(pinA2, OUTPUT);
pinMode(enableB, OUTPUT);
pinMode(pinB1, OUTPUT);
pinMode(pinB2, OUTPUT);
}
void loop(){
  int valleft= analogRead(irLeft);
   int leftsensor = analogRead(A2);  //in the side of motor B
  int rightsensor = analogRead(A3);  //in the side of motor A

   if ((leftsensor >= 700) && (rightsensor >= 700))
     forward();
        else if((leftsensor <= 150) && (rightsensor <= 150))
     backward();
     else if((leftsensor <= 150) && (rightsensor >= 700))
     turnright();
     else if((leftsensor >= 700) && (rightsensor <= 150))
     turnleft();
}
//Motors Foward
void forward(){
  digitalWrite(pinA1,HIGH);
  digitalWrite(pinA2,LOW);
  digitalWrite(pinB1,HIGH);
  digitalWrite(pinB2,LOW);
}
// Motors Backward
void backward(){
  digitalWrite(pinA1,LOW);
  digitalWrite(pinA2,HIGH);
  digitalWrite(pinB1,LOW);
  digitalWrite(pinB2,HIGH);
}
// turn left
void turnleft(){
  digitalWrite(pinA1,HIGH);
  digitalWrite(pinA2,LOW);
  digitalWrite(pinB1,LOW);
  digitalWrite(pinB2,HIGH);
}
// turn right
void turnright(){
  digitalWrite(pinA1,LOW);
  digitalWrite(pinA2,HIGH);
  digitalWrite(pinB1,HIGH);
  digitalWrite(pinB2,LOW);
}

You give way not enough information. This is how asking "I have a computer for gaming, but it doesn't work. How can I repair it?" Would you be able to do anything about this? I think not

i will guess .... you have a bad motor, get another one  .... here is another guess .... your program is bad, rewrite it ........... you gave no information, so you will only get guesses, instead of helpful answers

I edit the question

Have you tried a very simple sketch to just run your motors in one direction and not doing anything else? If not, try it. If the motors work then, we can exclude a problem with motor wiring or the driver.

check once individually your IR sensor and driver are working properly

Wire, write and debug just one part of your project at a time.

Can you just run a motor?
Can you run it in either direction?
Can this code do the same for either motor?
Can you run two motors?
Can you set either of them to run forward, reverse, or to
stop, independently of each other?

Then the sensors (forget the motors for now):

Can you read the right sensor and detect light or dark?
Can you adapt the code to read either sensor?

Then using the above pieces and knowledge:

Can you make one of the motors run or stop in response to one of the sensors?

Now you have enough pieces - known working! - to reassemble them into a device that uses sensors and motors to navigate. If it fails at this point, there's a whole lot you don't have to debug, and you can concentrate on whatever you haven't tested yet - your navigation algorithm, any rewiring you've done since you tested each part, and whether you've included the final known-working pieces from your tests, e.g., you used all of the latest and greatest bits of code you developed above.


text:
Problem sending SMS from a GSM SIM900
I have a laser security system project with a GSM SIM900 and a few sensors. I'm using an Arduino Mega 2560, and everything is working normally, except the GSM is not sending an SMS to the phone and I don't know why!
this is  my code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <SoftwareSerial.h>

SoftwareSerial sim900(0,1);
String  TextForSMS;

int dataldr =0;
int sensorldr = A0;
int ldrState = LOW;
int ldrthres = 900;

int pir = A1;
int pirState = LOW;
int val = 0;

int gas = A8;
int sensorgasThres = 400;

#define Password_Length 8
#define PINNUMBER ""

int signalPin = 2;
int led1 = 12;
int led2 = 11;
int led3 = 10;
int led4 = 9;
int led5 = 8;
int led6 = 7;
int laser =6;

char Data[Password_Length];
char Master[Password_Length] = "123A456";
byte data_count = 0, master_count = 0;
bool Pass_is_good;
char customKey;

const byte ROWS = 4;
const byte COLS = 4;

char hexaKeys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

byte rowPins[ROWS] = {30,31,32, 33};
byte colPins[COLS] = {34, 35, 36, 37};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

LiquidCrystal_I2C lcd(0x3F, 20, 4);

void setup(){

  lcd.init();
  lcd.backlight();

  pinMode(signalPin, OUTPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);
  pinMode(laser, OUTPUT);

  pinMode(gas, INPUT);
  pinMode(pir, INPUT);
  pinMode(sensorldr,INPUT);

 randomSeed(analogRead(0));
  Serial.begin(9600);
  sim900.begin (9600);
  Serial.println(" loggin time completed");
delay(5000);

}

void loop(){

     digitalWrite(laser, HIGH);
     digitalWrite(led1, HIGH);

     lcd.setCursor(0,0);
     lcd.print("Enter Password:");

   char customKey = customKeypad.getKey();

  if (customKey){

    Data[data_count] = customKey;
    lcd.setCursor(data_count,1);
    lcd.print(Data[data_count]);
    data_count++;
    }

  if(data_count == Password_Length-1){
    lcd.clear();

    if(!strcmp(Data, Master)){

      lcd.print("Correct");
      digitalWrite(led3, HIGH);
      tone(signalPin, 150,200);
      delay(5000);
      digitalWrite(signalPin, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(laser, LOW);
      ldrState = LOW;
      delay(5000);
      digitalWrite(laser, HIGH);
      ldrState = HIGH;

      }
    else{
            lcd.print("Incorrect");
            digitalWrite(led4, HIGH);
            digitalWrite(signalPin, HIGH);

      delay(2000);

            digitalWrite(led4, LOW);
           digitalWrite(signalPin, LOW);
 TextForSMS="\nIntruder password wrong";
  sendSMS(TextForSMS);
 lcd.setCursor(10,2);
  lcd.print("sms2sent");      }

    lcd.clear();
    clearData();
  }

  int   dataldr =analogRead(sensorldr);
     lcd.setCursor(0,3);
     lcd.print("Laser:");
     lcd.setCursor(7,3);
     lcd.print(dataldr);

  if(dataldr<ldrthres){
    digitalWrite(signalPin, HIGH);
    digitalWrite(led2, HIGH);
  TextForSMS="\nIntruder detected";
  sendSMS(TextForSMS);
  lcd.setCursor(10,2);
  lcd.print("sms1sent");

  }
  else
  {
    digitalWrite(led2, LOW);
    noTone(signalPin);

  }
  delay(100);

 int analogSensor = analogRead(gas);
  lcd.setCursor(0,2);
  lcd.print("Gas:");
  lcd.setCursor(4,2);
  lcd.print(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorgasThres)
  {
            digitalWrite(led5, HIGH);
            digitalWrite(signalPin, HIGH);

     TextForSMS="\nIntruder GAS";
  sendSMS(TextForSMS);
  lcd.setCursor(10,2);
  lcd.print("sms3sent");
  }
  else
  {
    digitalWrite(led5, LOW);
    noTone(signalPin);
  }
  delay(100);

  val = digitalRead(pir);
  if (val == HIGH) {
    digitalWrite(led6, HIGH);

    if (pirState == LOW) {
           Serial.println("Motion detected!");
           pirState = HIGH;
    }
  } else {
    digitalWrite(led6, HIGH);
 delay (5000);
    if (pirState == LOW){
           Serial.println("Motion ended!");
      pirState = LOW;
    }
  }

}

void clearData(){
  while(data_count !=0){
    Data[data_count--] = 0;
  }
  return;
}

void sendSMS (String message){
    sim900.print("AT+CMGF=1");
    delay(1000);

  sim900.println("AT+CMGS=\"+380633965886\"\r ");
      delay(1000);
sim900.println(message);
    delay(1000);
sim900.println((char)26);
    delay(1000);
sim900.println();
    delay(1000);

  }

Also on Github:
https://github.com/shiyaroo/gsm-sim900/blob/master/laser_security_system__gsm.ino

reduce your code to only send  a fixed text message ..... remove all code that is not related to sending the text message  ...... please post the result

its all related to each other but i will try to show u the main code about sending sms

can u see the last part of code void sendSMS (String message)   if i should change something ?

you are not understanding my comment

It’s not a good approach to put delay function between AT commands.
You have to parse SIM900 responses and check if module replies with OK.
If you don’t receive responses from module, could be different problems:

wrong baudrate
connection or power supply problem
SIM card problem (out of cash, sim lock with pin, etc..)

here you can find a useful guide:
https://randomnerdtutorials.com/sim900-gsm-gprs-shield-arduino/

the step 1,2,3 are checked and no problem , but i didn;t understood what u mean here (It’s not a good approach to put delay function between AT commands)

When you send an AT command like this sim900.print("AT+CMGF=1");, you shouldn’t put a delay function like this delay(1000);, but you should reading characters coming from Serial and check if module replies with OK or with some errors.

Try to do a fast test, Create a sketch that send only ‘’AT’’ command and check if SIM900 replies with OK.