text:
arduino didn't working properly
 arduino didn't working properly. When i using a alarm program on pin 6 and a blinking led on pin 2 alarm sound beeps once and then goes down but when using only alarm program it works perfectly. I see that arduino can handle one pin perfectly but when it comes to use two pins together it can't handle properly
float sinVal;
int toneVal;
void setup(){
                pinMode(7, OUTPUT);
                pinMode(2, OUTPUT);
}
void loop(){
                for(int x=0; x<180; x++)
                                { //convert angle of sinusoidal to radian measure
                                sinVal = (sin(x*(3.1412/180)));
                                //generate sound of different frequencies by sinusoidal value
                                toneVal = 2000+(int(sinVal*1000));
                                //Set a frequency for Pin-out 8
                                tone(7, toneVal);
                                delay(2); }
                digitalWrite(2, HIGH);
                delay(100);
                digitalWrite(2, LOW);
                delay(200);
}

please format your code properly .... highlight the code and click on the {} icon

How did you manage to get a tone playing with such a big speaker? I thought hooking up such a low impedance load would fry the pin it's connected to.

You need to learn the basics of electroncis before you start hooking random things up like that. That circuit is completely incorrect and most likely will damage the Arduino. Start by reading tutorials, and don't randomly miss out components just cus you don't fancy using them.

with this wiring setting pin 2 HIGH shorts pin 2 to ground and Arduino dies. you must use a resistor in series with LED. and better use one with the speaker too.

I'm not sure but its your power supply. I suggest to used another power supply on your arduino. Use 9V battery and connect it to Vin(+) and GND(-) and test if there is an improvement.

to burn pin 2 for sure?

No. I’m sure you are using Arduino Nano. Vin is on pin 30. And the official website state the Arduino deals 7-12v. Input Voltage (recommended): 7-12 V
Input Voltage (limits): 6-20 V

the LED on the photo shorts pin 2 to ground


text:
Write to EEPROM before shutdown
I'm currently designing a battery operated device that has to write data to an EEPROM before shutting down, or in regular intervals to save data. Would it damage the EEPROM if it had to shut down while it is being written to?
The first possible case is when it is transmitting the data over I2C. That shouldn't affect it much. But if it gets powered down while it is actually writing the byte to its memory, I don't know whether it would save it correctly or corrupt it.

Well I beleive the EEPROM writes are going to happen with a single full byte at a time. So if you are writing single bytes they will either happen or not happen depending on when power is pulled.  If you are recording a float(4 bytes) and power is removed half way through, then if you try and read data back out it will be corrupt. Without knowing the data you are trying to save, or how the device is being used, I cant really give you more advice then that.

Each byte is independent, it's like a snapshot of the current state of the Arduino.

Then I do not believe you will run into an issue with corrupting a single byte, but the problem you may actually be facing is how to know when to save the data. You dont want to write too often as you can eventually wear out the EEPROM, but you want to make sure it gets saved on power down ya?

@ChadG That is correct. I have a slave ATTiny85 that does the power-down through a mosfet.

So the 85 is what is controlling the power to the main board(uno or something)?  Then it can have a pin that tells the main board "im about to shut you down" and data can be saved at that time.

Good idea, shame on me that I didn't think about that

Might I suggest adding a second line between the tiny and the main board, so the main board can tell the tiny it's ready to be shut down. Also, make sure those pins are set back to inputs, before shutting down, or current might flow, through the input-protections diodes on the main board.

According to the datasheet, an EEPROM write takes 3.3mS. If power drops below the level needed to complete the write, the data will be corrupted.

source: Stack Exchange

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

sort: votes


text:
SoftwareSerial runs out of "text" space on ATtiny
I have an ATtiny and am trying to send a very large byte array stored in a separate .h file over SoftwareSerial:
for (int i=0; i<numElements; i++) {
    softSerial.println(myList[i]);
}

I imagine it will very slow, which is fine, but I'm getting a cryptic error when compiling:
Firmware.ino.elf section `.data' will not fit in region `text'

It seems that this is due to the println() command running out of memory for some reason – if I comment out the println() command everything works fine. How to fix this?

perhaps, if you remove the line where you use the array, compiler optimizes the code removing the not used array

how big is the .h file?

@Juraj – not sure I understand? The array is what's getting sent over serial, which is the point of my program.

@ChadG – it's about 140kb.

is it used elsewhere in the sketch or only in the commented println?

@Juraj – it isn't used anywhere else, just printed over serial.

how do you expect it to fit in 8KB worth of program space( thats what the ATtiny85 has)

if something is not used, the compiler doesn't put it into final code. it is why you do not get the warning if you comment the print of the array

The uno only has 32KB but the Mega does have 256KB. Remember though, there is a difference between where stuff is stored, program space and ram. There is still not enought ram on any of these devices to handle that large of a byte array.

have a look here     https://www.arduino.cc/en/Tutorial/Memory

Is there a way to compress this data? Any repeating sections? Only a limited amount of different characters? ASCII only needs 7 bit!

How big is the array? In other words, what is the data declaration for myList? Is it, for example: int myList [35000];

@NickGammon – the version I had was 143186 bytes long. I'm now seeing there's no way that takes up less that 141k in the Arduino's memory though, right?

I would prefer if you answered my question. How is the array declared? I don't care how big the file is, it might be full of comments.

However unless the file is 99% comments then it is unlikely that it will fit into 8KB of program memory. Also the compiler generates code to copy variables with initial values from program memory into RAM, unless you declared it as PROGMEM, and it is even less likely your data will fit into your 512 bytes of RAM. See my page about that.

@NickGammon – here's the first little bit: const unsigned char dna[] = { 0x37, 0x7a, 0xbc, 0xaf... }; I think I was confused since it compiled with no issues, until I actually needed to use the array.

OK, you are letting the compiler determine the size. Do you know offhand how many bytes are in this array? (eg. 0x37 is one byte). You could conceivably put that array onto a larger machine (eg. use gcc on your PC) and then use sizeof to find how big the array is.

Yes, it compiled with no issues, particularly if you didn't reference the array, so that the linker can then strip the array from the final hex file.

Your sketch doesn't fit into program memory of the ATtiny. If you comment out the println of the array, the compiler evaluates that the array is not used and doesn't attach it to the program. Then the program fits into memory.
EDIT
Chad suggests some good alternatives below, if you need to store more data than flash or PROGMEM will allow.

Thanks – 140kb is the ascii representation of all those bytes. I had read that it gets crunched down to binary on compile, and was trying to see if it fit. Didn't realize the array would be ignored until invoked by println().

There is not enough room in program memory for 140KB. ATiny only has 8KB for the whole program. So there is no way to fix this with your current hardware.
Options-
add a storage device (SD card, sram module, others....) where you can store the data, and then read it in small chunks and send it out
possibly use a arduino mega. It has 256KB of program space. you will still have to make sure you are not trying to store the whole byte array in an array since that would get stored in sram (which there is still only 8KB) but it could again to written in chunks to avoid this problem.

The ATTiny only has a limited amount of RAM. A lot less that flash-memory.
Using a normal array, the entire contents of the array are placed into RAM (during initialization). Which is very limited.
I'd suggest, looking into PROGMEM. This is a way to read the data directly from the flash-memory.

Looking at the comments, this will still not fit the 140kb you want. But the ATTiny85 only has 512 bytes of RAM, but a whole 8KB of Flash/Program memory.

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


text:
Has pt.h library been removed from arduino?
I'm trying to get a program to use protothreading and I've got an error at the include statement for the pt.h library stating that there is no such file or directory. This is how it's written in the program:
#include <pt.h>

Did you install it?

pt.h has never, and will never, be part of the Arduino core distribution.  It is a completely separate third party library that you have to install yourself.
I think the library you want is this one.


text:
Did I overheat my Arduino while soldering to perfboard?
So this is the second time that I've had a circuit that worked perfectly on a breadboard, but as soon as I connected it to a perfboard and soldered the joints together, the Arduino stopped working and wouldn't let me upload sketches (though I could see a COM port for it).
I'm using lead-free solder for the first time, and had the temperature at 750 deg Fahrenheit, and I'm thinking that while I had quick joints to connect the Arduino to the perfboard, when bridging two joints with solder, the iron might have been heating the header pin for 4-10 seconds... Is that enough to break the board?

(note - I'm using jumper wires on the other side to connect everything up, and I've already checked the board's connections using a multimeter and they're all as intended, and there are no accidental shorts/bridges)

That's rather unlikely, especially as your Arduino is a module rather than a bare chip, there's a fair amount of distance between the pins you are soldering on and those of the chip.  Melting the plastic web of the headers would be more likely though of little consequence once mounted.  Unfortunately, it's not really possible to tell what is actually wrong from the very limited information in your question.

-1 for lead-free. -1 for not enough flux. pro-tip: use a socket or female pin headers instead of welding to the board; prevents heat damage and lets you swap out failed parts.

I would like to clarify that my only question in ENTIRE post was: "Is that enough to break the board?"

The answer to that narrow question is that heat from soldering with an iron is extremely unlikely to have done this.  IC's are in practice (vs data sheet) quite heat tolerant, and further the pins you are soldering on are not even the pins of the IC or any electronic components, but rather those of the module headers.  You'd be more likely to melt the plastic web between those headers pins, but even that won't be a great problem since they are already in place. Or if you were soldering directly on the board, lifting a pad or trace - but you were not doing that.
Your actual problem is something else, what that might be is presently unanswerable due to the lack of detail in your question.

yeah, I'm also really perplexed at what my actual problem might be, so I've already asked an entire other question about it with more detail - https://arduino.stackexchange.com/questions/50329/ . I'll admit, my problem is ambiguous so even though that post has as much detail as I can think to include, I'm really stumped and not sure it's the kind of question that can be answered without being physically present

Bridging adjacent pins by heating for 10 seconds is not a great way of doing things. You are trying to cross the "solder resist" with solder, so you are basically fighting something.
I normally use some tinned copper wire to cross gaps like that. You should be able to keep the soldering times down to a couple of seconds.

Did I overheat my Arduino ... ?

We can't really say from where we sit, but maybe.

I could see a COM port for it

The Pro Mini doesn't have a USB chip, so how are you programming it?

I am using an FTDI breakout board to program the Pro Mini, which then attaches to a USB cable.

Right, well you are seeing the COM port from the FTDI breakout board, not the Arduino as such. You would see that even if there was no Arduino there at all.

The soldering on one of your pins (5th from the bottom, on the right) looks a bit dodgy. It might just be the light.
As I said earlier, you possibly overheated the processor chip. I would use the technique I described rather than a 10-second heat.
See my question/answer: Have I bricked my Arduino Uno? Problems with uploading to board - that describes various tests you can do to check if the processor is still good.

This is not much of an answer...  Seems like this should be a comment

It's like asking "did I burn my roast beef"? How are we supposed to know that? However we can talk about ways that roast beef could be burnt. Feel free to post a better answer.

We arent, and there isnt one.   Questions do not require an answer, if there is none, there is none.

Chad has a good point - questions which are unanswerable aren't supposed to get non-answer answers, rather they are supposed to receive comments towards improvement and/or close votes.

I would like to clarify that my only question in ENTIRE post was: "Is that enough to break the board?" This question objectively has an answer. I simplified the question in the title so that people would know what this post is about, but if the answer is "yes, that could break the board," then follow-on tips on how I can not overheat future circuits would be appreciated (?)

I am using an FTDI breakout board to program the Pro Mini, which then attaches to a USB cable.


text:
expected primary expression before ')' token
#define ANALOG_IN 0

void setup() {

  Serial.begin(19200);

  analogReference(INTERNAL);

}

void loop() {

  int val = analogRead(ANALOG_IN);

  Serial.print(0xff, byte);

  Serial.print( (val >> 8) & 0xff, byte);

  Serial.print( val & 0xff, byte);

}

This is my code and I'm getting this error for all 3 Serial.print commands. Please help.

if you want to send a byte use Serial.write()

Why are you putting byte there? That isn't in the Serial.print reference page.
This compiles OK:
#define ANALOG_IN 0

void setup() {
  Serial.begin(19200);
  analogReference(INTERNAL);
}

void loop() {
  int val = analogRead(ANALOG_IN);
  Serial.print(0xff);
  Serial.print( (val >> 8) & 0xff);
  Serial.print( val & 0xff);
}


text:
How to know the external interrupt origin from the ISR
I'd like to know if there is any way to know what is the origin of an external interrupt by programming inside the ISR.
I know I can use a different ISR for each external interrupt and that works but I'm thinking if it's possible to use the same ISR for all external interrupts
If you check the origin pin and trigger condition inside ISR it's not a reliable way to do.
Is there any memory record which store the external interrupt activation?
This is a general question for any AVR microcontroller.

Is there any memory record which store the external interrupt
  activation?

There is, but I do not think it will be easy to exploit.
At low level, each interrupt is handled by a different ISR. So you will
have INT0_vect handling external interrupt 0 and INT1_vect
handling interrupt 1. These ISRs are all defined by the Arduino
core library. In your case, they will both call the same handler that
you defined. Thus, the information about which ISR fired is now on the
stack: it is the return address of your function.
The reason this information will not be easy to use is that you do not
know how far it is from the stack pointer. It depends on how much stuff
your own handler pushed onto the stack. You could disassemble it and
count, but then your code will be fragile, as the smallest change in the
handler (or compiler version) may change this count.
An easier approach may be to define your own INT0_vect and
INT1_vect, overriding those from the Arduino core. These new ISRs
will both call your handler, but they will pass it an argument to tell
which interrupt fired.
Or you can register a different handler for each interrupt, each calling
a common function. But this adds an extra level of function calls.


text:
Need help with Arduino Love-O-Meter
not sure if this is the right place to post, but basically I am trying to make a Love-O-Meter, similar to the Arduino project example.
However, my method of determining the score is different. Instead of basing it on temperature, I am basing it on capacitance instead (Let me know if you think there are better ways to determine the score. I have tried body resistance, but it is too insensitive and I have also tried making it random but it doesnt make sense and its not as fun)
Another difference is that I want to make it only measure when both people place 1 of their hands on the foil and their other hand holding onto each other. However, the issue I have is Im not sure how to start measuring when the condition I mention happens.
Link to code: https://pastebin.com/bWyiDtfB (Using reference from here: https://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense) (The code starts measuring the capacitance when it detects that both foils have their hands placed on it, i.e.  when it detects that the capacitance exceeds a certain threshold, 200 for my case. It will then measure 100 samples and the score will be from the median of the 100 samples)
Link to fritzing diagram: https://i.stack.imgur.com/cOb7h.jpg (Ignore the black wire from A5)

I don't think you are going to get an answer here about a better way to measure "Love"   So then your whole question boils down to wating to  measure a connection between the two pads, as the two people would be completing the circuit between the two pads.  Do a little research, build a small test program for this "Sensor" only and post that code if you have any other questions about the specific problem you are having.

Basically the biggest problem I have now is to find a way to perform the measurement only when they hold hands and their other hand touch the foils.

that is simply a continuity test. Is there an electrical path from pad1 to pad2.  It will be very high resistance, but there will be an electrical path between them

I thought of trying to do that. Like connecting a 5V to 1 of the foil and the  analog pin to the other, but it will interfere with the capacitance measurement. Should I maybe make 2 more foils (1 connected to 5V and the other to the analog pin) so each person have to touch 2 foils with 1 hand?

Should be able to do both.  Can switch pin modes after deciding it us ready to start taking the reading. But them being joined could already effect the capacitance test

So what you are saying is that I dont code it to keep measuring the capacitance, but only start the measurement under the condition that the analogpin receives a signal right? Unlike what I am doing now, whereby I keep measuring the capacitance and only properly start the measurement when the capacitance exceeds the threshold.

@ChadG hmm I was thinking of adding a relay, so that when the hands are placed, the 5V will change to 1 of the digital pins instead.

The digital pins can be either output(5v) or input to measure capacitance.   So need to change which pin it's using, just change the pins mode

@ChadG so instead of using 5V, I use the digital pin to output a 5V. If so, then there shouldnt be any problem with the capacitance test right? I cant test it now but I will do so tomorrow.


text:
remove weird chars from char array ESP32
When I'm converting a string to a char array there are always some weird chars at the end.
I have to do it manualy because the convertTochar function crashes my ESP.
  String sssid = module.getCssid(); //String is stored in the eeporm
  char cssid[sssid.length()];
  Serial.println(sssid.length()); //prints correct length of 6
  //convert do ssid
  for( int i = 0; i<sizeof(cssid);i++){
    cssid[i] = sssid[i];
  }
  Serial.println(cssid); //prints myssid⸮?⸮2⸮?
enter code here

If I'm printing the value directly fromm eeprom there are no wired characters.
Also the max eeprom size for the string is 10 bytes...
Why are these characters at the end of string?

You forgot to add one more character to the array to place a \0 (0 value byte) in. This denotes the end of a string. If you forget this, the string will continue until it finds the first 0 byte, which will probably be after the original string copy. This can be dangerous, because it might be in memory that is not containing useful data, and those weird character can be many if there is not a 0 soon or at all.
Note that the 6 bytes you get are the bytes EXCLUDING this 0 byte, so you need to allocate 7 bytes to store a string of length 6.
Instead of the for loop you can use the strcpy function which copies a function including the 0 string.
See description:
Description
The C library function char *strcpy(char *dest, const char *src) copies the string pointed to, by src to dest.
Declaration
Following is the declaration for strcpy() function.
char *strcpy(char *dest, const char *src)
Parameters
dest − This is the pointer to the destination array where the content is to be copied.
src − This is the string to be copied.
Return Value
This returns a pointer to the destination string dest.
Example
The following example shows the usage of strcpy() function.
#include <stdio.h>
#include <string.h>

int main () {
   char src[40];
   char dest[100];

   memset(dest, '\0', sizeof(dest));
   strcpy(src, "This is tutorialspoint.com");
   strcpy(dest, src);

   printf("Final copied string : %s\n", dest);

   return(0);
}

Note that sizeof() only works for statically allocated arrays - that is, arrays that are allocated at compile time with a constant value. Using sizeof() with an array that is sized using a variable (or the return value of a function) will instead result in a pointer to a block of memory allocated on the stack, and sizeof() would return the size of that pointer - 2 on an 8-bit Arduino, or 4 on a 32 bit system like an ESP8266.  You need to use strlen() not sizeof().

Thank you for the answer! But strcpy only works when you copy char to char not string to char, right?  ('strcpy(myChar, mystring)') Making the size of the char array bigger fixed the problem.

Probably you have to make the string 1 bigger (to store the \0 at the end).


text:
Use LoLin V3 pins starting with 'S' in Arduino
I have this LoLin NodeMcu V3 board:

What are the pins S3, S2, S1, SC, S0, SK?
Can I use them as GPIO in Arduino?
Thank you for your help!

my experimentation notes say you can use GPIO 10 (S3) as an input, but only after boot.

These pins have 2 functions: They are the connections to an SD card and/or to its internal flash chip. The ESP8266 has the feature of when you set GPIO15 HIGH during bootup, it will load the program from SD card and execute it. See here for reference. On the normal board, these pins are however connected to an internal flash chip.
Signal name meanings:

SK: Serial Clock
SC: SPI Chip Select
S0 to S3: Data lines (Quad-I/O mode).

This picture found here explains the pins:

But as @Majenko already said, only the chip documentation matters, which is here:

Now to answer the actual question: Can you use these pins for arbitrary purposes? That depends. On the board they are all internally connected to a Quad-SPI flash chip. If you re-assign these pins to GPIO pins during normal operation in Quad-SPI mode, the chip hang up as the you just cut off one of the important lines to flash chip. However, if you really want you can modify your chip and cut two connections from the flash chip. Quad-SPI uses 4 data lines, but you can also operate the chip in Dual-SPI with 2 data lines (refer to here).
That means that you are able to cut 2 of the 4 data lines, GPIO9 (SPI_HD, S2 on the board) and GPIO10 (SPI_WP, S3 on the board) on the PCB from the ESP8266 to the flash chip and then use these two GPIO pins arbitrarily. This is to avoid interference with the flash chip when you are driving random signals to it while the lines are still physically conencted to the flash chip. You will ofcourse need to tell your flash tool (esptool.py) to use Dual-SPI mode for all subsequent firmwares. See here for that.
All other Flash GPIO pins can not be re-purposed, these conenctions (such as SCLK, MISO, MOSI, CS) are always needed for the flash chip.
GPIO15, which is D8 on the board, is easier to repurpose: You just need to make sure it's LOW during startup as to not trigger the SD card bootup by using a pulldown resistor. After flash bootup you can re-purpose it for input and output. This is already done on the board for you and you just need to use pinMode to set it as INPUT or OUTPUT. This is also described in here.
Obviously that's a lot of trouble to get 2 GPIO pins. If you just want more GPIO, you will find an I²C GPIO port expander such as the MCP23017 much more suitable for that -- 16 more GPIOs at the cost of 2 GPIO pins (the I2C bus). If you're already using the I2C bus in a project then you don't even loose additional GPIOs, it's just one more device on the bus.

My guess is those are the SDIO pins. They're meant for use with an SD card - 4 data pins, a clock pin, and a select pin.
To find out what more you can do with them you should ignore the fact that it's a "LoLin" and instead just look for documentation on the ESP8266 or ESP32 (whatever it is on there) that powers that board.


text:
If an I2C connection is lost for a short period of time will it work if the connection is live again?
I'm using an ESP8266 with the Arduino library to read from a sensor(MPU9250 specifically). The readings are done via I2C but I'm using a library that abstracts these methods.
The wires are not soldered together so temporary disconnections are possible and after these disconnects the sensor readings freeze. I'm new to the world of I2C so my questions are:

Do I have to re-init the connection after it disconnects or is there a way to continue on re-connection immediately?
Is there a way to prevent this to happen (for example to stop reading when there's no connection) or should I just solder together the pins?

When an I2C master starts a transmission or a request from a slave, it sends the slaves address and then check for an acknowledgement (ACK) from the slave (SDA LOW, when the clock has a HIGH pulse). When no slave is connected, or there is no slave with this address, then there isn't any circuit to pull SDA to LOW on the clock pulse, that is generated by the master. This is interpreted as No acknowledgement (NACK) and the transmission/request fails and should exit. So a disconnection between the transmission should not freeze your code (though I don't know what your library is doing exactly).
A quick google search gives me, that the esp8266 does not have hardware I2C, so your library does a pure software I2C. There are many pitfalls, which can block the I2C bus (especially, if one the lines is hold LOW by one of the involving circuits). Your library may or may not implement the correct I2C protocoll.
So to clearly answer your questions:

You don't have to reinit connection. Your master transmission fails, if there is no slave, and should give you an error as return value. But be sure, that there isn't happening anything on the SDA or SCL lines, when it starts up again after reconnection. Master or slave can interpret voltage spikes as signal.
If the library is implemented correctly, it will exit, when there is no ACK from the slave.

Look into the documentation of your library how it handles these events. And check the state of SDA and SCL, when a block occures. You can refer to this site for further information about I2C. It also gives some advice if your bus is blocked.


text:
my arduino uno board is not working
at once, when i connect arduino uno to my computer, my computer shuts down, after that i cannot upload programs to my computer,the board is not working but the led is ON. Before this, i upload programs 4 to 5 times continuously. i upload program with no physical connections in arduino except motor shield which is also not connected to anything.
i used three boards, all of them got damaged.
my computer's USB port and USB cable is in good codition.
i already updated my drivers.
computer spec: dell inspiron 15 3567
               windows10 x64 bit

Real Arduinos, or cheap chinese knockoffs?

Did you try without the shield connected? I think upload doesn't work when something is connected to D0, no idea if this applies to ohter pins too. When you try to upload, what error do you get? Enable verbose output during upload in the preferences.

Computer shutting down is often an indication that excess power is being drawn.
If you measure  between +5 and Gnd on the unpowered board with a meter set for resistance, do you get a reading in the 5Kohm range? Or something much lower? Much lower would be bad.


text:
Arduino: using digital pins to emulate USB device
Is there any "easy" way to emulate USB keyboard or gamepad using digital pins on Arduino Mega? I looked at Uno-Joy/Mega-Joy, but I dont find firmware changes appealing.

No.  There is not anything like that.

@Delta_G - that's not really true.  It is possible, see V-USB.  But perhaps not "easy".  Reprogramming the ATmega8u2/ATmega16u2 on boards having that for their USB-serial interface is also an option.

There is (or was) an implementation of software-only USB for the Arduino. I think it was called V-USB, though I am having trouble finding it now.
I think it may be this library though nothing has happened with that for a number of years.
Personally, I wouldn't recommend it, though, and would suggest using a board with a real USB interface, such as the Arduino Leonardo, chipKIT Lenny, or Teensy 3.x.

How much easier would it be with different hardware, say Leonardo?

Much easier. You just use the Joystick library: https://github.com/MHeironimus/ArduinoJoystickLibrary

Nice. However, there is one more problem: I am using Mega at the moment, because I need to read voltages off 8 different sources and make it to digital output. Is there any device that would have at least 8 analog pins?

Teensy 3.6, and you don't want the Joystick library - it has its own USB stack that works differently: https://www.pjrc.com/teensy/td_joystick.html

Thanks, but its a bit pricy, it would be cheaper to use two arduinos.

Or multiplex your analog inputs, or use an external ADC chip.

Right, didnt think about that. Leonardo it is, then. Also, according to arduino.cc, you can use some digital pins as analog pins.

Teensy 3.6 is probably overkill, check the number of analog inputs on the Teensy 3.2 or Teensy LC.

@VojtaDoležal You can get a Pro Micro for $4. It uses the same MCU as a Leonardo.


text:
Arduino - Finite State Machine does not start in the initial state
I'm building a state machine using 6 flip-flopsD, and an G input coming from an infrared sensor. This circuit should count from 0-35.
The problem is that it always starts in state 111111. That is, after it passes through Flip-flop D A, B, C, D, E, F = 1;
Here's my code:
#include "flipflopD.h"

boolean a1,b1,c1,d1,e1,g1;//display 1
boolean a2,b2,c2,d2,e2,f2,g2;//display 2
boolean Aa=false;
boolean Bb=false;
boolean Cc=false;
boolean Dd=false;
boolean Ee=false;
boolean Ff=false;
boolean A=false;
boolean B=false;
boolean C=false;
boolean D=false;
boolean E=false;
boolean F=false;
boolean G=false;//receiver

void setup() {

    //DISPLAYS
    pinMode(A0, OUTPUT);
    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);
    pinMode(12, OUTPUT);
    pinMode(13, OUTPUT);

    pinMode(A2, INPUT);// IR RECEIVER
}

void loop() {
    //  Counter
    G = digitalRead(A2);
    Aa = flipflopD((A||!B||!C||!D && !A||B||C||D||E||F||G), A, G);
    Bb = flipflopD((!A||B||!C||G && !A||B||F||!G && !A||B||E||!F && !A||B||D||!E && !A||B||C||!D && !A||!B||C||D||E||F||G), B, G);
    Cc = flipflopD((!A||C||!D && !A||C||!E && !A||C||!F && !A||C||!G && !A||!C||D||E||F||G), C,G);
    Dd = flipflopD((!A||D||!E && !A||D||!F && !A||D||!G && !A||!B||!C||D && !A||!D||E||F||G && !A||!B||C||!E||!F||!G), D, G);
    Ee = flipflopD((!A||E||!F && !A||E||!G && !A||!E||F||G && A||!B||!C||!D||E && !B||!C||!D||!E||F||G), E, G);
    Ff = flipflopD((!A||!F||G && !A||F||!G && !B||!C||!D||!F||G && !B||!C||!D||F||!G && A||!B||!C||!D||E||G), F, G);

    A=Aa;
    B=Bb;
    C=Cc;
    D=Dd;
    E=Ee;
    F=Ff;

    //   ABCDEF TO 7 Segments
    a1 = !A||B||D && !A||B||C & A||!B||!C||!D;
    b1 = !A||B && !A||C||E && !A||C||D && A||!B||!C||!D;
    c1 = !A||!B||C||E && !A||!B||C||D && !A||C||D||E && !A||B||!C||!D + A||!B||!C||!D;
    d1 = !A||B||D && !A||B||C && A||!B||!C||!D;
    e1 = !A||B||!C||D && !A||B||D||!E && !A||B||C||!D;
    g1 = !A||B||D && !A||B||C & A||!B||!C||!D;

    a2 = (!A||!C||E  &&  !A||!B||!D||!F  &&  !A||!B||D||F && !A||!B||C||!E && !A||C||D||!E && !A||B||!C||!F && !A||B||!D||F && !A||B||E||!F && !B||!C||!D||E||F && A||!B||!C||!D||!E);
    b2 = (!A||B||D && !B||!C||!D||!E && !B||!C||!D||!F && !A||!B||!E||!F && !A||!C||!D||F && !A||!C||!D||E && !A||!C||E||F && !A||!D||E||F && !A||!B||C||!E && !A||!B||C||!F && !A||C||!E||!F);
    c2 = (!A||F && !A||!D||!E && !A||C||E && !A||B||!D && !A||B||!E && !B||!C||!D||F && !A||!B||!C||D && A||!B||!C||!D||E);
    d2 = (!A||!B||!C||!D||!F && !A||!B||!C||E||!F && !B||!C||!D||E||F && !A||!C||D||!E||F && !A||!B||C||!D||!E && !A||!B||C||!E||!F && !A||C||!D||!E||!F && !A||!B||C||E||F && !A||C||!D||E||F && !A||C||D||E||!F && !A||B||!C||!E||F && !A||B||!D||E||!F && !A||B||!C||D||!E && !A||B||!C||D||F && !A||B||D||!E||F && A||!B||!C||!D||!E);
    e2 = (!A||!C||!D||!F && !A||!C||E||!F && !A||!D||E||!F && !A||B||D||!F && !B||!C||!D||!E||!F && !A||!B||C||!E||!F);
    f2 = (!A||!C||!E||!F && !A||C||!D||!E && !A||C||E||!F && !A||B||C||!E && !A||!B||!C||D||!E && !A||!B||!C||D||!F && !A||!B||C||D||E && !A||B||!C||!D||E && A||!B||!C||!D||E);
    g2 = (!A||C||!E && !A||!C||!D||E && !A||!C||E||!F && !A||!B||D||!E && !A||!B||C||D && !A||B||!D||!F && !A||B||!C||E && A||!B||!C||!D);

    // OUTPUTS

    //DISPLAY 2
    digitalWrite(A0,a2);
    digitalWrite(2,b2);
    digitalWrite(3,c2);
    digitalWrite(4,d2);
    digitalWrite(5,e2);
    digitalWrite(6,f2);
    digitalWrite(7,g2);

    //DISPLAY 1
    digitalWrite(8,a1);
    digitalWrite(9,b1);
    digitalWrite(10,c1);
    digitalWrite(11,d1);
    digitalWrite(12,e1);
    digitalWrite(13,g1);
}

Here's my Flip-FlopD:
boolean flipflopD(boolean D, boolean Q, boolean CLK){
  boolean Qo=false;
    if (CLK=true) {
      Qo=D;
    } else {
  Qo=Q;
  }
  return Qo;
}

Can someone tell me what's wrong?

One potential error source: In your D-Flip-Flop code, you have
boolean flipflopD(boolean D, boolean Q, boolean CLK){
  boolean Qo=false;
    if (CLK=true) {
      Qo=D;
    } else {
  Qo=Q;
  }
  return Qo;
}

You probably want to do a comparison with double == instead of an assignment with = in the line
if(CLK=true)

This causes the if to always evaluate to true and set Qo=D.
Also, I am not really sure if this is what you want:
a1 = !A||B||D && !A||B||C & A||!B||!C||!D;

First, you're mixing && (logical-and) with the bitwise & here. Next, C++ operator precedence dictates that the &&has a higher priority than ||. This looks like a conjunctive-normal-form of some boolean function, thus I would group the AND terms in parenthesis, like
a1 = (!A||B||D) && (!A||B||C) && (A||!B||!C||!D);

In the c1 expression you are also suddenly using the + operator in a chain of logical expressions, which looks wrong.
Overall I don't quite get how this should work. If you have an IR receiver connected to A2, from which you read the "CLK" input, it will get some 39kHz input wave when you point a IR remote at it and press a button. And you want that on each CLK rise/fall the Arduino reacts to it by calculating the output for a seven-segment display? Your Arduino Uno/Nano with its 16MHz will take some time to execute each of the statements in the loop, sequentally. So what you're doing is actually sampling the A2 input every now and then -- how often exactly, I don't know, maybe with a few kilohertz. Your Arduino might sample the input at the wrong time or not fast enough to react the way you expect. digitalRead and digitalWrite are notoriously slow, maybe try direct port access or an interrupt-based approach. Of course, calculating all these AND, OR and NOT expressions will take some processing time, too.
This sort of combinational logic is more suited for an FPGA implementation, not for an Arduino.


text:
sbi() and cli() implementation
I've often seen cli() and sbi() in Arduino code. I usually don't mind them as I know what they do (clear or set the bit given as second argument in the register of the microcontroller given as first). I've always thought that those functions where only a clear way to perform simple bit manipulation, which can be quite error-prone. Something like that:
#define cli(reg,bit) (*reg &= ~(1 << bit) and #define sbi(reg,bit) (*reg |= (1 << bit)).
Then I found out that the actual implementation is as follows:
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

It's quite like I used to think... but with two extra macros.
I looked for them in the Arduino libraries:
#define _BV(bit) (1 << (bit))

and
#define _SFR_BYTE(sfr) _MMIO_BYTE(_SFR_ADDR(sfr))

which contains
#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

and
#if _SFR_ASM_COMPAT
#if (__SFR_OFFSET == 0x20)
#define _SFR_ADDR(sfr) _SFR_MEM_ADDR(sfr)
#elif !defined(__ASSEMBLER__)
#define _SFR_ADDR(sfr) (_SFR_IO_REG_P(sfr) ? (_SFR_IO_ADDR(sfr) + 0x20) : _SFR_MEM_ADDR(sfr))
#endif
#else  /* !_SFR_ASM_COMPAT */
#define _SFR_ADDR(sfr) _SFR_MEM_ADDR(sfr)

Further research took me to definitions I couldn't understand (for example because they are explained in comments using a lot of acronyms I don't know).
So I have the following questions:

Why is sfr casted to *(volatile uint8_t *)?
What do the acronyms used in that code mean? (ASM, SFR, MMIO)
Under what circumstances is __ASSEMBLER__ defined, and where (in which file)?
Why can't we simply write #define cli(reg,bit) (*reg &= ~(1 << bit) and #define sbi(reg,bit) (*reg |= (1 << bit))?

Why is sfr casted to *(volatile uint8_t *)?

Because you want the content (the first *) of a memory address that you specify, and you need it volatile so it doesn't cache it. Oh, and it's an 8-bit value.

What do the acronyms used in that code mean? (ASM, SFR, MMIO)

ASseMbly, Special Function Register and Memory Mapped Input/Output

ASM means assembly language.
A Special Function Register is something like DDRB.
Memory Mapped IO is a way of interacting with peripherals by reading from and writing to locations in the normal memory address space.

Under what circumstances is __ASSEMBLER__ defined, and where (in which file)?

It is defined by the compiler when you are compiling an assembly file.

Why can't we simply write #define cli(reg,bit) (reg &= ~(1 << bit) and #define sbi(reg,bit) (reg |= (1 << bit))?

Because reg is just an address. You need to convert that into a variable in memory that you can reliably access (hence the volatile). Further to that, not all chips use MMIO for all peripherals - some can be accessed by more efficient IO instructions. That said, in many cases yes you can just use simpler code. After all, things like DDRB |= 0x04 works fine. It all depends on how the value to pass as reg is defined originally. By forcing a specific volatile cast you can ensure that whatever way it was defined (with or without volatile, etc) it will work.

Thanks for the quick answer. I’m realizing I forgot the * before reg, it’s a stupid copy-paste error. I’ll add it to the question (the edit will influence only the last part of your answer)

On Atmel (now Microchip) AVR microcontrollers, the sbi, cbi, sbis, and sbic assembly language instructions can only address the 32 IO ports at addresses between 0x20 and 0x3f. The Atmega168 and 328 (used in Arduinos prior to the Leonardo) has WAY more than 32 IO registers, so only a subset of them can be addressed by sbi and cbi (the AVR instruction set was nailed down YEARS ago, when 32 IO registers seemed like more than enough).
As a result, operations that set or clear a single bit in those 32 IO registers can be performed by a single instruction which executes in two clock cycles, but the same operations on the remaining IO registers require a full-blown load-operate-store sequence that takes at least three cycles to execute.
From what I recall, AVRlibC had multiple macros that did almost the same thing, but had different use cases:

One would compile to the fastest and most efficient instruction(s) available for that particular IO address.
One would always compile to sbi/cbi, and would throw a compiler error if you tried to access a register outside of 0x20-0x3f
One would ALWAYS compile to the load-act-store sequence, without regard to whether or not it could have used sbi/cbi instead.
One would always compile to the load-act-store sequence, but would throw a compiler error if you tried using it on an address between 0x20 and 0x3f.

Basically, the choice enabled you to decide between optimized (but variable) performance, uniformly-slow (but deterministic) execution time, or the fastest-possible (but deterministic-at-compile-time) variant [which required that the programmer be aware of whether the register in question was within or above 0x20-0x3f].

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


text:
Getting the voltage of an 18650 battery with an Arduino
I'm using a Arduino Pro Mini (5v) to sense the voltage of an 18650 battery. The battery (that is being sensed)is also used to power the Pro Mini but the MCU is behind a boost-converter which outputs 5.05v. Would I be able sense the right voltage of the battery?

simulate this circuit – Schematic created using CircuitLab
The boost converter has an input voltage ranges to 0.9 to 5 volts and current of 600mA.

most cheap switch-modes are not isolated, so the ground is common. there's little/no reason to isolate unless there's inverted voltages.

Yes, if Vin- and Vout- are joined together inside the boost converter or share a common ground on the boost converter circuit board such as this one:

My boost converter is different but the IN- and OUT- is connected.


text:
How can i check for valid fingerprint and no finger detected?
i am working in arduino fingerprint sensor with adafruit. i am using two leds to check if fingerprint is valid. my problem is that i need three cases instead of two.
1 case: when fingerprint is valid. turn on green led and turn off red led.
2 case: when fingerprint is not valid. turn on red led and turn off green led. i put a finger but was a not valid finger.
3 case: when there is no finger detected, turn off both leds.
Is there a way to do that?
i am using adafruit library and fingerprint sensor, with fingerprint.ino and using pin 11 and 12 for output.

it is unclear what you are asking ... are you asking about turning on LEDs? ... or are you asking about reading fingerprints? ... the two things are not really related at all

When there is no finger on the sensor, the function Adafruit_Fingerprint.getImage() from the Adafruit Fingerprint library returns the constant FINGERPRINT_NOFINGER. You can execute the function in a loop and setting the LED outputs in a switch statement according to the return value. Refer to the examples of the Adafruit Fingerprint Sensor Library. There you have directly the code for checking the sensor (since the full check for a valid fingerprint is longer than this one function call, you can use the getFingerprintIDez() function from the fingerprint example, or a variation of it).


text:
Why does the function esp8266.available() always returns FALSE?
I am trying to develop an Home automation system using Arduino and ESP8266 Module. But stuck at the very first step while checking is esp8266.available() available or not. This function always returns FALSE. Looking for solution. Thanks in advance.
CONNECTION
Vcc -----> 3.3
CH_PD ---> Vcc
RX ------> 2 (Arduino pin)
TX ------> 3 (Arduino pin)
GND -----> GND (Arduino)

CODE
#include <SoftwareSerial.h>
#define DEBUG true
SoftwareSerial esp8266(2,3);

void setup(){
    Serial.begin(9600);   // Setting the baudrate to 9600
    esp8266.begin(9600);  // Set it according to your esp’s baudrate. Different esp’s have different baud rates.
    pinMode(11,OUTPUT);   // Setting the pin 11 as the output pin.
    digitalWrite(11,LOW); // Making it low.
    pinMode(12,OUTPUT);   // Setting the pin 12 as the output pin..
    digitalWrite(12,LOW); // Making pin 12 low.
    pinMode(13,OUTPUT);   // Setting the pin 13 as the output pin.
    digitalWrite(13,LOW); // Making pin 13 low.
    sendData("AT+RST\r\n",2000,DEBUG);            //This command will reset module to default
    sendData("AT+CWMODE=2\r\n",1000,DEBUG);       // This will configure the mode as access point
    sendData("AT+CIFSR\r\n",1000,DEBUG);          // This will get ip address and will show it
    sendData("AT+CIPMUX=1\r\n",1000,DEBUG);       // This will configure the ESP8266 for multiple connections
    sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // This will set the server on port 80
}

void loop(){
    if(esp8266.available()){  // ALWAYS FALSE
        // My codes
    }
}

UPDATE
At the very first run time, the function is returning TRUE and showing an error
deprecated conversion from string constant to char wwrite strings arduino esp8266.find("+IPD,")

for line number

Also asked at: https://stackoverflow.com/q/49093800 If you're going to do that then at least be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

connect RX to TX and TX to RX. pin 2 is RX in your SoftwareSerial. did you set the AT firmware to 9600 baud? available() returns the count of available bytes.

@per1234 I am really sorry for that. During post on Arduino community suddenly I lost my internet connection and thought question was not publish. Then I directly posted id on Stackoverflow with arduino tag.

@Juraj Please look at the line number 3 "SoftwareSerial esp8266(2,3);".  Should I still connect RX to TX and TX to RX?

if you want two devices to communicate over Serial, then always one must listen on receive pin what the other transmits on transmit pin. in your SoftwareSerial setup pin 2 is RX and pin 3 TX.

Yes, so is this the problem?

Constructor parameter order is RX, TX (see https://www.arduino.cc/en/Tutorial/SoftwareSerialExample). So when you're connecting the RX of the ESP8266 to the RX of the Uno, that's wrong because both chips just listen on the same line where nothing ever happens. The transmitter must be conencted to a receiver (RX to TX) and TX to RX. So yes, put RX (ESP) -> 3 (Arduino) and TX (ESP) ->2 (Arduino).

"Yes, so is this the problem?" Probably. Why don't you test it and check if it works? RX-TX is definitely correct, not RX-RX, TX-TX.

@idkfa Checked, but no change.

@MaximilianGerhardt, Now the only difference is Blue LED is blinking. Nothing else.

There is a questions about baud rate in my first comment.

@Juraj, yes, baud rate is 9600

the warning about deprecated conversion can be from the compiler, but not from esp8266. you throw a bunch of AT commands at the esp8266 in setup(), what do they return? why should be there data available in loop?


text:
How to delay properly inside ISR
I am currently working on a little code which needs to react fast. Here is what I am trying to accomplish:
Using a sine wave phase detector I am detecting every zero crossing and feeding that pulse into the Arduino.
Using an ISR the Arduino detects this zero crossing pulse using RISING. Once one pulse has been detected AND I have pressed a button, I need there to be a delay of 0 - 10ms before switching on an output.
If I don't use an ISR and set a delay of up to 10ms inside the loop, it won't really be 10ms and it will be some other delay, nothing consistent. (I checked with an oscilloscope).
Only when using an ISR and using delayMicrosenconds() inside the ISR I can delay the output consistently for up to 10 ms everytime.
Now I have read that doing this is wrong...Even though it works perfectly. Which better way could I use?
Thanks!
EDIT: While 100% accuracy may not be possible, it needs to be as precise as possible. More important is the repeatability. Using my method I could reproduce the outcome everytime with an accuracy in the nano seconds range.

how critical is those 10 ms really?

If your program has nothing else to do during these 10 ms, and if you don't care about the Arduino timekeeping (millis() and micros()) getting off, and if you don't use libraries that rely on interrupts, then your method should be OK.

Those 10ms need to be 100% exact. I need to switch on an output which drives a TRIAC. The TRIAC will then turn on an electronic ballast at exactly the desired sine phase. I.e. if I delay for 5ms, the TRIAC will switch on AC at exactly 90°

“100% exact” is not achievable in the real world. Not with an Arduino nor with the most precise equipment available on earth.

The question of @ratchetfreak is very relevant because single cycle accuracy, while achievable, will require somewhat complex low-level programming. If you can live with a few 10 µs of jitter, then the problem is much easier. Please, edit your question to provide a reasonable answer to that question.

It's quite simple: You don't.
Instead you use your initial ISR to configure and enable one of the ATMega's Timer peripherals. Set that to the length of your required delay - then the ISR exists.
When the chosen time has passed the timer interrupt triggers, and you use that interrupt to turn on your output.

I have tried this. How would I enable for example Timer1 inside my initial ISR? TIMER1_OVF_vect and TIMER1_COMPB_VECT did not give me the expected results. When switching my output inside these routines, there was no delay.

Using the TimerOne library is easiest.

But would it be ok to completly configure the Timer1 inside the ISR? Setting prescaler, compare match register, etc?

Sure. Or do the config elsewhere and just turn it on in the ISR. Whatever makes more sense for your program.

You could configure the timer to make it trigger only once, using the technique used here: https://wp.josh.com/2015/03/12/avr-timer-based-one-shot-explained/  . (Though this might be overkill in this case. )


text:
Peer to Peer using Ethernet Module
I'm beginner here at arduino stuff. i just started learning arduino and i have this small homework where i NEEDED to connect 2 arduino using ethernet shield or module ONLY over a distance of 20 meters.
I don't have my modules yet but i want to atleast study it now while i'm waiting for it. I can't seem to see any tutorials about it nor anyone tried it. How can i do this? i hope you can help me and give some insights, links, etc reference. Thanks :)
EDIT:
I had in mind where these arduino will have their own identity, 1st arduino will be receiving only some data coming from 2nd arduino. The 2nd arduino will have sensors and read them then sends them to 1st arduino. Now, i like my 2nd arduino to have a power source coming from the 1st arduino to save power supply installation and since it'll be like a remote arduino. Thus has anyone has experience applying PoE on arduino?

PoE uses 48V ... if you want to use actual PoE injectors, then you will need to use a power supply at each arduino

You will need a crossover cable to connect two Ethernet shields peer to peer.
Then you configure the Ethernet library to use static IP address. Use 192.168.1.1 and .2 address. (Or other 192.168.x.x address). Set subnet 255.255.255.0. Gateway should be the IP address of the other Arduino.

hi juraj, :D thanks a lot, never knew i need to consider that, i thought i just have to buy ethernet cable, i'll drop by my progress here and notify if it work

i was thinking also regarding PoE application, goal was 1st arduino is like the server and only reads send messages from 2nd arduino as client since it will have sensors connected to it and i want 2nd arduino to have its power source coming from where 1st arduino is put. would that be possible?

sorry, I have no experience with PoE and having Arduino as a PoE source is not so common, I think


text:
Every loop other case
I need to achieve that in every loop my Arduino do other thing. Say in first loop do one thing, in second do second thing and in third loop do third thing. And again. And while doing one thing, other things are dead.
Not sure what approach to use.
This is just my 50 cents:
for(int x=0; x<2; x++)
  {
  switch (x) {
    case 0:
      //do something
      break;
    case 1:
      //do something
      break;
    case 2:
      //do something
      break;
  }
  delay(1);
}

I tried this from above but it stuck at case 0
Any point or link to explanation would be nice.

how do you know, "it is stuck in case 0"?

It don't do case 1. And it should.

The question was how you know that.  This question will probably not be answerable until you post actual code which causes the problem.

In your code the for loop is wrong: if you want to reach case 2, you need x <= 2; or x < 3 in the for. Then this code should in general work. You can also make a global variabe for the "step" you're currently in only write the switch part in the loop followed by step++;

Either the case 0 code is stuck in a loop or it exits abnormally.

The code i provide is just a guess. The main question is how to set that in each loop my Arduino do different thing.

Sorry, but it's not clear from either your words or your "guess" code what exactly you are trying to do.  The principle problem is the word "loop" - a loop is either infinite or has some terminating condition(s).  You mention doing a series of things, so you'll need to be specific about until what condition you want to do each before moving on.  And then be specific if the overall sequence should repeat.  Also, the need to let the Arduino-language loop() run repeatedly vs. only once per complete sequence is governed by things like intervening event methods it is unclear if you will use.

Your implementation is in principle correct. However, tradionally, you don't incrementally loop over all states from 0 to end using a for loop. The implementation is more flexible if it allows the state to go to any other state if it needs to. This would be a normal finite state machine (FSM).
#include <Arduino.h>
/* How many states are possible? */
#define MAX_STATES 2
/* global state variable */
int currentState = 0;

/* prototypes */
void Action1();
void Action2();

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

void AdvanceStateByOne() {
    currentState = (currentState + 1) % MAX_STATES;
}

void loop() {
    //Execute the action dictated by the current state
    switch(currentState) {
        case 0:
            Action1();
            break;
        case 1:
            Action2();
            break;
        default: //Catch for un-implemented states
            break;
    }
    //Go to next state, incrementally.
    //This could also be modified in one of the functions above
    //Loop back to zero state after MAX_STATES using modulo operator
    AdvanceStateByOne();

    //for testing, introduce some delay
    delay(1000);
}

void Action1() {
    Serial.println("Action 1");
}

void Action2() {
    Serial.println("Action 2");
}

This prints out "Action 1" and "Action 2" in a loop forever.
Now you could take this further and instead of using pure numbers for your states, you can use an enum representation of those to make the code clearer:
enum state_t {
    STATE_DO_ACTION_1 = 0,
    STATE_DO_ACTION_2,
    STATES_END
} ;

And then act on those accordingly. You can also use the C++ feature of a enum class to give you a nice notation like State::SomeState1.

for(int x=0; x<2; x++)
  {
  switch (x) {
    case 0:
      //do something
      break;
    case 1:
      //do something
      break;
    case 2:
      //do something
      break;
  }
  delay(1);
}

You will never do case 2, that's for sure, as you are incrementing to less than 2.


text:
What is best way to get data from sensors if arduino is slave?
Im working on a project where i have motor controller(arduino nano) being i2c slave. Its job is to get RF24 data and control motor and at same time send data to master about motor... Currently i have 2 ultrasonic sensors for distance sensing and if they are too close it will stop motor. I want to add 2-4 more but it adds a lot of delay because of
pulseIn();

command. I want to use attiny as sensor reader and just dump current data when requested.
Is it possible for arduino nano to be i2c slave (hardware i2c) and at same time i2c master (software i2c/please library without using timers... im short on them) or there is way to dump data in less than 2ms via serial or some other protocol? SPI is already used for RF24 and i need RF24 to be up all the time.

What is the length of the data to be transmitted? In any case using a UART you can send, at 115200, around 230 bits (23 bytes) in 2 milliseconds (count 8 bits/byte + start and stop bits). At 9600 you can send sligthly less than 2 bytes. Is this enough? Since the attiny just has to check it asynchronously an asynchronous transmission (UART) is better if it has enough bandwidth)

I would need around 6 bytes, struct of 6 bytes (6 ultrasonic sensor readings), is there Serial_Anything like I2C_anything?

What do you mean? Serial.write(buf, len) and, well, the reading has to done byte by byte using the Serial.read() function

Oh thanks, i didnt know that i could use (buf, len).

On simultaneous master/slave: Yes and no. You can initiate the Wire library as slave and despite of than using Wire.beginTransmission() and it's siblings to send as a master. The library will configure the hardware as master only for the time it needs to send. But there are 2 problems:

When you have multiple masters on the same bus, they have to continuously watch the bus, so that they are only starting a transmission, when the bus is free. The Wire library doesn't seem to do that.
If two masters start their transmission at the same time, the data will be good, as long all transmitted bits are equal. For other cases the I2C protocol has a rule: When 2 masters start a transmission at the same time, the first one to write a 1 to the bus (HIGH value) has to immediately back of to slave mode. (This is because to write a 1 to the data line the pullup resistors are used. When another master tries to write 0 to the bus (LOW value on SDA) he wins against the pullups, effectively writing 0 to the port, and not 1)

As mentioned on this Github issue there are some workaround, though I haven't tested them myself until now. All in all I2C multi-master may be to complex at this point.
As another option, you can use an extra line, connecting master and slaves (use the internal pullup on the masters side). Any slave can at any time write a LOW to this line, triggering the master to request data from all slaves (maybe via external interrupt or pin change interrupt).
Note: I don't know, for what purposes you used all your timers, but maybe there is a way to share one of them with other hardware, so that you don't have to use the blocking pulseIn() function. Or maybe you can tweak the timeout value of the function to a fitting value.

One timer is used for servo, other is used for millis and delay and pwm for controlling motors, third one is used by a some library i think.... Anyways in loop i have to read 5 ultrasonic sensors and it has to finish whole loop in less than 10ms, im scared that if i add too many ultrasonic sensors(max 6) that it will lag(be delayed because of 6x pulsein, i have timeout set to 60cm).


text:
Arduino - Push Button State Problem
My problem is I want the buzzer to stop after a certain amount of time, regardless if it is still pressed or not.
I have tried to implement a boolean statement to the code but to no avail(I'm not very good at this)
Can someone shed some light as to how I do this?
The code already times out after 1000ms when your finger is lifted off the buttin so I got that far but cant get any further.
Here is what I have.
Any other suggestions are also welcome as I know its not the prettiest or best implemented but i was just happy it worked for me.
// Setting The Pin Numbers
const int touchsensor = 2;                      // the number of the touchsensor pin
const int buzzer =  4;                          // the number of the LED pin

// variables:
int touchsensorState = 0;                       // variable for reading the
touchsensor status
unsigned long timestamp = 0;
unsigned long timeout = 1000;

void setup() {

  pinMode(buzzer, OUTPUT);                      // initialize the buzzer as an output
  pinMode(touchsensor, INPUT);                  // initialize the touchsensor as an input
 }
void loop() {

   touchsensorState = digitalRead(touchsensor);  // read state of the pushbutton value:

   if (touchsensorState == HIGH) {                 // check if the touch sensor is pressed. If it is, the touchsensorState is HIGH:
     digitalWrite(buzzer, HIGH);                 // buzzer will emit sound:
     timestamp = millis();                       // Timing button press
   }

   if(millis() - timestamp > timeout) {
   digitalWrite(buzzer, LOW);                  // buzzer will not sound:
   }
}

you will need to implement a edge sensor. Add a previousTouchsensorState to the globals and replace the if where you check the sensor state with:
if(previousTouchsensorState == LOW && touchsensorState == HIGH) {
     // check if the touch sensor is pressed and wasn't the last time though the loop.
     // If it is, the touchsensorState is HIGH and previousTouchsensorState is LOW:
     digitalWrite(buzzer, HIGH); // buzzer will emit sound:
     timestamp = millis();       // Timing button press
}
previousTouchsensorState  = touchsensorState;


text:
DHT 11 sensors and i2c LCD to Wemos Wifi not Working
Its my first time make arduino project. I make wemos d1  project using DHT11 temperature sensor and LCD 20x4 with i2c. The temperature data will display in LCD and sending to the bot telegram. For sending to the bot telegram it works, but why the data cannot display to the LCD? When I tried common charachter like "Hello World!" in the LCD it works. Can you help me? What should I do? Thanks before.
#include "DHT.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F,2,1,0,4,5,6,7,3, POSITIVE);
#define DHTPIN D14
#define DHTTYPE DHT11

byte degree[8] = {
  0b00110,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000
};

DHT dht(D14, DHT11);

void setup() {
  lcd.createChar(0, degree);
  Serial.begin(115200);
  Serial.println("DHT11 test!");
  lcd.begin (20, 4);
  dht.begin();
}

void loop() {
  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  lcd.setCursor(0, 0);
  lcd.print("Humi : ");
  lcd.print(h);
  lcd.print(" %");

  lcd.setCursor(0, 1);
  lcd.print("Temp : ");
  lcd.print(t);
  lcd.print(" C");
}

what you should do is to give us more information. so far, all you have said is that your project does not work. you posted no circuit diagram and no code, so it is impossible to even guess what the problem might be.

Will you show us your code please, or is it "top secret"?

please add the code to your question and delete these comments ... i do not think that anyone will be able to read your code in comments

I've been add my code at my question. thank you very well

Please define "not working". Does nothing at all get displayed?

Does nothing at all

We would expect at least that Humi :  would be displayed, so this is nothing to do with your DHT11 sensor. Unless ... try putting in a debugging print after getting the sensor data. Like: Serial.println (h);

Ya, I've tried to see is that any problems with DHT11 sensor by serial monitor, the sensor works good. But when I connect it to the lcd, it doesnt work. it's confusing. Anyway, thank you for the response,

what is D14? Wemos doesn't have pin D14

what is LiquidCrystal_I2C lcd(0x3F,2,1,0,4,5,6,7,3, POSITIVE)? I can't find such a constructor.

D14 is a SDA pin in wemos, and LiquidCrystal_I2C lcd(0x3F,2,1,0,4,5,6,7,3, POSITIVE) is lcd initiation based on i2c library.

Does wemos cannot display temperature data in the lcd? I think it should be fine but why still error. For i2c wire I connect VCC to 5V, GND to GND, SDA pin to D4 and SCL pin to D3.

Oh I see, I cannot connect DHT11 to the D14 pin, because it is used for SDA(D14/SDA/D4). when I move to the pin D2, it works. Thank you every one. Sorry if I make mistake because it is my first project.

@ChoirinNisa, it is not D4, only io 4. D4 is io 2. I formulated an answer, for future readers. You could accept it.

Constant D14 is for Wemos D1 and other esp8266 dev boards mapped in arduino core to esp8266 io pin 4. Pin 4 is used as I2C SDA pin. The LCD uses I2C so pin 4 (D14) can't be used for the sensor.
from pins_arduino.h for Wemos D1 R1:
#define PIN_WIRE_SDA (4)
#define PIN_WIRE_SCL (5)

static const uint8_t D14  = 4;
static const uint8_t D15  = 5;

The origin of this confusing esp8266 io pin to Dx constants mapping is the big Wemos D1. There are esp8266 pins mapped to standard Uno pinout.


text:
WS2812 HELP. Need name of Unkown component
https://i.stack.imgur.com/pbYn6.png
I need to know what the little "thing" that i marked in blue is and how it works.
Thanks.
picture taken here: https://www.sparkfun.com/products/13282

It's most likely a decoupling capacitor meant to smooth out the voltage supply to the internal control chip.
This is standard practice to add to any chip. Power cables create a small bit of parasitic inductance in relation to the area between the lines. This inductance can induce voltage spikes when current draw changes significantly. A capacitor shrinks the effective area between the power lines.
This is also why the general advice for decoupling capacitors is to put them as close to the chip as physically possible.

It's a capacitor. Specifically a decoupling capacitor of somewhere around 100nF to 1uF.
It works by storing an electrical charge in two plates with a dielectric between them. That specific type is a Multi-Layer Ceramic Capacitor and looks to be 0603 in size.

It's a capacitor connected between 5V and GND and it smooths out voltage spikes for a cleaner power supply to the chip. A cleaner power supply means the circuitry in the chip can more easily pick out the data signal (i.e., the reference voltage is more constant, so the actual signal appears more stage.)


text:
Fade out lightbulb 220V
I am trying to make a lightbulb fade to dark and back to light, for which I found the following tutorial online:
http://bildr.org/2012/03/rfp30n06le-arduino/
Unfortunately, the tutorial makes use of a 60V light source while my intention is to use the system on 220V. Would it be enough to solve my problem to replace the 60V MOSFET in the system with one of 220V?What would otherwise be a solution?
Thank you very much for your help!

I'm voting to close this question as off-topic because the actual question being asked is about mains powered dimming circuits, not about Arduino.

Absolutely not. Not under any circumstances.
Dimming AC is a considerably harder task, and doing it with 220VAC can be deadly.
To do it you need:

A zero-crossing detection circuit
A TRIAC driver circuit
A suitable TRIAC to do the switching
Software that will use the zero crossing information to time the switch-on of the TRIAC to a certain point in the waveform.

And most importantly:
Good knowledge of working with mains electricity - without which you will probably kill yourself or those around you.

a solid state relay w/zero cross is going to be the simplest way to accomplish all that.

@dandavis No, it's not. Not unless the ssr and the zero cross are completely separate units. You need to switch the SSR at a period after the zero cross to dim it. SSRs with zero crossing built in turn on at the zero crossing to prevent spikes.

of course, duh. i somehow forgot about the dimming part and focused on the safe part...

You can buy 220V dimmer modules controllable with 5V PWM from Arduino. Here is one controllable with this PWM digital potentiometer module.
I use Kemo 4000VA regulator module with that M150 digital pot module controlled with Arduino PWM for heater regulation.


text:
How do I use digital pin on sensor to analog on arduino uno
I am working on a autonomous fire extinguisher.i have run out of pins.I have the following question in my mind while working on my project
Is it necessary that the DO pin in a flame sensor must be in a PWM digital pin in Arduino.i have this doubt since when I connected it to non PWM pin it didn't worked.
Secondly it is possible for me to use the analog pin in Arduino for the DO pin of the flame sensor or trigger/echo pins of the ultrasonic sensor.
Thanks.

Perhaps you could add a url/referens to the flame sensor. As it is now it is totaly unclear!

http://www.theorycircuit.com/arduino-flame-sensor-interface/ I am having sensor having only digital output pin

@MatsK is it clear now

PWM stands for Puls Width Modulation and is only available when the Digital Pin is in OUTPUT mode.
And YES, you can connect the flame sensor's D0 to any digital pin on the Arduino.
And yes it is possible to connect the flame sensor's D0 to a analog pin, but why not use the A0 from the flame sensor and connect it toi a analog pin on the Arduino?

I have only 3 pin flame sensor

OK, the one that you refered to is a four pin....

@MatsK, that site shows both

You can use the analog pins (A0-A5, but not A6 and A7) also as digital pins. So you can set one of them as digital input, connecting it with the D0 pin of your fire sensor. You can read this pin with digitalRead(pin).
Regarding your problem with PWM:
There is no "PWM input" on an Arduino Nano (because PWM hardware in a microcontroller means pulse with modulated output). The example code of your sensor uses an analog input (ADC: Analog Digital Converter) (with usage of analogRead()). If you want to use this functionality you have to connect the A0 pin of your sensor to one of A0-A7 and reading it with analogRead() to get the fires intensity/distance.

Will if(digital read(A1)==LOW) work if I connect my DO pin of sensor to analog pin

The documentation, you linked, says, that it outputs LOW, when nothing is detected and "+Ve" (I guess that means HIGH) when a fire is detected. So to detect the existence of fire use if(digitalRead(A1)==HIGH). But be sure to initialize the pin as input


text:
File include error while using Arduino Nano
I am using the code below to interface the Arduino nano and android cell phone to enable serial communication through the USB port. I downloaded the filter library from GitHub https://github.com/JonHub/Filters
I am getting an error saying thet the library is not found.
I would really appreciate some suggestions on this.
Here is my code:
 //This code is for arduino communicating to android phone through USb serial port.
 //For arduino nano

 #include <Filters.h>   //implements digital filters which mimic the analog filter, keep track of variable statistics in realtime

char data_read; //character datatype takes up to 1 byte of memory
unsigned int analog_out;
unsigned long time;
float filterFrequency = 10.0;
FilterOnePole lowpassFilter( LOWPASS, filterFrequency );//implements digital RC type filter; both highpass and lowpass

 void setup()
 {
  Serial.begin(115200); //open the serial port and set the baud rate for communication
  // create a one pole (RC) lowpass filter

 }
 void loop()
 {
 }

 void serialEvent() { //Used when data is unavailable yet
 if (Serial.available()) //checks the number of bytes available for reading from the serial port
 {
data_read = Serial.read();

if (data_read == '0') {
  Serial.print("#");

  //Serial.print("10100");
  analog_out = lowpassFilter.input( analogRead(0) );
  Serial.print(analog_out + 10000);

  Serial.print(":");

  //Serial.print("20200");
  analog_out = lowpassFilter.input( analogRead(1) );
  Serial.print(analog_out + 20000);

  Serial.print(":");

  //Serial.print("30300");
  analog_out = lowpassFilter.input( analogRead(2) );
  Serial.print(analog_out + 30000);

  Serial.print("p");
}
/*if(data_read == '0' || data_read == '1' || data_read == '2' || data_read == '3' || data_read == '4' || data_read == '5'){
  analog_out = lowpassFilter.input( analogRead( data_read-48 ) );
  Serial.print((analog_out)+(data_read-48)*10000);
  Serial.print(":");
  }else if(data_read =='p'){
  Serial.print("p");
  }*/
   }
 }

Here is my error message:
  Arduino: 1.8.5 (Windows 10), Board: "Arduino Nano, ATmega328P"

  C:\Users\daphn\Documents\Arduino\Analog_Serial_out\Analog_Serial_out.ino:4:129: fatal error: Filters.h: No such file or directory

  #include <Filters.h>   //implements digital filters which mimic the analog filter, keep track of variable statistics in realtime

                                                                                ^

  compilation terminated.

  exit status 1
  Error compiling for board Arduino Nano.

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

And where did you put the library?

I've included the library in the same folder where I had saved my code

Have you read these 2 pages? https://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC6 , https://gcc.gnu.org/onlinedocs/cpp/Search-Path.html

You have to put the folder with the library files in the folder libraries under your sketchbook folder. Then the IDE should be able to find them.
I think there is also a possibility to save them in the same folder as your .ino file, but it I don't know how exactly you have to do this.

I did try including the filters.h header file under the main libraries folder, but still I get the same error. I am wondering if there is any mistake with the source of the header file itself. Usually, when I include external libraries, I place it in the same folder as the code itself and it works.

I tested it with your code and the linked library and it works for me. Check in the IDEs settings, to where the sketchbook folder is set

The library is more than a .h file. You need ALL the files, and all placed in a folder named Filters within your libraries folder in your sketchbook. Nothing else will do.

@Majenko What do you mean by ALL the files?

@DaphFab All the files for the library. Everything in that github repository. All the .h files, all the .cpp files, etc. There's 11 of them, plus examples.

Ok got it. I had already done that before. Anyway, I solved the issue by changing #include <Filters.h> to #include "Filters.h"

please elaborate why you did that, so that people can resolve similar issues in the future

Here is your definitive answer.
You have to do the #include like the following (with double-quotes, not < > brackets)
#include "Filters.h"
This will make Arduino compiler look in the project folder.
Using < > brackets tells the compiler that it is in the standard library area.
I just tested this with the following script.
#include "mytest.h"
void setup() {
  // put your setup code here, to run once:

}

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

}

The mytest.h file is blank (has no text in it).
It wouldn't work until I included it using the double-quotes method.


text:
Is checking an if statement every loop/while iteration inefficient?
I have code that changes a bool only time in the setup(), and in my loop() I have
if (setupBool) {
// ...
} else {
// ...
}

Is checking the bool every loop slower than having a while(true) with the same code?
And what about checking it in every loop in a while(true)?
Is there any reason I shouldn't do those?

I don't understand how a while(true) can be an alternative to if()...else...

I couldn't understand why you are checking setupBool in the loop if it can change only in the setup... Moreover you usually don't need a while(true) in the loop since it automatically gets executed forever

Of course an if statement cost time, although very little. However, it changes (although once), so if you need to vary depending on the value, you have to use the if statement.
A while(true) also cost a little time (a little bit less), but less than 1 us, same as the if statement. You can do perfectly do an if statement within the while(true), but remember, the loop itself is behaving like a while(true) already.
However, I wouldn't concern at all about optimizing performance, unless:

You know beforehand you will need the fastest code possible
You have already performance issues

Always prefer readability/maintainability about performance.

The actual full structure of the loop function is like this:

while(true)

Call loop()

if (condition)

Run your code

else

Run your other code

Check for serial data

By putting a while(true) inside your if you:

Remove the overhead of calling loop() every time
Remove the overhead of checking for serial data (that is what the SerialEvent system is all about)
Remove the overhead of checking the if every iteration.

So the executing part of your code now looks like:

while(true)

Run your code.

If your code needs to run in a tight loop it can provide some speed improvements, yes, but at the cost of:

No SerialEvent processing (normal Serial works, but the SerialEvent system breaks)
Harder to "get out" of the loop to do something else (although break can help with that).
On ESP8266 boards the watchdog will time out unless you manually yield() regularly.

Would I suggest doing it? Well, there are times when it can be beneficial, but those times are few and far between. If you don't need to do it then, in general, don't do it.


text:
Arduino Nano joystick x2 / potentiometer
will i be able to connect up all these parts to an arduino Nano
i noticed i will need to connect to the nanos v5 to the 2 joysticks and potentiometer slider if i share the voltage will it still function as intended

Parts
x1 = USB Arduino Nano V3.0 ATMEGA328P CH340G 5V 16M Micro-Controller Arduino
x2 = 3D Analog Joystick for Sony PSP 1000 Consol
+5v (possible 10kOhm resistance)
x1 = Electronic slider 10K potentiometer Slider Module for Arduino
Voltage: 3.3V or 5V / Resistance: 10K

Yes, this should work. The potentiometer slider will source about 5mA and each joystick axis about 50mA. In total this gives you 205mA. Here it is important, that your power source can provide enough current. If you are using an USB port from your computer, this would result in 500mA maximum that can be drawn from the bus. Since this is shared with the Arduino you can externally use about 400mA
For more information about current ratings refer to this question
EDIT: Since your previous resistance values were not correct, I edit my answer.
When all potentiometers have 10kOhm resistance (and this seems to be more likely the right values), each one draws about 5mA from the 5V pin (You can calculate this with Ohm's Law U = R * I, which gives you I = U / R. So you have to divide the voltage by the resistance.). So you aren't getting anywhere near the problematic currents. These potentiometers are designed this way. They don't want to draw a high amount of power, but only setting a certain voltage to the output pin.

I suspect the 100R pots are somewhat erroneously labelled. Especially as the slider certainly is incorrectly labelled.

ohh i could not find the joystick specs on that front this is my first project
this was listed as the slider i thought the 10k ment 10,000 did i get that wrong
Voltage: 3.3V or 5V
Port: Analog
Resistance: 10K

10k does mean 10,000 - but your schematic shows 1k for the slider and a mere 100R for the pots, which are almost certainly more likely to be around 10k or higher.

updated the image and info related to the parts still trying to find more info regarding the Analog Joystick Sony PSP 1000

The only way to be sure is to measure they resistance. But I also found a joystick, that is labeled as PSP on ebay. They claim to have 10kOhm resistance: Ebay

thanks for that been looking everywhere for some more info related to joystick


text:
Error in code (define a function)
I try to use this code, but it shows that I need to define again the last void turn_mer (int direction) function. How can I fix this?
#include <Servo.h> //create servo object to control a servo.
Servo myservo;

//pin configuration.
const byte servoPin = 2; const byte motorLeft = 5; const byte motorRight = 6;
const byte echoPin = 12; const byte trigPin = 13; const byte echoPin2 = 8; const byte trigPin2 = 9; // LET OP DE HOOFDLETTERS: echopin en echoPin
//delay determines how long the MER turns, increase to make the turning angle larger.
const int turnDelay = 500;
//standard angle for looking straight ahead, compensate for construction errors.
const int standardAngle = 90;
//angle in degrees that controls the direction in which the sensor looks.
const int viewAngle = 40;
//delay to let servo turn, not optimized; for smaller angles smaller delay could be used.
const int servoDelay = 250;
//object distance in cm at which the MER decides to look around and turn another way.
const int lineOfSight = 40;
//pwm duty cycle of the motor, use a value from 0 (no movement) to 255 (full speed).
const int motorSpeed = 90;

//const int lineDownSight = 35;
void setup() //setup pin configuration and initialize the sensor position.

{ delay(3000); //delay to give us some time to place the MER on the ground.
  myservo.attach(servoPin); //initialize the servo and look straight ahead.
  turn_servo(standardAngle);
  pinMode(motorLeft, OUTPUT); pinMode(motorRight, OUTPUT);
  pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); drive_mer();
} //start the mer.
void drive_mer() //this function lets the MER drive forward.
{
  analogWrite(motorLeft, motorSpeed);
  analogWrite(motorRight, motorSpeed);
}
void stop_mer() //this function stops the mer.
{
  digitalWrite(motorLeft, LOW);
  digitalWrite(motorRight, LOW);
}
void turn_servo(int angle)
//turn servo to given angle, do not return until angle is reached.
//if the servo is already at the correct angle, we don't have to do anything.
{ if (angle == myservo.read()) {
    return;
  }
  else {
    myservo.write(angle);
    delay(servoDelay);
  }
}

int look1() //looking function, returns distance in the observed direction as an integer.
{ int duration, distance;
  digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1; return distance;
}
//turning function: makes MER turn in preferred direction. 0 for left and 1 for right.
void turn_mer(int direction)

{ if (direction == 0) {
    digitalWrite(motorLeft, LOW);
    digitalWrite(motorRight, HIGH);
  }
  else {
    digitalWrite(motorLeft, HIGH);
    digitalWrite(motorRight, LOW);
  }
  delay(turnDelay); stop_mer();
}//stop the engines when the MER has turned far enough.

//this function turns the MER depending on the observed distances.
void handle_measurements(int distanceLeft, int distanceStraight, int distanceRight)// int distanceDown

{ if (distanceLeft < lineOfSight and distanceStraight < lineOfSight and
      distanceRight < lineOfSight) {
    stop_mer();
  }

  else if (distanceLeft < lineOfSight) {
    turn_mer(1);
    drive_mer();
  }

  else if (distanceStraight < lineOfSight) {
    if (distanceRight > distanceLeft)
    {
      turn_mer(1);
    } else {
      turn_mer(0);
    } drive_mer();
  }

  else if (distanceRight < lineOfSight) {
    turn_mer(0);
    drive_mer();
  }
 //if (distanceDown > lineDownSight) {
  //  stop_mer();
  }

  void loop()
  { int distanceLeft, distanceStraight, distanceRight;

    turn_servo(standardAngle + viewAngle); distanceLeft = look1();
    turn_servo(standardAngle); distanceStraight = look1();
    turn_servo(standardAngle - viewAngle); distanceRight = look1();
       handle_measurements(distanceLeft, distanceStraight, distanceRight);}

/*  void handle_measurements(lineDownSight)
   {(distanceDown > lineDownSight) {
    stop_mer();
  }*/
  //                                                                                sensor 2
  //______________________________________________________________________________________________________________________________________________________________________________________________________

 const int lineDownSight = 35;

  void handle_measurements (int distanceDown)

{if (distanceDown > lineDownSight) {
    stop_mer();}}

  int look2() //looking function, returns distance in the observed direction as an integer.
  { int duration, distance;
    digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH);
    delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH);
    distance = (duration / 2) / 29.1; return distance;
  }
  //turning function: makes MER turn in preferred direction. 0 for left and 1 for right.
void turn_mer (int direction)

{handle_measurements(distanceDown)}

Next time write in English not Dutch (I translated it now for you), use ctrl-K for aligning code (I did now), and add the error, please add it yourself.

But the main problem is that in C, you can only define a function with the same name once.
Halfway you defined the function turn_mer already, and again at the end.
Also, you are missing an end colon in:
{handle_measurements(distanceDown)}

It's better to align your code like:
{
    handle_measurements(distanceDown);
}


text:
NPN transistors level shifter
I'm going to use this for Arduino Pro Mini (5v version) to communicate with ESP32 via UART so I need level shifting. I found this circuit which uses NPN transistor and I'm also going to use it. This is the circuit I'm going to use...

simulate this circuit – Schematic created using CircuitLab
Are the resistors' value appropriate or do I have to change the collector resistor?

You don't have a collector resistor, you have a pullup resistor.

Can a moderator migrate this to the Electronical Engineering stackexchange please? This is purely about level shifting with transistors.

Are you aware that you can just use a voltage divider? Two resistors.

Those values look fine to me.


text:
'Serial1' was not declared in this scope
Trying to do serial communication between 2 Arduino Unos.
Code:
#include <SoftwareSerial.h>

int ledPin = 13;
int board;   // 1 = Uno. 2 = Mega.
int on_off;  // 1 = On. 0 = Off.
int buzzerPin = 9;
int Ack_tx = 2; //Acknowledgement tx.
int rec;

void setup()
{
  Serial.begin(9600);      // start serial communication at 9600bps
  Serial1.begin(9600);     // start serial1 communication at 9600bps

  pinMode(ledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);

  Serial.flush();
  Serial1.flush();

} // End Setup

void loop()
{

  Serial.println("Enter Uno=1/Mega=0 ...");  //Select board
  //  if(!Serial){ board = Serial.read();}
  while(Serial.available()==0) { // Wait for User to Input Data
  }
  board = Serial.parseInt();  //Read the data the user has input

  Serial.println("Enter LED On=1/Off=0 ...");  //Select On or Off
  while (Serial.available()==0) { // Wait for User to Input Data
  }
  on_off = Serial.parseInt();

  Serial.println();

  switch (board) {

  case 0:  //Mega board
    if (on_off == 1) digitalWrite(ledPin, HIGH); //Select Uno LED On
    else digitalWrite(ledPin, LOW);              //Select Uno LED Off
    break;  //End Case

  case 1:  //Uno board
    //Serial.println("Off to Uno...");
    //Send on_off info to Uno
    Serial1.write(on_off/256); //Send the Quotient or "how many times" value
    Serial1.write(on_off%256); //Send the Modulo or Remainder.
    delay(50); //Wait for the serial port.

    while(Serial1.available()<2) //Wait for 2 bytes to arrive
     {
      //do nothing
     } //End While

  byte b1=Serial1.read();  //Read Upper byte
  byte b2=Serial1.read();  //Read Lower byte
  rec=(b1*256)+b2;

    if (rec == Ack_tx) tone(buzzerPin, 300, 300); //Ack_tx from Uno
    break;
  } //End Switch Case

}

Error:
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\Akshit\Documents\Arduino\sketch_mar06a\sketch_mar06a.ino: In function 'void setup()':

sketch_mar06a:13: error: 'Serial1' was not declared in this scope

   Serial1.begin(9600);     // start serial1 communication at 9600bps

   ^

C:\Users\Akshit\Documents\Arduino\sketch_mar06a\sketch_mar06a.ino: In function 'void loop()':

sketch_mar06a:51: error: 'Serial1' was not declared in this scope

     Serial1.write(on_off/256); //Send the Quotient or "how many times" value

     ^

Multiple libraries were found for "SoftwareSerial.h"
 Used: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial
 Not used: C:\Program Files (x86)\Arduino\libraries\SoftwareSerial
exit status 1
'Serial1' was not declared in this scope

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

This is a very basic problem I know, but nothing on the internet is helping.

Why do you think "Serial1" should exist?

I picked this code off of the internet.
I feel it should exist because we would need one serial for communication with the serial monitor of computer
and a second one for the actual serial communication between the two arduinos
Pls correct me if I am wrong.

So... you saw it in random code and thought it would work everywhere?

The code made sense to me. Couldnt think of any changes to make..
Ill try the answer given by Majenko

@Aki An Uno has only one hardware serial interface (Serial). What do you expect Serial1 to be?

@gre_gor read my 1st comment. I am an extreme noob at this..

The Uno has no Serial1. It only has one serial port, called Serial. To use Serial1 you will need a bigger board such as a Mega2560, or define it as a SoftwareSerial port and use two other IO pins of your choice for it, though at lower baud rates than Serial can run at.

I have arduino micro, and I can use serial (form comunication pc )and serial1 (form com. wifi module).

You import the SoftwareSerial library but you however never instance an object of the SoftwareSerial class.
You just need to add the line
 SoftwareSerial Serial1(10, 11); // RX, TX

after including the library header (taken from here)
This now creates an object Serial1 on which the operations down there should work the same as with a real hardware serial (API-wise).
Side note: Careful with the wiring. You are using this Serial1 emulated UART to communicate between the boards, so if you're using above pin numbers (D10 = RX, D11 =TX) then you must connected D10 (Board1) -> D11 (Board2), D11 (Board1) -> D10 (Board2), i.e. RX->TX, TX->RX.


text:
Trouble uploading sketch / error in sketch
I am following this tutorial of a very basic serial communication between 2 arduino unos.
I have made the connections as given and connected the arduino unos to 2 separate laptops via USB.
Code1:
char mystr[3] = "Hello"; //String data

void setup() {
  // Begin the Serial at 9600 Baud
  Serial.begin(9600);
}

void loop() {
  Serial.write(mystr,5); //Write the serial data
  delay(1000);
}

Code 2:
char mystr[5]; //Initialized variable to store recieved data

void setup() {
  // Begin the Serial at 9600 Baud
  Serial.begin(9600);
}

void loop() {
  Serial.readBytes(mystr,5); //Read the serial data and store in var
  delay(1000);
}

Error on arduino following code 1:
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

Sketch uses 1602 bytes (4%) of program storage space. Maximum is 32256 bytes.
Global variables use 188 bytes (9%) of dynamic memory, leaving 1860 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
An error occurred while uploading the sketch

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

Arduino running code 2 is stuck on the uploading and does not fininsh uploading.
The solutions on the internet only talk of the scenarios where the arduino is having trouble communication with the computer and so the solutions given are:

check com port
check that correct board is selected
do not insert the arduinos in usb 3
press reset button

None of these is my problem as I have checked them all. The arduinos themselves are working fine. I have a very strong feeling that there is a problem with the pins 0 and 1, i.e. with serial comm.
Please help.

When you program the Arduinos you need to unplug all cables from D0 and D1, otherwise the upload will fail. Have you anything connected to D0 or D1 while uploading?

While not a solution to the problem you posed, this line in Code 1: char mystr[3] = "Hello"; //String data is not good -- you can't allocate 3 bytes in an array and assign a string that requires 6 bytes of data (5 characters, plus null terminator.)

Also, the error text you list for Code 1 can't be right with that code, because it should give a compile error. Are you sure you have pasted the right responses?

@josecanuc yes pretty sure I have pasted the right errors..
and I changed [3] to [6]

@MaximilianGerhardt yes the error goes away but now nothing is being printed. But what should be the correct algorithm to make the connections?
Like:
Ard 1 with pins empty to USB then
Ard 2 with pins empty to USB then
Common GND to both then
Rx tX in ard 1(or ard 2 first?) then
Rx tx in ard 2
??
Also are the codes correct?

Flash both Arduino boards without anything attached to them. Then plug the cables in (cross-over, i.e. D0 -> D1, D1 -> D0 from Board1 -> Board2), then plug both boards into your USB ports. Board1 will transmit data to board2 which you might see in the serial monitor for board2. This code uses the only hardware serial available and no other "debug serial port" from which you can observer something though. Your SoftwareSerial approach would be better.

one of the things that you have to learn in programming, is to identify a problem correctly. .... you are unable to upload a sketch to an arduino, yet your question title is Problem in serial communication between 2 arduinos ... that title is absolutely incorrect

I am guessing you have connected 2 arduinos together using their hardware serial ports while uploading. This cause uploading to fail as those ports are getting two signals at the same time.
Break this connection before upload and then it should work. You can reconnect them after upload.
If you want to avoid this you can use different pins with software serials for communication.
Also consider using Serial.available() on the reading end to see if there is data to be read.

Normally "guessing" is discouraged, but as this absolutely horrible "tutorial" literally instructs the unsuspecting to make this problematic connection, you are probably right.   Whoever wrote that terrible guide has done the world a disservice.