text:
Can anyone please help me to modify the code so that it runs faster?
this is a program for a blindspot detection system using 4 ultrasonic and 2 ir sensors.
can someone help me in modifyng the code so that this runs faster?
#include<LiquidCrystal.h>
#define trigbl 14
#define echobl 15
#define trigbr 16
#define echobr 17
#define trigfl 18
#define echofl 19
#define trigfr 8
#define echofr 9
#define bl 10
#define br 11
long durationbl;
long durationbr;
long durationfl;
long durationfr;
int distancebl;
int distancebr;
int distancefl;
int distancefr;
int irr;
int irl;
int a;
int b;
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
void setup()
{
  lcd.begin(16, 2);
  pinMode(trigbl, OUTPUT);
  pinMode(echobl, INPUT);
  pinMode(trigbr, OUTPUT);
  pinMode(echobr, INPUT);
  pinMode(trigfl, OUTPUT);
  pinMode(echofl, INPUT);
  pinMode(trigfr, OUTPUT);
  pinMode(echofr, INPUT);
  pinMode(bl, INPUT_PULLUP);
  pinMode(br, INPUT_PULLUP);
}
void loop()
{
  digitalWrite(trigbl, LOW);
  delay(2);
  digitalWrite(trigbl, HIGH);
  delay(10);
  digitalWrite(trigbl, LOW);
  durationbl = pulseIn(echobl, HIGH);
  distancebl = durationbl * 0.034 / 2;
  int a1=distancebl;
  digitalWrite(trigbr, LOW);
  delay(2);
  digitalWrite(trigbr, HIGH);
  delay(10);
  digitalWrite(trigbr, LOW);
   durationbr = pulseIn(echobr, HIGH);
   distancebr = durationbr * 0.034 / 2;
  int a2=distancebr;
  digitalWrite(trigfl, LOW);
  delay(2);
  digitalWrite(trigfl, HIGH);
  delay(10);
  digitalWrite(trigfl, LOW);
  durationfl = pulseIn(echofl, HIGH);
  distancefl = durationfl * 0.034 / 2;
  int a3=distancefl;
  digitalWrite(trigfr, LOW);
  delay(2);
  digitalWrite(trigfr, HIGH);
  delay(10);
  digitalWrite(trigfr, LOW);
  durationfr = pulseIn(echofr, HIGH);
  distancefr = durationfr * 0.034 / 2;
  int a4=distancefr;
  irl =digitalRead(bl);
  irr =digitalRead(br);
  lcd.setCursor(1, 0);
  lcd.print("RL  RR  FL  FR");
  if (a1<30 && irl==0)
  {
  a=0;
  }
  else
  {
    a=1;
  }
   if (a2<30 || irr==0)
  {
  b=0;
  }
  else
  {
    b=1;
  }
   if  (a==1 && b==1 && a3>30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("No Obstacle    ");
  }
  else if ( a==0 && b==1 && a3>30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX            ");
  }
  else if ( a==1 && b==0 && a3>30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("    XX        ");
  }
  else if ( a==1 && b==1 && a3<30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("        XX    ");
  }
   else if ( a==1 && b==1 && a3>30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("            XX");
  }
  else if ( a==0 && b==0 && a3>30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX  XX        ");
  }
  else if ( a==1 && b==0 && a3<30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("    XX  XX    ");
  }

  else if ( a==0 && b==1 && a3<30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX      XX    ");
  }
  else if ( a==0 && b==1 && a3>30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX          XX");
   }
  else if ( a==1 && b==0 && a3>30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("    XX      XX");
  }
  else if ( a==0 && b==0 && a3<30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX  XX  XX    ");
  }
  else if ( a==1 && b==1 && a3<30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("        XX  XX");
  }
  else if ( a==1 && b==1 && a3>30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX  XX      XX");
  }
  else if ( a==1 && b==0 && a3<30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX      XX  XX");
   }
  else if ( a==1 && b==0 && a3<30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("    XX  XX  XX");
  }
  else if ( a==0 && b==0 && a3<30 && a4<30)
  {
        lcd.setCursor(1, 1);
        lcd.print("Call Help ......  ");
  }
}

Remove the delays...?

@Majenko those delays are to generate pulses for ultrasonic sensors.

hint: observe the result of these two commands to give you an idea how to shorten all the else if blocks ...... lcd.print("abc");  lcd.print("123");

You may want to check the datasheet of your sonar sensors to see what is
the recommended trigger pulse duration. On a typical HC-SR04, it is ten
microseconds, not milliseconds. So use delayMicroseconds(10);.
If your program runs really slowly, the culprit is most probably
pulseIn(). This function will wait for an incoming pulse and, if there
is no incoming pulse, it waits one full second before timing out. This
can be simply fixed by providing a third argument to pulseIn(), which
is the desired timeout in microseconds. Set it to something reasonable,
maybe around 25,000 µs for a maximum detection range of 4 m.


text:
Deploying an Arduino Uno R3 standalone
I have an Uno R3 with a sensor board and a temperature sensor. I'm running a simple temperature check and would like to store that data outside the Ardunio for keeping records, graphs, etc.
I powered it from my PC during development, but obviously I want something more compact when deployed. It's still inside the house, but I want the PC shut down, not running 24/7.
I do have wireless access, and a Raspbery Pi 3 model B. Can any of those help? Or should I buy an ethernet/WiFi shield and try to get acces with those?

you can connect the sensor to Raspbery

add Ethernet shield, log to SD card and download logs over Ethernet to PC for evaluation

How much data are you storing?  Use the 328P's internal EEPROM, download it to the PC when you power the PC up.

@Juraj - Thanks for your suggestion. I actually prefer to make this completely unattended, with no PC involvement except to access the rendered data.Using the raspberpi would be ideal to me.

@CrossRoads - Thanks for your suggestion. I actually prefer to make this completely unattended, with no PC involvement except to access the rendered data.Using the raspberpi would be ideal to me.

wifi shield and SD card .... run a web server on the arduino .... download the data file using a web browser

The simplest is to use an SD card shield and write your data to the card, occasionally exchanging cards. This can be very infrequent if you like; SD cards are pretty dense. Advantage: Simple and direct. Data remains under your direct control. Disadvantage: Finite (but potentially large) capacity; Data remains on your Arduino -- sort-of. Not sure how "outside the Arduino" you need it to be).
Another option, though a little more complex, is to use a networking device to log your data to an online service such as Thingspeak. I personally favor ESP8266 radios, as they're very cheap and easy to work with, but the choice of an Ethernet shield, WiFi shield, or whatever else, is up to you, and the techniques (from the Arduino's point of view) are similar. Advantage: Your data is saved off your Arduino immediately, somewhere with an "approximately infinite" capacity; provider may (Thingspeak does) offer plotting and analysis tools. Disadvantage: Your data does not remain under your direct control (though you can presumably collect it if you need/want to).

I eventually went with a separate ethernet shield

My first reaction is similar to Juraj's - go straight to the PI with the sensor; this is the most straightforward and maybe the simplest answre.  There are caveats - your sensor may not have a straight-forward hookup and, more importantly, the Raspberry PI uses 3.3V inputs - the Arduino can take up to 5V.  Don't fry your PI.
Next, you'll have to program your PI to read the sensor.
Another option is to use your Arduino to send the data serially to the PI. Again, verify your voltages.
Third, you can, mentioned, use an Ethernet shield, or some wireless daughter-board to talk to another computer like the PI or a server somewhere that stores/analyzes the data.  It tends to get more open-ended and can be as complicated as you like at this point.  Good luck!

So you would rather use your Raspberry Pi than your PC? Easy, as it
turns out that a Raspberry Pi is not that different from a PC running
Debian or a Debian-like OS (e.g. Ubuntu).
Just connect the Uno to the Raspberry Pi through the USB link. Log the
data on your Raspberry exactly like you would do on the PC. You don't
need any Ethernet or WiFi shield. You just need to make sure that
whatever logging program you use on the PC can run on the Raspberry Pi.
This is most often trivial if the PC is itself running a Linux distro.

source: Stack Exchange

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

sort: votes


text:
Dimmer.h issues with ATmega 128
I am using a ZCD circuit controlling a TRIAC. Now I am using Dimmer library for this purpose. It works fine with ATMega 328 but whenever I try to upload the code in ATMega 128 using Arduino IDE this error pops up:
Arduino: 1.8.4 (Windows 10), Board: "ATmega128, 2.7v, Disabled (default), 16 MHz external"

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp: In member function 'void Dimmer::begin(uint8_t, bool)':

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:15:20: error: 'TCCR2A' was not declared in this scope

 #define _TCCRxA(X) TCCR ## X ## A

                    ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:16:19: note: in expansion of macro '_TCCRxA'

 #define TCCRxA(X) _TCCRxA(X)

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:157:5: note: in expansion of macro 'TCCRxA'

     TCCRxA(DIMMER_TIMER) = TCCRxA_VALUE;         // Timer config byte A

     ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:17:20: error: 'TCCR2B' was not declared in this scope

 #define _TCCRxB(X) TCCR ## X ## B

                    ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:18:19: note: in expansion of macro '_TCCRxB'

 #define TCCRxB(X) _TCCRxB(X)

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:158:5: note: in expansion of macro 'TCCRxB'

     TCCRxB(DIMMER_TIMER) = TCCRxB_VALUE;         // Timer config byte B

     ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:19:20: error: 'TIMSK2' was not declared in this scope

 #define _TIMSKx(X) TIMSK ## X

                    ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:20:19: note: in expansion of macro '_TIMSKx'

 #define TIMSKx(X) _TIMSKx(X)

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:159:5: note: in expansion of macro 'TIMSKx'

     TIMSKx(DIMMER_TIMER) = 0x02;                 // Timer Compare Match Interrupt Enable

     ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:21:19: error: 'OCR2A' was not declared in this scope

 #define _OCRxA(X) OCR ## X ## A

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:22:18: note: in expansion of macro '_OCRxA'

 #define OCRxA(X) _OCRxA(X)

                  ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:160:5: note: in expansion of macro 'OCRxA'

     OCRxA(DIMMER_TIMER) = 100 * 60 / acFreq - 1; // Compare value (frequency adjusted)

     ^

exit status 1
Error compiling for board ATmega128.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Any idea what is the issue ?

ATMega328 and ATMega128 are not completely interchangeable .... the header file has either different register names or the registers do not exist in ATMega128

what core you use? it is possible, it has only different names. I checked the Dimmer library with MightyCore and for Atmega16/32/164 I get errors because they don't have the timer used by the library. but your errors a different. MightyCore doesn't support 128 (although it is in readme)

@Juraj I am using Megacore. I need to use 128 because I need a lot of ports.

@jsotola What you have pointed out looks like the problem.. that is obvious. but is there any work around ?

I need a lot of ports .... for what purpose? ..... it appears that this is an X-Y problem ..... you may or may not have a misguided solution to a lack of I/O pins and you are asking your question in an effort to make the solution work

The Dimmer library doesn't support Atmega128/164/16/32. It has
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define DIMMER_TIMER 4
#elif defined(__AVR_ATmega32U4__)
#define DIMMER_TIMER 3
#else
#define DIMMER_TIMER 2
#endif

For the Atmega128/164/16/32 it will use timer 2. The main errors are:
'OCR2A' was not declared in this scope
'TCCR2A' was not declared in this scope
'TCCR2B' was not declared in this scope
'TIMSK2' was not declared in this scope

Possible solution:
You could try to use timer 3. Only you need to change the timer number in Dimmer.h and in Dimmer.cpp on line 159 change TIMSKx(DIMMER_TIMER) = 0x02 perhaps to bitSet(ETIMSK, 3);. Check the datasheet. I can't test it, I don't have the chip.

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


text:
Help with simple gradually brighter flickering led
im a newcomer for arduino and sorry for any grammar error.
So what im trying to do is replicating a flickering effect found on spacecraft thruster when they about to take off where the fire bursting from dim to bright with flickering,similiar to afterburner on aircraft model which use neopixel led but this time only using common led.
I could mimic the flickering on the led with various  brightness level using the simple analogWrite,the problem is i cant really merge them since i use delay which is affecting how fast the flickering effect is and i need 1 sequence of flickering to stay a while before going next to brighter flickering and so on.
My code is quite too simple
    Int led = 9;
    void setup () {
    pinMode (led, OUTPUT);
    }

    void loop() {
    {analogWrite (led, random (10,15));
    delay (30);}

    }

Im thinking adding a new line with higher random led states (ex. 50,100) should be okay,but then the delay which affect the flickering speed are too short and making both line merging useless since its will go to the brightest in no time.
Is there's any way to hold the first dim line for an amount of time then continue to the next brighter line and so on without affecting the filckering delay?
Any help will be appreciated
Thank you!

first learn the BlinkWithouDelay example

@Juraj thank you for your response juraj,already playing around with milis for a few times,but all its do is holding the line while the other line overlapping it(which is okay for cosmetic purpose,but i didnt want to wasting resource),and its become too complex if i want to address each line with each their own milis

you have only one LED?

@Juraj i have 1 WIRE to distribute this effect from pin 9,i believe i can power as many led as i like with or without the arduino later,so yeah you can say 1 led but not really

then add second analogWrite and a delay after it

Before using millis() you can try to create the thruster effect with delay().
I think 40Hz update rate for the led should be enough.
The sketch starts with a random value between 5 and 15 and ends with a random value between 80 and 256.
The part in the middle that gradually increases between those values is a mathematical problem.
// Led mimic spacecraft thruster.
//
// Update rate 40Hz for the led.
// That is a delay of 25ms.

#define RATE 40  // update rate of led in Hz
const int ledPin = 9;   // it must be a PWM pin !

void setup () {
  pinMode(ledPin, OUTPUT);

  Serial.begin(9600);

  randomSeed(analogRead(A0));
}

void loop() {
  int n;

  Serial.println("10 seconds low brightness");
  n = 10*RATE;
  for(int i=0; i<n; i++) {
    analogWrite(ledPin, random(5,15));
    delay(1000/RATE);
  }

  Serial.println("5 seconds gradually brighter");
  n = 5*RATE;
  for(int i=0; i<n; i++) {
    //   random start: from 5 to 80     (75 increase)
    //   random end  : from 15 to 256   (241 increase)
    //   The calculation is with long, it might not fit in a 16 bit integer

    int random_start = 5 + int((long(i) * 75) / long(n));
    int random_end   = 15 + int((long(i) * 241) / long(n));
    analogWrite(ledPin, random(random_start,random_end));
    delay(1000/RATE);
  }

  Serial.println("10 second full thrust");
  n = 10*RATE;
  for(int i=0; i<n; i++) {
    analogWrite(ledPin, random(80,256));
    delay(1000/RATE);
  }

  analogWrite(ledPin,0);
  delay(2000);
}


text:
ESP8266 - Sending a software Reset Command
I have an ESP8266 running an Arduino code to control a dual relay device ( Up, Down, Off ), both from a physical switch and MQTT commands. After mounting the device in place I have no access in case of a need to reset ( just as a precaution ).
My workaround:
1) condition: function that on 4 detection of 4 repeated UP button presses - it should send a reboot signal.
2) the reboot signal is :
void sendReset() {
  Serial.println("Sending Reset command");
  Serial.println(1/0);
}

sendReset function actually reboots the device and boot occurs as needed, BUT - is doing it this way is a valid solution ? does boot process actually boots all services and freeing/ memory or any other.... AS NEEDED ?
Guy

1/0 is an exception (divide by zero). esp8266 arduino core has soft reset: ESP.reset(). Calling this function you get a valid reset.
Note to software reset. esp8266 has a bug. If software reset (or exception) is executed in program started right after the flashing, the board goes back to flashing mode because the flashing flag is still active. Perhaps you noticed that after flashing the bootloader doesn't reset the board, but executes the flashed code.

Hi! Yes I know it is an exception, but it causes a reset. Does an Arduino board has also a reset function?

read the answer, please

I read your answer before it was edited ( 1st paragraph only ). Thanks for additional information. My question in the comment was a generelized question regarding Arduino boards ( Nano for example ) it it has also a reset command.

Nano? you write the code for esp8266. yes there is a reset solution for AVR too. with watchdog

Yes ! my code is for esp8266 and the reset command is intended for this code, but I wanted to know if such command exists for Arduino boards. thank you

not one general. different Arduino cores have different solutions for reset. SAMD has NVIC_SystemReset()

In case of serial upload, you need to power off and back on the port, in order to execute again sendReset to work as needed. What is the workaround in causes of OTA, that powering off is not an option ?

OTA makes ESP.reset(). it is good. (it doesn't work only at first reset after serial upload)


text:
Can batteries be damaged?
I have some questions when it comes to draining batteries with low power projects.
I have been making a few low power projects with Arduino Pro Minis running on batteries. Some run on single non-recharchable CR123As while others run on two or three recharchable AAAs. I have removed the regulator and the power led on the Pro Minis, and I have changed the fuses making them run as low as 1.8v (or according to my measurements 1.7v). This way they consume a few µA and should be able to run for years on those batteries.
Now, what started to concern me is that this setup will be able to run the batteries very low. According to the voltage curve of a CR123A, it will be practically drained when reaching 1.7v. The same goes for two or three recharchable NiMH AAAs, that will have an individual voltage of 0.85v or 0.55v. Unless the batteries themselves have a discharge protection built in. In that case there might be no problem at all; I just don't know if batteries such as Eneloops have that.
So my questions are:
1) Do batteries such as CR123As and Eneloops have built in discharge protection so that they stop supplying power when the voltage is too low?
2) If no, will draining a non-rechargable CR123A be dangerous or problematic in any way? And will draining MiMHs down to 0.85v/0.55v hurt the batteries?
3) And, a question that I suppose applies to any battery powered Arduino project: When the supplied voltage drops below the Pro Minis BOD limit, will the Arduino stop using any power, or will it continue draining the batteries until they are completely empty? (In the first case I guess I could stick with the factory set BOD at 2.7v to protect the batteries.)
4) Finally, relating to the first question: Should I try to construct some kind of battery protection in the circuit, or is unnecessary when using CR123A and NiMH batteries?

Consider posting this on Electrical Engineering SE rather than Arduino SE.

1) Do batteries such as CR123As and Eneloops have built in discharge protection so that they stop supplying power when the voltage is too low?

No, they don't.  They just run till there is nothing left.

2) If no, will draining a non-rechargable CR123A be dangerous or problematic in any way? And will draining MiMHs down to 0.85v/0.55v hurt the batteries?

A single cell can be run completely flat without problems. NiMH may need some "recovery" to wake them back up again, but shouldn't suffer serious problems (and no safety issues).  However, batteries are a different matter: see below.

3) And, a question that I suppose applies to any battery powered Arduino project: When the supplied voltage drops below the Pro Minis BOD limit, will the Arduino stop using any power, or will it continue draining the batteries until they are completely empty? (In the first case I guess I could stick with the factory set BOD at 2.7v to protect the batteries.)

It will continue draining power. The BOD is a reset circuit - designed to recover the system into a known good state after a dip in the power. A permanent decrease in the input power is beyond the scope of the BOD system.  It will just get stuck in a BOD reset loop and consume all your remaining power.

4) Finally, relating to the first question: Should I try to construct some kind of battery protection in the circuit, or is unnecessary when using CR123A and NiMH batteries?

For a single non-rechargeable cell you can just let it run flat. For NiMH you need to protect them.  Here's why (and what I was alluding to above):

When you have two or more cells in series (a battery) the current flows through all the cells of the battery equally. That is all fine when the cells are all fully charged - however no two cells are precisely the same.
As the battery runs down each cell will approach "empty" at a different time. With a single cell that's not really a problem, since it will just stop providing enough current to run.  However, with multiple cells one cell will run flat before the others. At that point the current provided by the other cells which still have some charge in them will be pushed through the flat cell backwards.  It is at that point that the flat cell becomes irrevocably damaged.  Current flowing backwards through the cell will try to reverse charge the battery and mess up the internal chemistry beyond recovery.
In the best case scenario, your battery will now have a much lower capacity and need recharging far more often. Worst case scenario: that damaged cell overheats and explodes.
The most prevalent problem that is caused by reverse charging is the depositing of metal crystals on the dielectric (the separator between the two electrodes) in the cell which grow and pierce the dielectric causing short circuits within the cell. There is no way back from that happening.
So you should protect your NiMH batteries from over-discharge by cutting the power to your circuit when the voltage drops below a specific threshold.  You should also recharge all the cells individually, not together in series, or they will end up unbalanced and the same problems of over-discharge can occur.

As a side note: I use the terms "cell" and "battery" with their "proper" usage: A cell is a single power-producing unit, such as an AA "battery".  A battery is a collection of cells.  This is the proper usage of the words, not the common usage where battery can also be taken to mean cell.  I use these terms specifically to differentiate between a single unit and a collection of units because of the major differences in how you need to handle them. It helps prevent confusion if you know that I am talking about just one AA (a cell) or a collection of three AA in series (a battery), for example.

Wow, thanks, Majenko, that was a quick and brilliantly explained answer.
The conclusion then would be that I can stop worrying about my project running CR123A cells (thanks for clarifying those terms!) while I need to make protective circuits for my projects with NiMH batteries.
I must admit that I am relatively new to electronics, so please excuse yet another question: What would be a simple way to introduce discharge protection to a low power project? Is it possible without drawing much current? My projects consume 5-30 µa in sleep mode, and I would love to keep them in that range.

You can measure the power supply voltage directly with the Arduino (see here), and implement a simple "soft power" switch using a P-channel MOSFET (wired so it's normally off, and the Arduino turns it on with a GPIO - use a button to bypass it to turn the system on).  Draws next to nothing, governed by the values of pullup resistors alone.


text:
4052 interfacaing with arduino uno
I am trying to interface 4052 demux with arduino, but my program is not working as high is not displayed on serial monitor corresponding to select lines.
//output coming from demux pins
int sensorValue0=A0;
int sensorValue1=A1;
int sensorValue2=A2;
int sensorValue3=A3;

void setup() {
  Serial.begin(9600);
  Serial.println("start");
  //select pins connected A,B connected to 2 and 3
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
}

void loop() {
  digitalWrite(2,LOW);
  digitalWrite(3,LOW);
  analogRead(sensorValue0);
  //Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  int voltage0= sensorValue0 * (5.0 / 1023.0);
  Serial.println("volatge0");
  Serial.println(voltage0);
}

Have you looked at any tutorials of references on how to use analogRead()?

You are ignoring the value read by analogRead().  You are then using the value A0 (14) in your sum to calculate the voltage.
Instead:
int adcReading = analogRead(sensorValue0);
int voltage0 = adcReading * (5.0 / 1023.0);

Although I think what you really meant to write was, in total:
int sensorPin = A0;
int sensorValue0;//output coming from demux pins
int sensorValue1;
int sensorValue2;
int sensorValue3;

void setup() {
Serial.begin(9600);
  Serial.println("start");
  pinMode(2,OUTPUT);//selecr pins connected A,B connected to 2 and 3
  pinMode(3,OUTPUT);
}

void loop() {
  digitalWrite(2,LOW);
  digitalWrite(3,LOW);
  sensorValue0 = analogRead(sensorPin);
  float voltage0 = sensorValue0 * (5.0 / 1023.0);//Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  Serial.print("voltage0 = ");
  Serial.println(voltage0);
}

Note that the value sensorPin is where you read the voltage from, and sensorValue0 is where you store that reading. Also note the use of a float type to store the calculated voltage, since an int will give you only values of 0, 1, 2, 3, 4 or 5 in this situation (so, pretty meaningless really).

actually select pins of demux are not selected according to program written.

I am assuming it's a partially written program at the moment.

sir,one more thing what should i write to control two demux in a program using inhibit pin and activate only one demux at a time..

Just use digitalWrite to activate the mux you want.

I have used digitalwrite(4,LOW); as 4 pin of arduino is connected with demux inhibit pin and demux is fuctioning but when m not using inhibit pin of demux den still demux working,not understanding whats happening.why inhibit pin not working as it should

i have used CD4052BE DEMUX


text:
SD card failed to initialize
I have a Pro Micro board and I try to make it list my files as in the example of the Arduino IDE.
The pins I use are the following:
board    micro sd module
   D4  ---> CS
   D15 ---> SCK
   D14 ---> MISO
   D16 ---> MOSI
   GND ---> GND
   VCC ---> VCC

On the serial monitor I get "initiallization failed".
What is wrong with my setup?
This is the code running:
#include <SPI.h>
#include <SD.h>

File root;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  root = SD.open("/");

  printDirectory(root, 0);

  Serial.println("done!");
}

void loop() {
  // nothing happens after setup finishes.
}

void printDirectory(File dir, int numTabs) {
  while (true) {

    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

And this is my wiring:

Please add your code.

maybe your program consists of only these two commands ..... Serial.begin(9600);  Serial.println("initiallization failed");  ..... that would give you the observed output

did you insert the card?

what are the voltages of board and SD module?

@jsotola I study computer science man, this is not one of my possible mistakes. But thank you for your comment

@Juraj Yes I inserted the card. How can I see the voltages?

in specification. pro micro's are 5 V or 3.3V. SD card modules are with voltage conversion to 5 V or only a holder for SD card with 3.3V native voltage

So the voltages are ok? I connect it to my pc via usb. How can I look further to this? I am sure it should have worked by now.

@MichelKeijzers I did, any guesses?

connection to USB doesn't say anything about voltages. add links to where you bought them, if you don't know the specs

I bought both the board and the module a long time ago from Ebay. The module is from Catalex and says v1.0. My sd card is a standard one (Kingston 4gb) and the module is probably the cheapest pro micro on ebay.

Catalex SD module is 5 V. On pro micro you could measure a voltage of an OUTPUT HIGH pin

How do I do this?

is the SD card formatted to FAT or FAT32?

I am not sure. Could this be the problem?

that would be definitely the problem. put the card in a computer and check it

it was ntfs I am sure, I am formating it to FAT now. But this should be a problem at software level, doesn't it? Due to my sketch it seems that it fails to init

do you have a voltmeter/multimeter to measure voltage of vcc or a pin?

No, not yet. I have ordered a multimeter but it has not arrived yet

is something written on the bottom side of the pro micro?

Let us continue this discussion in chat.

I only would think of inserting the SD card, using a FAT (not NTFS) formatted card, and optionally try another SD card (got problems myself depending on the SD Card). Also I would advice buying a (around 5$) logic analyzer from Ebay, than you can relatively easy find out what's going over the jumper wires.

@MichelKeijzers, read the chat finale

The SD library works only with FAT and FAT32 format. SD.begin() reads the 'disc volumes' and opens the root folder. If the card is not formatted or formatted with other file system standard, begin() fails.
EDIT: and the pin headers must be soldered

Yea, I got it. I just formated it to FAT32 and it didnt work either. What else could it be?

Here's my setup code for my SD card for a little circuit where I was writing temperature data to the card.
const int SD_CS = 10;
   const long SLEEP_TIME = 60000;  // write to card every minute
   long multiplier = 0;

   LiquidCrystal_I2C lcd(0x3F, 20, 4);

   void setup() {

     lcd.begin();
     lcd.setCursor(2,0);
     lcd.print("Hello, LCD!");

     if (SD.begin(SD_CS)) { // init SD
       lcd.setCursor(2,2);
       lcd.print("SD card init");
     }

 }

I set the CS pin to D10.
Try switching it to another pin like this and see if you get a different result.  I believe I had a challenge when I used pin 4 but can't quite remember.
Note: And of course remember to move your CS wire to pin D10 or whichever one you use.

the problem is revealed in chat

@Juraj Headers not soldered! Yipes! I asked a relevant question about this long ago -- https://electronics.stackexchange.com/questions/249140/how-can-i-make-connection-on-pcb-circuit-board-holes-without-solder-for-proto
Great catch!


text:
Problems on convert byte[] to String
I'm reading a RFID Card from RC522 and send the data to my computer. My problem is the conversion of byte[] to String or std::string.
#define SIZE_BUFFER     18
#define MAX_SIZE_BLOCK  16

byte buffer[SIZE_BUFFER] = {0};
byte tam = SIZE_BUFFER;

// get data
status = mfrc522.MIFARE_Read(bloco, buffer, &tam);

  Serial.print(F("\nDados bloco ["));
  Serial.print(F("]: "));

// printing...
 for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
  {
      Serial.write(buffer[i]);
      str += String(buffer[i]);
  }

OUTPUT:
Dados bloco []: asdas

So, it's ok! But if I try make a string:
  String str = "";

  for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
  {
      str += String(buffer[i]);
  }
  Serial.println(" ");
  Serial.println(str);

The output is:
97115100971153232323232323232323232

What is the correct way to create a String from byte[]?

byte and char are the same. If you set 0 as string terminator after last character in the buffer, you get a zero terminated string. If you really must use String, you can create an instance with a constructor that takes zero terminated string.
buffer[tam] = 0;
String str((char*) buffer);

Let in the buffer a place for the zero. (char*) is cast that says that the byte array is a char array.
Note: Don't use String class in a MCU, use zero terminated character arrays.

I just need the value, but String is easy to send via Bluetooth. I can send char too, but I don't know to convert.

set 0 as string terminator after last character in the buffer. but let space for it. if the RFID numbers are 18 chars, then allocate 19

If you change str += String(buffer[i]); to str += (char)buffer[i];, it will print the ascii characters to the serial monitor.
The following sketch can be used to see the difference in binary compiled size using these two methods of "adding to the string".
// 4026 to 3758 bytes.
#define SIZE_BUFFER     18
#define MAX_SIZE_BLOCK  16

byte buffer[SIZE_BUFFER] = {
  0x61, 0x73, 0x64, 0x61,
  0x73, 0x20, 0x20, 0x20,
  0x20, 0x20, 0x20, 0x20,
  0x20, 0x20, 0x20, 0x20
};

String str = "";

void setup(){

  Serial.begin(9600);

  for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
  {
      // 4026 bytes. Prints: "97115100971153232323232323232323232"
      //str += String(buffer[i]);

      // 3758 bytes. Prints: "asdas           "
      str += (char)buffer[i];
  }
  Serial.println(" ");
  Serial.println(str);
}

void loop(){}

Casting each element in the byte buffer to Char, then adding it to the string drops the binary compiled size from 4026 to 3758 bytes. This is good, but we can really improve the sketch by not using the String object at all.
This sketch is the same as the first one, except it uses a Character Array instead of a String.
// 2074 bytes.
#define SIZE_BUFFER     18
#define MAX_SIZE_BLOCK  16

byte buffer[SIZE_BUFFER] = {
  0x61, 0x73, 0x64, 0x61,
  0x73, 0x20, 0x20, 0x20,
  0x20, 0x20, 0x20, 0x20,
  0x20, 0x20, 0x20, 0x20
};

// Use a char array instead of the String object.
char outputBuffer[SIZE_BUFFER];

void setup(){

  Serial.begin(9600);

  for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
  {
      // 2074 bytes. Prints: "asdas           "
      outputBuffer[i] = (char)buffer[i];
  }
  Serial.println(" ");
  Serial.println(outputBuffer);
}

void loop(){}

The binary compiled size is 2074 bytes. That's 1684 bytes less than using the String object.
There are many functions available to work with Character Arrays on an Arduino, such as http://www.cplusplus.com/reference/cstring/ and http://www.cplusplus.com/reference/cstdlib/.


text:
Arduino Uno - Building a Controller
I have the Arduino Uno and I'm working on a project to build a controller with different inputs and some outputs for readouts. In classic style, I got the Arduino Uno before realising that I might not have enough I/O points to connect everything I want.
I believe there is a way to expand my Uno by using an I/O Expander? Has anyone done something similar? The controller will be for a specific game called Kerbal Space Station. There are quite a few articles helping with the build but not specific to what I am looking at.
Components I'll be using:
INPUTS:

2x 3 Axis Joysticks
11x Microswitches
6x Toggle switches
1x Analogue slider
1x 10 point rotary switch

OUTPUTS:

4x 12 pin LED Bargraphs
1x Serial LCD module display

yes, that sort of a thing has been addressed before ..... what type of joysticks will you be using?

Yes, all those things have been done before.  Here's some suggestions for components:

MCP23S17 / MCP23017 - SPI / I2C IO expander (16 IO pins, many can be connected together) (MCP23S17 library)
MCP3208 - 8 channel 12-bit SPI ADC (MCP3208 library)
TLC59116 - I2C Constant Current LED PWM driver (16 channel) (TLC59116 library)

Some other useful tutorials that may help:

Keypad - read lots of buttons / switches with not many pins
Multiplex - Control many LEDs with not many IO pins

Sparkfun also sells a SX1509 module for a very good price. It can do a matrix keyboard all on its own (hardware support) with similar (independent hardware-driven) LED heartbeat control. Aside from that, you can use any remaining pins as normal I/O (read/write/pwm).
There are 16 pins total, and it's controlled over I2C.
Adafruit also has a board called the Seesaw, which is a small Atmel SAMD09 with I2C slave firmware. It works similarly, but the pins are much more limited.
Either way, you simply include a library to your code, and use the object to interface with the pins rather than the usual functions on your Arduino. Most seem to use identical syntax (someclass.digitalWrite()...) to the normal Arduin functions.


text:
Can Arduino accept HDMI input video stream, and output it without any modification to the video?
I'd like to know please whether an Arduino can accept an HDMI signal from a satellite receiver, let it flow without any modification to the stream, and output it to TV?

what do you want to do that wire doesn't?

No.
HDMI uses multiple serial data streams at gigabit rates. No Arduino is ever going to do that sort of thing.  If you want something programmable to do that kind of thing you need an FPGA.


text:
How can I calculate approximate cycles per second from pulsed pin on Arduino MKR Zero?
The relevant tech specs for a MKR Zero are:
    32.768 kHz (RTC*), 48 MHz
*Real-Time Clock
What I'm curious about is how I might do an approximate calculation of cycles per second from operations.
I'm running the following (extremely simplified) code :
int pin3 = 3;
void setup() {
  //set digital pin pin3 as output

  pinMode(pin3,OUTPUT);
}

void loop(){
  digitalWrite(pin3,HIGH);//set pin pin3 to +5V
  delay(100);//wait 100ms
  digitalWrite(pin3,LOW);//set pin pin3 to 0V
  delay(100);//wait 100ms
}

Now I'm curious how many cycles per second (approximately) that might account for.
The Equation?
What would the equation be to calculate that?
Not Processor Op Codes
Is this even possible to approximate?  I understand it will be difficult because those lines of code do not equal the actual op codes and don't exactly break down to specific cpu cycles or whatever.
Would it be something like:
48,000,000 (48MHz) / 200 (millisecond pause) = 240KHz?

Or would I use the real-time clock speed?
32768 / 200 = @163Hz

Or something completely different?
I'm trying to better understand how I might create a very simple frequency generator and I know that depending upon the chip speed the code will vary.

Do you know the library for the internal rtc of a arduino mkr zero? https://www.arduino.cc/en/Reference/RTC You could increment a counter in the loop and measure it against the real time. For example during an hour, then you can calculate the actual cycles per second. It might be 4.999 Hz per second. You can also use millis to set the output exactly to a certain number of cycles per second. Perhaps even the tone function can be used.

It is unclear exactly what you are trying to do, however the frequency generated by the code would be ~5Hz - corresponding to a period of 200mS

Thanks, what is the equation that you applied to come to that answer?  Oh, (forehead slap) it is generating a pulse every 200mS so 1000mS (1S) / 200mS = 5Hz.  So it would actually be ~5Hz (not kHZ), right?  Thanks for answering.  If you change it to Hz I will mark it as the answer.  You helped me get to the right point.  I had been thinking something else.  Thanks.

The dependency on the clock speed is hidden in the implementation of the delay() function. It works with 'human readable' milliseconds.
Hertz is count of repeating in one second. One second has 1000 ms. So with 200 ms delay, 5 repeating happen in a second. Then the frequency is 5 Hz.


text:
Calculation error with Optical Encoder
I have corrected my code for reading the optical encoder index but I am now getting a different calculation error.  At the index the encoder reset's to zero but now my readouts are as follows:
Index point - resets to zero.
- At the 90 degree rotation mark I have a readout of 180 degrees.
- At the 180 degree rotation mark I have a readout of 0 because the code has it reset to zero after 359 degrees.
- At the 270 degree rotation mark I have a readout of 180 degrees.
- At the 0 degree mark it is zero again and that's what I would expect from the index.  If I restart the Arduino Mega at the 270 degree mark, the index resets itself to zero like it should.  Being new to this, before I had the index working it was working correctly minus the index function, now it seems to be double counting.  Any ideas?
// Wiring connections for my encoder:
// Brown : VCC = 5V
// Blue + Shield : 0V = GND
// Black : ENCODER0PINA, Pin 20
// White : ENCODER0PINB, Pin 17
// Orange : ENCODER0PINI, Pin 19

#define ENCODER0PINA         20      // this pin needs to support interrupts
#define ENCODER0PINB         17      // no interrupt required
#define ENCODER0PINI         19      // this pin needs to support interrupts

// variables modified by interrupt handler must be declared as volatile
volatile long encoder0Position = 0;
volatile long interruptsReceived = 0;
volatile byte INTFLAG1 = 0;

// track last position so we know whether it's worth printing new output
long previousPosition = 0;

void setup()
{

  // inputs
  pinMode(ENCODER0PINA, INPUT);
  digitalWrite(ENCODER0PINA, HIGH);  // turn on pullup resistor
  pinMode(ENCODER0PINB, INPUT);
  digitalWrite(ENCODER0PINB, HIGH);  // turn on pullup resistor
  pinMode(ENCODER0PINI, INPUT);
  digitalWrite(ENCODER0PINI, HIGH);  // turn on pullup resistor

  // interrupts
  attachInterrupt(3, onInterrupt, CHANGE);  // encoder track A on interrupt 3 - pin 20
  attachInterrupt(4, onReset, CHANGE);  // encoder Index track on interrupt 4 - pin 19

  // enable diagnostic output
  Serial.begin (115200);
  Serial.println("Ready.");
}

void loop()
{
  // only display position info if has changed
  if (encoder0Position != previousPosition )
  {
    Serial.println(encoder0Position, DEC);

    previousPosition = encoder0Position;
  }
}

// interrupt function needs to do as little as possible

void onReset()
{
  // read Index input
  int i = digitalRead(ENCODER0PINI);
  if (i == 1)
  {
  encoder0Position = INTFLAG1;
  }
}

void onInterrupt()
{
  // read both directional inputs
  int a = digitalRead(ENCODER0PINA);
  int b = digitalRead(ENCODER0PINB);

  if (a == b)
  {
    // b is leading a (counter-clockwise)
    encoder0Position--;
    if (encoder0Position < 0)
    {
      encoder0Position = (encoder0Position + 360);
    }
  }
  else
  {
    // a is leading b (clockwise)
    encoder0Position++;
    if (encoder0Position >= 360)
    {
      encoder0Position = (encoder0Position - 360);
    }
  }
}

please format your code as "code" .... highlight all the code text and click the {} button

I did it for him/her.

Thank you, I was wondering how to get the code to format as "code".  (him).

What is the encoder that you are using? Does it have a 0.5 degree increment?

It is a Omron E6B2-CWZ6C Incremental Rotary Encoder w/Index (360P/R).

One more comment on the code above.  It ran correctly before the Index was introduced.  I tested the index and it only fires once per revolution.

I have done more testing with the code and have noticed that when the encoder has been rotated clockwise past the index the readings do the following 359, 0, 1, 2, 0, 1, 2, 3, after that it reads correctly. When turning the encoder counter clockwise the following happens 1, 0, 359, 358, 0, 359, 358, 357, and then runs correctly. Does anyone see why the encoder would do this as well as the initial issue?

I have figured out my issue, at least I am getting good results.  With this code I had to change interrupts from CHANGE to RISING.  I want to thank everyone that has made comments on this question.

I have figured out my issue, at least I am getting good results. With this code I had to change interrupts from CHANGE to RISING. I want to thank everyone that has made comments on this question. –


text:
Nano & Ethernet will not write to PushingBox on a workplace network (but will at home)
I have a Nano+ENC28J60 and I'm using Pushingbox which I have setup to write data to a GoogleDrive spreadsheet which works perfectly at home. However when I take it to my workplace it no longer works.
At work, serial tells me that the

Ethernet connection is good;
I get a client connection OK too.

However, [edit] even with 5 attempts at a response client.read(); it reports nothing at all. Serial shows
OK connected! Written. Checking response: + + + + +

I assume it is to do with some firewall or other restriction, but if I can get a connection that should be enough, no?
[edit] note: i have also tried connecting to port 443 instead of port 80 in case it was an HTTPS issue - same results, though]
How I can write to GDrive on my work network?
The code [edit#2 modified client.connect() to try 5 times and a response check via client.read() to try 5 times and Serial.print("+ "); each time] :
#include "DHTesp.h"
#include <SPI.h>
#include <UIPEthernet.h>

DHTesp dhtA; DHTesp dhtB;

const int ledPin =  LED_BUILTIN;
int ledState = LOW;
int interval = 20; // this is the num seconds between reads (120=2mins) ***************************
int numReads = 2;   // Amount of reads between posting to Gdocs.  ***************************

byte mac[] = {0xAA, 0xF0, 0xDE, 0xDE, 0x06, 0xAF };  // Ethernet shield MAC addy
byte ip[] = { 10, 10, xx, yy };
char devid [] = "vXXXXXXXXXXXXXXXX";  //  device ID from Pushingbox

char server[] = "http://api.pushingbox.com";
EthernetClient client;

int c = '\0';

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

  Serial.print(F("dB_CoSdataV3.  Establishing..."));
  if (Ethernet.begin(mac) == 0) {
    Serial.println(F("Failed to configure ethernet"));

    //while (true); // no point in carrying on, so do nothing forevermore
  }
  else {
    Serial.println(F("Ethernet OK."));
    // print the Ethernet board/shield's IP address:
    Serial.print(F("local IP addy: "));
    Serial.println(Ethernet.localIP());
  }

  // give the Ethernet shield a second to initialize:
  delay(3000);

  Serial.println("____________________________________________");  Serial.println();

  dhtA.setup(3); //  sensor A
  dhtB.setup(4); //  sensor B
  //dhtC.setup(7); dhtD.setup(7);

  pinMode(ledPin, OUTPUT);

}

void loop(){

  int Ahumidity = 0;   int Atemperature = 0 ;
  int Bhumidity = 0;   int Btemperature = 0;

  int j = 0;
  for (j = 1; j <= numReads ; j++ ) {
    int p = 0;
    for (p = 1; p <= interval ; p++) {
      delay (1000);
      // if the LED is off turn it on and vice-versa:
      if (ledState == LOW) {        ledState = HIGH;       }
      else {        ledState = LOW;      }
      Serial.print (F("."));
      digitalWrite(ledPin, ledState);
    }

    Serial.print (" reading: ");
    Ahumidity += 10 * dhtA.getHumidity();  Atemperature += 10 * dhtA.getTemperature();
    Bhumidity += 10 * dhtB.getHumidity();  Btemperature += 10 * dhtB.getTemperature();

    Serial.print (j);     Serial.print (F("/"));     Serial.print (numReads);
    Serial.println();
  }

  Serial.print (F("Show the averaged val.s : "));
  Serial.print(F("\t\tA:")); Serial.print(Atemperature/(numReads)); Serial.print(F("\t")); Serial.print(Ahumidity/(numReads));
  Serial.print  (F("\tB:")); Serial.print(Btemperature/(numReads)); Serial.print(F("\t")); Serial.print(Bhumidity/(numReads));

  // now connect + write to Gdrive....................
  boolean connected;
  int counter1 = 0;
  do {
      connected = client.connect(server, 80);
      if (connected) { break; }
      client.stop();
      delay(1000);
      Serial.println("retry");
      counter1++;
  } while (!connected && counter1 <5);

//------------------
//if (client.connect(server, 80)) {

if (connected){
    Serial.println();
    Serial.print(F("OK connected! "));

      String buf;

      buf += F("GET /pushingbox?devid=");
      buf += String(devid);

      buf += F("&tempA=");  buf += String(Atemperature/numReads);
      buf += F("&tempB=");  buf += String(Btemperature/numReads);
      buf += F("&tempC=0&tempD=0&tempE=0&tempF=0&tempG=0&tempH=0"); // null data needed

      buf += F("&humidA=");  buf += String (Ahumidity/numReads);
      buf += F("&humidB=");  buf += String (Bhumidity/numReads);
      buf += F("&humidC=0&humidD=0&humidE=0&humidF=0&humidG=0&humidH=0"); //null data needed

      buf += F("&submit=Submit");
      buf += F(" HTTP/1.1");
      //client.println(F("Host: api.pushingbox.com"));
      buf += F("Host: http://api.pushingbox.com"); // trying the addition of http://...
      buf += F("Connection: close\r\n");
      //client.println();

      client.print(buf);
      Serial.print(F(" Written. "));
      delay(1000);
      int counter2 = 0;
      Serial.print ("Checking response: ");

      do {
          if (client.available()) {
              Serial.print("Y ");
              c = client.read();
              Serial.print((char)c);
          }
          delay(2000);
          Serial.print("+ ");
          counter2++;
      } while (counter2 < 5);

      Serial.println ();       Serial.println ();
      //client.stop();
  }

}

You should probably ask your local network administrator.  They are going to be the ones who know how they are blocking you.  You have given us absolutely zero information on the corporate network so there is very little chance of us being able to help you circumvent it.

sure, thanks @Delta_G. i'm happy to provide whatever information i can - what question should i ask the network administrator?

you use static IP?

Hi @ Juraj do you mean the question to ask is: "do we use a static IP here"? if yes/no what would that mean for the sketch? thx

I asked because you have byte ip[] = { 10, 10, xx, yy }; but I see ip is not used

I think you misunderstand what I meant.  Your fundamental problem isn't a problem with the Arduino code, it is a problem with the network at work.  You need to ask the network admins there to help you fix the network setting so that your device can connect.  They know what they're doing that's blocking you so they could unblock you.

you don't use available to check if the response is incoming. read returns -1 if nothing is available. See WiFiClient example on how to wait for the response and copy it to Serial Monitor

after next edit: if the server doesn't respond at all, connection is blocked. it is some restriction in the network at work

Your code for HTTP request has multiple issues.
After you connect to an HTTP server, it doesn't send anything until it receives your request. Your check for available bytes should always fail. Remove the if (client.available()) part, including the else part.
You make a POST request, but you put all parameters to URL and the request has no body. Change it to GET or put the parameters into request body and use "Content-type: application/x-www-form-urlencoded". Don't forget the Content-length parameter.
You send the request in very small parts. Every single print is send right away over network. Concatenate strings and print one or use buffered print.
And you should read the HTTP response and check the status.

some reading to content length and buffering https://github.com/jandrassy/StreamLib/blob/master/README.md

Thanks Juraj. i have 1. changed POST to GET (as it should have been:) 2. concatenated the separate client.print statements as a string and now client.print all in one go. Unfortunately same result :(  A question: where/how do i  read HTTP response? cheers

FYI i tried char c = client.read (); Serial.print (c); after the all-in-one client.print, and i get a backwards '?'

FYI#2 i also tried if (client.connect(server, 443) { in case it was a HTTPS issue... gives exactly the same results :(

see WebClient on example how to prin response. use available()

Thx Juraj. as i said in the comment above i just get a backwards '?' on the response. nothing else

add to code in Question the response read

you don't use available to check if the response is incoming. read returns -1 if nothing is available. See WiFiClient example on how to wait for the response and copy it to Serial Monitor/

code edited to incorporate @Juraj suggestions. Same result :( Any ideas from here?

if the server doesn't respond at all, connection is blocked. it is some restriction in the network at work

OK. i was really hoping to avoid IT who will just say "NO" because its easier for them.  Excuse the N00B question but would work WiFi end up at the exact same blockage?

it is not common to block port 80, so it will be something about known and temporary IP addresses. at my work we have a WiFi for guests which has Internet access but not intranet access


text:
What is a cheap way to measure co2 or o2 level in air?
I am making an air purifier which also increases o2 level as a school project but facing some difficulties. I plan to run the purifier whenever the co2 level is higher than usual or o2 level is lesser than usual but the sensor available in the market are quite expensive. So is there any cheaper alternative or any other method to detect a change in concentration?

why are you asking that question on an Arduino website? .... it has nothing to do with Arduinos ...... you may have better luck at a chemistry site

Well, MQ 135 sensor is very cheap general air quality measurement device. It costs around 3$. There is another similar on AliExpress, not even worth mentioning. What is your budget? Gravity from Adafruit seems proper, yet it is at 56$. One that seems actually serious is K30 sensor, but that is around 100$. That 3$ stuff is general, and will work when temperature is constant, humidity is constant and Mars is aligned with Venus.
I think 56$ is ok if they want to have something proper. Remember that you get what you pay for.


text:
Print out times tables from 1 to 10 with array
I would like to Serial.print(); the multiplication tables, 1 - 10. This is my work so far. Is there an easier way to do this with array? Thanks
// "MultiTable"

//Define global array, is this needed? Makes no difference for my output in serial monitor.
//int number[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

//Define variable
int prod;

void setup() {
  // Open serial connection at 9600Bd
  Serial.begin(9600);
}

void loop() {
  //Print the times table for 1

  for(int i = 0; i <=9; i=i+1) {
   prod = i*1+1;
   Serial.print(prod);
   Serial.print(",  ");
  }

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

//Print the times table for 2

  for(int i = 0; i <= 9; i=i+1) {
  prod = i*2+2;
   Serial.print(prod);
   Serial.print(",  ");
  }

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

//Print the times table for 3

  for(int i = 0; i <= 9; i=i+1) {
  prod = i*3+3;
   Serial.print(prod);
   Serial.print(",  ");
  }

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

why do you try it on arduino? learn codding on a computer. it is easier

Welcome to Arduino:SE.  I'm not sure how this relates to the Arduino though.  Perhaps it's a question better suited to Stack Overflow?  You might find it helpful to review the site tour and Help Centre and, in particular, [ask].

Thanks for helping!
I have the Arduino connected to my pc and would like to use it both in theory(programming) and practically.

So is arduino programed in c or c++? I have a textbook with the kit i got and the code in there is pretty different to what I get when i search for help.

why would you want to store the values?

note: in your existing code, change the loop to count from 1 to 10 instead of 0 to 9 .... for(int i = 1; i <= 10 ; i=i+1) { ..... that way you do not have to do the add in the next line

Okay, I thought that the first value were supposed to be at "place 0", but maybe that is not the case?

//Define global array, is this needed? Makes no difference for my output in serial monitor.
//int number[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

This is not needed, you can use a for lop from 1 to 10.
The void loop will look like this (not checked, no IDE nearby):
void loop()
{
  for (int multiplier = 1; multiplier <= 3; multiplier++)
  {
      for(int i = 0; i <= 9; i++)
      {
         prod = i * multiplier + multiplier;
         // or: prod = (i + 1) * multiplier;
         Serial.print(prod);
         Serial.print(",  ");
      }

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

Some remarks:

To go to the main for loop (with multiplier):

Identify the similar parts
Check the differences within each similar part (only the multiplier value, 1, 2 or 3)
Make this a for loop and instead of 1, 2, 3 use the multiplier variable
Instead if i = i + 1 you can use i++. It means exactly the same.
For clearity I put the Serial.println() together. You also can use Serial.print('\r\n\r\n') or Serial.println('\r\n') to achieve the same

For the record, the line terminator used by Serial is CRLF. Thus, a pair of Serial.println() is equivalent to Serial.print("\r\n\r\n") or Serial.println("\r\n").

@EdgarBonet Thank you for the remark, I updated the answer accordingly.

What's with the prod = i * multiplier + 1;...? Don't you just want to loop from 1 to 10, not 0 to 9, and not add 1 (which should be i anyway...)?

@Majenko I assume that is a question for the OP? I did not make any functional change. Although I would expect prod = (i + 1) * multiplier, but maybe he wants to start from 0.

But you have prod = i * multiplier + 1 whereas the OP had, in effect, i * multiplier + multiplier (i * 1 + 1, i * 2 + 2, etc...)

@Majenko: yes I copied it wrongly; I updated the answer, thanks for mentioning.

@AndreasH If it helps / if it is the correct answer, please press upvote and press the accept answer button.


text:
Save Data before Shutdown
I am building a positioner and I store the current position to EEPROM when the move is complete. On start up, I want the positioner to return to the HOME position. I am running an UNO powered from the USB.
My problem is that if the Arduino is turned off, I would like to stop the move and store the current position before the Arduino dies.
Note that this would also be relevant to devices like thermostats which remember the set point through a power outage.
POSSIBLE SOLUTIONS

Store position in EEPROM at each step. No, that will wear out the EEPROM.
Connect a large capacitor from +5V to Gnd. When this falls below a set level, trigger an interrupt (ISR) that stops motion and stores current position in EEPROM.

QUESTIONS

Will #2 work, and how could I program it?
Any other ideas I am missing?

Option 3: only store the position after 10 seconds of no change. Option 4: have a way of measuring the absolute position of the thing that is rotation, so there is no need to remember it's previous position. Option 5: Since you want to HOME it when power is reapplied, you could add a sensor that detects when it is in the HOME position. This is what some 3D printers do with limit-switches. They rotate the motor till the limit switch is triggered.

Why not just store the commanded position? If power should be lost, you can have it go to where it was last commanded.

@CrossRoads, that is option 6? Then option 7 is: use fram https://www.adafruit.com/product/1895 and store as often as you want.

Yes, FRAM would be great too, practically infinite # of stores (Trillions).  Store a hundred thousand a day for 100 million years.

How can I program that in Arduino? @Prof Huster > 5. When the number of writes gets to about 5000, increment the address of the data in EEPROM[0].

Thermostats would save the set point to eeprom once when the set point it set by the user. On startup it would just read the set point.
The analogue pins measure relative to VCC. So if you short the analogue pint to VCC the result will remain at max even as the voltage drops.
Instead use a diode to separate the measurement point from the power supply.

simulate this circuit – Schematic created using CircuitLab
As long as power is supplied the gpio input will be high. As soon as the power is removed the gpio pin will be low and the capacitor will need hold enough charge to save the position.
However what would happen if the positioner is manipulated when the arduino is off? Most devices have a callibration routine using end-of-travel detection or something similar they run on startup to find the home position.

Thanks for all the suggestions. At first I wanted a circuit like @ratchet freaks. I wanted to keep the mechanics and circuits very simple since the positioner is 3D printed and uses a standard M3 screw to move, so that rules out limit switches and encoders.
I also realized the typical move only takes a max of 10 seconds, so I could just store the commanded position like @CrossRoads suggested. When the HOME command is given it steps back to 0.
Here is my Answer:

Store the EEPROM address of the persistent information at EEPROM[0].
At that Address store the persistent information:
Item 1: EEPROM[EEPROM[0]] The number of writes to this address block as a two byte unsigned int.
Item 2: EEPROM[EEPROM[0]+2] The commanded position as a two byte signed int.
When the number of writes gets to about 5000, increment the address of the data in EEPROM[0].

Working this way I'll gradually burn out the Arduino EEPROM, but it will take many years!

@JRobert: With that scheme, EEPROM[0] gets written every 5000 cycles.

The address is updated every 5000 cycles of 5000 writes, so about 25 million position updates. Plenty for my use!


text:
Detecting pulsed LED
I am trying to use an Uno to detect if an LED is on or not. Sounds simple, but I am tearing my hair out on this one, here is why.... This is a model railway application and I want to detect an LED being lit on the control panel showing how a route (points/turnouts) is set. The LED is lit by a point position indicator (www.blocksignalling.co.uk/index.php/points-position-indicator-ppi4-dc) which works perfectly but the LEDs are not permanently on when lit, even though they appear so, they are pulsed at around 8khz. I tried using opto isolators triggering an digital input on the Uno. They all happily detect 'no light' and the pin goes HIGH, but when the led is lit, the pin flucuates between 0 and 1 so not a true or stable LOW. I also made my own opto using a TCRT5000 with the leds pointing at eachother encased in shrinkwrap, using standard breadboard set-up which worked perfectly when powering the transmitter from the Uno, but same result when powered from the LED. Anyone out there got any ideas please?

use a CDS sensor; they are slow enough that 8khz is no problem.

why don't you detect the state of the switch that operates the LED??

Yes, the point motor (solenoid) is triggered by the switch, but though a capacitance discharge unit (CDU) which fires a momentary high current that would damage the Uno.  The PPI detects this high value and lights the corresponding low voltage LED.

Count HIGH values read for example in 2 ms. It should be zero if the LED is not lit and more then zero if it is lit.

Good thought, the one thing I can rely on is the HIGH value stays there when it should be, so counting a fixed number of responses and if all HIGH then assume HIGH, anything else, assume LOW. Thank you.

Why not connect a low pass filter to the LED, and measure the DC level coming out? Will certainly be higher when on than when off.  Resistor from anode to analog input pin, and capacitor to Gnd.

Use a photoresistor (also called LDR).
Connect the photoresistor between Vcc and an analog input and place it physically next to the LED you want to monitor.
In your arduino code simply monitox the analog input value. When the LED will be on the photoresistor will have a lower resistance andyou will read a higher analog voltage.

good thought, I would need to add another LED in series to the one in the control panel as that doesn't show any light under the panel.


text:
ESP8266-12E as WiFi interface for Arduino Mega
I have an Arduino Mega 2560 that I would like to connect to the internet using an ESP8266-12E.
Searching the internet for relevant keyphrases only yielded one type of result: The articles all explain how to program the ESP using the Arduino. Been there, done that.
Does anybody know of a way to use the ESP as a "wifi interface" for an Arduino, e.g. using a Serial interface from the Arduino?
Basically, I'd want to use the library ESP8266Wifi transparently on my Mega 2560, and maybe in conjunction with something like WifiManager - all of that running on the Mega.
The only thing I found was this: https://www.hackster.io/jeffpar0721/add-wifi-to-arduino-uno-663b9e. But this uses AT commands only.
Any hint is appreciated.

"Any hint is appreciated", here is my two cents: this lack of information is related to the fact that ESP8266 has processing power of its own, AND, it can handles transparently annoying things like IP stack, Wi-fi connections and so on, in such a way that you could do all your project with ESP8266 (even using the arduino IDE), and more complex projects with an ESP32. You can not use ESP's specific libraries as ESP8266Wifi transparently on a Mega2560, just because Mega has not the hardware to handle the IP / wifi stuff. Instead, Mega's application must "talk" AT commands with ESP via serial I/O

Another option it would be to use libraries to write a custom-built application to ESP8266, where ESP8266 could talk to Mega's application over SPI, i2c, serial, a bit-banged protocol, whatever. I suggest that you spend some hours reading this. But, anyways, just forget about using ESP's wifi libraries in a Mega. It won't even compile.

@mguima: Thanks for that. I already thought about leaving out the Mega right away. The PCB is already done and the Wifi option came on top if it later. Will most probably have to look into AT commands then

you can program the ESP or use AT, what else is there? You can't run wifi manager on a mega...

If you know how to write code for the esp8266, then write the networking part in the esp8266 and exchange data and commands with the sketch in Mega over Serial.
Other option is to use AT firmware with the WiFiEsp library or WiFiLink firmware with WiFiLink library.
Or you can connect the ESP-12 to Mega over SPI and use the WiFiSpiESP firmware with WiFiEsp library.
All mentioned libraries are 'clones' of the WiFi library.

ESP8266-01 usually come pre-programmed with the "AT" instructions interpreter for WiFi communication. If your -12 didn't, or if you've reprogrammed it, you'll need to find and download a copy of the AT interpreter to re-load.
Then you'll cross-connect one of the Mega's UARTs to the ESP (Tx > Rx and Rx > Tx), respecting the voltage level differences between the Mega and the ESP (5v vs. 3.3v). You'll need use a level-shifter or make a voltage divider for at least the Mega Tx > ESP Rx connection.
Then it's just a matter of using an existing Arduino ESP-WiFi library, or writing your own serial communications using the ESP's AT commands if you want the challenge.
I generally use the Blynk Internet of Things service and libraries as the quickest and a full-featured way to put a device online with access to/by your cellphone. It's not the only way but it's a good start.


text:
Using mills() in place of delay() on relays not getting solid switch over
I know I should post some code that maybe cleaner but really I am just in need of a answer to a problem I seem to run into a lot when using mills() in place of delay(), whilst making a Christmas light display.
Maybe it's me but I do not get contestant switching over of mechanical relays when I try to use mills() timing to switch relays . I seems like the code trips the relay then untrips the relay in milliseconds and not really latching the relay like I get with delay(). Is this the nature of the mills() choice where the output is triggered every cycle  but is not truly an output during the whole process cycle?  Now if this is true, then is there a good way to latch a relay with out using a delay()?
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
//

  unsigned long currentMillis = millis();
  unsigned long previousMillis = millis();
  int interval_on = 2000; //  Length of time On

  unsigned long currentMillis_off = millis();
  unsigned long previousMillis_off ;
  int interval_off = 2000; // length of time off

//
#define button 4
int Lite_1=0;

RF24 radio(7, 8); // CE, CSN

const byte address[6] = "00001";
boolean buttonState = 0;

unsigned long time;

void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
  Serial.begin(9600);
}

void loop() {
  unsigned long currentMillis = millis();        // must be in loop
   unsigned long currentMillis_off = millis();  // Must be in loop
  //                             const char text[] = "Hello World";
 //                       radio.write(&text, sizeof(text));
  //delay(1000);

   //                       delay(5); Removed to help in timing
   //                       radio.stopListening(); removeded to help in timing
   // Lite_1 = 1;
    radio.write(&Lite_1, sizeof(Lite_1));
  //    delay(1000);
 //   Lite_1 = 0 ;
 // radio.write(&Lite_1, sizeof(Lite_1));
  // delay(250);

  if (Lite_1 == 0 && currentMillis - previousMillis > interval_off)
    {
    previousMillis = currentMillis;
    previousMillis + 10;
    previousMillis_off = currentMillis_off  ;
    Lite_1 = 1;
    Serial.println(currentMillis);    //prints time since program started
      }
    //Debug
  // Serial.print("Time: ");
 // time = millis();

 // Serial.println(time);    //prints time since program started
//  Serial.println(currentMillis);    //prints time since program started
//  Serial.println(previousMillis);    //prints time since program started
//  Serial.println(previousMillis_off);    //prints time since program started
 // Serial.println(currentMillis_off);    //prints time since program started
  //delay(250);

    if (Lite_1==1 && currentMillis_off - previousMillis_off > interval_on)
       {
    previousMillis_off = currentMillis_off;
    previousMillis = currentMillis;
    previousMillis + 10;
    Lite_1 = 0;
    Serial.print("OFF: ");
    Serial.println(previousMillis_off);    //prints time since program started
    }

  }

Format your code correctly by editing your question,selecting the code and click the {} button in the editors toolbar or press Ctrl+k on the keyboard.

At which part of the code do you switch the relays? I don't see any digitalWrite() or similar, which could be used to switch something. Only Serial output.

What should it do? Is it to turn on the relay half a second with 2 seconds in between? Is that continuous or is that triggered by an event? Please add the extra information to your question.

Ron, you can't answer comments until you register to SE. Check your email.

Can you explain the role of nrf24L01 in this code?  There may be other ways to achieve the functionality that you need.

"role of nrf24L01"  is a Wifi  device  code  as I under stand it.

The program opens a Network connecition to another arauduino on the network

No digital write since it is just telling the other arduino to do the digirtal Write function at Lite_1 = 1

Something like this works.
  unsigned long currentMillis;
  unsigned long previousMillis;
  unsigned long nextEventTime;

  unsigned long interval_on  = 2000;        // length of time On
  unsigned long interval_off = 2000;        // length of time off

  bool Lite_1;

  void setup() {

    previousMillis = millis();

    Lite_1 = false;                                     // start at the begining of the off cycle
    nextEventTime = previousMillis + interval_off;      // start at the begining of the off cycle

    Serial.begin(9600);
    Serial.print("starting in OFF cycle\t");
    Serial.println(previousMillis);
  }

  void loop() {

    if (millis() > nextEventTime) {                     // check the interval before doing any other checks

    currentMillis = millis();

    if (Lite_1) {

      nextEventTime = currentMillis + interval_off;     // do the calculation only once
      Serial.print("OFF:\t");

    } else {

      nextEventTime = currentMillis + interval_on;
      Serial.print("ON:\t");
    }

    Lite_1 = !Lite_1;                           // invert value
    Serial.println(currentMillis);              // prints time since program started
    }
  }

When a value is added to a value from millis, and then compared to millis, that causes a rollover problem. Always subtract a previous millis from the current millis.

Then how would I do this math if I can not add to the Millis()?

I believe the way to make that work is nextEventTime - currentMillis > interval_of.  Informally speaking, doing that subtraction instead of an addition guarantees that we are going to be doing the inequality with a small number, rather than a number that's potentially large enough to roll over when interval_off is added to it.

Firstly, what is the purpose of declaring all variables as global ones? Secondly, if (millis() > nextEventTime) - this will not work properly around the moment of millis() rollover.


text:
How to know which event fired first?
I want to automate the chicken coop of my grandmother. To do so, I want to use Arduinos and NodeMCUs, respectively. I want to check if all chickens are in the coop at night and then close a little door. I was trying to use RFID technology and tag the chickens with a little RFID tag but the read range I got was too short to get it working properly. Now, I am trying to implement a light gate with two small lasers and two receivers. I want to detect the direction (in or out) of the chickens. I got the lasers working and I get a signal (1  and 0 = light gate interrupted). I have to know which of the two laser detectors first detected a 0 (zero). I have no idea how to implement this in code. I was trying to use timers to no avail. I also was trying to use interrupts (see small code fragment).
I hope I made clear what I am trying to achieve. Please tell me if and how I can improve this question. Any google fu was to no avail. Every hint/help is greatly appreciated.
#include <Arduino.h>

// Functions
void pin_ISR();

const int detectorPin = 3;     // the number of the detector pin
const int ledPin =  13;      // the number of the LED pin
const int Laser = 6;
// variables will change:
volatile int buttonState = 1;         // variable for reading the status

void setup() {
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(detectorPin, INPUT);
pinMode(Laser, OUTPUT);
digitalWrite(Laser, HIGH);
// Attach an interrupt to the ISR vector
attachInterrupt(digitalPinToInterrupt(3), pin_ISR, CHANGE);
}

void loop() {
Serial.print(buttonState);
delay(100);
}

void pin_ISR() {
Serial.println("There was an interrupt!");
buttonState = digitalRead(detectorPin);
digitalWrite(ledPin, buttonState);
}

You have only one light gate in your code. Add the second.

Do the light gates both get active together, or one active then inactive, followed by the other? I.e., do you have a sequence of "HH -> LH -> LL -> HL -> HH" or do you have "HH -> LH -> HH -> HL -> HH" for the gates?

Consider using quadrature encoding to detect travel direction using two light beams. A method used in older mechanical mouse pointer devices and track balls. Using an Arduino to decode quadrature encoding is talked about in many places on the web.
Place beam A and beam B such that a chicken waling out of the coop will activate beam B first and beam A second.

Because the activation of beam B occurs first we know the chicken is walking out of the coop.  If beam A occurred first we know the chicken is walking into the coop.
The shape of a chicken is irregular and a chicken may change its mind half way out of the coop.  These and other unexpected anomalies may lead to unexpected results.  Consider supplementing the beams with a PIR sensor outside the coop to confirm there are no chickens left outside.

Thanks for all your help and efforts. @juraj, I was aware that I just implemented one light gate. It was just in order to deliver sample code for showing how I was using interrupts. st2000, Thanks for your big help, but I am not the lightest light in the room, so the quadrature encoding was a little to complex for me. I finally figured out that I have to search for "people counter arduino" or "bidirectional counter".  Here, I found a really similar project and I can adapt much of the code from there.

Don't sell your self short.  The program you linked to is using quadrature encoding. They just don't say it.  Perhaps it would help to think of the clock wise rotation of the wheel to be a chicken going into the coop and the counter clock wise rotation of the wheel to be a chicken going out of the coop.

@Strohmi, I asked you to add the second light gate, because  then it would be easy to add evaluation of which one triggered first


text:
Problem with interrupts
Alright. This is what I wanted to do:
Make a circuit and code the arduino such that there are 2 tactile switches, each with a predefined pwm value.
 Whenever any one button is pressed the led should run at that pwm value, until the button is released. There is
 also an ultrasonic sensor on the same arduino that triggers an interrupt at a threshold distance that
 stops the led. When no button is pressed or the ultrasonic isnt active, the led should run at another pwm value.
Here is the code:(updated)
const int trig = 9;
const int echo = 10;
const int redswitch = 2;
const int yellowswitch = 3;
int redled = 6;
int greenled = 5;
volatile int pwm = 50;

volatile bool rs = LOW;      //RS - RED SWITCH
volatile bool ys = LOW;      //YS - YELLOWSWITCH
bool last_rs = LOW;
bool last_ys =  LOW;
volatile long distance=0;
long duration=0;
long temp=0;

void setup(){
  pinMode(trig,OUTPUT);
  pinMode(echo,INPUT);
  pinMode(redled,OUTPUT);
  pinMode(greenled,OUTPUT);
  pinMode(redswitch,INPUT);
  pinMode(yellowswitch,INPUT);
  Serial.begin(9600);

  attachInterrupt(digitalPinToInterrupt(redswitch), red,CHANGE);
  attachInterrupt(digitalPinToInterrupt(yellowswitch), green,CHANGE);

  digitalWrite(greenled,LOW);
  digitalWrite(redled,LOW);
}

boolean debounce(boolean temp,int switchPin)
{
  boolean current = digitalRead(switchPin);
  if (temp != current)
  {
    delay(5);
    current = digitalRead(switchPin);
  }
  return current;
}

void loop(){

  //Ultrasonic sensor's distance calculation
  digitalWrite(trig,LOW);
  delayMicroseconds(5);

  digitalWrite(trig,HIGH);
  delayMicroseconds(10);
  digitalWrite(trig,LOW);

  duration = pulseIn(echo, HIGH);
  temp = duration * 0.0343 / 2;
  noInterrupts();
  distance = temp;
  rs = debounce(last_rs,redswitch);
  ys = debounce(last_ys,yellowswitch);
  last_rs = rs;
  last_ys = ys;
  if(distance>8)interrupts();

  Serial.println(distance);
  analogWrite(redled,pwm);
  analogWrite(greenled,pwm);
}

void red(){

  if(rs == HIGH) pwm = 150;
  else pwm = 0;

}

void green(){

  if(ys == HIGH) pwm = 250;
  else pwm = 0;

}

Now, when the arduino is connected to my laptop, led runs at the a particular value. But whenever I press a button they go off. Can you help me find out what's wrong here?

remove the constrain(pwm,0,255);. it does nothing. function constrain returns first parameter if the value is in constraints or one if the constraints if the value is outside

you code has too many problems. you use one variable for both outputs. you don't debounce the buttons. you reset PWM in every loop (you don't let it run). and I would say the whole concept of reading the buttons with interrupt is wrong

@Juraj. I use one variable for both outputs because I want both leds to have same pwm value. About deboucing, I forgot that completely. Sorry. And I dont understand this - " you reset pwm in every loop". where do I do that? i am not resetting pwm in loop(). Reading buttons with interrupt - I was following an online tutorial. I'm totally new to arduino. It would be immensely helpful if you could be a bit more clear and precise.

but you set pwm to 0 if one of the buttons is not pushed. PWM runs once started. it should do high, low, high,low,high... but if you start it again and again, it does high, and again high and high. interrupts are good for very short events. people hold the buttons long

I think that interrupts are the the correct way to go. It enables you to do all sorts of slow stuff in your main loop, while you buttons still works. Do not do any read or write in your interrupt functions - you already know the button has been pushed!, and the write happens in your main loop. Do nothing else than change the state of volatile variables. Add debounce.

@hpekristinsen and Juraj. Thanks a lot for that. I will do what you said and will update the code. I will add debounce. And Juraj, people won't hold the buttons long in this case. this is a task given to me and they aren't supposed to do that. And one more thing, should I use HIGH or RISING inside attachInterrupt() I dont quite get the difference

Look at these lines:
distance = temp;
duration = pulseIn(echo,HIGH);
distance = duration * 0.0343 /2;

Here is what they do:

The first line sets the variable distance to zero (that's the value
of temp).
The second line waits for the ultrasonic pulse to reach the target,
bounce against it and come back, while at the same time timing the
whole trip. This can take a long time (several milliseconds). Chances
are your program spends most of its time executing this line.
The third line sets the variable distance to something sensible.

This means distance is zero most of the time (while the second line
executes). When the interrupt fires, there is a very high probability
for the interrupt handler to find a zero distance, and thus to set pwm
to zero.
Simple fix: never set distance to an unreasonable value. Leave it's
value alone until you have a new distance measurement ready, and only
then update that variable. In other words, just remove the first of
those three lines.
But there is a catch now. The variable is four bytes long, and updating
it takes four instructions. There is a small probability that the
interrupt fire in between these instructions. When that happens, the
interrupt handler finds the distance variable half-updated, with a mix
of bytes from the previous and the current distance measurements. This
is called a “race condition”, and is one of the worst kind of bugs you
can meet, because it is very hard to systematically reproduce.
The fix to the race condition is to update the variable with interrupts
disabled. The wrong way to do it is:
duration = pulseIn(echo, HIGH);
noInterrupts();
distance = duration * 0.0343 / 2;
interrupts();

This is bad because interrupts are blocked during the distance
calculation, which is too much. The right way is this:
duration = pulseIn(echo, HIGH);
temp = duration * 0.0343 / 2;
noInterrupts();
distance = temp;
interrupts();

Now interrupts are blocked only while writing the distance variable.
Personally I don't think it is such a great idea to read the buttons
with interrupts. Buttons are extremely slow peripherals. If you make
your code non-blocking, your loop() will always be fast enough to deal
with them. Handling the buttons in loop() means you don't have to
worry about all the bugs that can easily sneak into interrupt-driven
code, like the above mentioned race condition.

Edit: In the original version of your code, interrupts were used to
read the switches. In the edited version, you added a debouncer, and you
don't need interrupts anymore. In fact, the way this version uses
interrupts makes no sense at all. The most problematic bit is the fact
that this code can disable interrupts for arbitrarily long times. This
is not good, and you should be aware that the Arduino's timekeeping
functions rely on interrupts to perform their job.
I suggest you just remove from this code every single line where you see
the word “interrupt” (singular or plural), and you replace
if(distance>8)interrupts();

by
if (distance > 8) {
    red();
    green();
}

or, to streamline things a little bit, by
if (distance > 8) {
    if (ys == HIGH) pwm = 250;
    else if (rs == HIGH) pwm = 150;
    else pwm = 0;
}

I updated the code in the question. Please check it. There is a great improvement. But right now, the problem seems to be that the code does exactly opposite to what i want. The led glows at a particular pwm value when no button is pressed. When it is pressed, it turns off. i want it to happen vice versa. And for this part There is also an ultrasonic sensor on the same arduino that triggers an interrupt at a threshold distance that stops the led -  I use if(distance>8)interrupts(). Is this the right way to go?

@Kishore: see amended answer.

the thing is I'm learning arduino right now. this is like a task that has been given to me. I have to use interrupts in this code. That is compulsory. I myself have another version of the code where i don't use interrupts and it still does the job. But I have to do the same thing with the use of interrupts. So, I can't remove them.

@Kishore: Then forget about my edit, and follow the path given in the first part of my answer. You will have to remove your debounce() function and find a algorithm suitable for interrupt-driven debouncing. An interesting problem in itself.


text:
Time between two IR beam sensors
I am working with two sets of IR beam, they are to be placed in X distance. My goal is to measure speed. I would like to measure time between the first IR beam to the second beam when the beam breaks.
I am not sure what's going on, I am not getting any time of the serial port but the LEDs are turning on and off the way I wanted.
Please help me with getting the time between two IR beam sensors.
This the sensor that I am using -  Adafruit IR breakbeam sensors
and I am working with a Mega2560.
#define LEDPIN 13
int startPin = 8, finishPin = 5;
unsigned long starttime = 0, finishtime, time_interval;
float distance = 1, Speed; // Speed calculated
int trigger1 = 0; // Sensor 1
int trigger2 = 0; // Sensor 2
int sensor1State; // Sensor 1 status
int sensor2State; // Sensor 2 status

void setup() {
  pinMode(startPin, INPUT_PULLUP); // Sensor 1 as input
  digitalWrite(startPin, HIGH); // Turn on the pullup
  pinMode(finishPin, INPUT_PULLUP); // Sensor 2s input
  //digitalWrite(finishPin, HIGH); // Turn on the pullup

  pinMode(LEDPIN, OUTPUT);
  time_interval = ((finishtime - starttime) / 1000000);
  Serial.println(time_interval);
}

void loop() {
  sensor1State = digitalRead(startPin); // Read the state of the IR sensor 1:
  if (sensor1State == LOW) // See if IR beam of sensor 1 has been broken
  {
    if (trigger1 == 0 && trigger2 == 0) // Check to make sure both sensors have not triggered
    {
      starttime = micros(); // Save time when sensor 1 was triggered
      digitalWrite(LEDPIN, HIGH);
      trigger1 = 1; // Prevent sensor 1 from triggering again
    }
  }
  if (trigger1 == 1) {
    sensor2State = digitalRead(finishPin); // See if IR beam of sensor 2 has been broken
    if (sensor2State == LOW) {
      // Check to make sure sensor 1 has triggered but not sensor2
      if (trigger2 == 0) {
        // Run speed function
        trigger2 = 1;
        finishtime = micros(); // Save time when sensor 2 was triggered
        digitalWrite(LEDPIN, LOW);
        // time takes to travel between 2 IR Beam  // divide by 1000000 to convert microsecond to second
        Serial.println(time_interval);
      }
      // Reset both sensors
      trigger1 = 0;
      trigger2 = 0;
    }
  }
}

Need to post your code correctly.  Please Edit and add 4 spaces before each line at a minimum.

You will not get a meaningful result with a 16 MHz processor, where every clock cycle takes 62.5nanoseconds, and the speed of light is basically instant at short distances.    time_interval probably needs to be a float also.

@CrossRoads, how is here speed of light in play?

Yeah, never mind that. I think you are close on the triggering and capturing the state kind of logic, just needs a little more thinking I think.  For example, in here you never calculate the interval that you print        if (trigger2 == 0) {
// Run speed function
trigger2 = 1;
finishtime = micros(); // Save time when sensor 2 was triggered
digitalWrite(LEDPIN, LOW);
// time takes to travel between 2 IR Beam  // divide by 1000000 to convert microsecond to second
Serial.println(time_interval);
}

You've tried to print an interval at the bottom of the setup() function, using finishtime before you have ever used it. Fortunately, finishtime will have been initialized to zero before the program runs so the the arithmetic result will be zero, though meaningless.
In loop(), you've never completed the interval calculation before you try to print it.
If nothing at all is being printed, check your wiring and be sure your code is getting the triggers. You haven't showed your wiring, so we can't help you debug that, in case there is a problem with that also.

You never calculate the time_interval that you print. Add that after the finishtime line
  if (trigger2 == 0) {
    // Run speed function
    trigger2 = 1;
    finishtime = micros(); // Save time when sensor 2 was triggered
    digitalWrite(LEDPIN, LOW);
    // time takes to travel between 2 IR Beam  // divide by 1000000 to convert microsecond to second
    Serial.println(time_interval);
  }

Thank you for the respond, I had it like that before still doesnt work, I am not getting any time, not sure whats going on ??

void loop() {
sensor1State = digitalRead(startPin); // Read the state of the IR sensor 1:
if (sensor1State == LOW) // See if IR beam of sensor 1 has been broken
{
if (trigger1 == 0 && trigger2 == 0) // Check to make sure both sensors have not triggered
{
starttime = micros(); // Save time when sensor 1 was triggered
Serial.println(starttime);
digitalWrite(LEDPIN, HIGH);
trigger1 = 1; // Prevent sensor 1 from triggering again
}
}
if (trigger1 == 1) {
sensor2State = digitalRead(finishPin); // See if IR beam of sensor 2 has brok

}
if (trigger1 == 1) {
sensor2State = digitalRead(finishPin);
if (sensor2State == LOW) {
  if (trigger2 == 0) {

    trigger2 = 1;
    finishtime = micros(); // Save time when sensor 2 was triggered
    Serial.println(finishtime);
    digitalWrite(LEDPIN, LOW);

    time_interval = ((finishtime - starttime) / 1000000);
    Serial.println(time_interval);
  }

my wire is good, i hard wire to pin, grd and 5 v. My 1st code that i wrote its work with it,  when i added the condition its not working anymore -  I didnt add any resister do you think thas a reason  its not working,

please do not put code into comments .... nobody will read that .... add the code to your question (make sure that it is indented at least 4 spaces so that it shows up as "code")


text:
ESP32 reset loop when using wifi.h
I have a strange behavior, using ESP32 devkit v.1 boards.
Everything works, I can upload blink sketch, serial works, led blinks.
However, once I upload any sketch which is using the wifi.h (and utilizing it for example calling WiFi.mode(WIFI_STA);), upon upload, the board keeps resetting the serial connection, stays up for not more then 1 second, resets again, and so on.
I could not debug the issue, since serial is unusable. Any ideas what is wrong? I did a fresh ArduinoIDE, ESP32 board manager install, etc. and normal sketches work flawlessly.

based on esp8266 experience. try to erase the flash with esptool.

Could be a power problem. WiFi needs a lot of power.

@Majenko, the devkit has USB connector. I assume Miro powers the board from USB.

Yes, but what from? An unpowered hub would be fatal...

Guys, Juraj was right, I had a too long usb cable, no idea that the power loss could be high enough not to run the esp. Sorry for an unnecesaary question. If anyone has reboots with wifi ON, try a shorter cable..

Majenko was right about powering issue, but the cable must be damaged somehow

The USB cable was too long, and hence power loss.
Sorry, I figured it out a day after I asked this question.


text:
Connecting a servo motor to an Arduino
I currently have a push solenoid connected to my standard Arduino board. The Arduino is powered via its USB cable, while the solenoid is powered using a 12V Huawei adapter (in conjunction with a MOSFET driver module).
How can I switch out the push solenoid for a servo motor? The operational voltage of the servo is 4.8 to 7.2V (with a stall torque of 13 kg-cm) to give you an idea of its size. I have been told to buy a DC-DC step-down module (to adjust the Huawei supply from 12V down to 5V) but I think it could be easier to power the servo using some sort of USB?
Or other suggestions are welcome. I want the easiest solution (since I am NOT tech savvy) and I can't buy parts until I am for certain the solution will work (that's research for you). Thanks!

You will have to check in the servos datasheet for the maximal current, that it draws (motors draw more current, when inhibited by mechanical force, so be sure to get the maximal current from the datasheet). From the data, that you gave us, I think it will draw rather much current. So you should not power it over the USB port of your PC (which gives 500mA at maximum). Also you should not use the 5V pin of your Arduino, or you may fry components like the diode, that lies in the current path from USB to 5V pin.
For your step down module, you will also have to check, if it can provide the current, that the servo needs, or you may kill it. If you want to use USB, you can use a standard USB charger or powerbank. Often these can provide more than 1A (depending on the actual product). Most USB wallwart chargers have a current specification on them. But (as said earlier) don't provide the power through the Arduino. Provide it directly from the source, so that the possibly high current for the servo does not have to pass trough the Arduino. You can also power the Arduino with the same source in parallel to the servo, so that you don't need two sources or a converter.
For more info, you will have to provide more information about the servo

Hey thanks so much for your reply :). I am going to be using the TowerPro MG995 servo. According to their website:
Current draw at idle 10MA
No load operating current draw 170MA
Stall current draw 1200MA
So I could buy a standard usb charger plugpack to power the servo (eg. 5V, 2A)? Then my next issue would be cutting and soldering these parts together I assume...

Yes, that should be sufficient. You can either cut the USB cable (charge-only cables only contain 2 wires), or you can solder your own wires directly to an USB plug. The outer contacts are connected to power. Be sure to use the correction polarisation, so that the charger is not connected the other way round.

I don't know if i understand your question properly, but if you want to connect the servo to the Arduino try connecting it to the 5v Output of your board.

Getting a DC-DC step down converter would definitely work and would be a good way to do it. However,realistically you will be fine if you connect the servo to +5V from USB, since you said it only draws absolute max of 1.2A. Almost all USB ports can handle that.