text:
What's in an Arduino?
I've been using an Arduino Uno Rev. 3 for a few projects and would like to switch to using a bare Atmega328 chip so I can keep everything on the same board. I've seen the Arduino on breadboard tutorial which is fine, but the Arduino board itself has a lot of other components that aren't in the tutorial. I realize I can go look up the actual design itself, but I'm looking for a high level description of what most of the components are used for.
I'm not interested in programming through the Arduino IDE, so I don't need parts for serial programming and such. But I'm wondering if leaving out some other components would leave me at a disadvantage. For example, the datasheet recommends connecting AVCC to VCC with an LC circuit for ADC noise cancellation, but the arduino on breadboard tutorial doesn't mention this and I otherwise never would have known.

I realize I can go look up the actual design itself - So do it! It is a very simple board. If you have a specific question about some part of it, then ask.

What do you expect us to tell you that is not "go read the schematic?" If you want a block diagram, it's just a microcontroller, USB-to-serial, and some voltage regulation.

If you're not interested in the Arduino hardware, and you're not interested in the Arduino software, why mention Arduino at all? Just work directly from the Atmega328 datasheet.

The schematic just has a lot to take in all at once for someone not used to very complex  circuits. It's not easy to figure out what everything does other than look at every detail, google pin names, etc. It just seems like some sort of resource could be made to make it a bit easier to parse. Though maybe that's a bit much for this site if that means just going through the schematic, highlighting bits, and explaining what each one does.

This is one of the rare hardware questions that are probably better suited for the Arduino SE. You want a description of the Arduino hardware, it can't be more Arduino-specific than that.

@JorenVaes As much as I love reading through documents  front to back with hundreds of pages (I mean that's how I learn programming languages) I don't get any sense of what I need to focus on or what capabilities it has. The Arduino is nice to prototype on as I clearly know everything I have, but then I just want to remove the bulk when I'm done.

Which Arduino? There are a lot of different board types.

Are you asking for a component-by-component description of (say) an Arduino Uno? Or are you asking for a sensible stand-alone board configuration?

Wel specifcally I'm trying to migrate from using an arduino to control an LCD, read 4 inputs where 3 of them are analog inputs, and output 2 signals, to having it on a standalone board without the unnecessary parts. So I tried to see if there were any general rules that apply.

This

You did not specify what Arduino board you are talking about. It would
have been useful to tag the question with the appropriate board name. In
the following, I assume you want something similar to an Arduino Uno,
i.e. an ATmega328P at 5 V and 16 MHz.

I realize I can go look up the actual design itself [...]

You should. There really isn't that much to it.
Let us take a look at the Uno rev. 3 schematic, and see what may be
useful to you:

ATmega16U2 and associated circuitry: This is for USB communication.
You have no use of it if you are not doing USB.
3.3 V regulator: This is for providing the Arduino 3.3V output.
Only a convenience feature, not used by the Arduino itself. You should
leave this out unless you need a 3.3 V supply.
5 V regulator. Only you know how you want to power your board.
This regulator is needed unless you have some reasonably stable
5 V supply like, e.g., a USB bus.
ISCP header: This is rarely used on an Arduino, but you are very
likely to use it in your custom board, as ICSP is the easiest way to
program an ATmega with no bootloader.
Reset button: Not always needed, as you can just power-cycle your
board.
10 kΩ pullup on RESET: Your board is very likely to work just
fine without this, but there is a little risk that you suffer from
random resets. You want this resistor on anything that is
“production”-like, for reliability concerns.
Decoupling capacitors: Just like the RESET pullup, the board may work
without them, but they provide reliability.
The MOSFET and OP-amp right before the 3.3 V regulator: This is
for automatically switching between the Vin and USB power supplies.
Unlikely to be useful on a custom board.
Ceramic resonator: For running the ATmega at 16 MHz, you need
either this or, for better timing characteristics, a quartz with
suitable capacitors.
LEDs: You know if you want them.
AREF capacitor: Only useful if you do analog readings, as it reduces
noise.

Yeah I was asking about the Uno Rev 3. I've edited my question to specify that. This is just what I was looking for! Ive looked at the schematic as well in the meantime but this goes over it in a very functional way.

It all depends on you want, and what you are talking or thinking about, when you ask What is an Arduino. There are two main things that I associate with Arduino: A family of Development Boards (maybe a hardware family of development boards) and a Software built to work with that development boards. This let me to answer you using that two focuses:

The hardware focus

I understand that the Arduino boards were intended to bring the electronics and programming, closer to artists. Also, as any development board, the Arduino boards allows the user to test the most quantity of features of the core microcontroller used in the board (for Arduino UNO, the Atmega328P). Thus implying that the most of components included are to allow you a "safe" development workaround.
Now, when you have worked in a project so many time that you are ready to replicate your design, maybe for a commercial implementation, an Arduino board can take up more space that if you design your own board, well by you are not going to use all the pins or well by that you noted that you are not going to mess up the microcontroller or other components (maybe you did it the necessary times to know it) and you want to choose a smaller package that don't needs an easy microcontroller replacement, or finally because you want to include in a single board all the components and circuitry you used for your project and remove the ones you are not going to use, that is the case you mention, and you can do more things... if you want to work from a CR2032 battery you won't need the regulator and so...

The software focus

When you decide to use your own circuitry, maybe you also want to program the IC by yourself, not through the 2K bootloader preprogrammed, but by your own ISP programmer. There are many workarounds using the Arduino IDE, but as apparently you don't want to use the Arduino IDE, the ISP programmer would be your programming interface.
A conclussion?: The minimal things you have to bear in mind to put in run the Atmega328P (and maybe most of microcontrollers) are 3: polarization, clock and Reset. The other things (the LC network you mentioned, the RC network I will mention, and so...) can improve the microcontroller stability and performance.

Polarization. Depending on the board, the DC supply used can be either 5V or 3.3V. Check the voltage used by your board.
Clock/Oscillator. See and reply the oscillator configuration used in the board. Then search where you can set up (in your IDE or code) the oscillator speed. Overall if you decide or want to use the internal oscillator, obtaining a minimal circuit or by playing with arduino config files. Note that, as example with the 328P, using the internal oscillator means that you are not going to reach the max number of MIPS the 328P can reach (with the internal you have 8MIPS, but you can use an external crystal up to 20 MHz to get 20 MIPS)... It really matters if you are going to do many processing tasks.
Reset. Please do not let it open, send it to VCC through a 10Kohm resistor, and (if available) additionally to GND with a 100nF ceramic capacitor.

There is very little on an Arduino aside from the chip itself, the regulator (sometimes) and the crystal / oscillator (sometimes).

But I'm wondering if leaving out some other components would leave me at a disadvantage.

Leaving out some parts will give you a disadvantage for some applications but give you an advantage for others; the same for adding some parts.
The right question is to figure out what you want to achieve with a given application and design towards that goal.
For minimum implementations, I have done plenty of nothing but the MCU - ghetto style.
On the flip side, there are plenty of applications where the MCU is literally buried in a sea of other parts: C8051F350 based LCR meter for example. so what to put in and what to take out is really application dependent.


text:
inttypes vs Arduino defined integral types
In my Arduino projects I use both Arduino types and types defined in the "inttypes.h" file, which #includes stdint.h. So far I've always written code only for the ATmega328P microcontroller (either in the UNO board or "standalone").
To be clear, in this question I'm referring to the following types:

"Arduino": char, int, long; byte, word, unsigned long
inttypes: int8_t, int16_t, int32_t; uint8_t, uint16_t, uint32_t

What is the actual difference between e.g. int and int16_t?
Is implicit conversion between corresponding types always possible, or should I avoid it even if the compiler doesn't complain? (quite often in my programs I pass an int16_t as int argument to a function and it always works, but is it good practice to do it, in general?

"Arduino": char, int, long; byte, word, unsigned long
inttypes: int8_t, int16_t, int32_t; uint8_t, uint16_t, uint32_t

A better classification would be:

C and C++: char, int, long, unsigned long
"Arduino": byte, word
inttypes: int8_t, int16_t, int32_t; uint8_t, uint16_t, uint32_t

I generally avoid the Arduino-specific types, as they are quite
non-standard, and do not usually exist outside the Arduino world. As for
the other types, just like Michel Keijzers suggests, I use the C types
when I do not care much about the exact size. int is guaranteed to be
at least 16 bits, but is likely to be 32 bits on a 32-bit architecture.
It is a good default type, as it is supposed to be efficiently handled
on any architecture. These types allow you to write portable code that
automatically selects the "right" integer width for whatever
architecture it is been compiled for.
If you care about the exact size, which can often be the case in a
memory-constrained environment, use the types from inttypes.h. And do
not worry about implicit conversions: as long as both types are wide
enough to hold the numbers you need to store, a type conversion, whether
implicit or explicit, always preserves the value.

int can be depending on the hardware architecture and is mostly 16 or 32 bit.
However, an int16_t is always 16 bit, regardless of the hardware architecture.
It will go wrong when you have a 32 bit architecture (for an int), and you are going to cast it to an int16_t, than you lose the MSB 16 bits. Although I think the compiler will give a warning in this case (so in your case you are ok, but it can prevent a lot of work when you port your code to a 32 bit architecture).
However, all Arduinos have int defined as 16 bit, except the Due and SAMD based boards, see: Arduino reference for int (updated after the comment of per1234 below, thanks for that).
Normally I use integer when I don't care much about the type (and know it will stay under 32768, like for most indices in loops). But if you define a (large) array it's better to use an explicit type, or if you know for sure the value will never be higher than 32768 (int8_t) or nonnegative and 65535 (uint8_t).
Also, for the 'eye' unsigned char for an unsigned 'integer' value upto 255, uint8_t looks better than a 'char' which seems more like a character instead of a value.

"However, all Arduinos have int defined as 16 bit, I think that's even true for the Due's." This is incorrect. See https://www.arduino.cc/en/Reference/Int

@per1234 Thank you, I updated my answer

"or if you know for sure the value will never be higher than 32768 (int8_t) or nonnegative and 65535 (uint8_t)."
Did you mean int16_t and uint16_t?
This topic can generate some confusion and casual errors like this can compound the problem.

source: Stack Exchange

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

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

sort: votes


text:
Reading an output analog pin with an input analog pin
I am having a hard time understanding why I can't read one analog pin's output with another analog pin. The docs state to put a delay in between, which I've done (I've tried up to one second with the same results). I've got this minimized code:
void setup() {
    Serial.begin(9600);
    pinMode(A0, INPUT);
    pinMode(A5, OUTPUT);
}

void loop() {
    for (int i=0; i<1024; i++){
      analogWrite(A5, i);
      delay(100);
      Serial.println(analogRead(A0));
    }
    Serial.println("done");
    delay(10000);
}

When it starts, it displays 6-9 for a few dozen iterations, then suddenly jumps to ~1018 and remains throughout the rest of the run.
A5 is connected directly to A0 via a 4" jumper cable. Nothing is connected to AREF. If I connect AREF to 5v, the output does not change but by a single digit. If I connect it to ground, it immediately outputs 1023.
I'm hoping this is a "do'h" moment here. Can someone please let me know what I'm not doing correctly?
Update: This is a legit Arduino Uno R3 board. When I connect A0 directly to 5v+, I get 1023 as expected as the output.

I do realize that PWM has a max value of 255, but updating the sketch changes nothing; the result is the same.

This page show several Arduino Capacitance Meters (http://www.circuitbasics.com/how-to-make-an-arduino-capacitance-meter/). The last one (Capacitance Meter for 470 uF to 18 pF Capacitors) use two analog pins for charging/reading voltages. It may be useful in your project.

For a start, A5 is not a valid pin to do analogWrite to. On a Uno they are marked with the "~" symbol, and are pins: 3, 5, 6, 9, 10, 11.
Thus the code will treat it as a digitalWrite, and will write LOW up to 127 and HIGH after that. From the code in wiring_analog.c:
    case NOT_ON_TIMER:
    default:
        if (val < 128) {
            digitalWrite(pin, LOW);
        } else {
            digitalWrite(pin, HIGH);
        }

You are then just reading back (close to) 0 or 1023.

Second, PWM output is not what you can read back using analogRead. An analogRead reads a voltage level, whereas PWM output is just 0s and 1s interleaved at the PWM frequency, and with a width of the duty cycle.
See https://www.arduino.cc/en/Reference/AnalogWrite, in particular:

The analogWrite function has nothing to do with the analog pins or the analogRead function.

Third, writing 1023 to analogWrite is out of range. See the documentation from the page linked above:

Parameters
pin: the pin to write to.
value: the duty cycle: between 0 (always off) and 255 (always on).

You can see that the most you can write is 255 (not 1023).

References

More information about the ADC (analogRead) at my page about the ADC converter.
More information about PWM output at my page about timers.

This is a fantastic piece of feedback, and I realize that I need to do further research and testing. There has been an obvious disconnect between my understanding, and what's actually realistic. Thanks for this... after glancing at the board and with the understanding I have, it has put me in the proper direction of where to look and what to do.

I'm accepting this answer not because I've tested it, but because it is thorough and makes sense. I'm confident it'll prove true :)

I have to admit that I did not understand that A'n' pins were not necessarily analogWrite() capable. I totally overlooked that in everything I've done. It explains quite a bit. I think my Arduino experience will be much nicer moving forward with this new comprehension.

analogRead and analogWrite are confusingly named as they are not symmetrical. A better name for analogWrite might have been PWMwrite.

...that would have made one think, at minimum. Thanks Nick.

Can someone please let me know what I'm not doing correctly?

the analog (output) pins on those chips are not exactly analog: they are pwm output pins. as such, their output is either 0 or 1, nothing in between, with the chance of being 1 equal the duty cycle.
that kind of output can be a steady "analog" if you run it through a low pass filter - the simplest would be an rc filter where the r is in serial with the c.
so if you hook th epwm pin up to a rc filter and adc the output of that rc filter, you will get a real "analog".

Your program is correct and I suspect the error is in the hardware. Arduino uses its internal timer and creates a high frequency PWM on the corresponding pin upon a analogueWrite() is called. Here what we should notice is the DC switching in the appropriate pin is not noticeable in most cases. (If you give it to an LED you can adjust its brightness).
But what you have done now is not correct. Since there is no current flowing in the pin there will not be a analogue voltage actuality. It is 5V and 0V switching in a high frequency. Those are the values which the A0 pin will see.
So try fixing a capacitor between the pin and the ground. and a 1k resistor to create a slight current flow to stabilize the voltage. then let us know your readings.

simulate this circuit – Schematic created using CircuitLab

Thanks for this, but I believe the answer that states that I was incorrectly assuming that the A'N' pins were analogWrite() capable is correct. I definitely know I had current flow without need of a resistor, capacitor or other intermediaries. I made bold mis-assumptions as to what pins can do what.

This answer completely misses the issue. No, you do not need the pin to source current in order to have a well defined voltage. And your 1 µF capacitor can damage the output pin due to the inrush current.

@EdgarBonet Srry, it should be .1uf. So do you mean to use analogueRead() and read a PWM value insted of a real analogue voltage between 0v and 5v.

You wrote: “do you mean to use analogueRead() and read a PWM value [...]”. No, I mean what I wrote, nothing more.

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


text:
Sending string over serial to nodejs app. Why does it get chunked?
I'm sending a string from my sketch over Serial port as follows:
Serial.println(F("Found ILI9341 LCD driver"));

On the other side, I have a nodejs app using the serialport npm module, with something like this:
var SerialPort = require('serialport')
var serialPort = new SerialPort('/dev/ttyACM1', {
  baudrate: 9600
})

// it opens the connection and register an event 'data'
serialPort.on('open', function () {
  console.log('Communication is on!')
})

// when your app receives data, this event is fired
// so you can capture the data and do what you need
serialPort.on('data', function (data) {
  console.log('data received: ' + data)
})

Communication works, but on nodejs side I get the output chunked, as if it had line breaks, like this:
Communication is on!
data received: Pa
data received: int!
data received:

data received: Fou
data received: nd I
data received: LI93
data received: 41 L
data received: CD d
data received: rive
data received: r

Why does this happen?

It seems I needed to add a parser to SerialPort nodejs module, in order to specify how the input should be treated.
I changed my code to this:
var SerialPort = require('serialport')
var Readline = SerialPort.parsers.Readline

var serialPort = new SerialPort('/dev/ttyACM0', {
  baudrate: 9600
})

var parser = new Readline()
serialPort.pipe(parser)
parser.on('data', function (data) {
  console.log('data received: ' + data)
})

serialPort.on('open', function () {
  console.log('Communication is on!')
})

Basically, I'm specifying a Readline parser, which matches with the Serial.println function calls on my arduino sketch. Now the console output works as expected:
Communication is on!
data received: Found ILI9341 LCD driver

You do not need to pipe(): you can new SerialPort('/dev/ttyACM0', { baudrate: 9600, parser: Readline("\r\n") }).

@EdgarBonet I'm not sure about that, because according to https://www.npmjs.com/package/serialport#module_serialport--SerialPort.parsers you need to register for the 'data' event in the parser, not the port, so you need the reference to the parser to do a parser.on('data', yourFunction). Recommended usage seems to be using pipe().

You are right. I was using an older version of the serialport module that doesn't work in the same way. Sorry for the confusion.


text:
UECIDE: linker error with U8g2 library
This sketch:
#include <SPI.h>
#include <Wire.h>
#include <U8g2lib.h>

//  OLED display.
U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
void setup() {
  u8g2.begin();
}
void loop() {
}

Compile OK with Arduino 1.8.3, but under UECIDE 0.8.9-pre15 fails to link, with this message:
Compiling...
• Preprocessing...
• Compiling sketch...
• Compiling core...
‣ arduino
• Compiling libraries...
‣ U8g2 [/home/look/Documents/UECIDE/libraries/U8g2]
‣ SPI [/home/look/.uecide/libraries/Communications/arduino/SPI]
‣ U8g2 [/home/look/Documents/UECIDE/libraries/U8g2]
‣ Wire [/home/look/.uecide/libraries/Communications/arduino/Wire]
• Linking sketch...
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::write(unsigned char)':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:248: undefined reference to `u8g2_DrawGlyph'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::initDisplay()':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:101: undefined reference to `u8x8_InitDisplay'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::clearDisplay()':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:104: undefined reference to `u8g2_ClearDisplay'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::setPowerSave(unsigned char)':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:107: undefined reference to `u8x8_SetPowerSave'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:62: undefined reference to `u8x8_ascii_next'
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:62: undefined reference to `u8x8_ascii_next'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::home()':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:278: undefined reference to `u8x8_utf8_init'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2_SSD1306_128X64_NONAME_1_HW_I2C':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_cb_r0'
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_cb_r0'
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_Setup_ssd1306_i2c_128x64_noname_1'
collect2: error: ld returned 1 exit status
Compiling Fail

Both IDEs are set for Arduino Pro Mini 3.3V 8Mhz. In UECIDE I'm using GCC 4.9.2 for AVR. I copied the same U8g2 source code to both Arduino and UECIDE own libraries directory.
U8g2 library is version 2.15.2 by Oliver, installed via Arduino IDE and copied to the UECIDE libraries directory,
The problem, so far, only happens with U8g2 and not other libraries.
How do I solve this problem?

Can you provide a link to the exact version of U8g2 library you are using?

I'm using U8g2 library version 2.15.2 by Oliver, installed via Arduino IDE and copied to the UECIDE libraries directory,

Got it.  The layout of that library is a complete mess and uses a non-standard folder layout that UECIDE doesn't like. It's simple enough to clean it up though. I'll show you how.

The layout of that library is in a non-standard format with folders that UECIDE doesn't know to look for or how to deal with.
The main culpret is the inclusion of big chunks of code in a "clib" directory (why on earth?!?!) which doesn't get included in the compilation. Then on top of that you have header files in there that are referenced both from inside it and outside it.
The simplest fix is just to copy and move the files to better locations:
$ cd ~/Documents/UECIDE/libraries/U8g2/src
$ mv clib/*.c .
$ cp clib/*.h .

Note you move the source, but copy the headers. That's to get around the problem of the headers being referenced from two locations with relative paths.
The problem stems from UECIDE having (by necessity) much stricter rules than the Arduino IDE over the layout of a library. This is to facilitate better identification and categorization of the libraries so that recursive dependency detection can take place.

But UECIDE is just applying Arduino own rules about libraries, not inventing new ones. Am I right?

Arduino IDE is very lax with its rules. UECIDE is far more strict in what rules it applies. UECIDE applies what the Arduino specifies, but because Arduino doesn't really care people don't always follow those rules. They made it more complex and woolly by adding this new library format for cross architecture libraries which is just plain nasty.

Another big part of the problem is that, because the Arduino IDE has been so flippant with its own rules those rules have actually never been strictly defined anywhere. So it's very much a "best guess" as to what should and shouldn't be done. For instance: when do you recurse a source folder and when don't you? In an old library format you mustn't, because the source folder is the root. In the newer 1.5.x format you maybe could, but should you? It's not defined.

I am working on improving the file finding routines for libraries - get it to work better for newer style libraries.


text:
12V from Arduino Uno
I don't think it's possible, but I want to drive my 433 MHz transmitter (FS21000A) from a 12V 'supply', to get more power (and thus more range).
However, I don't have an external power supply. I can add an adapter (12V/1A) to my Arduino with the barrel input, but I wonder where to get 12V from? I only see 5V or 3.3V outputs.
And as far as I know all GPIO output 5V ... so how can I get 12V (or maybe a bit less but more than 5V) out of an Arduino? (and what safety measurements I should take to not ruin my Arduino?)

VIN is the barrel jack less one diode drop.

So VIN is more like an output (to give power to external components)?

It is neither input nor output. It just is. Power has no concept of in or out.

Ok clear,  going to use it now

What transmitter is it?

It shows RF-5V, but it looks like the small right component in http://uploads.avc-shop.de/uploads/ebay/bilder/mhzsender-1402092733-21335.jpg

Oh, one of those. They're pretty naff really. Have you tried adding a 1/4 wavelength dipole to it?

@Majenko ... not yet ... I think I'm going to try it with two ... also ordered some (cheap) antennas for it to solder on ... I just bought these 433MHz to check, I hope in my project I can use nRF24L01 2.4 GHz, which are much faster (and hopefully more range). But if I get these to work to like 10 meters or so I can find some nice use for it later (and it's all part of learning about RF/electronics too)

I have got hundreds of meters from the nRF24L01+ modules with build in LNA and power amplifier. They work well.

@Majenko ... I ordered long time ago a cheap set of 5 ... still haven't received them but no problem to wait ... However, yesterday I ordered two with antennas and PA+LNA, think that is what you mean? https://www.aliexpress.com/item/1sets-Special-promotions-2-4G-wireless-modules-1100-Meters-Long-Distance-NRF24L01-PA-LNA-wireless-modules/32787846044.html?spm=a2g0s.9042311.0.0.97LZRv

Yep, that's the ones.

I think I will get the ultra-cheap ones first, so I can already experiment with those (in close range, like max 50 cm), I hope to get error-free communication with some speed with the PA+LNA ones.

@Downvoter, can you instead of downvoting all my posts, explain WHY you downvoted, so I may improve the post.

In crude terms the power supply of the Arduino is along these lines:

simulate this circuit – Schematic created using CircuitLab
It's actually more complex than that, especially concerning the USB power input, but that doesn't matter here.
As you can see the barrel jack (your 12V supply) first goes through a diode. Then it gets fed to the 5V regulator. The VIN pin also goes to the same pin of the 5V regulator, so it will see 12V minus the voltage drop of the diode (~0.7V).
So you can provide 12V to the barrel jack and use the VIN pin as an 11.3V supply.

It worked, thanks... however, I don't see any range increase (and also noticed I cannot upload a sketch while both USB and adapter are plugged in at the same time.
But I learnt something (again).. thanks again!

I want to drive my 433 MHz transmitter (FS21000A) from a 12V 'supply', to get more power (and thus more range).

that only works if the transmitter works at 12v and isn't powered through a regulator.
if not, applying 12v to it does nothing but generating some heat or damage, worse yet.

The transmitter is indeed able to work from 2-12V, and I according the scheme of Majenko the regulator is not going out of VIN (unless the regulator is in de adapter itself).
I checked, it worked, however, I don't see any noticeable gain.


text:
How to measure resistance of TFT Touchscreen
I'm using a TFT Touchscreen shield with my Arduino UNO, and I'm running "tftpaint" example by Adafruit.
I've noticed that when initializing the Touchscreen object, a resistance value must be provided. Library default is 300, but a comment in the code says:
// For better pressure precision, we need to know the resistance
// between X+ and X- Use any multimeter to read it

How should I perform such measurement? Where do I put the probes of my multimeter? FYI, my shield is this one:

Would you care to provide a link to the datasheet or at least provide the name of the TFT? The code clearly states X+ and X-, it's not as easy as the board having two pinouts named as such is it?

I couldn't find a datasheet for this particular shield. The board does not show pins labeled like that, but the hint to that was actually in the code, in variables named "XP" ("X Plus") and "XM" ("X Minus). I'll expand this in an answer of my own.

As pointed out in other answers and comments, step one was trying to get a datasheet for this component. I couldn't find a datasheet for the shield, but here is the link from the vendor I bought it from, and they provided with some articles were they explained how to perform the resistance measure. However, I then noticed the answer was in the example code itself.
Btw, the shield it's indeed based on SPFD5408 as correctly suggested by user Michel Keijzers on his answer.
So, in turns out the hint to which pins were X+ and X- was actually in the example code I'm using. Here the Touchscreen object is initialized:
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

Notice the usage of constants XP and XM. The names stand for "X-plus" (X+) and "X-minus" (X-). Now if we look a couple of lines above where these constants are defined, we see this:
#define YP A3
#define XM A2
#define YM 9
#define XP 8

In particular, we see that XM (i.e. "X-") is mapped to analog pin A2, and XP (i.e. "X+") is mapped to digital pin 8.
Now, by looking at how the shield couples with arduino, we can see that analog pin A2 of the Arduino board, connects with pin labeled "LCD_RS" in the shield, and that pin 8 connects with pin labeled "LCD_D0".
This is a picture (found online) of the bottom side of the shield, were we can see the labels for each pin:

Finally, with a multimeter at those pins, I measured the resistance and it was 292 Ohms. Not so different from the default of 300 in the library, but it's still a good thing to have the correct value.

If this was the correct answer then please mark it as accepted (button below the down arrow).

Your TFT seems like this: TFT LCD SPFD5408
I cannot find a datasheet, but normally the X+ and X- are shown on the device... if not, try to find the datasheet and look for the pin numbers.

Thanks, it is indeed based on SPFD5408. FYI, the link you provided points to a wireless module, not this TFT LCD display. X- and X+ where not shown on the device, but the hint to which pins they map was in the code.


text:
Menu with switch case not behaving correctly
I hope this the right place to post this question :)
I'm trying to display a menu on a SSD1351 OLED display, to which I communicate with U8glib. I'm trying to obtain an Init screen, then, with a long press on a button (Menu), get in to a menu with 3 options (let's say option1, option2 and back). I got it working this way:
#include <Button.h>  // https://github.com/JChristensen/Button.git
#include "U8glib.h"
#include <Wire.h>

#define PULLUP true
#define INVERT true
#define DEBOUNCE_MS 20

Button ok(2, PULLUP, INVERT, DEBOUNCE_MS);
Button menu(5, PULLUP, INVERT, DEBOUNCE_MS);
Button down(3, PULLUP, INVERT, DEBOUNCE_MS);
Button up(4, PULLUP, INVERT, DEBOUNCE_MS);
U8GLIB_SSD1351_128X128_332 u8g(8, 9, 7);
uint8_t screen = 0;
uint8_t menu_current = 0;
void setup() {
  u8g.setFont(u8g_font_unifont);
  u8g.setDefaultForegroundColor();
  drawScreen();
}

void loop() {
  ok.read();
  menu.read();
  up.read();
  down.read();
  if (menu.pressedFor(1000) && screen == 0) {
    screen = 1;
    menu_current = 0;
    drawScreen();
  }
  if (screen == 1) {
    if (up.wasReleased()) {
      if (menu_current > 0) {
        menu_current--;
        drawScreen();
      }
    }
    if (down.wasReleased()) {
      if (menu_current < 2) {
        menu_current++;
        drawScreen();
      }
    }
    if (ok.wasReleased()) {
      switch (menu_current) {
        case 0:
          screen = 2;
          break;
        case 1:
          screen = 3;
          break;
        case 2:
          screen = 0;
          break;
          break;
      }
      drawScreen();
    }
  }
  if (screen == 2 || screen == 3) {
    if (menu.wasReleased()) {
      screen = 1;
      menu_current = 0;
      drawScreen();
    }
  }
}

void drawScreen() {
  u8g.firstPage();
  do {
    whatToDraw();
  } while (u8g.nextPage());
}

void whatToDraw() {
  switch (screen) {
    case 0: {
        u8g.drawStr(0, u8g.getFontLineSpacing(), F("Init"));
      } break;
    case 1: {
      const char *menu_strings[3] = { "option1", "option2", "Back" };
      uint8_t i, h;
      u8g_uint_t w, d;
      u8g.setFontRefHeightText();
      u8g.setFontPosTop();
      h = u8g.getFontAscent() - u8g.getFontDescent();
      w = u8g.getWidth();
      for ( i = 0; i < 3; i++ ) {
        d = (w - u8g.getStrWidth(menu_strings[i])) / 2;
        u8g.setDefaultForegroundColor();
        if ( i == menu_current ) {
          u8g.drawBox(0, i * h + 1, w, h);
          u8g.setDefaultBackgroundColor();
        }
        u8g.drawStr(d, i * h, menu_strings[i]);
      }
    }
    break;
    case 2: {
      u8g.drawStr(0, u8g.getFontLineSpacing(), F("Option1"));
    }
    break;
    case 3: {
      u8g.drawStr(0, u8g.getFontLineSpacing(), F("Option2"));
    }
    break;
    break;
  }
}

Everything seems to be working except the back option: when I select it, the display gets blanked instead of visualizing screen 0 ("Init"). Variables seem to be set correctly. Does anybody have an idea why this isn't working?
Thank you :)
Dario
EDIT: copied the whole sketch as requested :)

Please, post your whole sketch, so others can test your code.

I don't see any back option; only up, down, ok and menu. What button was that?

I didn't define a back back physical button. "Back" is one of the options visualized in the menu. I'd like to be able to select it (highlight it with up and down buttons) and click the Ok button, to revert to Init screen :)

Correct me. Your test case is: screen 0; press menu; screen 1; press down; press down; Press OK over option BACK and then screen goes blank?

I only miss an u8g2.begin(), but all your execution paths include a drawScreen() call, and you always put something in the screen. You don't modify global vars inside de drawScreen() and it's the only place where you touch the screen. Good problem.

Yes, that's exactly my test case :) if I try to print the variables in serial monitor, everything seems to be working fine, but the display blanks out...

The only way to get a blank screen is when screen is out of range. Just to be sure, why don't you check its value upon entry into whatToDraw. I run your  sketch in a simulation and your logic is OK.

BTW, I'm using u8g2, the new version. I tried to compile your code using the new library, and it didn't like using F("init") as argument. It accepts the simple string "init", however. May be there is a bug in your version, so change F("init")for "init"(and every other use of F()). May be ...

@LookAlterno I tried to remove the 'F()' caption but nothing changed.. I also tried to remove the 'u8g.getFontLineSpacing()' but nothing changed too :(
Then I tried to print on serial the 'screen' variable and, in the test case, it correctly prints '0' but I keep having this problem. I'd like to solve it, but a workaround would be cool too.. Thank you :)

Summary: I tested @noospy project (with some modifications) and it works flawlessly.

I had to rename Button.h to ButtonM.h due name conflict with another button library. Also, I'm using new version U8g2, so I had to change some types and eliminate some calls. Finally, I used the I2C version of the OLED screen.
This is my adapted code:
#include <ButtonM.h>  // https://github.com/JChristensen/Button.git
#include "U8g2lib.h"
#include <Wire.h>

#define PULLUP true
#define INVERT true
#define DEBOUNCE_MS 20

Button ok(2, PULLUP, INVERT, DEBOUNCE_MS);
Button menu(5, PULLUP, INVERT, DEBOUNCE_MS);
Button down(3, PULLUP, INVERT, DEBOUNCE_MS);
Button up(4, PULLUP, INVERT, DEBOUNCE_MS);

//U8GLIB_SSD1351_128X128_332 u8g(8, 9, 7);
// Screen
U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);

uint8_t screen = 0;
uint8_t menu_current = 0;

void setup() {
    u8g.begin(); // Added
    u8g.setFont(u8g_font_unifont);
//  u8g.setDefaultForegroundColor();

    drawScreen();
}

void loop() {
    ok.read();
    menu.read();
    up.read();
    down.read();

    if (menu.pressedFor(1000) && screen == 0) {
        screen = 1;
        menu_current = 0;
        drawScreen();
    }

    if (screen == 1) {
        if (up.wasReleased()) {
            if (menu_current > 0) {
                menu_current--;
                drawScreen();
            }
        }

        if (down.wasReleased()) {
            if (menu_current < 2) {
                menu_current++;
                drawScreen();
            }
        }

        if (ok.wasReleased()) {
            switch (menu_current) {
                case 0:
                    screen = 2;
                    break;
                case 1:
                    screen = 3;
                    break;
                case 2:
                    screen = 0;
                    break;
                break;
            }
            drawScreen();
        }
    }

    if (screen == 2 || screen == 3) {
        if (menu.wasReleased()) {
            screen = 1;
            menu_current = 0;
            drawScreen();
        }
    }
}

void drawScreen() {
    u8g.firstPage();
    do {
        whatToDraw();
    } while( u8g.nextPage() );
}

void whatToDraw() {
    switch (screen) {
        case 0: {
            u8g.drawStr(0,getFontLineSpacing(),"Init");
        } break;
        case 1: {
            const char *menu_strings[3] = { "option1", "option2", "Back" };
            uint8_t i, h;
            int w, d;

            u8g.setFontRefHeightText();
            u8g.setFontPosTop();

            h = u8g.getFontAscent()-u8g.getFontDescent();
            w = u8g.getWidth();
            for( i = 0; i < 3; i++ ) {
                d = (w-u8g.getStrWidth(menu_strings[i]))/2;
//                u8g.setDefaultForegroundColor();
                if ( i == menu_current ) {
                    u8g.drawBox(0, i*h+1, w, h);
//                    u8g.setDefaultBackgroundColor();
                }
                u8g.drawStr(d, i*h, menu_strings[i]);
            }
         } break;

         case 2: {
             u8g.drawStr(0,getFontLineSpacing(),"Option1");
         } break;

         case 3: {
             u8g.drawStr(0,getFontLineSpacing(),"Option2");
         } break;

         break;
    }
}

int getFontLineSpacing() {
  return 24;
}

Hardware

Arduino Pro Mini 3.3v 8MHz
1306 0.96 inch White Color I2C IIC Communication 128 * 64 OLED Display.
4x push buttons with 1K pullup resistors.

So, I don't know what your problem is, but your code is impecable.

Thank you! Well, at least now I know it's not a coding issue. I'll try with your same hardware and report back!

You can consider using one of the existing menu libraries, there are some available on github. Just pick the one that best fits your needs
https://github.com/search?utf8=%E2%9C%93&q=arduino+menu&type=


text:
Change Token authentication method to MQTT authentication method(username, password, client_id, ssid, passwd)
I have a mq135 sensor abd nodemcu ESP-12E module to calculate air quality and monitor it via Cayenne platform.
How can I edit this below code to add and connect my Nodemcu ESP-12E module to cayenne with MQTT authentication(username, password, client_id, ssid, passwd) method?
We can’t add Nodemcu with token method, we should use MQTT authentication instead to add and connect nodemcu module to cayenne.
 #include “MQ135.h”
 #include “CayenneDefines.h”
 #include “CayenneWiFi.h”
 #include “CayenneWiFiClient.h”
 #define CAYENNE_DEBUG
 #define CAYENNE_PRINT Serial
 #define VIRTUAL_PIN 5
 #define ANALOGPIN A0

char token[] = “”; // Insert your token here
char ssid[] = “”; // Insert your SSID here
char pwd[] = “”; // Insert your SSID password here
MQ135 gasSensor = MQ135(ANALOGPIN);

void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Cayenne.begin(token, ssid, pwd);
}

void loop() {
// put your main code here, to run repeatedly:
Cayenne.run();
// float rzero = gasSensor.getRZero(); //this to get the rzero value, uncomment this to get ppm value
// float ppm = gasSensor.getPPM(); // this to get ppm value, uncomment this to get rzero value
// Serial.println(rzero); // this to display the rzero value continuously, uncomment this to get ppm value
// Serial.println(ppm); // this to display the ppm value continuously, uncomment this to get rzero value
// Cayenne.virtualWrite(VIRTUAL_PIN,ppm); // uncomment after rzero define and get your ppm calculation
}

You could have readily answered this question for yourself merely by looking at the example for the Cayenne-MQTT-ESP8266 library.
The key part being:
// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = "MQTT_USERNAME";
char password[] = "MQTT_PASSWORD";
char clientID[] = "CLIENT_ID";

Cayenne.begin(username, password, clientID, ssid, wifiPassword);

It is not readily possible to know if this is the same Cayenne library you were using before, as you neglected to specify what you were using.  The includes are different, but that could be a version difference, or it could be evidence of an entirely different approach.


text:
Arduino and 2 MOSFETs
I want to turn on 2 bulbs using 2 MOSFETs. The problem is that they both turn on when it should turn up just one light.
Code:
void setup() {
  pinMode(13, OUTPUT);
  pinMode(7, OUTPUT);
}

void loop() {
  digitalWrite(13,1);
  digitalWrite(13,0);
}

See circuit below:

What sort of MOSFETs are they? (part numbers)

Try adding a delay into your loop. In your code pin 13 will toggle very rapidly, much too fast to see it. For example:
void loop() {
  digitalWrite(13,HIGH);
  delay (1000);
  digitalWrite(13,LOW);
  delay (1000);
}

It doesn't look wired correctly. For an N-channel MOSFET the Source should go to ground, like this:

The following circuit diagram works perfectly.

i prefer you to use relay to control any ac appliance with arduino it very much safe...
Just follow this circuit diagram and use 5v relay in your project it will always work fine.....

I fail to see how this can help. OP is not attempting to control an A.C. appliance, the diagram clearly shows that they are D.C. Also, the OP has no button in their circuit, so that is completely superfluous.


text:
ATmega328p - ISC00 with INT1?
I was reading about external interrupts using the ATmega328p, and I saw in the chip datasheet under the paragraph "Bits 3:2 – ISC1n: Interrupt Sense Control 1 [n = 1:0]" the following table:
Value | Description
------+------------------------------------------------------------
00    | The low level of INT1 generates an interrupt request.
01    | Any logical change on INT1 generates an interrupt request.
10    | The falling edge of INT1 generates an interrupt request.
11    | The rising edge of INT1 generates an interrupt request.

From what I understand from the table title and the definition in the datasheet that ISC1n where n=1|0, is dedicated for INT1. And that ISC0n where n=1|0, is dedicated for INT0. However, in the table above, the value 00 is described as "The low level of INT1 generates an interrupt request.".
What I don't understand is how can ISC0n where n=1|0 be dedicated for INT0 but in the table above the value 00 (or ISC00) is used for INT1 ? I could totally be missing something but I would appreciate any guide.

From what I understand from the table title and the definition in the
  datasheet that ISC1n where n=1|0, is dedicated for INT1. And that
  ISC0n where n=1|0, is dedicated for INT0.

This is correct.

[...] in the table above the value 00 (or ISC00) is used for INT1

This is your misunderstanding. The value "00" in the table does not mean
ISC00. The "Value" column of the table is the value you get by
concatenating the bits ISC11 and ISC10. Thus:

"Value = 00" means ISC11 = 0 and ISC10 = 0
"Value = 01" means ISC11 = 0 and ISC10 = 1
"Value = 10" means ISC11 = 1 and ISC10 = 0
"Value = 11" means ISC11 = 1 and ISC10 = 1

Ohh I understand it now! Edgar that's an amazing explanation! Thank you so much!

It's a typo. My revision of the datasheet (revision G) properly says "INT0".

Thanks for your quick reply!!! Where can I find the newest version of the PDF, Google seems to index the one with the typo first ?

The latest revision of any Atmel datasheet is available from Atmel's website. I have confirmed that revision B of the 328/328P datasheet does not have that typo.

Cool I'll check on their website. Thank again!

I think this is it: ATmega48A/PA/88A/PA/168A
/PA/328/P DATASHEET - revision J.

Atmel split the 328/P parts into a separate datasheet recently (for a certain definition of "recently").

Revision B of the Complete datasheet of the ATmega328p has the same type, but some more recent PDFs like the one posted by @NickGammon does not. Thank Nick for the link!

Atmel-42735B-ATmega328/P_Datasheet_Complete-11/2016? I'm not seeing the typo there, unless I'm looking in completely the wrong place.

In the PDF at http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf, page 89 (Both tables)

I'm seeing "INT0" in the table on that page, under "Bits 1:0 – ISC0n".

Correct, but in "Bits 1:0 – ISC0n" table they also put "Value: 10, Description:
The falling edge of INT0 generates an interrupt request" that what confused me

I'm not seeing what's wrong with that. ISC0n is about INT0, and 0b10 means an interrupt on a trailing edge.

From what I understand from this PDF: ISC00, ISC01, ISC10 and ISC11 can be for both INT0 and INT1. However, the newer PDF mention: ISC00 and ISC01 is for INT0. And ISC10 and ISC11 are for INT1

The register descriptions explicitly state that ISC1n is for INT1 and ISC0n is for INT0 in the first two sentences of the first paragraph of each.

Yup, you're right, just the tables contradicted those statements. But it's good I know it's fixed in the newer revision. Thanks again!

Thanks again guys for the help, Edgar in his answer saw where my mistake is.


text:
Convert from 3 V to 5 V
I'm new to Arduino, electronics, and this forum.
I have made up a little project that connects an HC-SR04 ultrasonic range detector, and displays the distance on a 4 digit, 7 segment LED display.
When I have it plugged into my laptop for power, it runs beautifully on an Uno board.
But I want to mount all this in a Nerf gun (Nerf N-Strike Elite Firestrike) using a Nano board.
The Nerf gun has a built in "laser" (red light) that is powered by 2 x AAA batteries, which makes 3 V, I think. I want to rig this up so that pulling the laser/light trigger also triggers the range detector and display.
I want to run the range sensor and the display off the Nerf guns batteries, but they both use 5 V. Is there a way to do this? Or do I need a separate 5 V power supply?

I cannot answer the question as asked.  I don't know of a way to convert 3V to 5V.  Arduinos run better at 9V anyway.  You are probably going to want 9V battery for an Arduino Nano to mount in the Nerf gun.  Have you considered this?

Yes, I have considered a seperate power supply. Maybe a 9v battery powering the nano is the way to go.

You may want to use a boost converter which is a device that can step up voltage.
You can get them from eBay for around $US 2.

As Chris Stratton pointed out in a comment, the boost converter may run your batteries down quite quickly. Let's say you need 200 mA for your Uno, sensor and LEDs. At 5V power that is 1W of power (0.200 * 5).
However to get 1W from 3V you would consume 333 mA (0.333 * 3). Then take into account that the converters are not completely efficient. Let's say the converter has 90% efficiency. Then you need to multiply the current by the inverse of the efficiency, that is: 0.333 mA / 0.9 = 0.37 mA.
Another factor is the battery type. If you use NiCad batteries their nominal voltage is closer to 1.2V than 1.5V, especially after you have been using them for a bit. Ditto for NiMh batteries.
Reworking the above for 2 * 1.2V (2.4V) we see that the current will be:
1W / 2.4V = 0.4167A
0.4167A / 0.9 = 0.463A (allowing for 90% efficiency)

Now it potentially draws close to half an amp when active. Your batteries might not be able to handle that for long.

This is possibly, a solution, but may place a lot of load on the little AAA batteries, as the current drawn at the input voltage is the current needed at the output voltage multiplied by the ratio and the reciprocal of the conversion inefficiency.

Indeed. Still, to meet the requirements of the question it could work (for a while). I've edited the question to do some maths for the current draw.

All this math makes my poor head hurt.

Just to suggest an alternative, and more energy efficient, solution...
There appear to be newer versions of the HC-SR04 on the market that support 3.3V, such as the HC-SR04 v2 - Low Cost Ultrasonic Sensor (3V to 5V Supply).
So you could use an Arduino Pro Mini designed to run at 3V in conjunction with the 3.3 V HC-SR04, and run it straight off your nerf gun's power supply.

However, it might be worth taking these new versions with a pinch of salt, as modules seem to vary from one to another, see Re: Do HC-SR04 5V rangefinder sensors work in 3V battery mode?

I have a MKRFOX1200 working with HC-SR04 and it works fine. It is stated to work only at 5v but its fine with 3V. But I have another one (SF-SR02) with a higher range (6meters) and this one doesnt get any further than 1  or 2 meters under 3V. If I use the 5V for VCC while running on USB, it reaches full range. Digital inputs seem to be more tolerant than they state for 5V signals.. (although I'm not advising to do so!!)

An extremely useful comparison of these modules (the first generation) running at both 3.3 and 5 V can be seen here, Re: Ultra cheap ultrasonics, and a bit of a challenge:
3V3

5V

Notwithstanding, the newer versions of the HC-SR04 may have an improved response.

Arduino nano also have 5v-3.3v voltage regulator so you can power all this with only one power supply (power your arduino nano with 6x AAA batteries) and then just connect your nerf gun power with arduino nano 3.3v pin, it will work just fine............
                                      :)

I like this option. Rather that running the Arduino off the guns power, run the gun off the Arduino's power. Still means I need to put in more batteries. I was hoping to fit everything inside the Nerf gun, but that might not be possible. Or I just buy a bigger Nerf gun.

This is a very good solution.  And yes, they make bigger Nerf guns.  But also keep in mind that the Nerf gun is going to shoot much further than the ultrasonic sensor can measure.  While this is an interesting project, it may not turn out to be useful.

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


text:
Arduino Mega Timer1 in pure C problem - doesn't work
Does somebody know what can be wrong in this, where I try to set Timer1 interrupt in Arduino Mega in C code only. I'm trying CTC Mode and the purpose is LED blinking with 1[s] Period.
I work with documentation program doesn't work completely.
 #include <avr/io.h>
 #include <avr/interrupt.h>

 void setup()
 {
   //LED -> PB7 (Digital pin 13
     DDRB |= (1<<PB7);

  //FCPU = 16MHz, Prescaler :256 | CTC
   TCCR1B |= (1<<CS12) | (1<<WGM12);
   TIMSK1 |= (1<<OCIE1A);  // Compare Match A interrupt allowing
     OCR1A = 62500;

    sei();
    }

  void loop()
  {

   }

   ISR(TIMER1_COMPA_vect)
   {
     PORTB ^= (1<<PB7);
    }

Where is your main procedure? For toggling you can use PINB = _BV(PB7); // or (1<<PB7), for setting up timer you can use assigments directly, as you don't care about previous values...

Actually you should use assignments. The Arduino core library configures timer 1 for its own purposes (for phase-correct PWM at 490 Hz), so you should set both TCCR1A and TCCR1B to whatever suits your application, and not rely on their previous values. Alternatively, if you are not using the core, you could write your own main(), which would skip the Arduino hardware initialization.

Btw the arduino IDE requires using setup() and loop() section as a main(). So you suggest using "=" instead of  "|=" regarding to preliminary arduino settings?

So that "pure C" doesn't really mean you have simple *.c file with everything? You have *.ino and you're just using registers directly? Then yes, you have to make sure everything for Timer1 is in correct states. For example all counters are configured to the 8bit fast PWM mode and setting WGM12 doesn't change anything as it's already set.

Ok, ok. I catch it. To be clear. I'm want to code in pure C but using Arduino IDE. So It requires specific arduino's program structure with setup() and loop(). And apart from it, everything is as a normal pure C language, working with uC registers not with arduino's libraries. That's my purpose.

You wrote: “the arduino IDE requires using setup() and loop()”. No, the IDE does not require setup() and loop(), the Arduino core library does. You can use the Arduino IDE and write your own main() if you don't need the functionality from Arduino core. And that's the closest you can get to “pure C” with the Arduino IDE (but technically it's C++).

Edgar Bonet, Ok. But Is using just main() instead of setup() and loop(), possible with bootloader? Doesn't Arduino's bootloader need those 2 arduino's loops()? I'm not sure, I'm just asking. I need to programme via bootloader not via external programmator.

@M_K No, the Bootloader is completely unrelated to the main program. Bootloader waits short time to the control characters and if there are none, it just jumps to the address 0000H (there are few more steps, but that jump is the most important)

I work with documentation program doesn't work completely.

simple:
1) check out the datasheet;
2) identify those registers needed to get tmr1 to work;
3) set or clear, as appropriate, ALL bits that are needed. Do NOT rely on default values.
4) done.


text:
Arduino language
I'm learning with my school Arduino and how to use it etc.
I know Swift and a little bit of HTML and I would like to learn Arduino language, because I think it's easy!
What are the best resources for learning Arduino?
What are the best programs to write Arduino?
Thanks!

As FYI, there is a free/commercial Swift for Arduino available. I've not tried it ... yet. Just noting the option.

I would like to learn Arduino language, because I think it's easy!

it is C/C++.

Ok....  I dont know why, but when im writing Arduino, its not that hard like c/c++ .   Thanks

Maybe you find it easy because you have never written anything complex in it. And as arduino atmel chips are limited in memory, you wont write there complex applications...

@Divisadero οκ. I understand this. I have wrote complex code..   I have connected to an Arduino UNO an thermal censor, a temperature-humidity censor and a 16pin LCD 11x8 (I think, or 11x6 :)) ).   This code was my most complex. (I am learning Arduino with my school for almost a year.)

@AlexKordatzakis Do not take it personally, but what you have mentioned are not complex projects at all. I guess you have used the libraries for these projects. I suggest you look into the libraries and try to understand them.

@Divisadero 1st. I'm not taking it personally. :))   2) I didn't said that I have wrote the most complex code in Arduino..   3) For the libraries, should I download the arduino program, or just browse them?

'Arduino program' is Arduino IDE [integrated development environment]. Here is some documentation for libraries: https://www.arduino.cc/en/reference/libraries and here is some source code https://github.com/arduino/Arduino/tree/master/libraries You can find more directly in Arduino IDE folders.

To begin as a newbie get started with the inbuilt examples that are already given.You will learn one by one and its easy to understand anyways.Try few simple codes like LED BLINK,LED WITH SWITCH, SENSOR INPUT AND OUTPUT USING SERIAL MONITOR and you will get used to with the ARDUINO IDE.
Ofcourse the best site is www.arduino.cc but try few pdfs for Arduino beginners which are available on the internet.Try youtube if you are having any trouble working out with just text information.
Go through the book "ARDUINO PROJECTS FOR DUMMIES"
LINK: http://www.dummies.com/store/product/Arduino-Projects-For-Dummies.productCd-1118551478.html
check out this link:
http://www.makeuseof.com/tag/getting-started-with-arduino-a-beginners-guide/

I guess Arduino is not the best language to learn as a beginner if you are interested in programming. Try Python, C#, JavaScript. Or directly C++ (which Arduino is actually).
Arduino has too specific usage and is limited. You wont use OOP here very often and will miss a lot of programming principles and practices.

Ok. But I'm already learning. 2 Languages. I started with Swift and now I'm in HTML.  I will stop here, and when I learn very smoothly to use these two languages I will move to C++. What do you think?

Yeah, sorry, I havent't noticed Swift. My bad.

Is it good you mean?

It is not about being good or bad language. Who am I to say if one programming language is better or worse. But one can say if language is suitable for getting into programming for beginners. For me, personally, C# seems to be best for beginners. It is powerfull enough to learn you OOP, you can try design patterns and .NET contains enough frameworks to try client applications, web and SOA programming. Compared to C++ it abstract more difficult concepts you can grasp later. On the other hand, python seems to be to be too flexible for beginner.

I appreciate for giving me these advices!  But now I have to learn two languages and I like these languages.. thank you for the help anyway!!

Sure, I was talking in general. Acutally I have only basic knowledge about swift (as it targets apple), but I guess it is suitable as well. Good luck on your path.

Best resources:

Official website: www.arduino.cc
This site (duh)

I don't know what you mean with 'best programs' ... that depends on what you want. My 'best program' is probably not your 'best program'


text:
MAX7219 powered on via digital pin set to HIGH is not working good (I < 25mA)
I'm using 7-segment 8-digits MAX7219 eBuy module in my battery-supplied ATMega168P project to output some readings. MAX7219 in powerdown mode draws ~150uA (as stated in the datasheet) which is too much for me, because the rest of the circuit draws less than 1uA is sleep mode. So I decided to power off Vcc line for MAX7219 before entering sleep, and power it on just after wakeup.
Current draw for the software-dimmed display module is only 15..19 mA in my case, which is far less than 40mA pin maximum for ATMega168P, so I connect display Vcc line to one of digital pins and power it on at setup():
void setup()
{
  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);
}

However, display module works only 1..3 seconds after starting, then switches off. I checked display Vcc — 4.9V, but the display is off. (I turned off enterng to sleep mode for a while)
This display module doesn't have capacitors C3 and C4 between Vcc and GND (but there's a placeholder for it), recommended in some sources. I solder two capacitors of 100nF and 4,7uF in parallel. It helps only a little: after 1..2 seconds of normal working display shows only digit #0 and in much higher brightness than I set (see the photo).

I may only suggest my cheap multimeter is wrong and the display draws much more, but I dont know how to check it. Rset is 10k on this module, btw.

Why does it happen?
Is there a way to solve the issue without using a transistor / MOSFET / relay (I suppose it should obviously help).

EDIT: If the display is powered directly by controller Vcc it works correctly as expected. It's current draw is 15..20mA.

Well, the average current might be about 20mA. But peaks will be much higher. Simple mosfet for switching power will be much better.

Thanks, @KIIV ! This is obvious solution and I'm going to try some 2N3904 as a power switch here. But I'd like to understand the reason of issue: high current draw or some noise from ATMega168 pin or smth else...

After some research I eventually solved my problem, so here's the answer.

Why does it happen?

This LED display draws much more current than I measured on Vcc line between Arduino and display because of ghost powering via signal lines (DIN, LOAD, CLK). The display (although slightly dimmed) can even run without Vcc line connected! Real current draw was about 30-40 mA with peaks up to 100 mA.

Is there a way to solve the issue without using a transistor / MOSFET / relay (I suppose it should obviously help).

Yes, by limiting display current draw.
For an unknown reason these cheap MAX7219-driven LED boards has very small current control resistor RSet of 10 kOhm, resulting in huge Iseg ~= 40 mA. Replacing it by something like 62k will limit per-segment current to ~10 mA.
This is what the datasheet says:

And this is how it can be done:

Works perfectly! Now I can power off LED display completely, so it consumes no current when the device is sleeping.
NOTE: it's important to properly re-initialize MAX7219 after power on!
In the colorized table above one could find display current draw for different software-set intensity settings in case of using RSet = 62k. GND line values (blue column) seems to be correct as they well correspond with overall device's current draw (the most correct measurement, I suppose).

Using a led display in a low current application is an oxymoron. An LCD display is more appropriate.
With that said, you can switch the the 7219 from the high side and turn the pins into input mode to avoid ghost powering.
Od mode works but pull up has to be switched as well.

Thanks for replay!
Sorry, what is "od mode" and what kind of pull up you mean here?
I do digitalWrite(LOW) for display data pins now to avoid ghost-powering. Is it enough or I'd better change pin mode to INPUT?


text:
Get hour with ctime (time library with ESP8266)
#include <ESP8266WiFi.h>
#include <time.h>

const char* ssid = "";
const char* password = "";
int timezone = 3;
int dst = 0;

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("\nConnecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }
  configTime(timezone * 3600, dst * 0, "pool.ntp.org", "time.nist.gov");
  Serial.println("\nWaiting for time");
  while (!time(nullptr)) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println("");
}

void loop() {
  time_t now = time(nullptr);
  Serial.println(ctime(&now));
  delay(1000);
}

This is my code, but it shows the time like this: Sun Jul 23 15:21:12 2017. But what I want it to do is to only show the current hour, not everything.
Is it possible to do that?

Use gmtime() or localtime() instead of ctime(). Print the hour field tm_hour in the struct tm.

Welcome to the site. Next time for aligning code, select code and press ctrl+k

@MikaelPatel I am a beginner at this, could you please give me an example of how it should look like?

@MikaelPatel Okay i tried this Serial.println(gmtime(tm_hour)); but i get an error "'tm_hour' was not declared in this scope"

Here is an example of gmtime() and the struct tm; http://www.cplusplus.com/reference/ctime/gmtime/

The easiest way is to use the standard function localtime() or gmtime() and the struct tm.
void loop() {
  time_t now;
  struct tm * timeinfo;
  time(&now);
  timeinfo = localtime(&now);
  Serial.println(timeinfo->tm_hour);
  delay(1000);
}

Nice example thank you.


text:
Reading values from TTP229 capacitive touch sensor on arduino
I would like to be able to read the raw capacitive sensor values from a TTP229 chip through i2c in Arduino. I have one of these breakout boards to play with :

My goal is to get values similar to those of the MPR121 or the Capacitive Sensor Arduino library where the reading changes depending on proximity and how hard you touch the pads. I have tested the following code but I'm only able to detect an on / off reading.
#include <Wire.h>
#define ttp229 ( 0xAF>>1 )

uint16_t data_out = 0;
uint16_t data1, data2;
int count = 0;
boolean count2 = false;
int button[16];
int oldata[16];

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

void loop()
{
    Wire.requestFrom( ttp229, 2, true );
    //delay(1);
    while( Wire.available() )
    {
        data1 = Wire.read();
        data2 = Wire.read();
        data_out = (data1<<8)|data2;

        for(int i=1;i<17;i++)
        {
            uint16_t contrast = 0x8000;
            if(data_out & contrast)
            {
                //Serial.println(i);
                button[count]=i;
                count++;
            }
            data_out<<=1;
        }
        if(count2)
        {
            switch(count)
            {
                case 1:
                if( oldata[0] == button[0] )
                {
                    Serial.println( button[0] );
                    delay( 20 );
                }
                break;
                case 2:
                if(oldata[0]==button[0]&&oldata[1]==button[1])
                {
                    for(int i = 0; i < 2; i++)
                    {
                        Serial.print( button[i] );
                        Serial.print("  ");
                    }
                }
                break;
            }
        }
        for( int i = 0; i < 16; i++ )
        {
            oldata[i] = button[i];
        }
        count = 0;
        count2 =! count2;
    }
}

Even if i just print out data1 and data2 from the example it doesn't seem to produce readings that change with the capacitance. I originally thought this was a hardware limitation but then I came across this TTP229 product that has a linear touch sensor built into it.
Does anyone have any experience with this sensor and how I can access the raw readings?

I am afraid, the product you referenced seems to have 8 discrete pads underneath the slider. So I suppose, they really read out those 8 steps only. Check the images that show the device from the bottom side. This doesn't answer your question directly, but I still hope it helps.

mpr121 gives raw values
it has 12 electrodes/capacitance sensing inputs
https://www.sparkfun.com/datasheets/Components/MPR121.pdf
https://github.com/BareConductive/mpr121/tree/public/MPR121/Examples/DataStream

Thank you, but this is not an answer. My question is about reading raw values on the TTP229 not on the MPR121.


text:
What would be the Western / American equivalent of the Troyka Shield and modules?
I'm taking an online course on Arduino robotics, produced by the Moscow Institute of Physics and Technology. The lectures are translated into English, but all of the parts referenced are by the Russian company Amperka.
It seems the key parts I need to follow along are

The Troyka Shield
Troyka modules, like the potentiometer, Hall sensor, etc
Matryoshka Z set

As fun as it would be to order from the Russian store, there are several practical reasons I'd prefer an American (or Western) equivalent. If they even ship to the US, payment would be difficult, shipping slow, instructions in Russian, etc, etc.
I've spent time and money shopping around Adafruit and SparkFun, but as an Arduino beginner, I'm not 100% sure which parts are analogous to these Russian ones. If a more experienced hobbyist recognizes any of these and can help me identify it, that would be most appreciated.
I think the Troyka components are a necessity, but the Matryoshka Z is a "nice to have" bundle of components. I'm using Arduino Uno, so compatibility with that would be preferable, but I think one of his Russian controllers is supposed to be a clone of the Leonardo, so if these parts only work with a Leonardo that's fine too.
The shield is shown here:

In this view it's combined with its modules using this special snap-together PVC:

The instructor said that he helped invent the PVC components, so I guess there may not be an American version of that yet (or is there)?

This probably has no complete, general solution.
The Troyka Shield looks to be just a prototype shield with footprints for ground/power/data cables.  Likely you can just use a different mechanism to connect things, solder some additions to an everyday proto shield, or you could relatively quickly duplicate this in a PCB design program and have boards made.
There are probably many alternatives for the mechanical structure, ranging from cardboard and foam tape or hot glue to various toy building block sets, or you could try to duplicate their idea by making some grids on an everyday 3D printer.  Likely none of these satisfy formal ESD concerns - but then, Arduino projects are usually considered disposable enought that people rarely worry about this.
The modules are going to be the most problematic part.  They seem to encompass many of the peripheral parts and chips usually used in Arduino projects, and most of those are already available in canonical modules from a range of vendors like Adafruit, Sparkfun, Seeed, etc on down to clones and simple executions of chipmaker's recommended circuits.  So for most of these, you'll probably have no problem finding a substitute, the possible complication is if you have enough understanding of the details of each assignment to make any necessary changes to accommodate for differences in pinouts, components values, etc between the specified Troyka module and the chosen substitute.
You may in the end find it's better to just follow tutorials written around the specific parts and modules you find more readily available for purchase, and thus avoid the needs to translate the details.
Do beware however, that there are some really bad tutorials out there on the Internet - some in places like Instructibles are simply terrible engineering to the point where it is a minor miracle if they even worked once for their authors, and even some on the Arduino site cut corners in ways that can't be recommended.

Thanks, I upvoted; will accept as the answer if no one comes up with any direct solution. You're right - it's supposed to be some sort of expansion board that reduces the need for breadboards. I guess it is supposed to make the sensor modules more plug n play. It would've been nice to kind of accelerate things. I especially wanted the PVC plastic holders because right now trying to connect multiple sensors is just kind of a mess and I'm worried about the connections coming loose when I move from room to room or plug it into the computer to upload code.

You really could make your own version of that shield from a cheap proto board, a few snappable headers broken into 3-pin pieces, and an hour or two soldering bus wires across for the power rails and soldering short wires from the signal pins to the corresponding Arduino ones.

You have a very high opinion of my skill level! ;) But seriously, how concerned should I be that the Russians are beating us in the Arduino race?? This is feeling more and more like a matter of national security. Jkjk. It might be a good business opportunity to sell it domestically though. I really like those plastic holders for the parts. It's a minor thing but looks convenient and cool IHMO.

This one looks kind of like the shield https://www.adafruit.com/product/2077?gclid=EAIaIQobChMInu-ppMeg1QIVj0oNCh1inwcTEAQYASABEgIUUPD_BwE

That's the sort of generic proto shield I mean you could adapt.  If you like the modules in the question, you could contact them about being an importer/distributor.  I'm not yet seeing anything revolutionary in the collection of physical parts.


text:
Can't manually connect HC-05 master to slave
Using this as a tutorial, I've tried to connect the master Bluetooth module from my Nano to the slave module in my Mega. After following the steps in the tutorial, when I enter the command to my serial monitor:
AT+BIND=98d3,31,30690

I receive:
ERROR:(7)

After looking up the error, I only get results for ERROR:(0)
Does anyone know what the error means or how to fix it?

Error Codes and their definitions

I found the solution.
Apparently, both of my modules were at 9600 baud rate when the optimal rate is of 38400. I had to use AT+ORGL in command mode to reset both slave and master. Afterwards I was able to connect them manually.
So apparently ERROR:(7) represents a failed connection? Just don't forget to make sure everything is exactly like the tutorial that's teaching you.

Error 7 is "Bluetooth address LAP is too long" Other Error Codes are here

You need to add zeros to your address.
For example my address of slave is "FCA8:A7:A134"
So command to bind it to master will be "AT+BIND=FCA8,7A,00A134"
XXXX:XX:XXXXXX


text:
Is it possible to run two for loops separated?
I have three funtion which describe the brightness of three LEDs. I want the seconde loop run 1 second after the first one and the third 1 second after the second one. One loop needs approximately 5 seconds. So basically I need to run three loops separated. How is this possible?
Update:
So I have this code running which I can compile but does not work:
int LED = 3;
int LED2 =10;
int LED3 = 9;

bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

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

void loop()
{
// Update loop enablers.
switch(periodIndex)
{
case 0:
 loop1state = true;
 loop1index = 0;
 break;

case 1000:
 loop2state = true;
 loop2index = 0;
 break;

case 1500:
 loop3state = true;
 loop3index = 0;
 break;

case 4000:
 periodIndex = 0;
 break;
}

if (loop1state)
{
 for (loop1index = 0; loop1index<255; loop1index++){
  analogWrite(LED,loop1index);
 }

 loop1state = loop1index < 256;
 }

 if (loop2state)
 {
 for(loop2index = 0; loop2index<255; loop2index++)
 {
  analogWrite(LED2,loop2index);
 }

 loop2state = loop2index < 256;
}

 if (loop3state)
 {
 for(loop3index = 0; loop3index<255; loop3index++)
 {
  analogWrite(LED3,loop3index);
 }
 loop3state = loop3index < 256;
 }
 delay(10);
 }

it's often forgotten that you can use goto in arduino, not that you should...

A Scheduler might be an alternative (to avoid all the complexity:). See example sketch https://github.com/mikaelpatel/Arduino-Scheduler/blob/master/examples/SchedulerBlink/SchedulerBlink.ino and library https://github.com/mikaelpatel/Arduino-Scheduler.

Let me see if I understand correctly what you want... You want to ramp
up the brightnesses of 3 LEDs, one step every roughly 10 ms, and
you want the brightness ramps to start at different times. If this is
the case, I would start by writing a function that handles one LED,
increases its brightness by one step, and tells the caller whether the
ramp is done or not:
// Update the LED.
// Returns true if there are brightness steps left,
// false if we have finished the brightness ramp.
bool update_led_1()
{
    static uint8_t level = 0;  // brightness level
    analogWrite(LED1, level);
    level++;  // wraps to zero when we are done
    return level != 0;
}

This stores the brightness level as a single byte, rather than a
two-byte int, because I am cheap. ;-) Notice that on the last step of
the ramp, the value 255 is sent to the LED, then level++ wraps the
level to zero, then the function returns false to tell us the ramp is
finished. At this point, since level is zero, the function is ready
for the next ramp.
You can copy and paste this function three times, for each of the three
LEDs. Name them update_led_1(), update_led_2() and update_led_3().
The main loop can then go along these lines:
void loop()
{
    static int periodIndex = 0;  // increasing every 10 ms

    static bool led1active = false;
    if (periodIndex == 0)
        led1active = true;
    if (led1active)
        led1active = update_led_1();

    static bool led2active = false;
    if (periodIndex == 1000)
        led2active = true;
    if (led2active)
        led2active = update_led_2();

    static bool led3active = false;
    if (periodIndex == 1000)
        led3active = true;
    if (led3active)
        led3active = update_led_3();

    if (++periodIndex == 4000)
        periodIndex = 0;
    delay(10);
}

Notice the idiom if (led1active) led1active = update_led_1();. This
will be executed on every loop iteration, it will increase the LED
brightness if the LED is supposed to be active, and it will set
led1active to false when the brightness ramp is complete.
There is something I do not like in the solution I am suggesting here:
the copy-and-paste programming paradigm. If I am allowed to use C++
constructs, then I would encapsulate the ramp logic in a C++ class:
class RampingLed {
    const uint8_t pin;
    bool active;
    uint8_t level;
public:
    RampingLed(uint8_t pin)
        : pin(pin), active(false), level(0) {}
    void start() {
        active = true;
        level = 0;
    }
    void update() {
        if (!active) return;
        analogWrite(pin, level++);
        if (level == 0)
            active = false;
    }
};

Then the logic of the main program would appear more straightforward:
RampingLed led1(LED1), led2(LED2), led3(LED3);

void loop()
{
    static int periodIndex = 0;  // increasing every 10 ms

    // Start the LEDs at the appropriate times.
    if (periodIndex == 0)
        led1.start();
    if (periodIndex == 1000)
        led2.start();
    if (periodIndex == 1500)
        led3.start();

    // Update every LED.
    led1.update();
    led2.update();
    led3.update();

    if (++periodIndex == 4000)
        periodIndex = 0;
    delay(10);
}

No, but there is a solution to put the action in one loop (main loop).
If I understand you well, you have the following scheme:
Time[s]
0..1     Loop 1
1..2     Nothing
2..3     Loop 2
3..4     Nothing
4..5     Loop 3
Define a variable that keeps track of the time.
Check against the current time (millis) and when within the correct 'range' perform an action.
After 5 seconds start over again.
uint32_t lastTime = -1;

void loop()
{
    if (lastTime == -1)
    {
        lastTime = currentTime; // Initialization, can be done in setup too
    }

    uint32_t diffTime = millis() - lastTime;

    if (diffTime < 1000) // 0..1 sec
    {
        DoLoop1();
    }
    else if (diffTime < 2000)
    {
         // Do nothing();
    }
    else if (diffTime < 3000)
    {
       DoLoop2();
    }
    else if (diffTime < 4000)
    {
        // Do nothing
    }
    else if (diffTime < 5000)
    {
       DoLoop3();
    }
    else // diffTime >= 5000
    {
         lastTime == currentTime; // Reset after 6 s
    }
}

Update
Since you need all three loops together (and mixed), it's easier to define some variables.
bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

Too bad I don't know the conditions when a loop starts, but let's say each iteration is 10 ms, and loop 1 starts immediately, loop 2 after 1000 ms, loop 3 after 1500 ms. After 3000 ms it starts all over.
void loop()
{
  // Update loop enablers.
  switch(periodIndex)
  {
  case 0:
     loop1state = true;
     loop1index = 0;
     break;

  case 1000:
     loop2state = true;
     loop2index = 0;
     break;

  case 1500:
     loop3state = true;
     loop3index = 0;
     break;

  case 4000:
     periodIndex = 0;
     break;
  }

  if (loop1state)
  {
     DoLoop1(loop1index++);
     loop1state = loop1index < 256;
  }

  if (loop2state)
  {
     DoLoop2(loop2index++);
     loop2state = loop2index < 256;
  }

  if (loop3state)
  {
     DoLoop3(loop3index++);
     loop3state = loop3index < 256;
  }

  delay(10); // 10 ms
}

Note, not tested, but the idea shold be clear
New update
You should not do a full loop during each switch, but only one iteration of the loop.
I did not run the sketch, just out of my head.
Some tips: print out the variables during each loop, so you get a clear idea what is happening (so all loop states and indices, and the periodIndex).
int LED = 3;
int LED2 =10;
int LED3 = 9;

bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

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

void loop()
{
  // Update loop enablers.
  switch(periodIndex)
  {
  case 0:
    loop1state = true;
    loop1index = 0;
    break;

  case 1000:
    loop2state = true;
    loop2index = 0;
    break;

  case 1500:
    loop3state = true;
    loop3index = 0;
    break;

  case 4000:
     periodIndex = 0;
     break;
  }

  if (loop1state)
  {
    analogWrite(LED,loop1index++);
    loop1state = loop1index < 256;
  }

  if (loop2state)
  {
    analogWrite(LED2,loop2index++);
    loop2state = loop2index < 256;
  }

  if (loop3state)
  {
    analogWrite(LED3,loop3index++);
    loop3state = loop3index < 256;
  }

  periodIndex++;
  delay(10);
}

@ChrisStratton Updated my answer according to the recalling millis() problem. Delay is possible too indeed (with your remark when possible to use).

@ChrisStratton True, with some addition for 'no-action'parts

Oh,you're absolutely right, sorry about that! Feel free to change it back if you prefer the way you previously had it.

@ChrisStratton No I like this better, It's more clear I think.

I just wanted to try your sketch but I get an error at the bottom of the code at the last else loop: "currentTime was not declared in this scope"
However, I'm not quite sure if this code will work the way I was thinking of. The wirst loop should start an while x is increasing at the first loop, the second one should start.
Time[s]:0..1:Loop 1 starts, 1...2: Loop2 starts while Loop 1 is increasing, 2...3: Loop 3 starts while Loop 1 and 2 are increasing,3...5:all Loops are increasing until 255. In that order Loop 1 reaches 255 first, Loop 2 is second and Loop 3 third.

I updated my answer with your changed requirements, not tested, but the idea is clear I hope

Thanks for your help. Unfortunately it doesn't work. I'm still a beginner in coding so I think I misunderstood something. This is how I try to run my first loop:
if (loop1state)
{
for (loop1index = 0; loop1index<255; loop1index++){
analogWrite(LED,loop1index);
}
 loop1state = loop1index < 256;

}
I can however compile it but it does not work. I also wanted to ask you how I can change my delay of 10ms?

I forgot the delay indeed, I put it at the end

Thank you but I still got the problem that only one LED is shining. How can I fix that?

Can you update your question with your current sketch, it's hard to see from here

If your three described for loops are the only thing the Arduino needs to do, then you can simply use blocking delay() calls.  However, this scheme will not be extensible to also satisfying other needs at the same time - should you anticipate those, then you should use a mechanism of time comparisons instead.
void loop() {
    int i;
    /* First loop */
    for (i=0; i < 255 ; i++) {
        your_led_function(LED_1, i);
        delay(20); //256 * 20 = 5.12 seconds
    }

    /* I want the second loop run 1 second after the first one */
    delay(1000);

    /* Second loop */
    for (i=0; i < 255 ; i++) {
        your_led_function(LED_2, i);
        delay(20);
    }

    /* and the third 1 second after the second one */
    delay(1000);

    /* Third loop */
    for (i=0; i < 255 ; i++) {
        your_led_function(LED_3, i);
        delay(20);
    }
}

Ultimately which type of solution is best depends on your goals - you can do things in a simple but limited way, or a more complicated but less limited one.  For every 3d printer firmware that cleverly squeezes every last drop of coordinated capability out of an Arduino, there are also those that spend their days sitting in a blocking delay() waiting for the next trivial bit toggle task.

So I have this code running which I can compile but does not work:

because it is wrong.
try something like this instead:
  time_elapsed = millis() / 1000 - start_time;  //time past start time, in seconds
       if (time_elapsed < LOOP1_ENDTIME) loop1();
  else if (time_elapsed < LOOP2_STARTTIME) do_nothing();
  else if (time_elapsed < LOOP2_ENDTIME) loop2();
  else if (time_elapsed < LOOP3_STARTTIME) do_nothing();
  ...
  else start_time+=TOTAL_TIME; //update start time

edit 2:
so here is the above code in action.

three simple tasks: loop1() flips D12, loop2() flips D13 and loop3() flips D8.
The time duration + gaps for those tasks are specified by the following macros:
#define LOOP1_DURATION  5  //time in x100 ms for easier simulation
#define LOOP1_GAP       1
#define LOOP2_DURATION  4
#define LOOP2_GAP       2
#define LOOP3_DURATION  3
#define LOOP3_GAP       6

from those macros, I built the ending and starting time used in the code above.
the code is long-term error free and will never lose track of time.
As you can see, it is essentially a fancy way of executing the following:
  do {loop1();} while (loop1's time isn't up);
  do {nothing();} while (loop1's gap time isn't up);
  do {loop2();} while (loop2's time isn't up);
  do {nothing();} while (loop2's gap time isn't up);
  ...

the advantage with my implementation is that each loop run is very quick and you can execute other tasks as well.
But the general idea is the same.

I notice a number (maybe most?) of your posts do not have properly capitalized sentences. Please slow down and type proper English. A sentence starts with a capital letter. An example here. Your answers look good, now just take a bit of time to format them properly. Proper formatting makes the site in general look better. Thanks for your understanding and cooperation!


text:
How to store/get MIDI SystemExclusive data?
In the MIDI library from the Arduino (FourtySeven MIDI library), there exist a function to get the length and bytes of a System Exclusive message:
Functions
getSysExArray()
template<class SerialPort , class Settings >
const byte * MidiInterface< SerialPort, Settings >::getSysExArray

getSysExArrayLength to get the array's length in bytes.

However, since the Arduino Mega (in my case) has only 8 KB of memory, how can I get a MIDI SysExclusive message which is longer?
Also, I even have added a 128 KB SRAM (23LC1024), but that doesn't help me if I cannot store it in pieces.
Ignacio Vazquez-Abrams mentioned I should 'read' the message, however what message do I get if the system exclusive message is too large to be stored in (internal) SRAM? The read message (see here also does not have a partial read.
Update:
After a test with a large message, it seems the message is not received by the Arduino MIDI library.

That's why you have to do it on the fly instead of relying on a function for it.

And how do I do it 'on the fly' ... can I get to the raw data anyhow?

You read the message.

@IgnacioVazquez-Abrams I should rephrase my question, thanks

If you really, really want to do this, you'll need to rework the library internals to make use of your external memory, or else extract what you actually care about on the fly.  Realistically you have chosen the wrong board for this task.  You should look into using something with ample directly mapped memory instead, if you anticipate wanting to deal with very large messages.   Possibly a large Cortex-M part (maybe a high end Teensy?) or perhaps a small embedded Linux board with megabytes of dynamic RAM.

Well I can (for now) live without support of large sysex messages ... my project will already going to contain one STM32/F7 in the future for one device, maybe for the MIDI device I will also move towards a STM32. Probably system exclusive message will not even be received (but I will test it).
I want to stay away from Linux (not that I don't like it), but I also need quite fast latency which Unix might not be able to provide.

That may depend on what exactly you mean by fast latency and how far into the kernel you can push the critical parts.  Though a very good architecture can be to have a small MCU that does simple fast tasks and is supervised by a larger "embedded computer" which does more data intensive communication ones.

I need to some simple actions on a MIDI message (not system exclusive messages, on a Arduino Mega, for now), send it by RF (probably 2.4 GHz, max 10/20 meters) to a STM32 which will further process it, send it back (by RF) and sent by MIDI Out. All within 20 ms, my idea is to have a loop that can handle several messages in 5 ms by the Arduino Mega.

Do realize that anything coming over midi streams in byte by byte over the serial link - if you have logic to find the start and end of regions of interest, you can start writing that out to memory as received, and then return to ignoring what you don't care about.  It's also at a slow enough rate to do some processing as the data arrives, and should not be a problem for an embedded operating system as long as you use a real serial port and not one tunneled over a laggy USB connection.

Let us continue this discussion in chat.

For minimum latency try to avoid sending the data on a round trip over RF.  Instead, use commands sent via RF to alter an algorithm which processes it locally.   That said, you can just stream the serial data over the RF link, process it there, and send it back.  Midi data rates are pretty slow compared to what 2.4 GHz digital radio modules support.  It's only if you need to allow retries or have a bad packetization algorithm that you hit latency problems.

I hope I can prevent retries/wrong packets, since the distance is around 10-20 meters max, maybe for the MIDI device even much less (< 1 m). For future devices distances might be more. I thought about locally processing it, but that would much more complicate what I want. So I want to optimize it only when needed. I did some calculations and I think I can handle a lot of messages within reasonable time getting the latency.

This library tries to make its programming interface as simple as possible, which means that SysEx messages are put completely into a buffer in the internal memory, which means that larger messages cannot be handled.
The only way to handle larger messages is to read the bytes directly from the serial port, and parse the MIDI messages yourself. (The MIDI specification has a helpful flowchart about MIDI parsing in the first appendix.) When you have detected the start of your large SysEx, you can then do whatever you want with the following bytes, e.g., handling them as a stream, or write them to external RAM)^.

Thanks for your answer ... I'm sure I will be able to read it directly without the library, and possibly I will go that way later. But not to continuously change my 'design', I continue for now with the MIDI library and using your way (reading directly from Serial) later.
But very good to know it can be done that way fairly easily. It would even reduce the latency further if I can start handling bytes already without having to wait for the entire message, especially for critical latency messages (mostly non system exclusive messages).