text:
Servo wont work with LED code!
I'm basically trying to combine my servo code and my LED code but whenever I add my servo code the LED refuses to turn on at all.
I am super new to arduino sorry if this doesn't make any sense!

Servo myservo;

const int pushbutton_PIN = 2;
const int POT_PIN = A0;
const int LED_PIN = 3;

int pos = 0;
int buttonState = 0;
int lastbuttonState = 0;
int analogValue = 0;
int lightState = false;
int brightness = 0;

void setup() {
  myservo.attach(9);
  pinMode(pushbutton_PIN, INPUT);
  pinMode(POT_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  light();
  servo();
  }

void servo(){
        for (pos = 0; pos <= 180; pos += 1) {
    // in steps of 1 degree
    myservo.write(pos);
    delay(15);
  }
  for (pos = 180; pos >= 0; pos -= 1) {
    myservo.write(pos);
    delay(15);
  }
}

void light() {
      buttonState = digitalRead(pushbutton_PIN);
  if (buttonState != lastbuttonState) {
    if (buttonState == HIGH) {
      delay(300);
      lightState = true;
      light_on();
    }
  }
  lastbuttonState = buttonState;
}

void light_on() {
  while (lightState == true) {
    analogValue = analogRead(POT_PIN);
    brightness = map(analogValue, 0, 1023, 0, 255);
    analogWrite(LED_PIN, brightness);
    buttonState = digitalRead(pushbutton_PIN);
    if (buttonState != lastbuttonState) {
      if (buttonState == HIGH) {
        lightState = false;
        delay(300);
        analogWrite(LED_PIN, LOW);
        loop();
      }
    }
    lastbuttonState = buttonState;
  }
}

I think your problem is the blocking code. While your servo code run, the LED isn't handled in any way. To do multiple this at the same time (like controlling a servo, checking a button and controlling an LED, you actually need to do these this sequentially in very fast succession, basically only doing something, when it is time to do so, otherwise going further to the next thing. No delay calls (thats just busy waiting). Please look at tutorials about millis()and the BlinkWithoutDelay example, that comes with the Arduino IDE. It is very important coding principle for microcontrollers.

Common issue with PWM and Servo when it doesn't work is that used PWM pin is on the same Timer taken over by Servo library. But it's usualy using Timer1 and pin 3 is on timer 2, so it might not be issue in this case

Each call to your servo() function takes well over 5 seconds (5.4s, for the delay() calls alone!), during which nothing else - testing the button, f/ex - is being done. Seconding @chrisl 's suggestion to review the BlinkWithoutDelay example. Also search Arduino StackExchange for "non-blocking".

To add on to Chris's comment there is a really good sticky post on the arduino forum in the project guidance section which deals with this exact issue for newbies. I think it's called: doing several things at the same time

is there any reason why you are moving the servo in small steps?

@chrisl I've looked into what you suggested and I think I've figured it out, so thank you! However if I removed my delays for the servo I'm worried my servo will move too fast for what I need it for. Is there a way to slow my servo down without any delay calls?

Exactly as I wrote: With millis() and the principle in the BlinkWithoutDelay example. That requires a restructuring of your code.


text:
Multiple Wire.write() not working for Arduino Nano I2C
Code for Master
#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
}

void loop()
{
    Wire.beginTransmission(9);

    Wire.write('c');
    Serial.println('c');
    Wire.write('a');
    Serial.println('a');
    Wire.endTransmission();
}

In my case Wire.write('c') is performing the task which is assigned to 'c' in slave board.
Then its printing 'c' in serial monitor as intended.
But, Wire.write('a') line is being neglected and nothing happens on slave board.  But again, it's printing 'a' in serial monitor as per code.
Why is that Wire.write('a'); is neglected? Both boards are Arduino Nano.
Code for Slave
#include <Wire.h>
#define RED 8
#define GREEN 10
int x = 0;

void setup() {
  pinMode (RED, OUTPUT);
  pinMode (GREEN, OUTPUT);
  Wire.begin(9);
  Wire.onReceive(receiveEvent);
}

void receiveEvent(int bytes) {
  x = Wire.read();    // read one character from the I2C
}

void loop() {
    if (x == 'a') {
        digitalWrite(RED, HIGH);
        digitalWrite(GREEN, LOW);
    }
    if (x == 'b') {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, HIGH);
    }
    if (x == 'c') {
        digitalWrite(RED, HIGH);
        digitalWrite(GREEN, HIGH);
    }
    if (x == 'd') {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
    }
}

What is your slave board? Is it another Arduino? If yes, you need to show us the code for that too. Maybe you are misunderstanding how the Wire library works. Wire.write() does not send anything over the I2C lines. It only puts the data into the libraries internal buffer. Transmission is then done by Wire.endTransmission(), which sends out the content of the internal buffer as one I2C transmission. My guess is, that your slave is only reading the first byte of every transmission, thus ignoring the second byte ('a')

Thnak you for you reply i have added slave code also... please do see it.. thanks again

"transmission is then done by Wire.endTransmission()" this line gave me a hit, I modified my master code and now it working perfectlu.. thanks man

Make sure you mark the answer accepted and vote it up since it contains what you found useful.

Important information: Wire.write() does NOT send anything over the I2C lines. It just puts the data into the libraries internal buffer. The actual transmission is then done by Wire.endTransmission().
I2C is packaged transmission protocol. That means, that the transmission is done in confined data packages. In your master code you are calling Wire.write() two times before Wire.endTransmission(). That means you are sending 1 package with 2 data bytes in it.
Now for your slave code: You are using a callback function for the onReceive event. This callback function is called once per transmission. In there you can read all the data of that transmission. After that the data is thrown away (I think actually it gets deleted, when a new transmission is received). You are only reading once with Wire.read(). So you only ever read the first byte of every transmission, which is always the letter 'c'.
What to do know? This depends on how you want the code to behave. Since you are setting 2 LEDs based on the received byte it would be better to only send 1 byte transmissions. For that, you can change your master code. For example like this:
#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
}

void loop()
{
    // Send the command c
    Wire.beginTransmission(9);
    Wire.write('c');
    Wire.endTransmission();

    // Wait 1s, so that we can see the LEDs state accordingly
    delay(1000);

    // Send command a
    Wire.beginTransmission(9);
    Wire.write('a');
    Wire.endTransmission();

    // Wait 1s, so that we can see the LEDs state accordingly
    delay(1000);
}

This code will change between 'c' and 'a' every second. You need a delay there to actually see the LEDs light up. Otherwise they would change too fast for you to see it.
Note: Actually you need to declare the variable x as volatile, because the onReceive callback is called from an ISR. With that keyword you are telling the compiler, that x can change at any time (by the ISR of the corresponding I2C interrupt). It might be, that your current code works, because the compiler was smart enough to see that, but in general you should always use volatile with every variable, that can change in an ISR. Declaration then looks like this:
volatile int x = 0;

And to handle the ISR data really correct, you would need to make the usage atomic, because the ISR can happen in the middle of the comparison for the if statements. An int is two bytes, so the first byte might be updated and the second byte not. That would corrupt your data. There are two ways to handle that in your case:

Make the reading of x atomic: Normally one would turn of the interrupts, read the volatile variables into local variables (as a copy) and then turn the interrupts on again. That way the interrupt cannot corrupt the data in the variable during reading. The further calculation/comparison would then be done with the local variable.

Use a single byte as volatile data: The described problem does not apply to variables, which only use 1 byte (since on the 8bit Arduinos like the Nano the reading of a single byte cannot be interrupted). So just make x of type char (or uint8_t or byte).

You should use the second option.

The OP does use two LEDs to show the state, so he should be able to see which was the last received letter.

@PMF Yes, he/she uses 2 LEDs. But there are 4 states, each with a different pattern for those 2 LEDs. For each of the valid commands both LED states are written. So he/she can only see the last received command. If he/she sends two command without any delay between them, the first command is shown only a very short time (most likely too short to actually see it). Thus the delay

source: Stack Exchange

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

sort: votes


text:
ESP8266 requires two resets to wake up from deep sleep
I'm working with the following circuit using a NodeMCU:
I have the solder jumper bridged between RST and BTN. In addition to what's in the schematic, pins 2, 3, and 4 of J1 are connected to the cathodes of 3 LEDs powered via pin 1 on the same connector.
I'm using the following code to test waking up from deep sleep:
#include <Arduino.h>

void setup() {
  delay(1000);
  Serial.begin(9600);
  Serial.println("start");
  ESP.deepSleep(0);
  while (1);
}

void loop() {
}

I build the code with -DDEBUG_ESP_PORT=Serial -DDEBUG_ESP_CORE and observe the following behaviour on the serial port after startup:
SDK:2.2.2-dev(38a443e)/Core:2.7.3-3-g2843a5ac=20703003/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-30-g92add50/BearSSL:5c771be
start
bcn 0
del if1
usl
enter deep sleep␀

This looks as expected to me (except maybe for the trailing ␀?). The current consumption is as low as I'd expect from deep sleep. I now pull RST low by pressing the push button once and see a few bits of garbage (different every time) being output in the device monitor - nothing else happens:
SDK:2.2.2-dev(38a443e)/Core:2.7.3-3-g2843a5ac=20703003/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-30-g92add50/BearSSL:5c771be
start
bcn 0
del if1
usl
enter deep sleep␀␀�

At this point current consumption increases from single-digit milliamps to a few tens of milliamps. However, a full reset doesn't seem to happen and my program doesn't appear to execute again from the beginning.
If I now pull RST low again with a second press of the push button I see a bit more garbage being output before a proper reset seems to finally happen:
SDK:2.2.2-dev(38a443e)/Core:2.7.3-3-g2843a5ac=20703003/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-30-g92add50/BearSSL:5c771be
start
bcn 0
del if1
usl
enter deep sleep␀␀�␕{��1S�
SDK:2.2.2-dev(38a443e)/Core:2.7.3-3-g2843a5ac=20703003/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-30-g92add50/BearSSL:5c771be
start
bcn 0
del if1
usl
enter deep sleep␀

This cycle then repeats, always requiring two button presses for a reset.
Similarly, if I try to upload a new program to the ESP8266 after it entered deep sleep initially, the upload will fail with:
A fatal error occurred: Timed out waiting for packet header
*** [upload] Error 2

Trying the upload again right after that does succeed. The next upload after that will fail again, and so on.
Based on those observations it looks to me like the ESP8266 doesn't get fully reset on the first button push, or it does get reset but enters some state in which it's not executing my application for some reason.
What could be the reasons for that? Is it something I can work around either in hardware or code?
Thanks!

Add Serial.flush(); after your print. Otherwise you'll never see it print anything.

@Majenko I do see the serial output I'm expecting before going to sleep, and using other indicators such as the LEDs or buzzer to find out if my program is re-executed after a reset have the same behaviour of requiring two resets.

random ideas: might want to hard pull gpio 0 and 2. might need caps on vcc, rst, etc. might be a noisy switch on 16. Could be a power-hungry attachment; does the problem persist w/o buzzer and LEDs?

I ended up taking the ESP8266 out of the circuit to test the reset behaviour in isolation and to compare it to other ESP8266s. It turns out that only the one unit out of a total of 6 that I tested had that behaviour. Putting a different ESP8266 back into the same circuit works just fine and only one reset is needed. I'm not sure if there perhaps was some damage to that one unit, but just replacing the component was more practical than debugging it further.

add delay(500) after Serial.begin to wait for the CH340 to wake up. else the print is lost. and add flush() after print to wait until it is sent before going to sleep.

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


text:
NodeMCU server stops responding after a while
I'm new to NodeMCU and ESP. I've created a basic web server on my NodeMCU.
The server works fine for the first few minutes after resetting the board or re-uploading code. But after about half an hour, the server just stops responding and becomes unreachable. Funny thing is, after sending a few failed requests, server starts to respond normally again.
The code i'm using:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

String wifiName = "blablabla";
String password = "blablabla";

ESP8266WebServer server(9090);

void setup() {
  Serial.begin(115200);
  pinMode(5, OUTPUT);
  digitalWrite(5,LOW);

  connectToWifi();
  server.on("/", handleHomepage);
  server.on("/action", handleAction);
  server.begin();
}

void loop() {
  server.handleClient();
}

void handleHomepage() {
  server.send(200, "text/plain", "Welcome to esp8266 homepage!");
}

void handleAction() {
  String parameter = server.arg("value");

  if (parameter == "") {
    server.send(200, "text/plain", "No parameter supplied.");
    return;
  } else {
      if (parameter == "on") {
        digitalWrite(5,HIGH);
      } else if (parameter == "off") {
        digitalWrite(5,LOW);
      }
    server.send(200, "text/plain", "Action received successfully.");
  }
}

void connectToWifi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifiName, password);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
}

What should I do to keep the server always active? Thanks in advance.

research on ESP8266WiFiGratuitous

https://github.com/esp8266/Arduino/pull/6889


text:
Pn532 and Node MCU SPI
I'm trying the Android Hce example in this PN532 library. The serial monitor gives me "Didn't find PN53x board". Can someone help me?
#if 1
  #include <SPI.h>
  #include <PN532_SPI.h>
  #include "PN532.h"

  // SPI connections
  //GPIO 12   MISO
  //GPIO 13    MOSI
  //GPIO 14    SCK
  //GPIO 15 SS

  PN532_SPI pn532spi(SPI, 15);
  PN532 nfc(pn532spi);
#elif 0
  #include <PN532_HSU.h>
  #include <PN532.h>

  PN532_HSU pn532hsu(Serial1);
  PN532 nfc(pn532hsu);
#else
  #include <Wire.h>
  #include <PN532_I2C.h>
  #include <PN532.h>
#endif

void setup()
{
  Serial.begin(115200);
  Serial.println("-------Peer to Peer HCE--------");

  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print("Didn't find PN53x board");
    while (1); // halt
  }

        // Got ok data, print it out!
  Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);

Please share the full void setup as well as the loop and add your circuit. Did you check your connections if it doesn't find it?

@Juraj, So it is.  Thanks.

@PythonSchlange . I have shared the setup code above but it is not going in the loop part because when chip is not found it halts. I am mentioning here connections between esp8266 and pn532                                                                                //GPIO 12      MISO
//GPIO 13    MOSI
//GPIO 14    SCK
//GPIO 15    SS

@MuhammadUsman Are you sure all wires are perfectly connected? Did you measure the connection? I think it rather is a connection problem not a code problem, because you use the example. Please add an image of your setup to the question.

@PythonSchlange. Thank you for your help I was able to solve the problem by changing the SS line from GPIO 15 to GPIO 10. Thanks again for your help


text:
Arduino nano digital I/O overload
Is it possible to kill arduino nano with overload?
I wanted to drive a relay with arduino, and I used a BC547 to switch 12V for the relay.
But in the relay there was a diode, which sorted out the circuit (thats why I drawed in the wrong orientation)
I know it was a mistake to not use current limiting resistor on Base of the transistor.
Is it possible that this shorted circuit made too much current on the transistor base which killed my arduino?
I made this circuit:

Shouldn't the diode across the relay be the other way round? Like this, it shortcuts the relay, but what it should do, is shortcut the discharge current of the relay.

the backwards diode bypassed the relay ... when the transistor turned on, too much current flowed through the transistor and possibly damaged the transistor, the damaged transistor may have allowed the base voltage to rise to near 12 V

As mentioned, the frewheeling diode at the relay has wrong orientarion. You also must have a base resistor to limit the current the gpio has to source (you control a BJT just like an led). Some hundred ohm should work for the bc547

Short answer is probably.  There is a voltage drop from base to emitter that is about .7 volts.  But something still has to contend with the rest of the energy.  You might try a different Arduino digital output on the chance that the balance of the processor is working as expected.
I say probably because several things might have happened if the transistor actually turned on.  For instance the forward biased (backwards) diode may have allowed so much current to flow through the relay and transistor that the transistor failed first.  Or, if the power supply had a low current rating, it may not have had the capacity to burn anything out.  As you can see, it is difficult to say what exactly happened with out testing each part individually.

The transistor turned on, and something is blown out, i think the transistor but I'am not sure.
But the arduino is not working anymore, i can't write code on it, and the code on it doesn't do anything. When i power it, the power LED turns on. And I also can't see any damage on the arduino.

Disconnect everything from the Arduino then try to program it.  Burned out parts can fail open or shorted.  If it sill does not program and the Atmel processor is in a socket consider buying a new pre-programmed-with-the-Arduino-boot-loader processor.  Or a normal Atmel processor and program the Arduino boot loader your self.  Finally, consider starting over with a new Arduino.

I tried almos everything, there is no way to change the Atmel IC. The only way would be to buy a new one, but its sadly more than a week in shipping. I just wanted to know where i made a mistake which lead to damage the arduino. Thnak You for your help!

I applaud you wanting to learn. But perhaps for the first go you might consider buying a pre-made Arduino compatible relay board with built in drivers and even an optical isolator for added protection.  Also, when just starting out, there is no shame in copying an existing working project like this one.


text:
sim 900a mini status led glowing constantly instead of blinking
I am using sim 900a module for the first time(sim900a). Initially when i powered it with the arduino 5v supply, the power led of the board glow but the network status led never glow. After searching online for answers they showed to use external power supply with 5v 2A, then i used the specified power supply. It worked actually now the status led started to glow but it does not blink for ever 1sec or 3sec instead it glows continuously. I connected the module with the tx and rx of arduino and called the inserted sim the serial monitor detected the call and gave the output, but i cannot make a call or send sms from the module to other numbers. Pls help me out.

I am facing same problem... anybody found solution? Please help.


text:
Servo motor won't work for a specific code
I have written a code with interrupts to control the servo but my servos are not working. One is meant to work with interrupt but the other one has to simply move but it is also not working. Even the serial window shows that the code is working properly ut the servos aren't moving I have checked both my servos with same connections and Sweep example of Arduino and both work fine.
#include <TimerOne.h>                                 // Header file for TimerOne library
#include <Servo.h>
#define trigPin 12                                    // Pin 12 trigger output
#define echoPin 2                                     // Pin 2 Echo input

#define echo_int 0                                    // Interrupt id for echo pulse

#define TIMER_US 50                                   // 50 uS timer duration
#define TICK_COUNTS 4000                              // 200 mS worth of timer ticks

volatile long echo_start = 0;                         // Records start of echo pulse
volatile long echo_end = 0;                           // Records end of echo pulse
volatile long echo_duration = 0;                      // Duration - difference between end and start
volatile int trigger_time_count = 0;                  // Count down counter to trigger pulse time
volatile long range_flasher_counter = 0;              // Count down counter for flashing distance LED

int sound = 250;

Servo servo1; //Servos
Servo servo2;

const int button1 = 10; //Buttons
const int button2 = 8;
const int button3 = 13;
const byte interruptPin = 3;
int pos;

void setup() {
  servo1.attach(9); // servo for arm
  servo2.attach(5); // servo for base
  pinMode(trigPin, OUTPUT);                           // Trigger pin set to output
  pinMode(echoPin, INPUT);                            // Echo pin set to input
                      // Onboard LED pin set to output

  Timer1.initialize(TIMER_US);                        // Initialise timer 1
  Timer1.attachInterrupt( timerIsr );                 // Attach interrupt to the timer service routine
  attachInterrupt(echo_int, echo_interrupt, CHANGE);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin),Metal_detected, HIGH);

  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:

  servo1.write(0); // These will make the servos move to the mapped angles
  servo2.write(90);

  distance_checking();
  if(digitalRead(button1) == HIGH)
  {

      while(digitalRead(button2) == LOW)
        {
          Serial.println("Entering Sweeping mode");
       for (pos = 30; pos <= 150; pos += 1)
       { Serial.print("Angle is :");
         Serial.println(pos);
         servo2.write(pos);
         distance_checking();
         //delay(0.1);                       // waits 15ms for the servo to reach the position
         if(digitalRead(button2) == HIGH)
          {
            Serial.print("Exiting Sweeping");
            goto label;}
          }
          for (pos = 150; pos >= 30; pos -= 1) { // goes from 180 degrees to 0 degree
          Serial.print("Angle is :");
          Serial.println(pos);
          servo2.write(pos);              // tell servo to go to position in variable 'pos'
          distance_checking();
          //delay(0.1);                       // waits 15ms for the servo to reach the position
          if(digitalRead(button2) == HIGH)
          {
            goto label;
            Serial.print("Exiting Sweeping");}
          }

 }
 }
//reset th
label:
  if(digitalRead(button2) == HIGH){

    servo1.write(0);
    servo2.write(90);
    Serial.println("press the sweeping button to enter sweeeping mode");
    delay(300);
  }

}

void distance_checking()
{

if (echo_duration/58 <= 20)
{
Serial.println("the servo angle is 30");
servo1.write(30);
delay(1500);
}

else {
servo1.write(0);
}

delay(500);
}

void Metal_detected()
{if(digitalRead(button2) == LOW)
{delay(5000);
  Serial.print("Metal detected at servo angle:");
Serial.println(servo2.read());
servo1.write(servo1.read());
servo2.write(servo2.read());
Serial.println("Motion is stopped");
Serial.println("Press reset to go to the home position");

}
//while(digitalRead(button2) == HIGH)
// {
//  Serial.print("Reseting");
//  return 0;}
 }
void timerIsr()
{
    trigger_pulse();                                 // Schedule the trigger pulses
                             // Flash the onboard LED distance indicator
}

// --------------------------
// trigger_pulse() called every 50 uS to schedule trigger pulses.
// Generates a pulse one timer tick long.
// Minimum trigger pulse width for the HC-SR04 is 10 us. This system
// delivers a 50 uS pulse.
// --------------------------
void trigger_pulse()
{
      static volatile int state = 0;                 // State machine variable

      if (!(--trigger_time_count))                   // Count to 200mS
      {                                              // Time out - Initiate trigger pulse
         trigger_time_count = TICK_COUNTS;           // Reload
         state = 1;                                  // Changing to state 1 initiates a pulse
      }

      switch(state)                                  // State machine handles delivery of trigger pulse
      {
        case 0:                                      // Normal state does nothing
            break;

        case 1:                                      // Initiate pulse
           digitalWrite(trigPin, HIGH);              // Set the trigger output high
           state = 2;                                // and set state to 2
           break;

        case 2:                                      // Complete the pulse
        default:
           digitalWrite(trigPin, LOW);               // Set the trigger output low
           state = 0;                                // and return state to normal 0
           break;
     }
}

// --------------------------
// echo_interrupt() External interrupt from HC-SR04 echo signal.
// Called every time the echo signal changes state.
//
// Note: this routine does not handle the case where the timer
//       counter overflows which will result in the occassional error.
// --------------------------
void echo_interrupt()
{
  switch (digitalRead(echoPin))                     // Test to see if the signal is high or low
  {
    case HIGH:                                      // High so must be the start of the echo pulse
      echo_end = 0;                                 // Clear the end time
      echo_start = micros();                        // Save the start time
      break;

    case LOW:                                       // Low so must be the end of hte echo pulse
      echo_end = micros();                          // Save the end time
      echo_duration = echo_end - echo_start;        // Calculate the pulse duration
      break;
  }
}

I tested my motors with this code one by one and they worked absolutely fine:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Your code is really hard to follow and the indention is all over the place. Also I don't understand the reason why you are using a timer interrupt and an external interrupt just for reading the ultrasonic sensor, but then using many long delay() calls. Can you please describe how exactly you want the code to behave?

I think the Servo library uses Timer1. Thus using both at the same time can lead to problems

The thing is that I am using both interrupts of Arduino Uno. One for the data from Ultrasonic and one for the other signal that I have to attach to pin3. The code works the way that one servo keeps sweeping to the angle between 30 and 150 until the distance from the ultrasonic is greater than 20cm ,as the distance gets less it has to follow the function "distance_checking"


text:
Driving a servo with an ATTiny13A
So, I managed to fry my cheap servo/ESC (electronic speed controller) and decided to make my own using an ATTiny13A on some perfboard. But, I have run into some issues getting the servo to respond.  I'm assuming the servo.h library is not compatible with the ATTiny13A because of incompatible internal clock speeds not creating the right PWM signals. And I haven't found a solution for this.
I have messed around with the Servo8Bit.h library, but this also doesn't seem to work (as its designed for the ATTiny45 and the ATTiny85 ). Is the ATTiny13A even able to produce the needed PWM signals?
Any help/links to documentation would be appreciated!
Thanks in advance.
Code:
#include <Servo.h>

Servo myservo;
int potpin = A3;
int val;    // variable
int Toggle = 2;

void setup() {
  Serial.begin(9600);
  pinMode(Toggle, INPUT);
  myservo.attach(1);  // Servo/ESC is attached to pb1
}

void loop() {
  int ToggleState = digitalRead(Toggle);
  Serial.println(ToggleState);
    val = analogRead(potpin);

  if (ToggleState == 0) {
  val = map(val, 0, 1023, 0, 180);  //Servo motor
   myservo.write(val);
  delay(15);
}
else {
  val= map(val, 0, 1023,1000,2000); //ESC
  myservo.write(val);
  delay(15);
 }
}

Servo8Bit relies on an 8-bit timer, and the ATtiny13A does have an 8-bit timer. It should not be too hard to port this library to that micro. Study the source code, then study the datasheet of the tiny13A (mostly the chapter dedicated to the timer). You should then be able to easily see what changes are needed.

Are you sure, that the ATtiny is actually running at the frequency you think it does? I did have timing problems with my ATtiny85, whem trying to use it with 8MHz. The fuses actually were still set for 1MHz. I first had to burn the bootloader to set the fuses correctly.

does a blink sketch run at an expected speed?

Servo8Bit and ATTiny13(A)
I had a look at the Servo8Bit and had pretty much the same thoughts on this as Edgar Bonet in his comment:

Servo8Bit relies on an 8-bit timer, and the ATtiny13A does have an
8-bit timer. It should not be too hard to port this library to that
micro. Study the source code, then study the datasheet of the tiny13A
(mostly the chapter dedicated to the timer). You should then be able
to easily see what changes are needed.

Ignoring the timing differences between the ATTinyx5 and ATTiny13(A), I just went ahead and saw if I could get it to compile.  And yeah, it's pretty easy to compile.  This mostly consists of adding 0 to some hardware register names.  The bad news is:

Sketch uses 1486 bytes (145%) of program storage space. Maximum is 1024 bytes.
Global variables use 31 bytes (48%) of dynamic memory, leaving 33 bytes for
local variables. Maximum is 64 bytes.
Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it.
Error during build: text section exceeds available space in board

So, yeah, that was a bit much to hope for, I guess.  The library does use ISRs to support a number of servos kind of like the more common servo library that you'd use on an UNO.  I haven't looked into chopping it down to size; I expect that will be impractical.
PWM... sort of.
Prior to considering modifying Servo8Bit, I kind of thought it made sense to just use the timer counter directly to produce a waveform.  The problem is the conventional servo signal is 20ms long, and does all of its control in a 1ms window.  If you try to fit the whole 20ms frame into a single 8bit timing interval, what you end up with is pretty crappy angular control.  So, doing it is a bit painful without a 16-bit timer counter.  But, I guess that's the game.
So, the below is a crude and barely tested attempt at it.  The code that follows is state machine inside the OCR0B overflow vector that schedules the rising an falling edges is "normal" mode.  Just to warn you, I don't actually have an ATTiny13(A) on hand.  And in fact I don't happen to have a servo hand either.  But I do have an ancient storage scope and an ATTiny85 and the ability to compile for ATTiny13(A), and a calculator for working out the 8 MHz vs 9.6 MHz difference.
So here's what I came up with, which I think (but don't know) will work if you compile and upload using MCUDude MicroCore, ATTiny13(A) with the 9.6 MHz internal oscillator chosen.
It's only designed to operate 1 servo.  Extending it to two should be easily doable.  Going beyond that you're likely run into problems.
Code:
// +---------------------------------------------------------------------------------------+
// |                                                                                |
// |                                 +-------------+                                       |
// |                                 |             |                                       |
// |                                 |      A      |                                       |
// |  PCINT5 ADC0 dW  /RESET  PB5 *--|-1    T    8-|--* VCC                                |
// |                                 |      T      |                                       |
// |  PCINT3 ADC3      CLKI   PB3 *--|-2    I    7-|--* PB2  SCK   ADC1 T0         PCINT2  |
// |                                 |      N      |                                       |
// |  PCINT4 ADC2             PB4 *--|-3    Y    6-|--* PB1  MISO  AIN1 OC0B  INT0 PCINT1  |
// |                                 |      1      |                                       |
// |                          GND *--|-4    3    5-|--* PB0  MOSI  AIN0 OC0A       PCINT0  |
// |                                 |      A      |                                       |
// |                                 |             |                                       |
// |                                 +-------------+                                       |
// |                                                                                |
// +---------------------------------------------------------------------------------------+

#if !defined(__AVR_ATtiny13__) && !defined(__AVR_ATtiny13A__)
#error This code is written specifically for ATTiny13(A) devices.
#endif

#if F_CPU != 9600000
#error  This code is written specifically for 9.6 MHz
#endif

//
//
//
#include <avr/io.h>
#include <avr/interrupt.h>

//
//
//
constexpr uint8_t TCCR0A_config(
  int com0b // two bits
) {
  return
      (    0 << COM0A1) // normal
    | (    0 << COM0A0) //   port operation
    | (com0b << COM0B0) // bits 5 AND 4
    | (    0 <<      3) // reserved
    | (    0 <<      2) // reserved
    | (    0 <<  WGM01) //  lower two bits
    | (    0 <<  WGM00);//     of Normal (mode 0);
}

//
//
//
constexpr uint8_t TCCR0A_config_for_go_low()  {return TCCR0A_config(0x2);}
constexpr uint8_t TCCR0A_config_for_go_high() {return TCCR0A_config(0x3);}

//
// 50 Hz (hobby servo frame frequency); period 20 ms
//
// In the below you'll see the numbers 150 and 300 and 3000.
// The reason for these numbers is that I've chosen to to use a /64
// timer prescaler.  At 9.6 MHz, with a /64 prescaler, 1 millisecond
// is 150 timer timer counts.  There's as fixed 1 MS high in the servo,
// followed by 0 to 1ms variable portion.  The number 150 helpfully
// fits within the 8-bit timer registers and also gives a reasonable
// number of increments to the servo control.  For 180 degrees, 150 increments
// is 1.2 degrees.
//
// The maximum high time is the fixed 1ms high time and the maximum
// variable high time, totalling 2 MS, or 300 timer ticks, that's what that
// number is about.
//
// 3000 is the number of timer ticks for a full 20ms signal frame,
// that is 20 * 150 = 3000.
//
//
// Deriving the 150 figure:
//
//  At 9.6 MHz and /64 prescaler
//
//        1 second         64 mcu_cycles   A_MS_DURATION timer_counts
//  -------------------- X ------------- X ---------------
//  9_600_000 mcu_cycles   1 timer_count    0.001 seconds
//
//
//       1      64    A_MS_DURATION
//  --------- X -- X  -----
//  9_600_000   1     0.001
//
//
//     64       A_MS_DURATION
//  --------- X -----------
//  9_600_000      0.001
//
//
//     64 x A_MS_DURATION
//  --------------------
//        9_600
//
//
//  A_MS_DURATION
//  -------------
//      150
//

static constexpr uint8_t  ONE_MS_WORTH_OF_TICKS    = 150;
static constexpr uint8_t  MAXIMUM_HIGH_PERIOD      = ONE_MS_WORTH_OF_TICKS * 2;
static constexpr uint16_t TWENTY_MS_WORTH_OF_TICKS = 3000;
static constexpr uint16_t MAX_WASTE_CYCLES         = 0x80;

static volatile uint8_t g_pulse_width = ONE_MS_WORTH_OF_TICKS / 2;  // default to mid-range.

ISR(TIM0_COMPB_vect) {
  static uint8_t l_pulse_width; // this caches g_pulse_width
                                // and is updated from g_pulse_width
                                // only between frames

  //
  // The ISR is a state machine with four macro states.
  //
  enum class t_signal_generator_state : uint8_t {
    timing_to_variable_high_period,
    timing_to_set_pulse_width,
    calculate_time_to_start_of_next_pulse_and_waste_a_bit,
    timing_to_start_of_pulse
  };

  //
  // Macro state variable
  //
  static t_signal_generator_state g_signal_generator_state =
    t_signal_generator_state::timing_to_variable_high_period;

  // low_time_remaining is an extended state variable
  // for the timing_to_start_of_pulse state
  static uint16_t low_time_remaining;

  switch (g_signal_generator_state) {
    case t_signal_generator_state::timing_to_variable_high_period:
      // We just went high at the OCR0B value that triggered this interrupt
      // and we need to retrigger ((MAXIMUM_HIGH_PERIOD==300) - 256 == 44)
      // timing cycles later such that there are 256 timing cycles left of the
      // 2ms (maximum) high part of the frame.
      OCR0B += (MAXIMUM_HIGH_PERIOD - 256);  // 2ms worth of timer nicks minus the resolution of our timer

      // We're remaining HIGH as we head into the variable portion of the HIGH period.
      g_signal_generator_state = t_signal_generator_state::timing_to_set_pulse_width;
      break;
    case t_signal_generator_state::timing_to_set_pulse_width:
      // We're retrieving the global variable which holds a (potentially new) value from 0 to 150
      // representing a span of 0ms to  1ms (the full range of the servo), but
      // we're starting out the variable pulse a head of time, part way through the always-on first ms.
      // There are (150 - 44) timer cycles, that's 1 ms worth of timer cycles
      // where the timer remains high to finish out first millisecond of HIGH.
      // So we add this to the requested variale pulse width time.
      l_pulse_width = g_pulse_width + (ONE_MS_WORTH_OF_TICKS - 44);

      // Set adjust pulse width
      OCR0B += l_pulse_width;

      // We'll be going low and the end of the variable high period.
      TCCR0A = TCCR0A_config_for_go_low();

      g_signal_generator_state = t_signal_generator_state::calculate_time_to_start_of_next_pulse_and_waste_a_bit;
      break;

    case t_signal_generator_state::calculate_time_to_start_of_next_pulse_and_waste_a_bit:
      // We just went low at the OCR0B value.

      // Calculate remaining timer cycles to the beginning of the next pulse
      // accounting for the MAX_WASTE_CYCLES we're about to waste in this state.
      low_time_remaining = (TWENTY_MS_WORTH_OF_TICKS - 44 - MAX_WASTE_CYCLES) - l_pulse_width;
      OCR0B += MAX_WASTE_CYCLES;

      // We will remain LOW since the pulse is done and we've not finished out the 20ms period
      g_signal_generator_state = t_signal_generator_state::timing_to_start_of_pulse;
      break;

  case t_signal_generator_state::timing_to_start_of_pulse:
      // Continue retriggering the timer until we've used up 20ms total,
      // in increments of not more than MAX_WASTE_CYCLES.

      if (low_time_remaining > MAX_WASTE_CYCLES) {
        low_time_remaining -= MAX_WASTE_CYCLES;
        OCR0B += MAX_WASTE_CYCLES;
        // We'll need to wast more, so we're remaining LOW.
      } else {
        OCR0B += low_time_remaining;
        low_time_remaining = 0;

        // This is out last round through this state to finish out the 20ms
        // window, so we'll be returning to HIGH.
        TCCR0A = TCCR0A_config_for_go_high();

        g_signal_generator_state = t_signal_generator_state::timing_to_variable_high_period;
      }
      break;
  }
}

//
//
//
void servo_init() {
  const auto SREG_saved = SREG; cli();

  DDRB |= 1U << 1;  // Servo data pin attached on Attiny PB1 aka (OCR0B)

  // select no clock source / stop counter
  TCCR0B &= ~(
      (1U << CS02)
    | (1U << CS01)
    | (1U << CS00)
  );

  // reset counter
  TCNT0 = 0x00;
  OCR0B = 0x80;

  TIMSK0 =
      (0 <<      7) // reserved
    | (0 <<      6) // reserved
    | (0 <<      5) // reserved
    | (0 <<      4) // reserved
    | (1 << OCIE0B) // we *ARE*  using output-compare B interrupt
    | (0 << OCIE0A) // we aren't using output compare A interrupt
    | (0 <<  TOIE0) //             nor overflow interrupt
    | (0 <<      0);// reserved

  TIFR0 = 1U << OCF0A;

  TCCR0A = TCCR0A_config_for_go_high();

  TCCR0B =
      (0 << FOC0A) // We're not doing any
    | (0 << FOC0B) //   output compare forcing.
    | (0 <<     5) // Reserved.
    | (0 <<     4) // Reserved.
    | (0 << WGM02) // High order bit of Normal mode (0)
    | (0 <<  CS02) // Clock source
    | (1 <<  CS01) //    prescaled
    | (1 <<  CS00);//      by 64.

  SREG = SREG_saved;
}

//
//
//
void setup() {
  servo_init();
}

//
//
//
void loop() {
  for (g_pulse_width = 0; g_pulse_width < 150; ++g_pulse_width) {
    __builtin_avr_delay_cycles(F_CPU >> 5);
  }
  for (; g_pulse_width > 0; --g_pulse_width) {
    __builtin_avr_delay_cycles(F_CPU >> 5);
  }
}

//  vim:sw=2:ts=2:et:nowrap:ft=cpp:

On the scope, this produces servo signal that should sweep a servo on pin OCR0B (PB1).  Something like 4 to 5 seconds going one way and same going back.
If I put an ATTiny13A on an order sometime and manage to dig out a servo myself, I'll actually test it.  It may be a very long time before I can do that though.  But the results on the scope look good.  Admittedly everything is scaled by 9.6/8.0.  It should be accurate on a ATTiny13(A).  I verified that it compiles for it.  The workings of the thing are explained in the code as I can.
For comparison:

Sketch uses 490 bytes (47%) of program storage space. Maximum is 1024 bytes.
Global variables use 10 bytes (15%) of dynamic memory, leaving 54 bytes for local variables. Maximum is 64 bytes.

That's still a good chunk of what little code space you have, but it should be enough to read a switch and potentiometer.  This is using the timer the device has, so millis()/delay() usage are kind of out-the-window, I think, I didn't try to see what happen when you call them or study their code in MicroCore.  You could recreate your own millis() by making a timer overflow interrupt and it would overflow at about 1.7 ms intervals.  As you can see, I just used __builtin_avr_delay_cycles to keep things simple.
If you, or anyone else, gets it working on at ATTiny13 before I try it myself, I'm curious to know that it worked (or didn't).

+1. A few comments: 1. MAX_WASTE_CYCLES = 256 would reduce the interrupt load and remove the need for OCR0B += MAX_WASTE_CYCLES;. 2. Possible race condition: if low_time_remaining is 1 and the interrupt is slow or delayed, TCCR0A could be updated too late. This could be mitigated by putting the variable part of the low time (low_time_remaining % MAX_WASTE_CYCLES) at the beginning of the low period. 3. The include file <util/delay.h> provides a macro for writing the fixed delay in a more convenient form: _delay_ms(32.25);. The generated code is the same.

Yeah, I was considering bumping MAX_WASTE_CYCLES all the way up (and probably giving it a better name). The original plan, I think, was to find a value to advance OCR0B by that such that the final pass through the that state somewhere TCNT0 and OCR0B half the timer ticks (0x80) ahead the rising edge, so it was scheduling that rising at at a more idea moment. So that constant was supposed to be something like FINAL_APPROACH_LENGTH_TO_HIGH_EDGE, but I just never got to doing that.  That sounds like what you're describing with the modulus.

I was hoping to find a way to do without without division (modulus), like find some happy medium that was close enough on both extremes.  But yeah, the way it is now it probably makes more sense to put it all the way up to 0xFF.

Modulus 256 is cheap: it is achieved automatically by casting low_time_remaining to uint8_t.

I'm aware with regard to modulo 256.  I'm probably not explaining myself well or I'm just not awake enough to be thinking about it.  When I get back into looking at the code, I'll look at your comments again, and it may get updated in exactly the way you're thinking.  I don't have that much time into that part of the problem, to the point where you may have actually spent more time thinking about than I have.


text:
Arduino code not working properly (Please Help)
I am having some trouble getting my board to perform the function I want it to perform. This is a project I have due in a few days, and I have hit a wall I just can't seem to get past. Now, I will say the issue is definitely in the way I coded the program, but I don't really know enough about Arduino (and coding) to understand why it is not working. My board is properly hooked up to use 3LEDs, a speaker, a photoresistor, and an ultrasonic sensor (detects distances). My Arduino program takes serial input from a GUI that I created in MATLAB. I have verified the MATLAB code is good, and the serial port is communicating properly. I have made an alarm that goes off when light or motion is detected. It has 3 basic functions:

Set the alarm
Turn off the alarm
"snooze" which just delays for 5 minutes and then the alarm goes off

The snooze and turn off alarm parts of my code are working great, but the set alarm is where I am having trouble. The snooze option sets off the yellow LED to verify it is on "snooze". The red LED comes on when the alarm is currently going off. The green LED comes on when the alarm is set. When I try to activate the "Set Alarm" function, which is case 'O' in a switch case, the light does come on, but the sensors are not picking up any input as far as I can tell. Again I have verified the pins and everything are set up correctly as I have isolated those and verified they work. I have a suspicion that the problem is because I have the sensors initialed within the switch case of the "Set Alarm" (case 'O', not 0). I don't really know how to get the sensors to run continually within that switch case until the "turn alarm off" case is activated. I need the sensors to be activated/reset by "Set Alarm" case.
**I am also new to this forum so please let me know if I am missing anything!
here is my code:
void setup()
{
  Serial.begin(115200);
  pinMode(12,OUTPUT); //RED
  pinMode(13,OUTPUT); //GREEN
  pinMode(14,OUTPUT); //YELLOW
  pinMode(16,OUTPUT); //SPEAKER
  pinMode(4,INPUT); //Echo
  pinMode(2,OUTPUT); //Trig
}

void loop()
{
 if(Serial.available() >0)
 {
 char b = Serial.read();

  switch(b)
  {
    //Turn Alarm off
    case 'A' :
    {
    digitalWrite(12,LOW);//red off
    digitalWrite(13,LOW); // green off
    digitalWrite(14,LOW); //yellow off
    noTone(16);
    delay(500);
    }
    break;

    // Set alarm
    case 'O' :
    {
      int light;
  light = analogRead(0);
  unsigned long distance;
    digitalWrite(2,LOW);
  delayMicroseconds(2);
  digitalWrite(2,HIGH);
  delayMicroseconds(10);
  digitalWrite(2,LOW);
  distance = pulseIn(4,HIGH);
  distance = distance/58; //centimeters
  delay(500);

    digitalWrite(12,LOW); //red off
    digitalWrite(14,LOW); //yellow off
    digitalWrite(13,HIGH); //green on

  if (light < 400)
    {
     digitalWrite(12,HIGH);//red on
    digitalWrite(13,LOW); // green off
    digitalWrite(14,LOW); //yellow off
    tone(16,832);
    delay(500);
    }

  if (distance < 50)
    {
     digitalWrite(12,HIGH);//red on
    digitalWrite(13,LOW); // green off
    digitalWrite(14,LOW); //yellow off
    tone(16,832);
    delay(500);
    }

    }
    break;

    // snooze option
    case 'Z' :
    {
    digitalWrite(14,HIGH); //yellow on
    digitalWrite(12,LOW); //red off
    digitalWrite(13,LOW); // green off
    noTone(16);
    delay(300000UL);
    digitalWrite(12,HIGH); //red on
    digitalWrite(13,LOW); // green off
    digitalWrite(14,LOW); //yellow off
    tone(16,832);
    delay(500);
    }
    break;
   }

  }
}

Any help would be very much appreciated!

Hi Geraldo and welcome to Arduino Stack Excange. Please take the [tour] and read all the way to the bottom to earn your first badge. Your code appears to missing the top section with your includes and global variable declaration. Could you please check and add it.

Please use the Auto Format to format your code. In the Arduino IDE, go to Tools > Auto Format or use the keyboard shortcut Ctrl + T.

The most simplest way to troubleshoot a program is to add Serial.println(); statements everywhere. For example you could add Serial.println("Setting Alarm"); in the first line of the case for setting the alarm.
You will notice that the set alarm code only runs once through, instead of continously. You should use the case to set a mode or a state in where the sensors are checked continously.
First I would create a variable called setAlarmMode and set it to false.
setAlarmMode = false;

Then I would remove the reading of sensors from the case statement and instead set setAlarmMode to true.
// Set alarm
case 'O' :
  {
    Serial.println("Setting Alarm");

    // Set the LEDs for the mode
    digitalWrite(12, LOW); //red off
    digitalWrite(14, LOW); //yellow off
    digitalWrite(13, HIGH); //green on

    setAlarmMode = true;
  }
  break;

Now I would insert this code outside of the if (Serial.available() > 0) code block:
// Read sensors
if (setAlarmMode == true)
  {
    Serial.println("Reading sensors");
    int light;
    light = analogRead(0);
    Serial.print("Light sensor value: ");
    Serial.print(light);

    unsigned long distance;

    // Do trigger pulse
    digitalWrite(2, LOW);
    delayMicroseconds(2);
    digitalWrite(2, HIGH);
    delayMicroseconds(10);
    digitalWrite(2, LOW);

    distance = pulseIn(4, HIGH);
    distance = distance / 58; //centimeters
    Serial.print("   Distance sensor value: ");
    Serial.println(distance);

    if (light < 400)
    {
      Serial.println("Light below threshold");
      setAlarmMode = false;
      activateAlarm();
    }

    if (distance < 50)
    {
      Serial.println("Distance below threshold");
      setAlarmMode = false;
      activateAlarm();
    }

    delay(500);
  }

I have also created a function to hold the common code of showing the alarm:
void activateAlarm(void)
{
  digitalWrite(12, HIGH); //red on
  digitalWrite(13, LOW); // green off
  digitalWrite(14, LOW); //yellow off
  tone(16, 832);
  delay(500);
}

Thank you so much for your help! I really appreciate it. The program works great now.

The problem is that, if you enter 'O', you go thorugh the set alarm case only once. If no alarm was triggered, it just falls through the if statements and is then back in the main loop. In that main loop, you only check for your sensors, if something was entered to the serial console. That means if you do not enter anything during a loop, nothing happens.
The solution to this would be to implement a finite state machine.
That means you use a state variable for the switch case. You then update your state based on the state and the external conditions. In your case you can just update the state using user input.
I changed your code a bit for a possible (but bad) implementation. I did not verify or check for errors. I recommend using a more solid implementation, if you plan to build upon this code for more complex behavior.
char state = 'A'; //initialize state in Off state
char b;          // make user input variable global
void setup()
{
  Serial.begin(115200);
  pinMode(12, OUTPUT); //RED
  pinMode(13, OUTPUT); //GREEN
  pinMode(14, OUTPUT); //YELLOW
  pinMode(16, OUTPUT); //SPEAKER
  pinMode(4, INPUT); //Echo
  pinMode(2, OUTPUT); //Trig
}

void loop()
{
  if (Serial.available() > 0)
  {
    b = Serial.read();
  }
  // close user input section

  switch (state) // run switch case every loop
  {
    //Turn Alarm off
    case 'A' :
      {
        digitalWrite(12, LOW); //red off
        digitalWrite(13, LOW); // green off
        digitalWrite(14, LOW); //yellow off
        noTone(16);

        delay(500);
      }
      break;

    // Set alarm
    case 'O' :
      {
        int light;
        light = analogRead(0);
        unsigned long distance;
        digitalWrite(2, LOW);
        delayMicroseconds(2);
        digitalWrite(2, HIGH);
        delayMicroseconds(10);
        digitalWrite(2, LOW);
        distance = pulseIn(4, HIGH);
        distance = distance / 58; //centimeters
        delay(500);

        digitalWrite(12, LOW); //red off
        digitalWrite(14, LOW); //yellow off
        digitalWrite(13, HIGH); //green on

        if (light < 400)
        {
          digitalWrite(12, HIGH); //red on
          digitalWrite(13, LOW); // green off
          digitalWrite(14, LOW); //yellow off
          tone(16, 832);
          delay(500);
        }

        if (distance < 50)
        {
          digitalWrite(12, HIGH); //red on
          digitalWrite(13, LOW); // green off
          digitalWrite(14, LOW); //yellow off
          tone(16, 832);
          delay(500);
        }

      }
      break;

    // snooze option
    case 'Z' :
      {
        digitalWrite(14, HIGH); //yellow on
        digitalWrite(12, LOW); //red off
        digitalWrite(13, LOW); // green off
        noTone(16);
        delay(300000UL);
        digitalWrite(12, HIGH); //red on
        digitalWrite(13, LOW); // green off
        digitalWrite(14, LOW); //yellow off
        tone(16, 832);
        delay(500);
      }
      break;
  }

  state = b; // update state based on input

}


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:
Speaker-dependent Voice Recognition
I would like to install speaker-dependent voice recognition in a robot equipped with Arduino Uno compatible boards.
Specifically, I want to record the robot's name beforehand and have it respond when I call the robot's name.
Although it is not an Arduino, there is a person who has developed a function that I would like to realize with the M5StickV.
This person used isolated_word.py, a library published by Sipeed, as a reference.
【K210】マイク搭載版M5StickV,Sipeed Maixシリーズで音声認識をする
After some research, I found Maix_Speech_Recognition in the library of Maixduino, which can use Arduino IDE.
Apparently, it uses Mel-frequency cepstrum coefficients analysis of speech input, and then uses dynamic time stretching to find the similarity.
The MFCC uses the K210 FFT on the Maixduino.
Arduino Uno does not have an FFT accelerator, but it can do FFT.
Therefore, I thought it would be possible to use Maix_Speech_Recognition for specific speaker speech recognition on ArduinoUno compatible devices.
Question

Is it possible to use Maix_Speech_Recognition for speaker-dependent voice recognition on Arduino Uno compatible boards?
What part of Maix_Speech_Recognition should I modify to make it work on Arduino Uno compatible boards?

Why don't you try it out? I doubt the UNO has enough processing power for voice recognition, but I might be wrong.

The UNO has way too little RAM to do an FFT big enough to be useful for this... only 2K.  And since it doesn't have a math coprocessor in hardware to compute all the trig factors on the fly, it would have to store those in the same limited RAM space or else your FFT would slow to a crawl.  I think you should consider another approach.

Is it possible to use Maix_Speech_Recognition for speaker-dependent voice recognition on Arduino Uno compatible boards?

No. It's not.

What part of Maix_Speech_Recognition should I modify to make it work on Arduino Uno compatible boards?

Don't even think about it. The UNO cannot do anything even remotely like speech recognition of any form without adding extra specific speech recognition hardware.
Just get a K210 board - they're cheap enough.


text:
Substring: What is causing my output to be truncated?
I suspect that I might be using too many resources, because of the strings, but I am new to Arduino, so not sure where I am going wrong.  Any help would be appreciated.
What it should do when complete:
"Birthday Reminder"

Read the SD card for a "birthday" file ("MM-DD.txt" ) that matches
"today".
The file contains the Name of the person and year of
birth.
Flash LED's and display the person's name and age on the
OLED.
The unit will not displayed anything until someone's birthday.

I am using the SD card with a simple format, to easily add new birthday's.
Output:
⸮Initializing SD card...
card initialized.
25
111
opening: 04-25.txt
2020"Test Person"
bYearStr: 20

The sd card file:
Name: MM-DD.txt
Example: 04-25.txt

Contents: Birthyear, Name
Example: 2020"Test Person"

The Sketch
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "RTClib.h"

RTC_DS3231 rtc;

int age;
int led;
int dly;
String bName;
String bYearStr;
int bYear;
int currentDay;
int  tDy;
int  tMth;
int  tYr;

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

void setup() {
  Serial.begin(9600);
  delay(3000); // wait for console opening

  // Setup Candle pins
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.clearDisplay();
  display.display(); // this command will display all the data which is in buffer
  display.setTextColor(WHITE, BLACK);

  const int SdCardPin = 10;
  Serial.println("Initializing SD card..."); // Verifying SD Card.
  //  if (!SD.begin(SdCardPin)) {
  if (!SD.begin(10)) {
    Serial.println("Card failed, or not present"); // don't do anything more:
    while (1);
  }
  Serial.println("card initialized.");

  currentDay = 111;
}

void loop() {
  age = 0;

  DateTime now = rtc.now();
  tDy = now.day();
  tMth = now.month();
  tYr = now.year();
  Serial.println(tDy);
  Serial.println(currentDay);

  if (currentDay != tDy) {
    String fileName;
    String m = String(tMth);
    String d = String(tDy);

    if (tMth < 10) {
      String mm = m;
      m = "0" + mm;
    }
    if (tDy < 10) {
      String dd = d;
      d =  "0" + dd;
    }
    fileName = m + "-" + d + ".txt";

    //String fileName = "01-01.txt";
    Serial.println("opening: " + fileName);
    File f = SD.open(fileName);
    delay(3000);

    if (!f) {
      Serial.println("open failed");
    } else {
      while (f.available()) {
        String line = f.readStringUntil('\n');
        Serial.println(line);
        bYearStr = line.substring(0, 4);
        bName = line.substring(4);
        delay(1000);
        currentDay = tDy;
        break;
      }
      f.close();
    }

    Serial.print("bYearStr: ");
    Serial.println(bYearStr);
    Serial.print("bName: ");
    Serial.println(bName);
    int bYear = bYearStr.toInt();
    age = tYr - bYear;
    Serial.print("Age: ");
    Serial.println(age);

  } else { // Start current day equal
    display.setTextSize(1);
    display.setCursor(38, 10);
    display.print("Birthday!");
    display.println();

    display.setTextSize(1);
    display.setCursor(0, 30);
    display.print("Name: ");
    display.print(bName);
    display.setCursor(0, 40);
    display.print("Age: ");
    display.print(age );
    display.println();

    led = random(3, 6);
    dly = random(80, 250);
    digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(dly);              // wait
    digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  } // End current day

  display.display();

} // End void Loop

There is no  more Serial output after the 2 first characters of the String "2020" ?
Very strange. You might simplify your sketch to a test environment only, without all the display stuff, eventually even without RTC.

Don´t use String class. Replace it with char arrays. You are probably running out of heap memory.

Thanks.  @DataFiddler I have done that and it works to the serial print.  The sketch also works when I don't us the SD card, but put the birthday's in an smaller test array (3 names).  I run into problems with larger arrays (13 names).  I broke it apart and have been building it back up. For info, I am not getting the display at all, it appears the script stops at the output.

Thanks, @SBF I was afraid that is what was happening.

It is quite likely you're out of memory. To know, really you need to keep track of the stack pointer and heap structure. There's enough going on in your code, that I'm not reasonably going to be able to set up an identical scenario to prove it.
Display Library
The greatest use of SRAM in your project comes from the Adafruit SSD1306 library.  It's allocating a buffer for the entire frame, which is 128 * 64 == 8192 bits, or 1024 bytes, half your Nano's SRAM.  It will use more than that for other data, though probably not a lot more by percentage.
You may be able to mitigate this usage with a library like trades some SRAM usage for extra execution time or lower frame rates.  One is the U8g2 library.  You can read about how it can use half-buffer in some documentation to the older version of the library; the concept carries over to the newer library.
SD Library
The next largest usage is the SD card libraries sector buffer, which is 512 bytes.
So between the two of them, there go 3/4 of your SRAM in just the two buffers, nevermind anything else.
You may be able to avoid this buffer by using a different library.  You could try PetitFS.  The library it wraps says it uses something like 44 bytes plus whatever call stack is needed.
String Literals
You have at least 206 bytes of string literals in your sketch alone, assuming the compiler can't determine that any of them are in fact unused.  There may be others in the libraries, though probably not many. So now we're down to at least 306 bytes or less SRAM.

Size
String

35
"RTC lost power, lets set the time!"

28
"Card failed, or not present"

24
"Initializing SD card..."

18
"Couldn't find RTC"

18
"card initialized."

12
"open failed"

11
"bYearStr: "

10
"opening: "

10
"Birthday!"

10
"01-01.txt"

8
"bName: "

7
"Name: "

6
"Age: "

5
".txt"

2
"-"

2
"0"

206
Total

The "0" is only counted once in the above, even though you have two of them.  Fun fact: the C and C++ languages allow identical string literals to be colocated or overlap.  I don't know whether or not avr-gcc will combine "Name: " into "bName: ", since you have bigger problems to worry about, I'm just pretending it won't without looking.
Mitigation can include use of the F() macro to move some of these string literals into PROGMEM (flash).  You can't do this to every string literal, but the ones where you're involving them in a String(F("we're trying to avoid these right?")) constructor or in Serial (or other Stream/Print instances)'s .print(F("Hello World"));
The guts of the F() macro is another called PSTR(), which does the actual work of putting the string literal into PROGMEM.  F() tags the resulting pointer with a dummy type that is used in function overloading in Arduino libraries.  The only reason why I mention this is because below, you'll see me use PSTR to do the same thing, only with a function that belongs to avr-libc rather than Arduino.
Note when you're initializing a String object from a regular string literal, you're paying the SRAM cost twice for the lifetime of the String object.  One copy is in SRAM for the literal used to call the String constructor, the other copy is in the dynamic memory allocated to the String object.
String class
This was pointed out in the comments; and it's true that it's better to avoid them.  Although, I think not actually the greatest problem in your case.
I see you've avoided unnecessarily adding them together for Serial output and instead are using separate .print() calls, so you're ahead of the game there.
For your filename, mitigation could be using fixed size local char array and snprintf_P() to cobble together your filename, something like:
char filename[sizeof "MM-DD.txt"];
snprintf_P(
    filename, sizeof filename,
    PSTR("%02u-%02u.txt"),
    tMth, tDy
);

or if you wanted to avoid pulling the beast of printf into your sketch, assuming it's not already there, you could do something like:
const char filename[] = {
    '0' + tMth / 10,
    '0' + tMth % 10,
    '-',
    '0' + tDy  / 10,
    '0' + tDy  % 10,
    '.',
    't',
    'x',
    't',
    '\0'
};

Serial
What Serial?  Yup, I mean, there's not a lot you can do about it, but I bring it up because the last conservative figure above was 306 bytes, and we didn't try to account for the what String is doing in the heap at all.  Well Serial takes 157 bytes according to a simple test here, which makes sense, because on the UNO it has two ring buffers for transmit and receive that are 64 bytes in size each, half a dozen pointers for configuring hardware registers to use, and head and tail indices for those buffers.  There's also another 12 bytes that are used for HardWareSerial's vtable.
So that puts you down to conservatively 137 bytes of SRAM for well, everything else.
Everything Else
There's a lot not accounted for here. Your globals, the libraries globals, other vtables, the String data on the heap, and the stack.  Those are just the ones coming to mind.  I mean just the millis()/micros() counter variables and fract take 9 bytes.  If you really want to dig into the details here, besides looking at the stack pointer and heap structure, the avr-nm command run on your sketch's .elf file with its -D, -S, and --size-sort is helpful for locating global variable usage and similar things.

Actually you could modify the core files (or possibly the board definition) to get HardwareSerial to use a smaller buffers.  So, it's not completely out of your control.  Not sure if it's worth editing in; it's kind of lower on te list.


text:
ESP32 cam offline
Can the ESP32 cam be used with no internet connection.
I have my newly acquired ESP32-CAM up and running as per this really great tutorial:
https://randomnerdtutorials.com/esp32-cam-video-streaming-face-recognition-arduino-ide/
But I just realized the sketch has no HTML in it and must rely on internet access.
I need to stream video to my tablet when I don't have an internet connection.
Possible using the ESP32 Cam?

You could make your own WiFi-Network with the ESP32, just google for it. Then you'd have to connect your tablet to it and open the Website.

Why do you think, that the linked tutorial requires internet access?

When I shutdown my access to the internet (via my phone hotspot) the ESP32 CAM stops streaming.   But upon closer examination if I reboot the router as well.... even with no inter connection it works again.  Guess I have egg on my face.

Of course it's possible. Just write a sketch that does what you want. The camera operation has nothing to do with the internet. Only the pretty website that is coded into that sketch.


text:
How do I get sensor values using transmitter and receiver?
I used an HC-SR04 sensor and connected it to an Arduino board (BOARD1) with a 433 MHz transmitter, and the other board (BOARD2) is connected to the 433 MHz receiver. I don't know how to see the sensor value readings from the (BOARD1) in the serial monitor.
HERE IS THE CODE OF THE TRANSMITTER
#include <RH_ASK.h>
#include <SPI.h> // Not actually used but needed to compile

RH_ASK driver;
int echo=11;
int trig=9; int sensorval;
void setup() {
   Serial.begin(9600); // Debugging only
   driver.init();
}

void loop() {
   digitalWrite(trig,LOW);
   delayMicroseconds(10);
   digitalWrite(trig,HIGH);
   delayMicroseconds(10);
   digitalWrite(trig,LOW);
   delayMicroseconds(10);
   sensorval=pulseIn(echo,HIGH);
   const char *msg = sensorval;
   driver.send((uint8_t *)msg, strlen(msg));
   driver.waitPacketSent();
   delay(200);
}

HERE IS THE CODE OF THE RECEIVER
#include <RH_ASK.h>
#include <SPI.h> // Not actually used but needed to compile

RH_ASK driver;
const int sensorval;
void setup() {
    Serial.begin(9600); // Debugging only
    driver.init();
}

void loop() {
    uint8_t buf[4];
    uint8_t buflen = sizeof(buf);
    if (driver.recv(buf, &buflen)) // Non-blocking
    {
    Serial.print("message Received: ");
 Serial.println((char*)buf);
    }
}

First: A short excourse about c-strings
In C a string is an array of characters. Such an array is defined with
char msg[10];

10 being the size of the array. Every valid c-string needs to be terminated with the null character \0. This character is not printable, thus you don't see it normally. But the standard string functions (like printf(), strlen(), etc) use the null character to find the end of the string. So when handling strings as char arrays, you absolutely always need to terminate the string with the null character. The standard functions are incrementing through the array, until they find the null character. If it is missing, they don't stop at the end of the array.
Needing the null character also means, that the above char array can only hold 9 characters (since the 10th is the null character).
The standard functions for creating a string (like printf() and its siblings) already terminate the string correctly with the null character.

You are obviously trying to send an ASCII encoded string. But sensorval is not a string, it is of type int (a number). In C/C++ one does not simply implicitly convert a number to a string (please insert the image of boromir from Lord of the Rings here in your head). You actually have to say the compiler how to convert the number to a string. Also sensorval cannot itself hold that string (as it is an integer number). For that you need a char array (often called c-string) for saving all the characters of your string.
So first we need to define the char array to hold our string:
char msg[10];

This creates a char array with 10 elements, each one can hold a character of your string. So you have space for 9 characters. If you need more, you can increase that number.
Now we need to build a string in msg, that represents the value of sensorval. For that we can use sprintf(), which lets us format a string out of data and save it in a char array.
sprintf(msg, "%d", sensorval);

The first parameter is the char array to put the string in. The second parameter is called format-string. That is a string literal, that defines the format. %d represents an integer value; it is a placeholder for the actual data and describes, how it should be formatted (you can read about the different format options in the C++ documentation if you search for printf()). The following parameters (here only one) are the data values for the placeholders in the format string. Let's take an example: Assume sensorval is 1000. Then msg will be:
1000\0

The \0 being the null character.
So in your code you would replace
const char *msg = sensorval;

with
char msg[10];
sprintf(msg, "%d", sensorval);

What you have done in your code:
This line
const char *msg = sensorval;

will NOT create a string. You are defining msg as a pointer to a constant character (a pointer is a variable, that holds the address another variable in the memory, use google terms like "C pointers" for more info). And then you set the pointer to sensorval, which of course is not a valid pointer (valid meaning pointing to something reasonable here). It just points somewhere in the memory.
The example, that you got it from uses:
const char *msg = "hello";

This works, because the compiler takes all string literals (the strings enclosed by the double quotes) and puts them fixed into the memory, somewhat like a variable without a name. So here the compiler instructs the microcontroller so save the string "hello" in the memory. With the above line we define a pointer to the place in the memory, where this string is saved.
So this works good for string literals, but not, if you first need to actually build the string.

i'm sorry i am new to this so i don't quite understand what to do. From what I have read on your answer, should I replace the const char *msg=sensorval;  to  char msg[10]; sprintf(msg, "%d", sensorval); or before the void setup, I will put a string sensorval;?

@ThomasRaymondSantos I overhauled my answer to explain in more depth, what is happening here and what to do.

okay i'll try to understand, thank you so much for the help!

Otherwise it might be good to do some tutorials about c-strings. I'm sure there are many online

thank you @chrisl appreciate it!


text:
Nano 33 BLE Sense LED flashing 3/5 slow/fast after upload
I'd successfully got my Nano 33 BLE Sense to read accelerometer data and subject to there being a difference between current and last readings, to send this via the EasyTransfer library to an XBee module over hardware serial that communicated with another module which published the readings to the AWS Cloud via a Nano IoT.  I then ambitiously decided I'd add more sensor data to the payload to include pressure, temperature and humidity.  I added these floats to my data structure (see code below) as well as Boolean flags to indicate if there had been an event (i.e. a reading over a threshold) and if any one of the flags was true, to transmit the payload.  The code compiles fine, uploads to complete but then the LED on the Nano flashes 3 times slowly and 5 times quickly in succession.  I had this last time because I'd forgotten a .begin() statement but adding this fixed the issue.  However, I've gone through my code and can't see what is causing the issue this time.  I have run smaller code units to check the sensors are working which they are. Help!!
#include <EasyTransfer.h>
#include <Arduino_LSM9DS1.h>
#include <Arduino_LPS22HB.h>
#include <Arduino_HTS221.h>

#define TX_PIN 6
#define RX_PIN 5

const float MOTION_TOLERANCE = 0.01;
const float PRESSURE_THRESHOLD = 1000.00;
const float TEMPERATURE_THRESHOLD = 20.00;
const float HUMIDITY_THRESHOLD = 50.00;

UART XBeeTx(digitalPinToPinName(TX_PIN), digitalPinToPinName(RX_PIN), NC, NC);

EasyTransfer ET;

struct SEND_DATA_STRUCTURE {

  String sensorLocation;
  bool motionEvent;
  float xAcc;
  float yAcc;
  float zAcc;
  bool pressureEvent;
  float pressure;
  bool temperatureEvent;
  float temperature;
  bool humidityEvent;
  float humidity;

};

SEND_DATA_STRUCTURE myData;

float xAccCurrent, yAccCurrent, zAccCurrent, xAccLast, yAccLast, zAccLast, pressureReading, temperatureReading, humidityReading;

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {

if(!IMU.begin()) {

  // Stop if IMU fails to initialise
  while(1);

}

if(!BARO.begin()) {

    // Stop if pressure sensor fails to initialise
  while(1);

}
if (!HTS.begin()) {

  // Stop if temp and humidity sensor fails to initialise
  while(1);

}

 // Accelerometer code
   IMU.setAccelFS(3);
   IMU.setAccelODR(5);
   IMU.setAccelOffset(0.003955, -0.010136, -0.013462);
   IMU.setAccelSlope (0.997163, 1.000438, 0.995678);

if (XBeeTx.available()) {

  XBeeTx.begin(9600);
  ET.begin(details(myData), &XBeeTx);

  }

   myData.sensorLocation = "Zone 1";

}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {

if (IMU.accelerationAvailable()) {

    IMU.readAcceleration(xAccCurrent, yAccCurrent, zAccCurrent);

  }

if ((abs(xAccLast -xAccCurrent) > MOTION_TOLERANCE) || (abs(yAccLast -yAccCurrent) > MOTION_TOLERANCE) || (abs(zAccLast -zAccCurrent) > MOTION_TOLERANCE)) {

  myData.motionEvent = true;
  myData.xAcc = xAccCurrent;
  myData.yAcc = yAccCurrent;
  myData.zAcc = zAccCurrent;

  xAccLast = xAccCurrent;
  yAccLast = yAccCurrent;
  zAccLast = zAccCurrent;

}

pressureReading = BARO.readPressure(MILLIBAR);
if (pressureReading > PRESSURE_THRESHOLD) {

  myData.pressureEvent = true;
  myData.pressure = pressureReading;

}

temperatureReading = HTS.readTemperature();
if (temperatureReading > TEMPERATURE_THRESHOLD) {

  myData.temperatureEvent = true;
  myData.temperature = temperatureReading;

}

humidityReading = HTS.readHumidity();
if (humidityReading > HUMIDITY_THRESHOLD) {

  myData.humidityEvent = true;
  myData.humidity = humidityReading;

}

if (myData.motionEvent || myData.pressureEvent || myData.temperatureEvent || myData.humidityEvent) {

 ET.sendData();

 delay(1000);

 myData.motionEvent = false;
 myData.pressureEvent =false;
 myData.temperatureEvent = false;
 myData.humidityEvent =false;

}

}

Add serial prints to find out how long each part of the code takes

Hi,  I could do the board is locking up so the serial monitor doesn't load.  Oddly if I comment out the if (XBeeTx.available()) and just begin() the XBeeTx and ET then it seems to load fine and I can see from the Xbee LEDs that data is being sent by one and received by the other.  So not sure why the XBeeTx.available() isn't triggering the right outcome - it obviously is available otherwise I couldn't begin it?

K, I have no experience with your hardware. Is 9600 the correct baudrate?

Are you sure that calling .begin() after .available() is correct? Seems odd to me.

I've got the code loading ok and the Xbees are obviously communcating but the nano board doesn't seem to be getting any data.  Looking at the GitHub docs for the EasyTransfer library there is some mentioned of a limit of 255 bytes for the struct() so I may have hit that issue but I have the same problem if my struct is just a string and 3 floats.  Worlds fine with 3 floats but adding the string seems to cause a problem.  odd!

Also saw a reference online to a similar (not the same) issue and slowing the baud rate to 1200 seemed to sort that out so I'll look at that as well.

"Odd behaviour" often is a sign that there is a problem with ram usage and if it works when you remove a string strongly suspects the same. Especially on a microcontroller where software is much more predictable, chances are relatively high that ram violations don't result in a crash, but unpredictable behaviour. But if it is a ram problem, decreasing the baudrate should make it even worse as more data is accumulated in a dynamic buffer, so my guess is, that this is only a phantom fix.


text:
ESP8266 not running when connected to 3V3
I have a simple code that uses a tactile button and ESP8266.  I have one wire going from GND to one leg and one wire going from D3 to the other leg.  Works perfectly.  When I start it up, I have write statements in setup() which show that it is starting up and working.
I wanted to switch to a Touch Sensor.  I added a wire from one of the 3V3 to the VCC of the sensor.  If I do this while the program is running it seems to work... (it recognizes when I touch the sensor).  However, if I reset the ESP, then it no longer runs.  I see nothing in the serial window.
I tried to narrow the problem down and here's where I'm at...

The ESP is connected via USB to the computer so I can look at the console window to track how it's running.
I have a wire connected to D3 and GND (but the ends aren't connected to anything).  I reset the ESP and I see in the console window that it is printing out the expected print statements in setup().
I add a wire to 3V3 (it is not connected to anything).  I reset the ESP and now no print statements are in the console window - so I believe it is not running.

Why?  I thought 3V3 was to connect to sensors to power them.  Not input to the ESP.  So what am I missing?
RESOLVED:  I randomly picked the wrong GPIO to use... I switched to D1 and it now works ok.


text:
Accessing start up bits of SRAM from MicroBit for PUF
https://infocenter.nordicsemi.com/pdf/nRF51822_PS_v3.4.pdf
The aim is to extract (output in serial monitor) the start up bits from  the SRAM of this microbit which is located at memory address 0x20000000, given by the datasheet above, all done in the arduino IDE.
After some searches I emerged on this code
void setup()
{
  uint8_t const * p;
  uint8_t i;

  Serial.begin( 115200 );

  p = 0;
  i = 0;

  do
  {
    Serial.print( *p, HEX );
    Serial.print( ' ' );

    ++i;
    ++p;

    if ( (i & 0xF) == 0 )
    {
      Serial.println();
    }
  }
  while ( i != 0 );
}

void loop()
{
}

From this link https://forum.arduino.cc/t/accessing-sram-on-arduino-uno/267777/6
However this pertains to an arduino uno and I'm not entirely sure how I would transfer it to my microbit.


text:
Basic hardware debouncing
I was watching Jeremy Blum's Arduino tutorial series, and he explained the need for debouncing in a simple circuit involving a pushbutton. Pressing the button once should mean the led stays on, and pushing the button again should mean the led should stay off, and so on.
He implemented hardware debouncing on this circuit: using an RC circuit along with an inverting Schmitt trigger.
https://www.youtube.com/watch?v=CRJUdf5TTQQ&list=PLA567CE235D39FA84&index=10 2:45-8:45.
However, the circuit isn't performing as expected, when I implemented the denbuncing. Its behaving as if the debouncing has no effect:-

If anyone wants to see the simulation:-
https://www.tinkercad.com/things/dniOQmnxJPY
Where exactly have I gone wrong? I have checked all the connections multiple times, it seems to be what Jeremy blum had in his video...

I changed the "debugging" in the title to "debouncing", because obviously you meant that. Also "hardware debugging" has a specific meaning with microcontrollers. That would only lead to confusion

When following the link for your simulation I am required to log in. Maybe you need to make the simulation public somehow, before anyone can see it.

I see, thanks for letting me know

@chrisl I have made it public now.

@chrisl i have edited the link

@PythonSchlange I gabe edited the link/

@jsotola it means the circuit is behaving similar to how it behaved prior to debouncing.

You have shortened the lower and upper pins of 74HC14, no?

@SBF how have I shorted it?

what connects the top right resistor to the LED?

@jsotola I dont..get your question.... The cathode of the led is connected to ground through a resistor...

what makes the connection between the resistor and the LED?

@jsotola the metallic rails of the breadboard....?

yes, that is correct ... now look at where you plugged in your IC

@satan29 What SBF meant is the following: The 74HC14 has 2 rows of pins you have put it on one side of the breadboard. That means, that the first on the left pin row of the chip and the first on the right row are connection. Similar for all other pins. Such chips need to be placed right in the middle of the breadboard, so that there is no electrical connection between the sides. That is your problem.

You should look up a tutorial on youtube about how to use a breadboard. Your configuration has serious issues. Fyi, on your74hc14, pin 7 is ground, and pin 14 is Vcc (power). You have power going to pins 1 and 14, and ground going to pins 7 and 8. You have the other opposing pins connected to each other as well.

oh i see @chrisl, thanks.

@lurker tinkercad offers to let you know which pin does what in the IC. I know how to use a breadboard! but i haven't worked with IC's much, and I do understand the error crisl has pointed out.

You did not change the lastbutton, but you compared it to HIGH. Change your code to the one below.
You can more easily avoid such mistakes, if you put spaces around operators.
//sp is switchpin, lp is ledpin

int sp=2; //interrupt enabled pin (interrupt 0)
bool ledon=LOW;
bool lastbutton=LOW;
int lp=9;
void setup()
{
  Serial.begin(9600);
  pinMode(sp, INPUT);
  pinMode(lp,OUTPUT);
}

void loop()
{

   if (digitalRead(sp)==HIGH && lastbutton==LOW){
      ledon=!ledon;
      lastbutton = HIGH; // previously here was lastbutton==HIGH;
   }

   else {
     lastbutton=digitalRead(sp);
      }
   Serial.println(ledon);
   digitalWrite(lp,ledon);

     }

Ah yes. Thanks! The debouncing works perfectly now. But for some weird reason the LED turns on at the start of the simulation....without pressing the switch or anything....any idea why?

I think because of your filter. It takes some time to charge up that capacitor, that means your Inverting Schmitt Trigger input starts low, and at the first run of the loop, your pin 2 starts high. If you put a small delay in your setup(), the LED starts off.

indeed. delay(100) fixes this . Thanks a lot!


text:
Would someone provide an example of extracting data from a char array?

I have tried so many things now that I am just confused.
I am not understanding the way char arrays work.
I can't get the date and names extracted.  And when I use just strings, I jam up the memory.

Below was my last attempt, before asking the question.
while (f.available()) {
  String line = f.readStringUntil('\n');

  if (line.startsWith("04-23")) {
    currentDay = 1;
    int str_len = line.length() + 1;
    char char_array[str_len];
    line.toCharArray(char_array, str_len);
    Serial.println(char_array);                 // Everything works to here
    for (int j = 0; j < 2; j++) {
      b += char_array[j];
    }
    bMth = b.toInt (); // This should be an int of the birth month in this case: 04
  }
}

Var:
format: MM-DD-YYYY,Name  // this is inside the file
line = "04-23-2020,James"  // This is the output from - Serial.println(char_array);

What I am trying to do is

Extract the month/day so that I can compare it to today.
The year so I can calculate the age.
The name to display on OLED.
Everything else seems to work, but I can't get my head
wrapped around the char array access.

To do this in PowerShell I would do:
$line = "04-23-2020,James"

$dob = ($line.Split(","))[0]
$bMth = ($dob.Split("-"))[0] # This is not used in this example
$bDy = ($dob.Split("-"))[1]  # This is not used in this example
$bYr = ($dob.Split("-"))[2]

$age = $(get-date -UFormat %Y) - $bYr

Clear-Host
Write-Host (@'
Name: {0}
Age:  {1}

'@ -f $($line.Split(","))[1], $age)

In Python:
import datetime as dt

line = "04-23-2020,James"

dob = (line.split(',')[0])
bMth = (dob.split("-"))[0] # This is not used in this example
bDy = (dob.split("-"))[1]  # This is not used in this example
bYr = (dob.split("-"))[2]

age = int(dt.datetime.now().year) - int(bYr)

print('Name: ',(line.split(',')[1]))
print('Age: ', age)

Does this help? https://majenko.co.uk/blog/splitting-text-c

I recommend learning how to use the strtok() function. It is also described in Majenkos blog entry

When working with Arduino, cplusplus.com is your friend. Scroll down and look on the left side under (string.h). Lot's of great char functions there. Other useful functions such as iota() - cplusplus.com.
Here's one way to accomplish the parsing of the input data.
// Sketch uses 2064 bytes (6%) of program storage space.
// Global variables use 323 bytes (15%) of dynamic memory.
// Arduino IDE 1.8.9.
char line[] = "04-23-2020,James";
char Name[100];
unsigned int Month, Day, Year;

// Make an attempt to validate the input data.
byte Counter = 0;

void setup(){

  Serial.begin(9600);

  char * pch = strtok(line, "-,");

  while(pch != NULL){
    if(Counter == 0){Month = atoi(pch);}
    else if(Counter == 1){Day = atoi(pch);}
    else if(Counter == 2){Year = atoi(pch);}
    else if(Counter == 3){strcpy(Name, pch);}
    pch = strtok(NULL, "-,");
    Counter += 1;
  }

  // Print out the data.
  if(Counter == 4){
    Serial.println(Month);
    Serial.println(Day);
    Serial.println(Year);
    Serial.println(Name);
  }
  else{
    Serial.println("Error");
  }

}

void loop(){}

You could try sscanf if your data format is fixed, something like this:
char line[] = "04-23-2020,James";
int day, month, year;
char name[100];
if (sscanf(line, "%d-%d-%d,%s", &month, &day, &year, name) == 4)
{
    // Process the four items.
}

but the code for scanf takes 1.5kB flash memory


text:
Networking Multiple Arduinos -- Is It "Rocket Science?"
Have a set of Arduinos that need to swap data--for a model rocket launch controller!
How to send 24 bits of info (launch commands) from a "master" Arduino, 12 bits each to two "slave" Arduinos that are 15' to 150' away from the "master.
Each "slave" needs to send 12 bits of info (continuity statii) to the "master."
"Master" <--- 15' to 115' ---> "Slave 1" <--- 10' to 35' --> "Slave 2"
Seems too long for I2C?

This can be improved by getting rid of "TiA..."  I don't know what "RSO Boxes" and "Pad Boxes" are.  I suspect that, if described differently, you'd be drawing answers from a large(r) group of people.  If the question comes down to conveying 16 bits worth of information between two Arduinos at low frequency, over a distance of 100 feet, probably a lot of people here can answer that.

do some research about fireworks fire control systems .... perhaps you should be thinking of using multiple pins for issuing a launch command to one launch platform

This sounds like a job for DMX512...

Hmmm.  Had thought about using DMX cabling.  But yes, if one has to add a sub-PCB, DMX signaling might be as valid yet simpler than 802.{whatever} networking.  Has anyone tied DMX signals to Arduino?

Check this link about DMX512 on Arduino: https://playground.arduino.cc/Learning/DMX/

The best solution would be to use an RS485 adapter connected to each Arduino via serial port. This is a tried and true solution that is perfect for a setup like this and only costs a few bucks of extra hardware per node.
If you can't use additional hardware, you can also create a poor-man's current loop system like RS485 using normal Arduino pins since they are capable of sourcing and sinking 20mA.
With either of these solutions, you can send however much data as you want as long as you have some kind of minimal protocol to serialize it into a sequence of bits on the wire. To send 12 bits, you might just define a start condition as an idle "0" on the wire for a certain period of time, followed by a "1" start bit, followed by you 12 data bits, followed  maybe a parity bit or a checksum, and completed by a "1" stop bit.
Check out how, say RS232 or RS485 serialize bits to get an idea of how this works. If you end up using hardware that only supports sending data in 8 bit chunks, then you could, say, send two bytes per data "packet" where each byte has 6 bits of your data, plus one bit that indicates if ths byte is the first group of 6 bits or the second group, and then one bit of parity for error checking.

I've got I2C to work reliability between Arduinos with different byte sizes. I have copied the test code below. Note that there is separate code for sending and receiving. It may need to be tweaked but contains the basic idea.
One (or more) Arduinos sends to main I2C controller:
Sender Code:
//sender test

#include <Wire.h>

#include <Wire.h>
#define NUMDATA 4

byte byteData[2 * NUMDATA]; //= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

//test

void setup()
{
  Wire.begin(3);                // join i2c bus with address #3
  Wire.onRequest(requestEvent); // register event
}

void loop()
{
int aData;
  for(int i = 0; i < NUMDATA; i++){
    aData = analogRead(i);

    byteData[i*2 + 1] = ((aData >> 8)  & 0xFF);
    byteData[i*2] = (aData & 0xFF);

   // memcpy((void *)byteData[i*2], (void *) analogRead(i), sizeof(int));
  }

}

void requestEvent()
{
  Wire.write(byteData, 2 * NUMDATA);
}

Receiving Code:
#include <Wire.h>

void setup()
{
  Wire.begin();        // join i2c bus (address optional for main controller)
  Serial.begin(9600);  // start Serial for output
}

void loop()
{

  getSenderData();

  Serial.println("Hello");
  delay(500);
}

void getSenderData() {
//Gets sensor data for one grid

    //Byte Array to get raw bytes
    byte ICdataAsBytes[8];
    int i = 0;

    Wire.requestFrom(3,8);    // request 6 bytes from sending device #2

    while(Wire.available())    // sender may send less than requested
        ICdataAsBytes[i++] = Wire.read();

    int *tempData =(int*)&ICdataAsBytes;

    for( i = 0; i < 4; i++)
        Serial.println(tempData[i]);

}

I2C at distances up to 115 ft (≈ 35 m) ? Really ?

Ah I missed this important note, thanks.  Yep, the distance seems way out of spec.


text:
Interfacing LM35 and MQ2 with Arduino
When I interface LM35 temperature sensor and MQ-2 gas sensor with Arduino - my LM35 sensor gave incorrect values. From research I've found out that MQ-2 gas sensor dragging the AREF voltage down and causing the error due to its 31ohm heater that drawn 161mA current . What'll I do to solve this problem?

A wiring diagram would help! But it sounds like you're powering your sensor from the Arduino's AREF pin. That is not the purpose of AREF; AREF is there for you to provide an accurate +5v or other reference voltage to the A/D convertor.
You need to power the sensor independently from your 5v supply (and not through the Arduino either, because of the sensors current draw); connect the sensor's Analog Out to one of the Arduino's A/D pins, sensor Ground to the supply ground. The digital out appears to be optional, if all you want is a go/no-go output that you adjust with the on-sensor potentiometer.