text:
watchdog timer giving me fits on ESP8266, how to find relevant code from Serial output describing the RST?
I've written a pair of sketches for two NodeMCUs to implement a noise meter. The master MCU voltage samples off an opamp's output pin and periodically digests 500 samples at a time into an RMS-type calculation. Every 500ms or so, when it has accumulated 10 of those RMS samples, it sends off a packet with a timestamp and checksum to the slave MCU. This mostly works -- It's been running for about 4 and a half hours without a RST. However, I added a bit of logic recently to request an updated value from the slave and now I'm having trouble with the watchdog timer resetting the master MCU. These resets lose anywhere from a single packet to about 2 minutes of data.
NOTE: WiFi is disabled on this master MCU using a preinit function.
I've done some trial-and-error, including:

adding delay(1) to allow housekeeping and interrupts but this seems to introduce other instabilities
add calls to system_soft_wdt_feed() which has very little explanation in the docs.

Given that the problem is infrequent, it's quite difficult to reproduce the conditions for it to happen. There appears to be some perfect storm of unusual conditions that cause it to trigger. So my question is this:
Is there some way to determine from the serial monitor output where the watchdog timer is firing? And a follow-on question what does this wdt output (boot mode, csum, etc) mean? Here are a handful of watchdog timer messages I see in the serial monitor when the reset happens:
ets Jan  8 2013,rst cause:4, boot mode:(3,2)

wdt reset
load 0x4010f000, len 3456, room 16
tail 0
chksum 0x84
csum 0x84
va5432625
~ld
--
 ets Jan  8 2013,rst cause:4, boot mode:(3,2)

wdt reset
load 0x4010f000, len 3456, room 16
tail 0
chksum 0x84
csum 0x84
va5432625
~ld
--
 ets Jan  8 2013,rst cause:4, boot mode:(3,2)

wdt reset
load 0x4010f000, len 3456, room 16
tail 0
chksum 0x84
csum 0x84
va5432625
~ld
--
 ets Jan  8 2013,rst cause:4, boot mode:(3,2)

wdt reset
load 0x4010f000, len 3456, room 16
tail 0
chksum 0x84
csum 0x84
va5432625
~ld
--
 ets Jan  8 2013,rst cause:4, boot mode:(3,2)

wdt reset
load 0x4010f000, len 3456, room 16
tail 0
chksum 0x84
csum 0x84
va5432625
~ld
--
 ets Jan  8 2013,rst cause:4, boot mode:(3,2)

wdt reset
load 0x4010f000, len 3456, room 16
tail 0
chksum 0x84
csum 0x84
va5432625
~ld
--
 ets Jan  8 2013,rst cause:4, boot mode:(3,2)

wdt reset
load 0x4010f000, len 3456, room 16
tail 0
chksum 0x84
csum 0x84
va5432625
~ld

As you can see, the RST output seems quite consistent, I just have no idea how to locate the point in my code where code execution goes on too long. The docs here have a stack trace associated with these resets if they are triggered from the software watchdog, but my serial monitor output does not have these stack traces, which suggests that it's the hw watchdog that's doing it. That page says:

Please note that for restarts initialized by h/w wdt, there is no stack trace to help you identify the place in code where the lockup has happened. In such case, to identify the place of lock up, you need to rely on debug messages like Serial.print distributed across the application.

Sadly, I don't know how wise it is to use Serial.print in my loop. The code inside my loop() completes in an average of about 5 microseconds so the output might be extremely verbose. In practice, adding Serial.print commands to track things tends to destabilize the sketch even more, dwarfing the problem I'm trying to solve.
The sketch is pretty lengthy, but its code is here. I've removed the comments for brevity, but it's still about 500 lines. I'm happy to post that code in this post, but worry it might make this post too long.
EDIT: If this is indeed the hardware watchdog that's firing, I would add a question: Is it possible to disable the hardware watchdog or somehow adjust its behavior? I am certain that my app is not locked up because its output continues to be communicated to the slave which posts the samples to a web server. Is the only solution to allow the loop function to complete more frequently?
EDIT: I added a timer which checks micros() at beginning and tracks the maximum amount of time to execute the loop. Usually, this is less than 2500 microseconds, although in one case it took 100ms -- but this did not cause a watchdog reset. The hardware watchdog reset doesn't appear to be related to how much time it takes to execute my loop function. It's something else.
EDIT: I updated my ESP8266 core to 2.7.2 and this did not solve the problem. I would add an additional question: Why is the hardware timer firing and not the software timer?. I have not disabled the software watchdog, and I have no indications that there are any infinite loops preventing completion of the main loop() routine.

system_soft_wdt_feed appears to be related to some type of a software watchdog timer ... that particular command pospones the software WDT reset ... i have a suspicion that it is different from the hardware WDT ... it is unclear if the software WDT triggers the hardware WDT

@jsotola I agree. It would appear from the docs here that software watchdog resets come with a stack trace, but hw wdt resets do not. Also, I have tried numerous calls to system_soft_wdt_feed() and these don't seem to remedy the problem. Sounds like hw watchdog to me, too. Is there any way to disable it? Or appease it somehow?

googled esp8266 feed watchdog ... found this ... https://techtutorialsx.com/2017/01/21/esp8266-watchdog-functions/

@jsotola I've read that, and it mostly just refers back to the docs i linked. It does provide a bit of additional detail -- e.g., the argument to ESP.wdtEnable() isn't even used -- but it does not provide any detail about how to pinpoint the code where timeouts are happening, or how hw wdt works or how to adjust its behavior.

it shows you that disabling the software WDT allows the hardware WDT to take over .... it also shows you how to feed the hardware watchdog .... feed the watchog at the begining of loop() ... if that is not enough, feed near middle of loop() also .... otherwise time your loop and find out how much time various parts use

@jsotola ahhhh I missed the part where it says the feed function also feeds the hw wdt. If you look at the source I linked, you'll see that I'm already calling system_soft_wdt_feed() in at least a couple of spots and also that the entire loop() runs in an average of 5 microseconds. Any thoughts on where to put yet another call to system_soft_wdt_feed?

maybe the way to debug this is to determine the baseline ... write a minimal sketch that only includes a delay ... vary the delay to find out where the hardware WDT fires  ... start with 8 seconds ... add or subtract 4 seconds, then 2 seconds, then 1, then 0.5, etc. .... you do not have to run too many iterations before you determine the delay to within a couple of milliseconds

i re-read that page and it is confusing .... this page https://sigmdel.ca/michel/program/esp8266/arduino/watchdogs_en.html says that the software watchdog feeds the hardware watchdog

@jsotola that sigmdel article looks pretty informative, but I can't imagine any situation that would cause my loop to run anywhere nearly as long as an entire second. also, i do not turn off the software wdt, so i don't know why the hw wdt would fire first. EDIT: I'm also calling the system_soft_wdt_feed fn in four places.

system_adc_read() can cause this if used frequently (in every loop). but I would not expect it if WiFi is off

@Juraj thank you for your response. WiFi is indeed off as you can see from the preinit fn in the  sketch. I also call WiFi.forceSleepBegin(0); in the setup fn.  I do use system_adc_read in the hw timer function which runs as often as possible -- every 100ns. However, it didn't cause any problems in a sketch that is only the tiniest bit simpler than this one. I find it puzzling that the hw watchdog would fire instead of the software watchdog.

then it hangs or crashes somewhere

if i take more than about 800 adc reads per second, the same thing happens to me. i put a 10u cap on it and lowered my sampling rate to fix it w/o much loss of signal.

@Juraj: if it hangs or crashes, shouldn't I see a stack dump? I don't see any stack dump, just the terse reset reports like I provided in my original post.

in corrupted stack anything can happen.

Juraj: i have repeatedly reloaded new code over the past week as I've tried various tweaks. i finally altered the loop() fn to remove the while loop that retried delivery of my data packets, leaving packet delivery to a subsequent loop iteration. i also removed a master-slave status exchange which seemed unecessary. it's been running for 17 hours now. I may have solved the problem, but my question remains unanswered. every crash has nearly the exact same rst message, which is in my original post.

I opened an issue at the 8266 arduino repo and got a response that's pretty high-handed, and wrongly accuses me of using third party libs or hardware, but also has some useful information. Ironic part: they told me to post on stack exchange.


text:
Running hardware interrupt function on NodeMCU ESP8266, Exception(0) after four iterations, can't disarm interupt function
I've been trying to test the stability and consistency of hardware interrupts on my NodeMCU ESP8266. I'm using the Arduino IDE. This sketch should not require any external circuitry and I think, but am not certain that the problem is a value overflowing somewhere. QUESTION 1: Can anyone point out where the problem that's causing Exception(0)?
The hw_timer_* functions are documented in the ESP8266 NONOS SDK reference pdf. The hw_timer_* declarations where not found by the Arduino IDE after I set it up with the board manager url here, so I copied hw_timer.h and hw_timer.c from the Expressif github repo into the same folder as my .ino file. The interrupt functions run now, but after four iterations, I get the exception & a stack dump and then the board reboots with this rst message:
 ets Jan  8 2013,rst cause:4, boot mode:(3,6)

The code of my sketch is here. You shouldn't need any pins or anything.
EDIT: I added volatile before the 3 vars referenced in interrupt and in the other fns.
#include "user_interface.h";
#include "hw_timer.h";
#include "hw_timer.c";

// interrupt interval used for my hw_timer
#define timerInterval 100

// the number of cycle count samples we collect before analyzing
#define totalSamples 500

volatile uint32_t cycleSamples[totalSamples];
volatile uint16_t cycleSampleCount = 0;

// calculate min/max/mean
uint32_t elapsedCycles; // the number of cycles elapsing between two samples
float elapsedSum = 0; // cycles are large numbers...just in case we exceed 2^32 we use a float
uint32_t elapsedMax = 0;
uint32_t elapsedMin = 0xFFFFFFFF;
uint32_t elapsedCount = 0;
float elapsedMean;

// for std dev calculation
float diffSumSquared = 0;
float variance = 0;
float stdDev = 0;

// set to true by the timer fn when it has gathered the samples
volatile bool analyzeSamples = false;

// The hardware timer callback function must NOT be defined with ICACHE_FLASH_ATTR.
// Interrupt callback functions must be in IRAM, because the flash may be in the middle
// of other operations when they occur. Do this by adding the ICACHE_RAM_ATTR attribute
// on the function definition
// @see https://arduino-esp8266.readthedocs.io/en/latest/reference.html#interrupts
ICACHE_RAM_ATTR void my_timer_callback(void) {

  if (analyzeSamples) {
    // if this fn has collected all the samples, we have to skip this until it’s finished analyzing them
    // and resets this
    return;
  }

  if (cycleSampleCount >= totalSamples) {
    // we can't disable this timer
    analyzeSamples = true;
    return;
  }

  // take a peek at the cycles counter to check timing accuracy
  cycleSamples[cycleSampleCount] = ESP.getCycleCount();
  cycleSampleCount++;

}

void setup() {

  Serial.begin(115200);

  for(uint8_t i=5; i>0; i--) {
    Serial.printf("counting %d\n", i);
    delay(1000);
  }

  // START THE SAMPLE TIMER USING HARDWARE INTERRUPTS
  // use NMI_SOURCE for highest priority and quickest/most accurate timing
  hw_timer_init(NMI_SOURCE, 1);
  hw_timer_set_func(my_timer_callback);

  // If NM is used as the ISR source for auto-loading the timer, parameter val of hw_timer_arm can not be less than 100
  hw_timer_arm(timerInterval);

}

void loop() {
  // TODO we need to do something nondeterministic here to see if it fucks up timing of interrupts

  if (analyzeSamples) {

    // this doesn’t work to try and disable the interrupt fn
    // hw_timer_set_func(0);
    // nor does this
    //hw_timer_arm(0);

    Serial.println("Sampling complete, analyzing...");

    elapsedSum = 0; // cycles are large numbers...just in case we exceed 2^32 we use a float
    elapsedMax = 0;
    elapsedMin = 0xFFFFFFFF;
    elapsedCount = 0;

    // we loop from the 1th (i.e, the second) item
    for(uint32_t i = 1; i<totalSamples; i++) {
      elapsedCycles = cycleSamples[i] - cycleSamples[i-1];
      Serial.printf("%d %d\n", i, elapsedCycles);
      elapsedSum += (float)elapsedCycles;
      elapsedMax = max(elapsedMax, elapsedCycles);
      elapsedMin = min(elapsedMin, elapsedCycles);

      elapsedCount++;
    }
    // calculate mean
    elapsedMean = elapsedSum / (float)elapsedCount;
    Serial.print("Average elapsed cycles: ");
    Serial.println(elapsedMean);
    // report min/max
    Serial.print("Elapsed cycles max: ");
    Serial.println(elapsedMax);
    Serial.print("Elapsed cycles min: ");
    Serial.println(elapsedMin);

    // calculate the variance/std dev
    diffSumSquared = 0;
    for(uint32_t i = 1; i<totalSamples; i++) {
      elapsedCycles = cycleSamples[i] - cycleSamples[i-1];
      diffSumSquared +=  sq(elapsedCycles - elapsedMean);
    }
    variance = diffSumSquared / elapsedCount;
    Serial.print("Variance: ");
    Serial.println(variance);
    stdDev = sqrt(variance);
    Serial.print("Std Dev: ");
    Serial.println(stdDev);

    // reset the samples to zero and let's try again
    Serial.println("Gonna reset...");

    ets_intr_lock( ); //close interrupt
    for(uint32_t i = 0; i<totalSamples; i++) {
      cycleSamples[i] = 0;
    }
    cycleSampleCount = 0;
    analyzeSamples = false;
    interrupts();
    ets_intr_unlock(); //open interrupt
    system_soft_wdt_restart();

    Serial.println("Reset complete.");

//    stopStopStop = true;

  } else {
    Serial.println("not yet!");
  }
  Serial.println("sleeping 1...");
  delay(1000); // sleep 1000ms

}

This brings me to QUESTION 2: How do you disarm/cancel a hw_timer? As you can see in this code, I've tried setting the FN to zero and/or null and I've also tried setting hw_timer_arm(0).
The exception and stack dump seem to consistently happen after the sleep 1... debug message which corresponds to the end of the loop() function. Some typical debug output:
// useful and happy output above right up to this point
497 8000
498 8000
499 8000
Average elapsed cycles: 8000.00
Elapsed cycles max: 8263
Elapsed cycles min: 7738
Variance: 396.13
Std Dev: 19.90
Gonna reset...
Reset complete.
sleeping 1...

Exception (0):
epc1=0x40201030 epc2=0x00000000 epc3=0x400043a3 excvaddr=0x00000000 depc=0x00000000

>>>stack>>>

ctx: sys
sp: 3ffedf20 end: 3fffffb0 offset: 0190
3ffee0b0:  00000000 00000000 00000000 4010480d
3ffee0c0:  40105513 00000000 00000000 00000000
3ffee0d0:  00000010 00000000 00000000 40000f68
3ffee0e0:  00000004 00000000 40000f58 00000000
3ffee0f0:  60000200 3fffeed0 00000002 7c097c08
// giant stack dump continues....

Any help would be much appreciated.

I have not looked at your code in detail, but you should declare any global variable that can be changed inside an ISR as volatile, which you haven't done.

@StarCat thanks for that. I've added volatile before each of the 3 vars mentioned in both the interrupt fn and in the other fns. It still crashes and dumps the stack after about four iterations.

So these docs say that RST cause 4 is watchdog reset. Evidently arduino has a watchdog timer to check and make sure that your program isn't stuck in an infinite loop. Therea are some tips in that link on how to avoid this reset. Generally speaking, you need to make sure your loop doesn't spend too much time doing any one thing or handling too many interrupts or it might start to get overwhelmed and then the arduino code can't get around to all the housekeeping it has to do.
Regarding the disabling of a hardware timer function, I posted an issue on the ESP8266 github repo and someone offered what looks like a helpful response, which I have not tested. They suggest:

Call hw_timer_init with second argument = 0; then in your ISR call hw_timer_arm() if you want to keep it going and do not call it if you want to "disarm."

source: Stack Exchange

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

sort: votes


text:
Trying a crude water level sensor
first of all, Im from Cuba, that means I may have some problems to find parts...
I have a little system to measure the water level in my house water tank. The system is pretty rough: a proximity sensor HC-SR04 well fixed in the top of the tank, some long wires to an ArduinoNano, and a LCD screen where I display information as: water level in liters and in %.
The problem is the proximity sensor HC-SR04 seems to be broken now, not work at all and I was thinking in replace it by raw cables
Something like in the image below, but maybe with more steps:

So... My questions are:
-Is this posible? I just test it with a glass of water and two short wires and it work, but sometimes it throw me some falses-positives... It may be my code: just light on a led if digitalpin X is high when I put two wires in the water (1 wire to arduino 5V pin and the other to the digitalpin I wanna check if is high), and it do it, but when I pull out the wires the led stay on for more than a few seconds.
-If it is posible, how long can be the wire? Is 10m ok?
Thanks

have you thought of using a float?

Hi @jsotola, how can I connect the float to the arduino in order to show the level tank in a display?

You need large pulldown resistors to prevent the input signal from floating.

@k.Cyborg I'm thinking of a pulley mounted high above the tank ... cable over the pulley ... a weight atached to each end of the cable ... one weight heavier than the other ... the heavier weight inside the tank attached to a float .... the lighter weight outside of the tank .... code disk on the pulley

Several years ago I tried something similar for the company I worked at that time. Since DC (direct current) lets the electrodes corrode faster, we used AC (alternating current) with a rectangular wave form. Sounds scientific, but it was simply done by changing between VCC and GND. The current through the water is different from the current through air, and it can be detected. You might need some analogue circuitry, though, before you can attach your Arduino. However, I don't recall any experiences how long this worked.

make sure to only turn on the 5v when measuring to prevent corrosion. I would read with analog instead of digital, so you get a feel of the values you should be expecting. I would take about 5 samples, sort them, throw away the highest and lowest, the avg the middle 3 to get a stable reading that doesn't jump around from EMI.

As others have said, you need to make sure you have pull-up or pull-down resistors on all digital inputs so their value doesn't "float" (fluctuate between high and low.)
Given that water tanks and wells tend to be strongly earth grounded, I would suggest some changes:
Change the common wire to a ground, not +5V
Change all of your other pins to analog inputs. Connect them to high ohm pull-up resistors (say 10kΩ). They will read a full 5V when their ends are not in water. When the water rises and the ends dip into the water, their voltages will drop. Use analog readings to detect those voltage drops.
You could also use something like graphite a pair of graphite rods in the water, and a voltage divider circuit. As the water level rises, the current would travel through less graphite, and the resistance would drop. I don't know if that would give you enough top-to-bottom measuring distance.

You can also create a capacitive sensor using aluminium foil and plastic piping. https://www.instructables.com/id/Capacitive-Fluid-Level-Sensor/

I sort of stumbled on how to determine the depth of my outside fish pond, about 1.5 meters. I run a air pump to oxygenate the water for the fish and fitted it with a sensitive pressure transducer. I put a meter reading the pressure and added analog alarm set points. I noticed the first summer as the water went down so did the pressure, conversely when the water rose the pressure rose. With some experimenting I was able to determine the water level. The pond is outside, the air pump is in basement with an outside air inlet because of the cold temperatures. It has been operational 5 years

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


text:
Inaccurate and non-precise voltage reading from Arduino Analog pin
float get_volt() {
  rawVolt = analogRead(voltageSensor);
  vOUT = (rawVolt * 4.6) / 1024.0;
  vIN = vOUT / (R2/(R1+R2));
  //if(vIN>12.0){vIN=12;}
  //if(vIN<11.12){vIN=11.12;}
  //return (vIN - 10.18) * (100 - 0) / (12.0 - 10.18) + 0;
  return vIN;
}

I am using a voltage sensor module which has a voltage divider with R1=30K Ohms and R2=7.5K Ohms and can measure up to 0-25V by using 10-bit Analog pin of arduino. the battery voltage comes as 11.4 volts when measured with a multimeter but I am getting an inaccurate reading from arduino ranging from 10.8 to 11.4. the Arduino voltage reference is stable at 4.6 V. Please help me to fix this, you can see the voltage reading in the image
PS: the battery and arduino are connected to the same ground.

edit1: adding 0.1uf capacitor helped to improve from this

to this!

the data is taken for over a period of 1 hr at every 5 seconds, its a 12V 4000 mAh battery

Are you measuring also something else on ADC? Recommended maximum input impedance is 10K, and it looks like yours might be bit weak, so charging sampling capacitor from different levels (= previously measured value) may result in huge differences in measured values

nope, I am only measuring the voltage  on A1, the current is being measured using A2.  So it can be a problem with the uC?

Try adding capacitor between GND and A1 first (about 1uF should be fine).

There is only one ADC in the Arduino, which can be used for several pins. If you are also measuring current inbetween voltage measurements, @KIIV's comment applies; the pins used don't matter. You would have to reduce the voltage divider's impedance, give the ADC more cycles per sample, or measure the voltage twice and discard the first measurement.

what's the difference between inaccurate and non-precise?

Does the accuracy improve when you only measure voltage and not current?

This should be a lot of fun but you might consider doing some research on analog circuits and A/D circuits. You have way too many digits to the right of the decimal, the accuracy is not there. The best you can get is 0.0044 volts per count with a 4.6v reference. What are you using to make your measurements, you need at 5 1/2 digit meter to have the decade better accuracy then what you are calibrating to. Your reference you state is 4.6 volts, something is not correct is should be 5.000V. You know any load placed on the on board regulator will have an effect on your A/D readings. The tolerance of the resistors you are using will have an impact on your reading. They generate noise that could be affecting your readings. 100nF should be enough capacitance,this will lower the input impedance. Increasing capacitance beyond this will slow the settling time of the circuit. If you are powering this from a computer USB expect noise from that power source, That would also explain the lower reference voltage on the A/D. With what you indicate you have, you are actually doing very well.

Are you saying resistors make noise? I.e packed carbon tubes?

Very definitely as do all other components.  At 10 digits to the right of the decimal point it can become a big problem. For more background try this link: https://www.allaboutcircuits.com/technical-articles/electrical-noise-what-causes-noise-in-electrical-circuits/  This is based on the numbers he printed out. In reality it should not be a problem until you get mayne 14 bits or more depending on the design.

Thanks a lot !! adding a 0.1uF capacitor did solve the problem but still there is a noise of 0.1 V, checking out if averaging the readings solves the problem, if you all have any other suggestions please do let me know!


text:
Wind speed measuring using Hall sensor

Hi!
I require your help regarding a problem I’m encountering.
I am trying to measure wind speed using Hall sensor, Neodymium magnet & below mentioned code. But I only get “0” value for both RPM & KPH values. Can you help me to solve this?
volatile byte revolutions;

unsigned int rpmilli;
float speed;

unsigned long timeold=0 ;

void setup()
{
    Serial.begin(9600);
    attachInterrupt(digitalPinToInterrupt(2), rpm_fun, RISING);

    revolutions = 0;
    rpmilli = 0;
    timeold = 0;
}

void loop()
{
    if (revolutions >= 1) {
         //Update RPM every 20 counts, increase this for better RPM resolution,
         //decrease for faster update

         // calculate the revolutions per milli(second)
         rpmilli = revolutions/(millis()-timeold);

         timeold = millis();
         revolutions = 0;
         // WHEELCIRC = 2 * PI * radius (in meters)
         // speed = rpmilli * WHEELCIRC * “milliseconds per hour” / “meters per kilometer”

         // simplify the equation to reduce the number of floating point operations
         // speed = rpmilli * WHEELCIRC * 3600000 / 1000
         // speed = rpmilli * WHEELCIRC * 3600

         speed = rpmilli 1.288053600;

         Serial.print(“RPM:”);
         Serial.print(rpmilli * 60000 ,DEC);
         Serial.print(" Speed:");
         Serial.print(speed,DEC);
         Serial.println(" kph");
    }
}

void rpm_fun()
{
    revolutions++;
}

rpmilli = revolutions/(millis()-timeold);

All variables in this line are of type int, so this is an integer division. When the time delta in ms is larger than the number of revolutions it counted, this always returns 0. You need to change this to:
rpmilli = ((float)revolutions)/(millis()-timeold);

and change rpmilli to float.

Thank you so much for the help


text:
questions about sketch
int k ;
int q ;
int f;//pot

void setup() {
  pinMode(k, OUTPUT);
  pinMode(q, OUTPUT);
  pinMode(f, INPUT);
}
void loop() {
  zzf();
}

void gf()
{
  int a = f;//test the conditions of f and store in new variable int a
  if (a == 80)//if a reads 80 then increment a by 1
  {
    ei();//run the ei() function
  }
}

void ei() {
  int k = 3;
  int a = Serial.read();
  {
    digitalWrite(k, a);
  }
}

void zzf() {
  for (f = 0; f < 80; f++) {
    analogWrite(q, f);
  }
}

You have now changed your question, but I'll give you a hint. Learn C first. Then look carefully at the errors. They are telling you exactly what is wrong; a little bit of searching through StackOverflow will help you immensely.

And may I suggest to give understandable names to functions? Maybe to you they are so meaningful, but I bet that if you'll read this sketch in a week you won't understand it at all. It's just an advice :)

A practice in writing gibberish? What's the problem with giving functions good names?

Which is the question?

@fabrosel the question was answered

There is no question, this should be closed.

@jai Insulting and other vulgarities are not tolerated on Stack Exchange.

Lean the proper C syntax. This is completely wrong:
void gf()
int a = f;//test the conditions of f and store in new variable int a
{

And this is just as wrong for the same reasons:
void ei()
int k = 3
int a = Serial.read();
{digitalWrite(k, a);}

Majenko is right. The { comes after the function name and arguments, not a few lines further on.

@Majenko telling me what i did wrong does not contributes towards the help, the ide debugger already tells me that theres is something wrong and thats what im looking for help on here

And I have told you that your syntax is wrong and that you need to learn the right syntax. Look at your code and then look at someone else's code and spot the difference. That way you will learn.

@NickGammon thank you for being helpful, im not sure why this guy just dint lead of with you very simple approach of helping. i did noticed not what i was missing i was stuck on the fact that i had already used those brackets but i failed to see how i forgot to initialize for the function itself

@Majenko like i said telling me whats wrong is what the ide debugger did, i did not wanted any one to reiterate that but to point to me in detail what i did not understood about the debugger

@jai This is the first time I'll say that you need to open a C(++) tutorial and start from the beginning and learn what's C(++)'s syntax. I can tell that you need to put { after a function name and (). For example void learnthesyntax(){ <code here> } but it won't help you much without you understanding what's right and why.

updated my original post

@jai You've been so busy arguing about the answer that you haven't actually learned anything, have you? Look at your ei() function and tell me what is wrong with it.

If you write "ei()" the compiler sees it as the calling of a function, but the compiler doesn't know where is the function defined, so is say ei' was not declared in this scope. Since compilers are clever they search for the body of the function after "ei()" but it doesn't find the braket: here comes the second error you get expected initializer before 'int. As Majenko said you should learn the syntax, and then learn how to understand the esoteric language of the compiler. I'm still learning so don't worry.

@Majenko yeah its called cant focus with you bashing on the kid rather then focus on keeping the bashing away from the post and focus on being understanding, but yes thanks for the point out, i just noticed

@FrAxl93 thanks for the looking out...i just got it to compile, now i gotta learn about using Boolean Op in my conditionals in order to tell if a function is currently being exercise i can have the program do other functions if one of the other functions are being bool as TRUE

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


text:
Neopixel Ring - How to breathe in a circle motion?
I'm trying to get an effect like (https://vine.co/v/Mwwbi5a1BFK) using a neopixel ring. I can get the neopixels to turn on and off in a circle motion and I can get the neopixels to fade all at once. What I can't get working is combining the two together. Any help would be much appreciated!
EDIT Tried making fade with the circle motion
#include <Adafruit_NeoPixel.h>          // Library for NeoPixels

#define pinPix 6                       // Pin driving NeoPixel Ring or String
#define numPix 8                       // Number of NeoPixels in the Ring or Strip

// Setup NeoPixel Ring
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number driving the strip
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel myNeoPixels = Adafruit_NeoPixel(numPix, pinPix, NEO_GRB + NEO_KHZ800);

void setup() {
  myNeoPixels.begin();   // Initialize the NeoPixel array in the Arduino's memory,
  myNeoPixels.show();    // turn all pixels off, and upload to ring or string

}

void loop() {
  ledTrail(50, 100, 100,255,255, 0,0,0);       // Pause; R,G,B foreground; R,G,B background
}

// Pause = delay between transitions
// Rf, Gf, Bf = RGB "Foreground" values
// Rb, Gb, Bb = RGB "Background" values
const byte extra = 4;  // how many ahead, and behind, to light up

// Pause = delay between transitions
// Rf, Gf, Bf = RGB "Foreground" values
// Rb, Gb, Bb = RGB "Background" values
void ledTrail(int pause, int steps, byte Rf, byte Gf, byte Bf, byte Rb, byte Gb, byte Bb) {

  int tmpR, tmpG, tmpB;         // Temp values
  // Fade up
  for (int s=1; s<=steps; s++) {
    tmpR = (Rf * s) / steps;     // Multiply first to avoid truncation errors
    tmpG = (Gf * s) / steps;
    tmpB = (Bf * s) / steps;

  for (int i=0; i<numPix; i++) {
    myNeoPixels.setPixelColor(i,Rf,Gf,Bf);

    // now go "extra" pixels ahead and behind
    for (int s = 1; s < extra + 1; s++)
      {
      tmpR = (Rf * (extra - s)) / extra;     // Multiply first to avoid truncation errors
      tmpG = (Gf * (extra - s)) / extra;
      tmpB = (Bf * (extra - s)) / extra;
      myNeoPixels.setPixelColor((i + s) % numPix,tmpR,tmpG,tmpB);
      myNeoPixels.setPixelColor((i + numPix - s) % numPix,tmpR,tmpG,tmpB);
      }

        // Fade down
  for (int s=steps; s>0; s--) {
    tmpR = (Rf * s) / steps;     // Multiply first to avoid truncation errors
    tmpG = (Gf * s) / steps;
    tmpB = (Bf * s) / steps;
  }

    myNeoPixels.show();
    delay(pause);
  }
   }
}

LED TRAIN CODE
#include <Adafruit_NeoPixel.h>          // Library for NeoPixels

#define pinPix 6                       // Pin driving NeoPixel Ring or String
#define numPix 8                       // Number of NeoPixels in the Ring or Strip

// Setup NeoPixel Ring
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number driving the strip
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel myNeoPixels = Adafruit_NeoPixel(numPix, pinPix, NEO_GRB + NEO_KHZ800);

void setup() {
  myNeoPixels.begin();   // Initialize the NeoPixel array in the Arduino's memory,
  myNeoPixels.show();    // turn all pixels off, and upload to ring or string

}

void loop() {
  ledTrail(100, 255,255,255, 0,0,0);       // Pause; R,G,B foreground; R,G,B background
}

// Pause = delay between transitions
// Rf, Gf, Bf = RGB "Foreground" values
// Rb, Gb, Bb = RGB "Background" values
void ledTrail(int pause, byte Rf, byte Gf, byte Bf, byte Rb, byte Gb, byte Bb) {

  for (int i=0; i<numPix; i++) {
    myNeoPixels.setPixelColor(i,Rf,Gf,Bf);
    myNeoPixels.show();
    delay(pause);
  }

  for (int i=0; i<numPix; i++) {
    myNeoPixels.setPixelColor(i,Rb,Gb,Bb);
    myNeoPixels.show();
    delay(pause);
  }
}

BREATHING CODE
#include <Adafruit_NeoPixel.h>          // Library for NeoPixels

#define pinPix 6                       // Pin driving NeoPixel Ring or String
#define numPix 8                       // Number of NeoPixels in the Ring or Strip

// Setup NeoPixel Ring
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number driving the strip
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel myNeoPixels = Adafruit_NeoPixel(numPix, pinPix, NEO_GRB + NEO_KHZ800);

void setup() {
  myNeoPixels.begin();   // Initialize the NeoPixel array in the Arduino's memory,
  myNeoPixels.show();    // turn all pixels off, and upload to ring or string

}

void loop() {
  breathe(20, 100, 255,255,255);       // Pause; Number of steps; Full-on R,G,B values
}

// Pause = delay between transitions
// Steps = number of steps
// R, G, B = Full-on RGB values
void breathe(int pause, int steps, byte R, byte G, byte B) {

  int tmpR, tmpG, tmpB;         // Temp values

  // Fade up
  for (int s=1; s<=steps; s++) {
    tmpR = (R * s) / steps;     // Multiply first to avoid truncation errors
    tmpG = (G * s) / steps;
    tmpB = (B * s) / steps;

    for (int i=0; i<numPix; i++) {
      myNeoPixels.setPixelColor(i,tmpR,tmpG,tmpB);
    }
    myNeoPixels.show();
    delay(pause);
  }

  // Fade down
  for (int s=steps; s>0; s--) {
    tmpR = (R * s) / steps;     // Multiply first to avoid truncation errors
    tmpG = (G * s) / steps;
    tmpB = (B * s) / steps;

    for (int i=0; i<numPix; i++) {
      myNeoPixels.setPixelColor(i,tmpR,tmpG,tmpB);
    }
    myNeoPixels.show();
    delay(pause);
  }

  delay(pause * 30);
}

Try to describe the effect in words, and it might shed light on how to write it in code.

I don't have any NeoPixels to try it with (yet) however this should do it. Replace the ledTrail function by this:
const byte extra = 4;  // how many ahead, and behind, to light up

// Pause = delay between transitions
// Rf, Gf, Bf = RGB "Foreground" values
// Rb, Gb, Bb = RGB "Background" values
void ledTrail(int pause, byte Rf, byte Gf, byte Bf, byte Rb, byte Gb, byte Bb) {

  int tmpR, tmpG, tmpB;         // Temp values

  for (int i=0; i<numPix; i++) {
    myNeoPixels.setPixelColor(i,Rf,Gf,Bf);

    // now go "extra" pixels ahead and behind
    for (int s = 1; s < extra + 1; s++)
      {
      tmpR = (Rf * (extra - s)) / extra;     // Multiply first to avoid truncation errors
      tmpG = (Gf * (extra - s)) / extra;
      tmpB = (Bf * (extra - s)) / extra;
      myNeoPixels.setPixelColor((i + s) % numPix,tmpR,tmpG,tmpB);
      myNeoPixels.setPixelColor((i + numPix - s) % numPix,tmpR,tmpG,tmpB);
      }

    myNeoPixels.show();
    delay(pause);
  }
}

What this is doing is having an inner loop that "looks ahead" and behind another extra pixels and makes them brighter/darker. Debugging code (since removed) shows the effect:
i = 4, R = 255, G = 255, B = 255   <-- original code
i = 5, R = 191, G = 191, B = 191   <-- one ahead  (darker)
i = 3, R = 191, G = 191, B = 191   <-- one behind (darker)
i = 6, R = 127, G = 127, B = 127   <-- two ahead  (darker still)
i = 2, R = 127, G = 127, B = 127   <-- two behind (darker still)
i = 7, R = 63, G = 63, B = 63      <-- and so on
i = 1, R = 63, G = 63, B = 63
i = 8, R = 0, G = 0, B = 0
i = 0, R = 0, G = 0, B = 0

Ahh I see! Is there a way to fade the LEDs as they move around in a circle? Right now, they still just turn on and off abruptly so you can still see the "steps" as the light rotates. I tried updating the code in OP.

It should fade as my debugging displays show. I can't see why it isn't. I'll have to wait until my NeoPixels arrive in the mail so I can try it out myself.

Ok cool. I'll try at it for now then. :)

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


text:
Arduino serial hex decimal values code
I'm trying to send heximal values from arduino to PZEM-04 power module (it shows voltage, current and ect.) over serial communication in heximal format and get values in decimal format for further actions with them. Any help with the code please?
One of the commands:
Send command: B4 C0 A8 01 01 00 1E
Reply data: A4 00 00 00 00 00 A4
Edit: I am connecting wires from PZEM module TTL to arduino "serial port": TX-RX, RX-TX, VCC-VCC, GND-GND, so it's serial communication..
    PZEM module: http://www.aliexpress.com/store/product/PEACEFAIR-AC-100A-Electric-power-monitoring-and-communication-module-power-meter-power-energy-Volt-Ammeter/1773456_32373508101.html

Please add link to communication format/protocol.

I just added more information.

What code have you tried?

That for the extra info. I read this differently. You should send binary data with the hexadecimal values.

A possible implementation of the protocol using serial read/write of binary data (command and response).
void send(Stream& ios, uint8_t cmd[6])
{
  uint8_t sum = 0;
  for (int i = 0; i < 6; i++) {
    uint8_t c = cmd[i];
    sum += c;
    ios.print((char) c);
  }
  ios.print((char) sum);
}

bool recv(Stream& ios, uint8_t res[6])
{
  uint8_t sum = 0;
  uint8_t c;
  for (int i = 0; i < 6; i++) {
    while (!ios.available());
    c = ios.read();
    sum += c;
    res[i] = c;
  }
  while (!ios.available());
  c = ios.read();
  return (sum == c);
}

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

  uint8_t cmd[] = { 0xB4, 0xC0, 0xA8, 0x01, 0x01, 0x00 };
  uint8_t res[6];
  send(Serial, cmd);
  recv(Serial, res);
}

void loop()
{
}

Cheers!

Thank you very much Mikael Patel, you cleared it a lot to me. Now it's only needed to analize code, and insert other commands. After that I'm going to connect bluetooth module and send values to smartphone somehow, haha. Thanks again!


text:
Buttons, LOW vs no connection
I'm working with a very simple circuit to understand push buttons. The code in the tutorial uses the INPUT_PULLUP pinmode. I understand the idea of the pinmode, but I have two questions:
There must be a difference between a LOW reading and no connection, correct? How does the arduino differentiate between the two?
I tried to experiment with this idea. So my thought was that you could create a circuit where the LED only stays lit when you hold the button down. In this setup, I used just normal INPUT for pinmode. So the logic was: if LOW then turn light on, else light off. The turnout was the light was almost always on and just really finicky when i moved the board. Why?
Thanks!

To us to fully answer this question you need to post your schematic and your code.

Upvoted for the good question which I learnt from by the comments and answer of Nick.

There must be a difference between a LOW reading and no connection, correct?

No, the input circuitry measures a voltage. The exact details are in the datasheet, but how could it know there is nothing connected? There is not some sort of sensor that detects the insertion of a wire into the input. Therefore it is trying to read a voltage all the time.
With nothing connected then stray voltages from nearby circuitry will influence the reading.

... and just really finicky when i moved the board ...

Yep, you are influencing the voltage by capacitance from your hand.
You need to have a definite voltage for "no switch pressed" which can be a resistor to ground (eg. 10k) or a resistor to +5V.
I have a tutorial on this.

It sounds like you have wired your switch like this:

Because you don't have a definite voltage there, the input could "randomly" switch between LOW and HIGH.

You could add a pull-down resistor:

Or a pull-up resistor:

Or use the INPUT_PULLUP mode to create a pull-up resistor in the processor hardware. (There is no INPUT_PULLDOWN mode).
Then you will get consistent results.

Upvoted ... thanks Nick for this great answer... I learnt a lot from it (and thought the Arduino also had an INPUT_PULLDOWN mode.


text:
Enroll more than one finger on Unique Id in R305 FingerPrint Module Working With Arduino
I am working on a project when I have to enroll and Submit the attendance of the fingerprints.
What I have : I am able to enroll single fingerprint on a different unique ID. Using AdaFruit FingerPrint Sensor Library.
I have :

R305 FingerPrint Sensor having 1000 fingerPrint storage and
  Arduino Uno

What I want : I want to enroll more than one finger Prints on same Unique Id.
How to do it, Please anyone Help me with  this.
Help will be appreciated. Thanks

your project seems to have a lot of issues with privacy  ... why are you capturing people's fingerprints?

No, You are getting me wrong, it is just a college project but i want to enroll more than one finger on same unique id

i do not think that you can ... the reader outputs a unique ID for each fingerprint ... the controller has to keep track of all the ID numbers belonging to an individual

Each fingerprint must have a unique ID that refers to that fingerprint.
What you need next is a table to associate multiple fingerprint IDs with "persons" so that you can find out which person belongs to a particular print scan.
You didn't say if you were holding fingerprint and person data within the Arduino or on some network-based storage system, but if we assume that this is entirely self-contained in the Arduino you would need to write the association table to some kind of storage that won't reset when the Arduino loses power, such as an EEPROM. The Uno has a "built in" EEPROM on the ATMega328p chip, but it only holds 1024 bytes. There are external EEPROMs that communicate via SPI or I2C that can hold more data.
As to the actual data structure -- it can be as simple as a 2-dimensional array, with one dimension holding the fingerprint ID, and the other holding a person ID. For multiple fingerprints of the same person, the table would have multiple rows with the same person ID, but different fingerprint IDs.
You could also make an array of struct datatypes, or create class, etc. But the point is that the "Unique ID" matching only ONE print from the fingerprint sensor is a limitation you have to work with.


text:
Slave unreliably sends bit 7
I'm trying to send a byte from an Arduino Nano I2C slave to a Raspberry Pi 3B Master by directly connecting the two I2C pins of each device with no external pull-ups or level converters. It mostly works but the high bit is sometimes misread as a 0 when it should be a 1.
It seems to be caused by that bit being put on the data line at the same time as the clock rising edge so it's not clearly a 0 or a 1. Here's a scope trace showing what I think the problem is for slave address 4 (binary 0000100) and data 231 (binary 11100111). Why is it doing that and how can I fix it?

Another guess is that the Raspberry Pi might be holding the data line low and blocking the slave's value.
Using Wire library on the Arduino and SMBus on the Pi.
EDIT: I added a level converter and the problem is still there, so it's not caused by the 3.3V/5V difference.

With no pull-up and no level converter you shouldn't expect it to work.  Actually it may damage the Pi unless you have the Nano running at 3v3.

@Delta_G Pi has internal 3.3V pull-ups and Nano has higher-valued pull-ups to 5V which don't seem to cause any problem since signals are all 3.3V as shown in scope.

Depending on the speed, the built-in pull-ups might be too large. What happens if you add external pull-ups?

The waveforms aren't rounded off and the voltages are easily correct. How could too-high pullups affect the timing of one or two pulses but none of the others?


text:
Setting an array pointer to null on declaration
How can I set an array pointer to null?
I have a pointer to a 3 int array that I am trying to set to null.

int (*EXCLUSIVE_COLOR)[3];

Per this link I was trying to set it to null upon initialization.
However this does not assign a null value to it. It assigns three 'random' integers to the array elements:

{128, 447, 451}

How can I make it point to a null or empty value?

if you assign null, test it for null, not read it

What were you expecting to  get when you read a null pointer?  That's undefined behavior.  It could give you anything.  If you want to make the thing pointed to zero then do that.  That's not the same as assigning a null pointer.

Does this answer your question? Assigning an element of a multidimensional array to a second array

Here is a full example that shows you all thing things you have been asking over the past few days:
int colors[][3] = {
    {255, 0, 0},
    {0, 255, 0},
    {0, 0, 255}
};

#define NCOLOR (sizeof(colors) / sizeof(colors[0]))

int *EXCLUSIVE_COLOR = NULL;

void setup() {
    Serial.begin(115200);
    Serial.print("You have ");
    Serial.print(NCOLOR);
    Serial.println(" colors defined.");
    reportColor();
    EXCLUSIVE_COLOR = colors[2];
    reportColor();
    EXCLUSIVE_COLOR = NULL;
    reportColor();
}

void loop() {

}

void reportColor() {
    if (!EXCLUSIVE_COLOR) {
        Serial.println("Color is not set");
    } else {
        Serial.print("Color is set to ");
        Serial.print(EXCLUSIVE_COLOR[0]);
        Serial.print(",");
        Serial.print(EXCLUSIVE_COLOR[1]);
        Serial.print(",");
        Serial.println(EXCLUSIVE_COLOR[2]);
    }
}

You have an array of colours. You have a pointer that can point at a colour or at nothing. It starts off pointing at nothing. The code recognises that it's pointing at nothing and reports it. It gets assigned to a specific colour in your colours array. The code recognises that it's now a valid value and reports it. The pointer then gets pointed to nothing again. Again the code recognises that and tells you.
The result:
You have 3 colors defined.
Color is not set
Color is set to 0,0,255
Color is not set


text:
TX Pin Stays Lit After Removing Voltage Regulator

To save power, I removed the linear regulator from my Arduino Nano clone and powered it via the 5V pin from a regulated source (a rechargeable USB phone charger). However, I've noticed that removing the linear regulator causes the TX pin to stay on all the time, which results in my phone not being able to communicate with the HC05 bluetooth module although it connects fine. I checked that the TX pin is not caused by Serial.print and noticed the same behavior on all the Nano's I've removed linear regulators from. The Nano's I've tested with the linear regulator work fine, though they use more power than I'd like. I've tried resetting the device, but the problem persists.
I'm wondering what's causing this? Isn't powering via 5V pin suppose to bypass the regulator? So what could cause the missing regulator to affect the TX pin? Unfortunately, I'm not experienced enough to connect the dots using the schematic so I was hoping someone could help me.
Though I'm not sure if it'll help, I'ved included my sketch below. Basically, I'm making using a ultrasonic sensor to communicate distance with my phone via bluetooth. It also plays music when it detects movement (using PIR sensor). Since the application is outdoor use I'm powering via battery and trying to minimize energy use. I got it down to ~4 mA by removing linear regulator.
#include <avr/sleep.h>

#define bluetoothIntPin 2
#define pirInterruptPin 3
volatile int state = 0;

int bt_pin = 9;
int pirPin = 8;
int stateData = 0;
int ultraPin = 10;
int trigPin = 11;    // Trigger
int echoPin = 12;    // Echo
int piezoPin = 5;
long duration, cm;
unsigned char inches;
unsigned long timer;
volatile bool signalReceived = false;
volatile bool pirSignalReceived = false;
bool toggle_pir = false;
int incomingByte = 0;
bool song_in_progress = false;
int song_type = 69;

int nokia_melody[] = {

  // Nokia Ringtone
  // Score available at https://musescore.com/user/29944637/scores/5266155

  NOTE_E5, 8, NOTE_D5, 8, NOTE_FS4, 4, NOTE_GS4, 4,
  NOTE_CS5, 8, NOTE_B4, 8, NOTE_D4, 4, NOTE_E4, 4,
  NOTE_B4, 8, NOTE_A4, 8, NOTE_CS4, 4, NOTE_E4, 4,
  NOTE_A4, 2,
};

void setup() {
  pinMode(13, OUTPUT); //set pin 13 as output
  pinMode(ultraPin, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(pirPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(bt_pin, HIGH);
  digitalWrite(bluetoothIntPin, HIGH);
  digitalWrite(pirInterruptPin, HIGH);
  digitalWrite(ultraPin, LOW);
  digitalWrite(pirPin, LOW);
  Serial.begin(9600); // Default communication rate of the Bluetooth module
  attachInterrupt(digitalPinToInterrupt(bluetoothIntPin), bluetooth_interrupt, CHANGE);
  attachInterrupt(digitalPinToInterrupt(pirInterruptPin), pir_interrupt, CHANGE);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sleep_cpu();
}

void pir_interrupt(){
  // play sound effect
  digitalWrite(LED_BUILTIN, HIGH);
  delay(5000);
  digitalWrite(LED_BUILTIN, LOW);
  pirSignalReceived = true;
}

void bluetooth_interrupt(){
  state = !state;
  signalReceived = true;
}

void play_song(int melody[], int notes){
      // sizeof gives the number of bytes, each int value is composed of two bytes (16 bits)
    // there are two values per note (pitch and duration), so for each note there are four bytes

    // this calculates the duration of a whole note in ms
    song_in_progress = true;
    int wholenote = (60000 * 4) / tempo;

    int divider = 0, noteDuration = 0;
    for (int thisNote = 0; thisNote < notes * 2; thisNote = thisNote + 2) {

    // calculates the duration of each note
    divider = melody[thisNote + 1];
    if (divider > 0) {
      // regular note, just proceed
      noteDuration = (wholenote) / divider;
    } else if (divider < 0) {
      // dotted notes are represented with negative durations!!
      noteDuration = (wholenote) / abs(divider);
      noteDuration *= 1.5; // increases the duration in half for dotted notes
    }

    // we only play the note for 90% of the duration, leaving 10% as a pause
    tone(piezoPin, melody[thisNote], noteDuration * 0.9);

    // Wait for the specief duration before playing the next note.
    delay(noteDuration);

    // stop the waveform generation before the next note.
    noTone(piezoPin);
  }
  song_in_progress = false;
}

void play_tone_once(){
  if (!song_in_progress){
     if (song_type==69){
      int notes = sizeof(nokia_melody) / sizeof(nokia_melody[0]) / 2;
      play_song(nokia_melody, notes);
    }
    if (song_type==79){
      int notes = sizeof(starwars_melody) / sizeof(starwars_melody[0]) / 2;
      play_song(starwars_melody, notes);
    }
  }
}

void loop() {
  if (signalReceived){
    sleep_disable();
    Serial.write(50);
    delay(500);
    timer = millis();
    digitalWrite(ultraPin, HIGH);
    digitalWrite(pirPin, HIGH);
    while (true){
        digitalWrite(trigPin, LOW);
        delayMicroseconds(2);
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigPin, LOW);
        pinMode(echoPin, INPUT);
        duration = pulseIn(echoPin, HIGH);
        cm = (duration / 2) / 29.1;   // Divide by 29.1 or multiply by 0.0343
        inches = (duration / 2) / 74; // Divide by 74 or multiply by 0.0135
        Serial.write(inches);
        delay(50);
        incomingByte = Serial.read();
        if (pirSignalReceived){
          play_tone_once();
          pirSignalReceived = false;
        }
        else if (incomingByte == 69){ // automatic pir
          song_type = 69; //nokia
        }
        else if (incomingByte == 79){
          song_type = 79; // starwars
        }
        else if (incomingByte == 89){
          toggle_pir = !toggle_pir;
          if (toggle_pir){
            digitalWrite(pirPin, HIGH); // automate tone
          } else {
            digitalWrite(pirPin, LOW);
          }
        }
        else if (incomingByte == 99){
          digitalWrite(pirPin, LOW);
          play_tone_once();
        }
        if (incomingByte != 49 && incomingByte!=69 && incomingByte != 79 && incomingByte != 89 && incomingByte != 99){
          // receipt from android
          unsigned long timeElapse = millis() - timer;
          if (timeElapse > 7000) {
            break; // exit and SLEEP
          }
        }
        else {
            // reset the timer
            timer = millis();
          }
  }
  digitalWrite(pirPin, LOW);
  digitalWrite(ultraPin, LOW);
  digitalWrite(LED_BUILTIN, LOW);
  signalReceived = false;
  sleep_enable();
  sleep_cpu();
  }
}

you made a hardware change to the board ... please provide a schematic diagram for the board, not a program listing

My Nano clone appears to be the same make as yours.  Certainly the underside of it looks identical.  On my clone, and I believe yours, the TX LED is wired as follows
5V -- RESISTOR -- LED -- TXD/D1

The 5V node is just the 5V pin which is fed by USB bus voltage via a diode or by the output of the AMS1117 voltage regulator.  The TTL level serial TX signal idles high and sinks current through the LED when transmitting the start bit and low data bits.  Incidentally, the RX led is wired in the same manner.  By contrast the official Nano uses an FTDI that has dedicated LED driving pins.
It seems likely that you have bridged something with the solder that was holding the AMS1117 on the board in the process of removing it.  I would note that the regulator is mounted directly under the LEDs and their current limiting resistors and there are at least three vias in that part of the board.

Would it be possible to bypass the regulator by bridging the Input and Output pins of the voltage regulator instead of completely desoldering it?

That's kind of a new question, but I'll just say this much: If the point is to not have any sort of current being used by the regulator, I don't think that will do it.  Take for example whatever it is using internally for a voltage reference.  This is connected somehow to the input (and in the scenario you outlined the output as well) and gnd.  If you can find a schematic for the board, I would add it to your question as jsotola mentioned.

thanks. you are right that i probably messed up the circuitry. I desoldered just the legs of the regulator (excluding the heatsink) and avoided the hidden traces.

I gather you're saying this to indicate that you achieved some success that way.

mostly to validate your answer, but yes i did bypass the regulator


text:
What do you do when you finish a project?
I have just about completed my first Arduino project using an Arduino Uno board, but is that what I use inside the finished device? I figured I’d keep the Uno for future projects and have something else controlling the finished product. Are you supposed to just keep purchasing the Uno board every project?
I just got it a couple of days ago so I’m not very familiar with any of it. If that is the case do you use the batter for power since I can’t have it connected to my laptop once it’s done.

https://majenko.co.uk/product/arduino-prototype-plus

There are many options, so it all ends up depending on your personal
preferences:

You could indeed dedicate this Arduino to this project, and buy a new
one for the next project. This may be the simplest solution, if not
the cheapest. Just make sure you are not using a breadboard for the
other parts. A “proto-shield” may be a good option for soldering the
rest of your circuit in a permanent form.

You may replace the Uno with a smaller Arduino, like the Micro (but
beware it uses a different MCU) or a Pro Mini clone (same MCU). These
smaller boards can then be soldered onto a PCB using standard 0.1” pin
headers.

You could buy a cheap clone, test it to make sure it works as intended
on this particular project, and dedicate the real one for further
prototyping.

You could get a bare ATmega328P plus crystal and caps and put them,
together with the rest of your circuit, onto a perf-board or a
strip-board. C.f. Michel Keijzers’ answer. Note that if your program
can run happily off a somewhat inaccurate 8 MHz clock, you can
use the MCU's internal oscillator instead of a crystal.

If your program is far from using all the resources of the Uno, you
may consider a smaller MCU. The ATtiny85 is a popular “minimalistic”
choice. Make sure an Arduino core is available for it, unless you want
to program all low-level.

For the most professional result, you could design and order a real
PCB for your whole circuit, including the MCU.

Regarding your fifth point: There are many people who have made available Arduino "cores" for the ATtiny85:  ATtinyCore by Spence Konde seems to be well-regarded. It does introduce a lot of extra options in the tools dialog. . ATtiny by David A Mellis is simpler.

Thanks a lot. I’m brand new to this so have no knowledge but I knew I could count on SE.

What you can do is:

Buy the main IC (Atmel 328P)
Use some external components to get it working (like a crystal). Check this on a breadboard to see if it works (and check.
Buy a case to put it in
Buy some protoboard or PCB to solder it on (or use a footprint)
For power, use some components (voltage regulator) or an adapter, or battery, whatever you need. Make sure you check this on a breadboard before you solder it.

If you want to read more about the subject, search for 'prototyping'.

I particularly like Adafruit's high quality proto-boards for my one-off builds. There are several sizes but the 1/2-breadboard size I linked to is the size I use most.

They seem very easy to convert from breadboard to proto board. If you have no space constraints,  those are probably the easiest.


text:
Arduino Micro: Why am I getting 6.00 as a result instead of 6.66?
Basically, on the TWR calculator page, when I entered 20 as the initial value and 3 as the value that comes after, I somehow get 6.00 as a result instead of 6.66 in the computeTWR() function. How can I fix this?
// ------------------- DIVIDER ---------------------
/*
   Jebediah's Launch Control System for Kerbal Space Program
   Alpha Build 1.1
   An Open-Source Project by John Seong
*/

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>

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

char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {12, 11, 10, 9};
byte colPins[COLS] = {8, 7, 6};

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

// Show a two-line message on the LCD.
void lcdShow(const char *line0, const char *line1) {
  lcd.clear();
  lcd.print(line0);
  lcd.setCursor(0, 1);
  lcd.print(line1);
}

void computeTWR(int thrustR, int weightR) {
  float result = thrustR / weightR;
  lcd.print(result);
}

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcdShow("Jeb's Launch", "Control System");
  delay(3000);
  lcdShow("Alpha Build 1.1", " STUDIO HORIZON");
  delay(3000);
  lcdShow("Welcome, Kerman", "Press any key...");
  while (!keypad.getKey()) ;  // wait for key press
}

void loop() {
  static enum {START, MENU, SET_COUNT, COUNT_DOWN, SET_THRUST, SET_WEIGHT, TWR_COMPUTE} state = START;
  static uint32_t last_second;  // millis() value on last full second
  static int count, thrust, weight;             // countdown, thrust, weight value
  static float ratio;

  char key = keypad.getKey();

  switch (state) {
    case START:  // transitional state
      lcdShow("1. Countdown", "2. TWR");
      state = MENU;
    /* fallthrough */
    case MENU:
      if (key == '1') {  // Countdown
        lcdShow("Countdown Timer", "Seconds: ");
        count = 0;
        state = SET_COUNT;
      } else if (key == '2') {  // TWR
        lcdShow("TWR Calculator", "Thrust: ");
        thrust = 0, weight = 0, ratio = 0;
        state = SET_THRUST;
      }
      break;
    case SET_COUNT:
      if (key >= '0' && key <= '9' && count <= 99) {
        lcd.print(key);
        count = 10 * count + (key - '0');
      } else if (key == '#') {
        lcdShow("Lift off in", "     seconds");
        // Force a refresh on entering COUNT_DOWN:
        last_second = millis() - 1000;
        count++;
        state = COUNT_DOWN;
      } else if (key == '*') {
        state = START;
      }
      break;
    case COUNT_DOWN:
      if (millis() - last_second >= 1000) {
        last_second += 1000;
        count--;
        if (count == 0) {
          Serial.println("Lift off!");
        } else if (count < 0) {
          state = START;
          break;
        }
        lcd.setCursor(1, 1);
        lcd.print(count < 10 ? "  " : count < 100 ? " " : ""); // pad
        lcd.print(count);
      } else if (key == '*') {
        state = START;
      }
      break;
    case SET_THRUST:
      if (key >= '0' && key <= '9' && thrust <= 9999) {
        lcd.print(key);
        thrust = 10 * thrust + (key - '0');
      } else if (key == '#') {
        lcdShow("TWR Calculator", "Weight: ");
        state = SET_WEIGHT;
      } else if (key == '*') {
        state = START;
      }
      break;
    case SET_WEIGHT:
      if (key >= '0' && key <= '9' && weight <= 9999) {
        lcd.print(key);
        weight = 10 * weight + (key - '0');
      } else if (key == '#') {
        lcdShow("Thrust-to-weight", "ratio: ");
        computeTWR(thrust, weight);
      } else if (key == '*') {
        state = START;
      }
      break;
  }
}

Where? From what? Some calculation? Some entry? What?

Divide two integers you get an integer. No matter what you assign to, you're calculating with integers, so the result is an integer.

use float as parameter types

float result = (float) thrustR / weightR;

OO thanks! I was dumb

thats a blooper

(community wiki answer derived from comments - takes Q off unanswered list)

Why am I getting 6.00 as a result instead of 6.66?

because integer arithmetic discards fractional parts of results, including intermediate results
static int count, thrust, weight;             // countdown, thrust, weight value

If some of these are intended to have decimal values you need to use a more suitable data type (e.g. float)


text:
Arduino Micro: Button inputs are not working!
I have no clue why this is happening to me but the buttons (in this case, buttonAbort and buttonStage) are not working whatsoever.
Edit:
Basically the LEDs are placed right next to the button,(e.g. ledStage -> placed next to the buttonStage) they start to blink when the timer hits zero with a buzzer noise, and if the user presses one of the buttons, the buzzer noise stops and the LED placed next to the button they pressed turns on whereas the other turns off. I also connected the buttons without resistors. (directly to the pins)
/*
   Jebediah's Launch Control System for Kerbal Space Program
   Alpha Build 2.00
   An Open-Source Project by John Seong
*/

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>

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

const int buzzer = A3;
const int ledAbort = 5;
const int ledStage = A5;
const int buttonAbort = 4;
const int buttonStage = A4;

char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {12, 11, 10, 9};
byte colPins[COLS] = {8, 7, 6};

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

// Show a two-line message on the LCD.
void lcdShow(const char *line0, const char *line1) {
  lcd.clear();
  lcd.print(line0);
  lcd.setCursor(0, 1);
  lcd.print(line1);
}

void lcdShowResult(float result) {
  lcd.print(result);
}

void setup() {
  pinMode(buzzer, OUTPUT);
  pinMode(ledAbort, OUTPUT);
  pinMode(ledStage, OUTPUT);
  pinMode(buttonAbort, INPUT_PULLUP);
  pinMode(buttonStage, INPUT_PULLUP);

  Serial.begin(9600);
  lcd.begin(16, 2);
  while (!keypad.getKey()) ;  // wait for key press
}

void loop() {
  static enum {START, MENU, SET_COUNT, COUNT_DOWN, LAUNCH, SET_THRUST, SET_WEIGHT} state = START;
  static uint32_t last_second;  // millis() value on last full second
  static int count;
  static float thrust, weight, ratio;

  int stageConfirm = digitalRead(buttonStage);
  int abortConfirm = digitalRead(buttonAbort);

  char key = keypad.getKey();

  switch (state) {
    case START:  // transitional state
      lcdShow("1. LAUNCH SEQ", "2. TWR CALC");
      state = MENU;
    /* fallthrough */

    case MENU:
      if (key == '1') {  // Countdown
        lcdShow("COUNTDOWN TIMER", "SECONDS: ");
        count = 0;
        state = SET_COUNT;
      } else if (key == '2') {  // TWR
        lcdShow("TWR CALCULATOR", "THRUST: ");
        thrust = 0, weight = 0, ratio = 0;
        state = SET_THRUST;
      }
      break;

    case SET_COUNT:
      if (key >= '0' && key <= '9' && count <= 99) {
        lcd.print(key);
        count = 10 * count + (key - '0');
      } else if (key == '#') {
        lcdShow("    T-MINUS", "     SECONDS");
        // Force a refresh on entering COUNT_DOWN:
        last_second = millis() - 1000;
        count++;
        state = COUNT_DOWN;
      } else if (key == '*') {
        state = START;
      }
      break;

    case COUNT_DOWN:
      if (millis() - last_second >= 1000) {
        last_second += 1000;
        count--;
        if (count <= 10) {
          tone(buzzer, 500);
          delay(500);
          noTone(buzzer);
        }
        if (count == 0) {
          Serial.println("Lift off!");
        } else if (count < 0) {
          state = LAUNCH;
          break;
        }
        lcd.setCursor(1, 1);
        lcd.print(count < 10 ? "  " : count < 100 ? " " : ""); // pad
        lcd.print(count);
      } else if (key == '*') {
        state = START;
      }
      break;

    case LAUNCH:
      tone(buzzer, 3000);
      digitalWrite(ledAbort, HIGH);
      digitalWrite(ledStage, HIGH);
      lcdShow(" T-ZERO WARNING", "CONFIRM IGNITION");
      delay(1000);
      lcd.clear();
      digitalWrite(ledAbort, LOW);
      digitalWrite(ledStage, LOW);
      delay(500);

      stageConfirm = digitalRead(buttonStage);
      abortConfirm = digitalRead(buttonAbort);

      if (stageConfirm == LOW) {
        noTone(buzzer);
        digitalWrite(ledStage, HIGH);
        digitalWrite(ledAbort, LOW);
        lcdShow("  LIFT OFF", "HAVE A SAFE FLIGHT");
        break;

      } else if (abortConfirm == LOW) {

        break;
      }
      Serial.println(stageConfirm);
      Serial.println(abortConfirm);

      break;

    case SET_THRUST:
      if (key >= '0' && key <= '9' && thrust <= 9999) {
        lcd.print(key);
        thrust = 10 * thrust + (key - '0');
      } else if (key == '#') {
        lcdShow("TWR CALCULATOR", "WEIGHT: ");
        state = SET_WEIGHT;
      } else if (key == '*') {
        state = START;
      }
      break;

    case SET_WEIGHT:
      if (key >= '0' && key <= '9' && weight <= 9999) {
        lcd.print(key);
        weight = 10 * weight + (key - '0');
      } else if (key == '#') {
        lcdShow("THRUST-TO-WEIGHT", "RATIO: ");
        if (thrust != 0 || weight != 0) {
          ratio = thrust / weight;
          lcdShowResult(ratio);
        }
      } else if (key == '*') {
        state = START;
      }
      break;
  }
}

Try printing the values of stageConfirm and abortConfirm right after you read the buttons and see if they read what you think they should.  Your logic in your if statements seems weird to me, if the stageConfirm button is not pressed OR if the abort button IS pressed then say "Have a safe flight".  Seems to me like pressing the abort button should not lead to a liftoff.

Show your wiring as well.

That commented /* ... */ music stuff is distracting. Why do you keep it? Would you mind creating a copy of your program and remove everything that is not related to the button problem, e.g. the LCD intro in setup(). That would help as well.

Oh, it's supposed to be && not ||. Sorry for the confusion!

you have to explain what you expect the buttons to do

if buttonStage == 1 -> ledStage = 1, ledAbort = 0

if buttonAbort == 1 -> ledStage = 0, ledAbort = 1

Basically the LEDs are placed right next to the button,(e.g. ledStage -> placed next to the buttonStage)  they start to blink when the timer hits zero with a buzzer noise, and if the user presses one of the buttons, the buzzer noise stops and the LED placed next to the button they pressed turns on whereas the other turns off.

This code is reading the buttons at two places in loop(), but the
first time the results are ignored. Only the readings done in the LAUNCH
state can have any effect. The problem is that the reading is done only
at one very specific time, 1.5 seconds after displaying “CONFIRM
IGNITION”. If you press the button before or after this moment, it has
no effect.
Reading only once per loop iteration is fine, as long as the loop turns
fast enough, without getting stuck in a delay(). As a general rule,
you try to avoid delay() whenever you want to write a program that
should react to external events such as button presses. See the Arduino
example Blink without delay for a technique for achieving that. A
finite state machine is a good way to program without delays, and
fortunately you are already working with one. To detect a button press,
you typically use two distinct states:

a “wait for button press” state that is sensitive to the button
a “button has been pressed” state that is reached when the user
presses the button.

There can be multiple “button pressed” states if there are multiple
buttons to wait for. The transition from the “waiting” state to the
others is then conditioned on the button presses:
case WAIT_FOR_BUTTON_PRESS:
    if (digitalRead(button_1_pin) == LOW) {
        do_the_action_relevant_to_button_1();
        state = BUTTON_1_HAS_BEEN_PRESSED;
    } else if (digitalRead(button_2_pin) == LOW) {
        do_the_action_relevant_to_button_2();
        state = BUTTON_2_HAS_BEEN_PRESSED;
    }
    break;

Obviously you would choose state names that are more relevant for your
specific project.


text:
Setup of Arduino Uno as ArduinoISP for programming attiny45
I have an Arduino Uno SMD and an attiny45, which I want to use as a sensor communicating via i2c. For a first step in finding out how to work with the attiny45 I just want to use the attiny as controller for a blinking led.
When first setting up the Arduino as "Arduino as ISP" some questions came up:

I found a lot of different information about wheter or not to use a capacitor between RESET and GND on the Arduino. Also the capacity differs between 0.1uF and 10uF. Unfornately, I found not a single comment on why this capacitor is needed (or not) and which capacities are suitable. All tutorials used electrolytic capacitors (which I only have in 100uF at hand). I have 10nF and 0.1uF at hand but only the film capacitor type. It would be brilliant if some could help me with deciding if I should use a capacitor, which one is suitable and what's the reason for using it.

My second question is about the clock rate I should set in the Arduino IDE. I added the board package from https://github.com/SpenceKonde/ATTinyCore to my Arduino IDE, which offers a large variety of clock rates in the tools dropdown menu. In some tutorials they mentioned that it's crucial to pick the correct clock speed to avoid wrecking the attiny. But, unfortunately, the mentioned clock speeds vary between "1 MHz (internal)" and "8 MHz (internal)". In the attiny45 datasheet (http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf) I found the "Calibrated Internal Oscillator" to be the clock set up in freshly shipped chips, which I understand to operate at 8 MHz. But, the datasheet also says, that the CKDIV8 fuse is set on shipment, which leads to a clock prescale value of 8 and to a clock rate of 1 MHz. I'm highly confused... Maybe someone here can help me to find the correct clock rate to set.

I hope I didn't forget any important information. If so, please let me know.
Kind regards and thank you in advance,
Matthias

The capacitor is meant to prevent the programming Arduino from being reset. Normally, when you open the serial connection, the Arduino gets reset and first starts into the bootloader (which would be used to program it). But when using the Arduino as ISP programmer, you don't want to run the bootloader of the programmer. You want to let the programmer sketch work as intended. Thus you want to prevent the programmer from resetting on serial connection. The capacitor between Reset and ground holds the 5V level of the reset pin for the time, that the reset pulse from the USB Serial chip is trying to pull the pin to low. So it prevents the reset from happening.
The value and type of the capacitor is not critical here. I always use a 47uF bipolar electrolyte capacitor, because I have a bunch of them just laying around. The value just shouldn't be unreasonable small or big. The mentioned range of yours is just giving you a hint in which order the value should be. Also you can simply test, if the reset happens with your capacitor. You cannot break things with a wrong value here.

Which clock frequency to use is up to your exact requirements. There is no "this is the best for all occasions"-frequency. Also you are not wrecking the Attiny with any of the clock speeds. Though you should note, that choosing an external clock source means, that you actually need to provide that clock source for the ATTiny to work. The fuses can be reprogrammed, if you have chosen a wrong frequency by accident.
The datasheet states just as you wrote. The interal oscillator is by default set to 8MHz, while the prescaler divides that down to 1MHz as the main CPU clock. So by default the ATTiny runs on 1MHz. You can change that, if you like.
For my Attiny85s I always used internal 8MHz as the setting (the option, that appears in the IDE menu). That is the easiest way (internal means you need no external components for the clock), while being the fastest speed you can get with the internal clock, I think.

Great, that helped me a lot. Thank you very much @chrisl

The reset pulse goes through a 0.1 µF cap, so a 0.1 µF holding cap is really borderline. I would aim for ≥ 0.47 µF, or 0.22 µF as the very minimum.


text:
Code question: LCD keypad Shield. How do I define the buttons?
I am trying to adapt a alarm clock sketch that used external buttons, but I would like to utilize a LCD Keypad Shield.  The data sheet says all the buttons are on pin A0, so every button is "set time" in the original sketch.
After reading this post
I found the values when I press each button, :
Right    0
Up     100
Down   257
Left   410
Select 640

and have tried to define them by modifying the existing code:
LiquidCrystal lcd(2, 3, 4, 5, 6, 7); //Arduino pins to lcd
#define bt_time   A0
#define bt_up     A1
#define bt_down   A2
#define bt_alarm  A3

With:
LiquidCrystal lcd(8, 9, 4, 5, 6, 7); //Arduino pins to lcd
int lcd_key     = 0;
int adc_key_in  = 0;
#define bt_time   0
#define bt_up     1
#define bt_down   2
#define bt_alarm  3

#define buzzer 10

int read_LCD_buttons()
{
 adc_key_in = analogRead(0);      // read the value from the sensor
 // my buttons when read are centered at these valies: 0, 144, 329, 504, 741
 // we add approx 50 to those values and check to see if we are close
 if (adc_key_in < 50)   return bt_time;
 if (adc_key_in < 150)  return bt_up;
 if (adc_key_in < 307)  return bt_down;
 if (adc_key_in < 690)  return bt_alarm;

}

I got this from here
It doesn't work.... when you press the buttons nothing happens.
It up loads with no errors, but the buttons don't do anything.
Please help, your my only hope.
Edit:
The linked "Real_Time_Clock_With_Alarm.ino" is the source file, all I have changed is the above code.  It works except I can't interact with it...  because no buttons....  I have also tested the hardware with other sketch and it works as expected.

What do you return if no button is pressed? And how can it ever be not less than 4600 when the ADC gives you 0-1023 (or 0-4096 on some better boards)?

To true, typo it should have been 690 not 4600.....

You haven't answered my first question though: what do you return if no button is pressed?

you code says analogRead(0) ... is that same as analogRead(A0)?

What does “It doesn't work” mean? Could you please write a minimal test sketch, post it here, explain how it behaves and how that is different from what you expect?

@jsotola In short, yes. In more detail:  Those shields are a 5V design that practically work with the UNO/Leonardo/Mega boards, all of which use a wiring_analog.c implementation that behaves the same for A0 and 0.

In your current revision, you're checking < 307 and then < 690 but two of your observed readings 410 and 640 sit between these numbers.


text:
Arduino uno holder
Arduino sells a holder for the UNO board, but without much documentation or detailed specifications, see this link.  Can anyone give the diameter of four small holes, two located on the top edge and one each on the left/right edges?   What size of screw will fit?  They are smaller than M3 / 4-40 apparently.
Also, does anyone know what material is the holder made from?

If you can read the recycle logo on the plastic, you should be able to determine the material. The image is too unclear to determine from the post.

** Self answer:
I obtained several of these holders from Arduino starter kits.  They are made from a clear, colorless plastic that seems to have been injection molded.  However, it is hard to tell exactly which plastic, since these does not have any recycle logo!  The image posted in the original question is perhaps a newer version.
The four smaller holes can accept M2.5 screws, I checked.

Arduino UNO holes are just over 3mm in diameter. Both 4-40 and M3 bolts will work well, giving you a bit of wiggle room. You will have to file down the width of the bolt head to fit against the 6 pin header near D13.
As far as the holder material, I don't know. I 3D print my own.

The holes I asked about are smaller than M3 (i.e. while on the Arduino PCB they may be M3, on the holder M3 screws are too large and do not fit), sounds like a design flaw.

Probably M2.5. The Arduino Uno is full of design flaws. Idiotic design "decisions" that normal people would never have made.


text:
Did I fry a Sainsmart 1602LCD (not shield, just LCD), HD44780 compatible
Each new circuit I build, I seem to make every possible mistake, including inverting 5V and ground.
I did that precise mistake on this 2x16 Sainsmart LCD. The backlight definitely works, but is the only thing I seem to be able to make work. Do you believe I fried the screen, or do they maybe have a diode to protect from erroneous cabling, and my mistake is another one?
EDIT :
I found this somewhere, on a board that might be the one driving this LCD screen or not :
Operating Voltage VDD -0.3 to +7.0 V
Driver Supply Voltage VLCD VDD - 10 to VDD + 0.3
So I mistakenly put 5V in VLCD, and 0V in VDD, which makes VLCD 5V and not 0.3V above VDD, would you suppose I fried it?
Thanks for your input :)

Make sure you set the contrast using a potentiometer. Not seeing anything on the display, doesn't mean it's not working. If you only connect Vcc, GND and the Contrast pin, and you turned the pot to the correct position, you should see the first line filled with solid block, and the second line should be clear.

These things are reslient, because, according to the datasheet I was 4.7V outside specs, and your trick did it. I suppose if I saw the matrix of dots, it means it can print dots, and if it can print dots, it ain't fried. Thanks. Now I'll have five extras, but that'll just mean five projects who could do without will do with a LCD :D

I just succesfully did the hello world, thanks to you. If you'd only make an answer rather than a comment, I'd be able to select it. In any which case, thank you.

For me, it's extremely hard to tell if you did or did not fry a device.
Even if you have the device right in front of you, it's often hard to tell.
You've got two options:
Attempt to diagnose it
First you should try to run example code and follow the "instructions". I believe this product is relatively well documented (/libraried?) and shouldn't be all too hard to set up.
If this isn't working, it's likely the device is dead (given the situation). You could go on and fiddle around with it for hours, which might not be worth the effort.
Buy a new one
This will cost you some money. But if you get the new one working, you can test the same code on your old one.
Tips

First connect the wires, check the wiring and AFTER THAT connect the power. (Especially take care on GND/VCC wiring.)
Use black wires for GND/ground and red wires for VCC/5V.(It'll be easier to manage/spot)
Check the devices datasheets (which pins, what maximal voltage)
Try to use female connectors as power-output. (They don't short everything they touch)
Try to use irreversible connectors.
Don't have loose leads dangling around.
Put a casing/backplate on your Arduino (and/or avoid placing it on metal)
Keep your desk clean, bits of solder, wire, leads or screws may cause shorts between pins.

It may also be worth checking if only the "LCD driver" isn't working.

I ordered some LCDs (5 for 7 euros, crazy); they will probably take some time to come here, I'll answer when they do and I test a hello world on them.

Neat! Do they come with an "LCD driver"? Or well, it would be possible to drive them directly, but that would take a little more pins.

No, no driver, six pins (if you only write, seven if you read)


text:
Arduino fried? Onboard blink ok; offboard blink not ok
EDIT :
I have plenty of weird bugs. I will open another thread, and come back to this one when I have better understanding, rather than completely modify this one halway through. Sorry to every answerer for my electronic incompetence which led me to ask the wrong questions; I hope the other thread makes more sense.
I have recently exhumed an arduino from a cupboard, and can't seem to make even a blinking LED circuit work correctly.
Here's the sketch :
void setup() {
  pinMode(9, OUTPUT);
}

void loop() {
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(1000);
}

This has been tried without the circuit, on pin 13, using the onboard LED, and it worked.
However, using the following circuit, it did not result in a blinking LED, using several pins (8, 9, 12, 13) and LEDS.
May I assume the arduino is fried?
Here is a thumbnail of the circuit :

What happens if you plug the white jumper into 5V rather than the current digital pin 12 ?

The LED doesn't light. I also just tested the LEDs with 3 x 1.5 batteries, and they are functional.

Was the battery test using the circuit as above ? If so which pole of the battery was connected to the white lead ?

Positive. Anyways, I tested several pins, and inverted the led poles on each test, just to be sure; measure thrice, cut once ;)

Is it just me, or that resistor looks odd? What is its value? Can you measure it with a multimeter? Did you try changing the holes on the breadboard?

My arduino is not bricked, I just don't know how many things I don't understand about electronics, and make every single mistake I can make, especially while cabling.

Here's a guide posted by Nick Gammon for checking if your Arduino is bricked Is My Arduino Bricked ?

I will read this guide; thank you for the link.

It it possible the non-working LED got wired backward (it wouldn't be the first time!)? If the LED is clear enough, hold it up to the light and look inside the plastic bubble. There will be two bits of metal, one attached to each lead. One of them is significantly larger than the other; that's the cathode and it needs to be connected to the more negative side of the circuit. Here's a picture.

You haven't exactly got the LED connected to pin 9, as in the code, have you?
I find it hard to believe that you can upload new sketches, but none of the pins work. Try pins 0 or 1, in the sketch, for example. Or the whole lot:
void setup() {
  for (int i = 0; i < 20; i++)
    pinMode (i, OUTPUT);
}

void loop() {
  for (int i = 0; i < 20; i++)
  {
    digitalWrite(i, HIGH);
    delay(1000);
    digitalWrite(i, LOW);
    delay(1000);
  }
}

Now methodically test every pin.

What happens if you plug the white jumper into 5V rather than the current digital pin 12

The LED doesn't light.

Something's wrong with your testing. The processor cannot be powering up, and accepting new sketches, yet not have power to the +5V pin.

you're going to have to wait 40 seconds (worst case) for one blink? I would advise setting all pins HIGH, then put a delay, then put all pins LOW and put a delay again. (Instead of putting a delay between each set)

Try lighting up the LED without using any resistance in the middle, if that doesn't work try with a LED which consumes less current even if that doesn't work put the pin to HIGH state in code and measure the voltage of the given pin using a multimeter it should read above 3.3V. If neither of these work then you can be sure that your arduino is fried

Measuring between ground and that pin, is that correct?

Yes, Measure between the ground and the pin

I put a LED between GND and the pin directly in the arduino, and it worked


text:
How do I specify a particular pin to use as output for the Print class?
all.
I'm attempting to write a class that inherits from the Print class.  I only need serial output.
However, I'm having difficulty locating any reference on how to specify which pin on the ATMega my class will use as output of the write(...) functions.
How does the Print class know where to send output to ??
Thanks in advance.

You need to do far more than just "specify a pin". You need to write the software that transmits data through that pin in your chosen format.
You cannot send data through a pin. You can only set a pin HIGH or set a pin LOW. It is the sequence (and most importantly the timing) of setting a pin HIGH and LOW that constitutes sending data.
So you have to write the software that sets the pin HIGH and LOW in the right way and at the right time.
Fortunately sending is far simpler than receiving, as you can see if you look at the source code to SoftwareSerial.
Specifying the pin itself though is simple:
class MyClass : public Print {
    private:
        uint8_t _pin;

    public:
        MyClass(uint8_t pin);
        size_t write(uint8_t data);
};

MyClass::MyClass(uint8_t pin) {
    _pin = pin;
}

size_t MyClass::write(uint8_t data) {
    // In here you do whatever you have to in order
    // to manipulate _pin in the right way to send your data.

    // Don't forget to return the number of bytes written (there
    // is only one, so either 1 for "it got sent" or 0 for "it
    // didn't get sent".
    return 1;
}

It can be quite useful to have a begin() function for setting things up, such as configuring the right pinMode() for _pin, and maybe setting a baud rate like Serial does (although for simplicity you may choose to just have a single fixed baud rate, which means you can pre-calculate delay loops etc).

It seems I got past the "brain block"...  Just had to walk away from it for a while and the procedure just came to me.
Thanks to all.

The parent class (your class, in this case) provides read() and write() functions which in turn, know what ports to use. Presumably those were provided to the parent class' constructor. Now the Print class just has to know the standard function names.

Thank you, JRobert.
Apparently, it's specifying the "specifying which pin to use in my class' constructor" that's causing my "obvious brain block".
I don't want to use the hardware serial so I can leave normal TX and RX available for re-programming.
I tried inheriting from SoftwareSerial, but it apparently requires both TX and RX to be specified, and I only need

I only need my class to send data (not receive).
I hope I stated that clear enough.

It won't hurt to implement the read function anyway; make it an empty one if you wish. But I'd expect Print would refer to it (statically) and you'd get an undefined function error at compile time if no such function is present.


text:
When is following code is dumped into Arduino NANO the output is not as expected after few trials
I'm a beginner of Arduino programming,  when I dumped the following code into Arduino NANO board, at the first the output is as expected. But After few trials the 16*2 LCD display is getting off and DC motor pump is running continuously.
      #include <Wire.h>
      #include <Adafruit_MLX90614.h>
      #include <LiquidCrystal_I2C.h>
      LiquidCrystal_I2C lcd(0x27, 16,2);

      char *typeName[]={"Object","Ambient"};

      Adafruit_MLX90614 mlx = Adafruit_MLX90614();

      const int trigPin = 13;
      const int echoPin = 12;
      #define DCwater_pump 11

      long duration;
      int distance;

     void setup()
     {
          Serial.begin(9600);
          Serial.println("S.O.A.P. DISPENS");

          Serial.print("Ambient = ");
          Serial.print(mlx.readAmbientTempF());
          Serial.print("*F\tObject = ");
          Serial.print(mlx.readObjectTempF());
          Serial.print("*F");

          Serial.println();

          delay(500);

          if (!mlx.begin())
          {
              lcd.print("MLX90614 Failed");
              lcd.setCursor(0,1);
              lcd.print("check wiring!");
              while (1)
              ;
          }
          Wire.begin();
          lcd.begin(16,2);
          lcd.backlight();
          lcd.print("S.O.A.P.D. Temp");
          lcd.setCursor(0,1);
          lcd.print("S.O.A.P.D. Temp");
          delay(500);
          clearCharacters(2-1,0, 16-1);

          pinMode(trigPin, OUTPUT);
          pinMode(echoPin, INPUT);
          pinMode(DCwater_pump, OUTPUT);

    }

void loop()
{

        printTemp('C');
        delay(1000);

        printTemp('D');
        delay(1500);

}

float getTemp(char type)
{

  float value;
    float tempObjec = mlx.readObjectTempC();
    float tempAmbient = mlx.readAmbientTempC();

   if(type =='C')
   {
    value = tempObjec;
   }
   else if(type =='D')
   {
    value = tempAmbient;
   }
   return value;

}

            void printTemp(char type)
  {
            clearCharacters(1,0, 16-1 );
            float TmpC =getTemp(type);
            float TemF;
            TemF = (TmpC*1.8)+32;
            lcd.setCursor(0,1);
            if(type =='C')

              {
                lcd.print(typeName[0]);
                lcd.print(" ");
                lcd.print(TemF);
                lcd.print((char)223);
                lcd.print("F");
               }

                  else if(type =='D')
                  {
                    lcd.print(typeName[1]);
                    lcd.print(" ");
                    lcd.print(TemF);
                    lcd.print((char)223);
                    lcd.print("F");
                  }

  }

void clearCharacters(uint8_t row,uint8_t start, uint8_t stop )
{
    for (int i=start; i<=stop; i++)
    {
    lcd.setCursor (i,row);
    lcd.write(254);
    }

    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

    distance= duration*0.034/2;

    Serial.print("Distance: ");
    Serial.println(distance);

           if (distance < 30)
          {
           digitalWrite(DCwater_pump,HIGH);
           Serial.println("DC Pump is ON Now!!");
           delay(500);
          }
          else
          {
           digitalWrite(DCwater_pump,LOW);
           Serial.println("DC Pump is OFF Now!!");
           delay(500);
          }

}

Try to fix the formatting of your code first. This is very hard to read.

Your code is very confusingly organized. You clearCharacters function, which suposedly should clear the display, does a distance measurement (using an HSR-04 module?) and enables/disables the water pump as a side effect.

How is the pump motor connected? Do you have a flyback diode? Did you try using external pullups in the range of 4.7kOhm at the I2C lines (they might get problems with the motor generated noise, when you only use the internal pullups)?

I connected DC pump using a relay.


text:
My esp01 code keeps on erasing after reboot
I am uploading a simple Blynk cloud example code to control a led on GPIO2 of my esp01 board.
#define BLYNK_TEMPLATE_ID ""
#define BLYNK_DEVICE_NAME ""

#define BLYNK_FIRMWARE_VERSION        "0.1.0"

#define BLYNK_PRINT Serial
//#define BLYNK_DEBUG

#define APP_DEBUG

// Uncomment your board, or configure a custom board in Settings.h
//#define USE_SPARKFUN_BLYNK_BOARD
//#define USE_NODE_MCU_BOARD
//#define USE_WITTY_CLOUD_BOARD
//#define USE_WEMOS_D1_MINI

#include "BlynkEdgent.h"

BLYNK_WRITE(V0)
{
 int pinValue = param.asInt();
  Serial.println("Value Change");
  digitalWrite(2,pinValue);
}
void setup()
{
  pinMode(2,OUTPUT);
  Serial.begin(115200);
  delay(100);

  BlynkEdgent.begin();
}

void loop() {
  BlynkEdgent.run();
}

when I run it for the first time it works flawlessly, it gets configured easily with Blynk app and i am able to control the led.
but, when I reboot my esp01 it does not store the credentials and again starts the code from beginning!!
I think I am not able to get out of programming mode.
Please help me out !!
Thanks

try to add WiFi.persistent(); and WiFi.setAutoConnect();. it was the default until esp8266 Arduino version 3, but now both are off by default

@Juraj but it works fine for my nodemcu? So do you think it is the real prob?