Eclipse C++ Ide for Arduino 2.0 and eeprom.h (no such file or directory)

I'm sorry but it's quite difficult to understand what you are asking. Are you saying you are trying to write some code to write to an EEPROM and you can't find eeprom.h?

1,000 lines isn't a big enough program to cause issues unless there is a problem with your IDE. This file should be included from you main file. If you were using the Arduino IDE then there is a feature to include the library and it adds the #include statement for you.

I don't know what operating system you are using, you didn't say but have you searched for the file? Does it exist? Have you got the correct case for the filename (doesn't matter on Windows)? I think it is called EEPROM.h, maybe changing the name in the include statement will help.

What can't find the file, Eclipse or the compiler? If it's your IDE it shouldn't matter.

Have you got an EEPROM library and can you build and run the examples?

I don't know if this version of Eclipse and the plugin is recent or not, it's possible that the EEPROM library is not supported on this version. You would need to research that. When you encounter problems with third-party tools, it is usually best to revert to the Arduino IDE and check that the tool is functioning correctly.


L298N, HC-05 Simple Bluetooth remote car not running in Arduino

sorry for my careless. finaly its works....wrong pin assign the main problem....should be IN1, IN2, IN4 and IN3 not IN1, IN2, IN3 and IN4. thank you for all hands for help before


How to fix HC05 burning even after while using voltage regulator?

You said "I should mention that I was using voltage dividers for both of the transmitter, and receiver circuit's HC05 Bluetooth modules."
Voltage dividers are not a good way to lower voltage for power components. The voltage output will vary based on load, and they also dissipate the excess voltage as heat, so you need high current resistors.
Post a schematic of your system with the specific batteries, regulators etc that you are using.


Most of Arduino relay modules have a relay and a supporting circuit. The circuit connects the VCC line to relay coil if signal line is HIGH. Some relays have it conversely, they disconnect if signal is HIGH and hold the coil if signal is LOW.

Your relays need VCC which you can supply for 8 relays from 5 V pin of Arduino. This pin is connected over regulator to power supply of the board so it is limited only by power supply and regulator parameters. The power doesn't go over MCU.

The signal pins of individual relays should be connected to digital pins of Arduino. The signal pins don't draw much current since they only signal a state to the circuit of the relay module.


Can't identify + or - in the 5v USB wall adapter, does it matter?

Power (which comes from your wall outlet), is AC, which means alternating current. It changes 50 or 60 times per second from direction, so this is the reason it does not matter if you plug it reversed or not. Some countries have plugs which can be plugged in normally or 180 degrees rotated (but you cannot see what is 0 or 180 degrees since these are symmetrical).

The circuit inside the adapter makes sure the AC is converted to DC, where it matters what is Plus or Minus.


Just choose a smaller font. You know, I showed you the documentation earlier. You really should read it, because it contains all the information you need.

For instance, here is the section on the available fonts: https://code.google.com/p/u8glib/wiki/fontgroup - each section contains a link to download the font group which of course you will need to do before you can use it.

You might find something like:

u8g.setFont(u8g_font_fixed_v0);

more to your liking. And don't forget to download it via the link above first.


Code for password-activated LED via Bluetooth serial

Try using the following code you need to use String and concatenate that

    String rcev_data="";
bool chk=false;
\#define output 9

\#define output2 10

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(output, OUTPUT);
  pinMode(output2, OUTPUT);
}

void loop()
{
  // put your main code here, to run repeatedly:
  while(Serial.available())
  {
    char rxx = Serial.read();
    recv.concat(rxx);
    delay(10);
    if (recv == "QWER")
    {
       chk=1;
       break;
     }
    else
     chk=0;
 }

  if (chk)
  {
    digitalWrite(output,HIGH);
    Serial.println("ON");
    delay(3000);
    chk=0;
  }

  else
  {
    digitalWrite(output,LOW);
  }
  recv="";
}


Can I connect a camera to an arduino mini?

Not really (at least, not with any appreciable quality). Basically, the bandwidth involved is simply too much for the Arduino's relatively slow 16MHz core speed. You might be able to periodically capture greyscale lowres frames, but capturing the full 1280x960 resolution at any decent framerate is basically impossible.

If you want to find Arduino projects that involve capturing video like this, the search term is arduino composite video input. There are many projects out there that interface the Arduino with a composite input, but none that I know of that can capture full video. Consider the following: your Arduino runs at 16 MHz. If you were to handle 640x480 greyscale video (1 byte per pixel), that would be a data bandwidth (disregarding signal bandwidth) of 640*480*30 = 9216000 bytes/second. That's a pretty tall order: even if you could process each pixel in two (single cycle) instructions with no overhead, you still wouldn't have enough processor bandwidth.

If all you want to do is record composite video to an SD card, there are far easier options out there, search composite video recorder sd.


Solution: Remove ground from Q0 as Gerben correctly pointed out in comments.

Also: rotate LEDs 90 degrees so that the anode and cathode are on different rows.

What was tripping me up is in the Arduino tutorial diagram is a little unclear on this (I now understand why their way is correct and my way (in the question) was wrong:


Serial.read() is getting a whole string rather than just a character?

You only think it is a string, it actually returns character by character. You can know by adding something like a delay after you Serial.print(). What the program actually does is that it receives one character each time you type one and it prints it, then the void loop repeats.


Likely all programmable pins on modern embedded processors are able to perform digital I/O.  In addition, many can also perform other tasks such as PWM, or Analog to Digital Conversion (ADC).  This is true for many of the different processors used on different Arduino boards.

Often, the nice people who write the C++ driver class of programs or Arduino Libraries offer the user the ability to change pin assignments used by the Arduino Libraries when instantiating an instance of the driver.  This is true for the LiquidCrystal driver in the tutorial in the question.  This can be an advantage as processor's resources are limited.  For example, if you need PWM controlled pin to dim LEDs, you can move LCD controlling pins to other non-PWM pins.

The LCD specified in the tutorial linked to in the above question uses a common Hitachi HD44780 interface.  Such assemblies only need embedded processor Digital I/O pins for control.  Had the LCD no electronic driver, the segments need to be directly driven by very low alternating current (AC).  This is difficult for embedded processors.  However, it may be possible using enough PWM pins and some clever software & hardware.


It immediately loops, from the digital write low to digital write high. Add a second delay after the low, so that it waits before it loops to the top again.


Maybe it's my background of old C programmer but... I would just write
plain functions, no classes, like in C. And I would keep all this stuff
in a single file, to provide some form of encapsulation:

my_parser.h:

some_type get_numbers(int arg1, char arg2);

my_parser.cpp:

static int performFirstAction(float arg1, int arg2, char arg3)
{...}

static bool performSecondAction(long arg1, void *arg2, int arg3)
{...}

some_type get_numbers(int arg1, char arg2)
{...}

Note that there is only one function declared in the .h: this is the
“interface” to your module. Note also that all the other functions are
defined as static. This tells the compiler to keep them hidden from
the linking phase, so they do not pollute the global namespace. And
finally, note that there is no global shared variable: everything is
passed as arguments to the functions.

The rationale for the last point is that this helps the compiler
optimize things. A static function that is called only once is almost
guaranteed to be inlined by the compiler. Which means there is no
overhead in passing the arguments. On the other hand, if you use global
variables and the compiler doesn't manage to optimize them away, you
will incur the cost of RAM access.


When you ask: "why?". The cheapest answer is: "why not?".

The compiler can do clever optimizations as @Majenko wrote. That is what this is about.

Even for such a small sketch, the compiler has many optimization methods to choose from. Changing a single line or adding a variable can make the compiler to choose other optimizations. It is therefor impossible to link the increased number of bytes to those extra pointers.

Sometimes the compiler can decide to keep a variable in a register instead of storing it in a memory location. Sometimes the compiler understands that a variable has a constant value and is used only once, then the compiler might not even use dynamic ram for it.

The used dynamic ram by the sketch is even more trivial, since Arduino sets the compiler to use the minimal size for the code.

Optimizing a sketch is best done with a large sketch. Your small sketch uses the Serial library, and that is the main part of the compiled code. Your own functions and pointers is just some code on the side.

For beginners, the compiler optimizations can be magical Abracadabra. However, using arrays will prevent the compiler to do extreme optimizations. There might even be a logical explanation for the number of increased bytes if the assembly code is studied as @Gerben wrote.


Barebones 328p, 2xAA vs 3xAA, which will last longer?

Yes, running at a higher voltage will consume more current.  In the datasheet you have this nice graph:

I have highlighted the two voltages at 8MHz for you. At 4.5V you would typically be using about 4.7mA.  At 3V you would be using around 2.8mA.  That's not taking into account anything else in your circuit of course - just the ATMega itself.


Identifying a counterfeit or authentic Arduino

It looks like an R3 Uno, but then pictures can be misleading.

However:

Arduino is open source - anyone can make one
Because of that there are many many "clones" of the Arduino
A clone, as long as it's got the right circuitry (and an Arduino is incredibly simple) is as good as the "real thing".

The only problem Arduino have with clones is the use of the Arduino name and logo.  IIRC they don't mind you claiming "Arduino Compatible", but trying to be an Arduino they don't much like.

If it's just their reference designs re-printed (which you can download for free from the Arduino Uno web page) and no further design work has been done, then although it isn't made in Italy by Arduino, it's still an Arduino.

That's the beauty / curse of open source - anyone can make one.

However, that specific one looks like it fits into the "claiming to be an Arduino" category.  It uses Arduino artwork and logos, and tries to make it look like it's an Arduino made by Arduino in Italy, when in fact it isn't.  Legally speaking, they are ripping off the Arduino brand.  Practically speaking, since it's all open source, the actual device (assuming the components aren't counterfeit) should be perfectly fine.

If they were to change the artwork, so it didn't look quite so much like an Arduino, and had something like "Arduino Uno Compatible" on it, then it would be categorized as a clone, and would be fine - you'd know where you were standing.  As it is though, the artwork on it is breaking copyright laws.

The image shown is too low quality to give much information about it, but the two big pointers that it's not made by Arduino are:

The PCB is too blue (real Arduinos are teal)
The polyfuse is the wrong colour (green instead of grey/gold)


Arduino motor control using digital pins

You can implement PWM using digital pins by turning the pin on and off with respect to your duty cycle, because PWM (Pulse Width Modulation) depends upon the duty cycle the % amount during which the pin is HIGH or LOW

Let say pin 13 of arduino is connected to your l293D enable pin

Sample Code:

void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  digitalWrite(13, HIGH);
  delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz
  digitalWrite(13, LOW);
  delayMicroseconds(1000 - 100);
}

Details are also on Arduino Help

https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM


Is there a board that can act as both a USB host and client for HID devices?

The TMK USB to USB converter is a thumb drive sized board with ATMega32u4 and max3421e with pass through/remapper software. It has the same functionality as a Leonardo with USB host shield.

https://geekhack.org/index.php?topic=69169.0


What is the minimal possible latency between arduino and PC

There is more to low-latency communication than just squirting data as fast as you can (though that is an important part of it).

One thing people often forget is that the Arduino can only (easily) do one thing at a time. While you're sending your buffer to the PC it can't be sampling and filling your buffer.  If you have a buffer which fills up over the period of 1 second and you want to send that buffer to the PC when full, what happens during the subsequent second while you're sending the buffer? The buffer can't be being filled while it's being sent.

Using a normal UART to USB connection as most of the normal Arduino boards (Uno, Mega, etc) use the fastest you can reasonably expect is around 1MBaud. That's about 100kB/s.  Less if you use a cheap Chinese clone with a CH340G.  Even at 100kB/s your 1kB buffer, if sent completely raw and in binary, would take around 10ms to transfer. But getting the computer to make any sense of that raw data would be hard. So you'd need to wrap it in some form of protocol (up to you to design that...) so you may get half that speed (or worse depending on your protocol design).

And during that time not much else can happen.

For smooth low-latency communication of data it is much more preferable to use "ping-pong" buffers and interrupt- or DMA-driven sampling of your data. That means that one buffer is receiving your data from whatever source, and the other is being sent to the PC. Once the first buffer is filled up they reverse roles. However, the little 8-bit Arduinos aren't really suited for that kind of thing:

They don't have much RAM to waste on two buffers
They don't have interrupts with priorities to allow samples to occur while sending
They don't have DMA to do background transfers of data to/from peripherals

If latency is really that critical you would be better using one of the ARM-based Arduinos, such as the Due, where you can also then take advantage of a high-speed native USB interface which can give much higher throughput than a UART connection. Your choice of USB endpoint can also influence the latency of your design:

Isochronous - Lowest latency, small packets, not guaranteed to be delivered
Interrupt - Medium latency, small packets, delivery guaranteed
Bulk - High latency, large packets, delivery guaranteed

Isochronous is used mainly for audio where you would notice the slightest delay in sound, but wouldn't necessarily notice or worry about a slight glitch in the quality. Interrupt is used for things like HID where you need it to respond to you pressing the keys on your keyboard nice and fast, but you're never sending much data (64 byte packet limit on interrupt transfers).  Bulk is used for things like CDC/ACM (Serial over USB) where you may want to tranfer lots of data but wouldn't notice if it's pausing for a few ms every now and then (HS USB has a 512 byte packet limit on bulk transfers, FS USB has a 64 byte limit).

One of the great things with a direct USB connection is that underneath it is all packet-based, so you can use that as your transfer protocol if you know what you're doing. Don't just rely on the CDC/ACM "pipe", but instead make use of the underlying USB protocol to send individual packets which the receiving program can then understand and break apart into the right data without adding any extra protocol overheads.

For more advanced USB programming the Teensy and chipKIT cores have far more sophisticated USB support than the Arduino core, so you may fancy taking a look at their offerings in the way of boards that may suit your needs better.


Serial Port configuration with asio C++ library

Can you include all the other calls you make related to setting up the serial port along with asio::serial_port_base::baud_rate(baudios)? Ideally, split that out into a separate function (that takes parameters such as baud rate) that you know is the only thing doing this setup.

As I mentioned in the comment, getting back the right number of chararacters but incorrect characters looks as if the baud rate is correct but something else is wrong. The first thing that comes to mind is the bits/parity/stop bits settings. Typically you want to be using 8 bits, no parity, often referred to as "8N1".


PC not recognizing Arduino when working with a class and MIDIUSB library

You need to take care with constructors in C++.  They get called during the global variable initialisation phase of the execution, which happens before main() gets called.

main() calls the routines that initialise and configure the peripherals and such in the chip, and by having analogRead() in your constructor (which is itself another error I will mention below) there is a good chance (I don't know the full initialisation sequence of that chip though) that it will never complete, and thus your program hangs at that point.

Your analogRead() doesn't want to be in the constructor, anyway, since that will only execute once when the object is constructed.  Instead you want to have analogRead() called at the point you need to get the analog value. In your code that would be at the start of int Pot::getValue().


Try calling noTone() after the tone is played. This is a kind of "reset" for the pin.

Also, you forgot a } at the end of your code.

If these didn't solve your code, then it most probably is an electric problem.


Update: the original question mentioned timers, so this answer is for a hardware timer interrupt handler. It doesn't apply to Ticker, which is what the question is now about.

The callback that you attach to blinker will be called as an interrupt handler, so it's important to make sure it's already loaded into executable instruction memory (iRAM) on the ESP8266. When you pass anonymous function inline to blinker.attach() it won't tagged to be stored in iRAM.

Try this instead:

void ICACHE_RAM_ATTR blinker_handler(){
    digitalWrite(LED,!(digitalRead(LED)));  //Toggle LED Pin
}

...

blinker.attach(1, blinker_handler);

ICACHE_RAM_ATTR tells the system to keep the code in the instruction RAM. There's not a lot of iRAM (32Kbytes) so you don't want to do this too often, but it's important for interrupt handlers (another reason to keep them short and sweet).


It should be

String model = "GET /kanbanDB/arduino?model=1 HTTP/1.1\r\n";
model+="Host: 192.168.1.9\r\n\r\n";

remove Serial.println("\r\n\r\n"); before Serial.println(model); it is send before GET line

Serial.println("AT+CIPSTART=\"TCP\",\"192.168.1.9\",8000");
String model = "GET /kanbanDB/arduino?model=1 HTTP/1.1\r\n";
model+= "Host: 192.168.1.9\r\n\r\n";
Serial.print("AT+CIPSEND=");
Serial.println(model.length());
delay(1000);
Serial.print(model);
delay(1000);

EDIT:
Remove debug prints to Serial or use SoftwareSerial to connect the esp8266 to Uno. Now the debug prints are sent to esp8266 mixed with AT commands and data. For SoftwareSerial change the default baud rate of the AT firmware.


Analog INPUT_PULLUP for resistive sensors?

Can you use the internal pull-up on an ADC pin?

Yes.

  Is it correct usage?

No. The exact pullup resistance varies from pin to pin and chip to chip, so depending on it for the high side is problematic at best.

Ideally you should be disabling the digital circuitry on an analog input entirely by writing to the DIDR0 and DIDR1 registers appropriately.


double type sensor data is not displayed on bluetooth terminal app on phone

You can convert you double data to string type.this trick may help. And you also can just sent a byte for different positions and decode them in app.


Arduino Clock Speed effect on Stepper Speed

Without seeing the rest of your code, the best guess - and I think it is quite likely - is the use of delay() and printing within the stepper function. With 2 motors running, and even ignoring the printing time, there will be a total of 200ms taken up by the delays. That means each motor gets serviced a maximum of 5x/sec. Stop one motor, and the other one can double that to 10x/sec.

Look at the Blink Without Delay example for one way of managing timed events without calling delay(). The SimpleTimer library provides another.

Update:

  ...run() events are triggered within a while() loop ...

Ah, yes, I see that. So it looks like only one motor could run at a time - the while() loop runs until this motor reaches its target. But you said you run two at a time. So yes, I think understanding the rest of the code will help.


Sorry, but.. Why integration? Just use a peak detector like this one:

The output will "float" to the peak value of the input signal, minus the voltage drop across the diode:

The output oscillates between 9.7V and 9.2V, which is a 5% maximum error. If you want to reduce it, sample with a sample rate not multiple of 50Hz and average the measures.

The RC constant is 500ms. This means that it will require less than a second to pass from a value to a lower one:

Here in almost 500ms it will go from 10V to 5V.

If you want to reduce the diode effect (9.7V instead of 10V) use a schottky diode. This, however, will not reduce the 9.2V effect.

You should divide by 2 the voltage; you can either

divide it before the diode (but then the diode effect will be more evident - you can however correct it in software
divide it after the circuit (In this case, replace the 500k resistor with two 250k resistors and take the voltage in the middle)

Of course 500k and 250k are not standard values, but you can use any nearby value without affecting the behavior


Public variable in class not incrementing

It's difficult to pin down the exact details as to why the problem it's manifesting exactly the way it is. But, in short, it's fair to say you're running out of memory.
First, just a note:  The code I'm testing with (because it compiles) is the code out of your github repo, which used a char type variable for linesInserted and had a commented-out println(linesInserted);, so it kind of seems like at one point you'd been trying to print the count as character, specifically non-printable control characters.  So that might may have been confusing you.  I uncommented it and added a , DEC) parameter to it (rather than casting) to coerce println into treating it as an int.
I tested your code without the display library in a PC environment to allow me to run valgrind on it.  It didn't find anything; I wasn't necessarily expecting it to.  But, I did crudely instrument your code in this enviroment to see that you're calling malloc()/new 124 times, for a total of 500 bytes, but importantly this does not include the structure heap overhead, which is significant because you're new-ing tiny four-character chunks.
Then I ran your code as compiled for an AVR.  Because I don't have your display, and wanted to match your environment as closely as possible, I left the display code in but NOPed out a few function calls that would have screwed up my test rig.
The primary finding is that you're dangerously close to "running out" of memory:

000005e0 | 01 00 02 04  00 01 00 02 - 00 04 00 03  01 03 05 04 | ........ ........
000005f0 | 00 01 03 02  03 04 00 01 - 06 02 06 04  00 00 00 00 | ........ ........
00000600 | 00 04 00 02  00 02 00 04 - 00 01 01 01  01 04 00 00 | ........ ........
00000610 | 02 00 02 04  00 02 02 02 - 02 04 00 01  03 01 03 04 | ........ ........
00000620 | 00 00 04 00  04 04 00 02 - 04 02 04 04  00 01 05 01 | ........ ........
00000630 | 05 04 00 00  06 00 06 04 - 00 02 06 02  06 00 00 00 | ........ ........
                                                      ^^
                                                 [__brkval]

                          [SP]
                           VV
000006b0 | 00 00 00 00  00 00 b7 09 - 03 01 01 06  02 a5 02 00 | ........ ........
000006c0 | 00 00 00 01  00 57 05 06 - cc 00 03 8f  0f 01 00 00 | .....W.. ........
000006d0 | 00 01 00 00  03 00 03 00 - 00 00 07 02  a4 00 01 00 | ........ ........
000006e0 | 03 02 a4 00  05 f8 0d 06 - f6 00 03 00  00 08 c3 08 | ........ ........
000006f0 | de 00 01 00  01 80 1a ed - 02 04 00 41  a4 02 04 00 | ........ ...A....

There's 120 byte separation between the edge of the heap and the stack pointer.  The implementation of the malloc that I ran this under checks to see whether or the the stack pointer is within 128 (__malloc_margin) bytes.  As your code was building in my environment, without the counter-printing in, this managed to not-fail to allocate.  However adding a single additional call to addNewLine was enough to cause malloc() via new to fail.  So you are indeed right on the edge.  And you have no checks to see if malloc or new returning nullptr.
You're making one allocation after another without deallocation anything, which is resulting in a fairly simple pattern of the heap edge advancing by the requested size of your allocation plus 2 bytes each time.  So that's about 248 bytes waste in just heap structure.
I'm not sure on the exact cause of your counter being overwritten, assuming that's what's actually happening.  In fact I was having a hard time finding an case where it would overwrite anything in memory with the code as you have it, but here's a good candidate:
lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};

With generated code looking like:

0x24c6 [addNewLine+244] ldi    r25, 0x00       ; 0
0x24c8 [addNewLine+246] call   0x3830  ;  0x3830 [malloc]
0x24cc [addNewLine+250] movw   r30, r24
0x24ce [addNewLine+252] st     Z, r10
0x24d0 [addNewLine+254] std    Z+1, r11        ; 0x01
0x24d2 [addNewLine+256] std    Z+2, r17        ; 0x02
0x24d4 [addNewLine+258] std    Z+3, r16        ; 0x03

So, if malloc() fails, apparently the new statement will just assume that it didn't and goes ahead and writes into the memory at 0x0000 (nullptr) anyway, ugh.  I think this is because technically you're calling the normal new that is supposed to throw an exception on failure.  But there are no exceptions with the way avr-g++ is set up for Arduino.  As it exists in ArduinoCore-avr version 1.8.3, the new code just returns what malloc returns and the compiler thinks an exception will be in progress if it fails.  Normally you would call the std::nothrow version of new[] that returns nullptr on failure, as in:
lines[linesInserted - 1] = new(std::nothrow) char[4]{startX, startY, endX, endY};
// check lines[linesInserted - 1] against nullptr here

However, there's no facility to do that in 1.8.3.  The master as of writing appears to have addressed this, but that's not shipping yet.

The short answer to this is basically: Don't do that. That is:

Avoid dynamic allocation altogether where possible.

This was mentioned in the comments, but it's worth repeating, use flash where you can.  Besides getting your character data into PROGMEM, you also have some string literals that can be moved into flash by way of F().

To the extent that you're doing dynamic allocation requests:

Check to see that they're actually succeeding

Make as few requests as possible.

Do them up-front at the beginning of the code.  The "up-front" part you're more or less already doing, so that much is good.

It seems if you're going to dynamically allocate under core version 1.8.3 and you're at all in danger of having an allocation failure, it is important that you not use new, since doing so may cause it to overwrite memory for the initialization/construction part after the allocation proper has failed.  Alternately, seriously consider modifying your Arduino core's new.cpp file to do something like call abort() if malloc() returns nullptr, at a minimum, if not something more sensible.  Otherwise, this could drive you insane.


I don't want to apply any changes to my original strings

You should read about PROGMEM and/or the __FlashStringHelper ( F-Macro ) . Probably you can even handle that vast amount of constant texts on your Nano controller, which is meant to be a controller, not a text processing computer.


A problem with measuring time in a for loop

Old time and new time are wrong way round on a part where the LED'd are switched off

else if(oldTime-newTime >= dt){
          oldTime=newTime;
          digitalWrite(led1,LOW);
         }

When simple processors reach the max or min value and continue counting, they overflow and start counting from far end: So 5-8=maxint(largest number)-3
Result is that the difference is a massive number greater then 2000 except every few weeks when millis() overflows and become larger then Unsigned large int can store and starts counting from zero. (many codes fail working on that occasion, your would only works then ;-)
Correct version:

else if(newTime-oldTime >= dt){
          oldTime=newTime;
          digitalWrite(led1,LOW);
         }

Although I have noticed that testrange (both) only returns its value onto true on limited circumstance if input from encoder increased considerably very quickly to catch-up with growing inputs, so the next values will never pass condition to switch them on

if(encoder>=array1[i] && encoder<=(array1[i]+tolerance) && testRange)

will never return true because testRange stays false. Add

testRange=true;
testRange2=true;

at the end of the loop otherwise it does return into true for next loop()iteration. I guess question is if you want other functions to run while LEDs are on or not.

It is a bad habit to make unnecessary variables like i,j,k,l global as they waste memory even when not needed you can define them within structure itself Eg: for(int i=1;... this way as soon as for, while etc loop (brackets close)finishes you get your memory back and you can use variable again


A circuit diagram or photo would help, but I would guess you have taken the lead from the PC that is marked Rx and connected to the pin on the ESP marked Rx.  That's the wrong thing to do.  Firstly the PC will use 5V and the ESP uses 3.3V, so you need a little board called a level shifter something like this 2 channel level shifter.  This will let a 3.3v device talk to a 5V device.  Some ESP boards are 5V tolerant, but I don't know what you have so ...

Then when you "talk" over serial you need to cross the Tx and Rx between the two devices, so the can 'hear' each other

 PC - Tx  ---> Rx - ESP
 PC - Rx <---- Tx - ESP

(Lots of other level shifters are available and a lot are cheaper than the example shown, a lot cheaper!)


The way to do this isn't to overload the loop function, the way to do this is to abuse the linker and replace main().

The main.cpp file that gets used in the Arduino make prototypes main as int main(void). On my system at least the linker prefers the longer prototype, so you can just do this:

int main(int argc, char* argv[])
{
    init();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    //The one shot loop...
    loop();
    if (serialEventRun) serialEventRun();
    //Put whatever else you need to do between before the unending loop here.

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

Both get compiled, but the int main(int argc, char* argv[]) prototyped version gets linked as the entry point, so your "invisibile" code gets executed.


Can I change font Color and/or Type for IDE 1.5.6r2?

Yes.

Under the file menu select the preferences. From this you can find and than view/edit the preferences.txt file, which has the color settings.

Example preferences.txt


How to connect gyro to Arduino Uno via I2C

I needed to connect the gyro's reset input to V_DD_IO. See gyro datasheet, table 1, pin 4. This corresponds to pin 7/RST_21002 on the breakout board. The gyro works like a charm now!


How to power multiple LEDs with a microcontroller

I see no reason why you would not be able to light 30 LEDs.
ATtiny85 only has 5 pins for use (unless you want to use the reset pin as well in which case hell will cover you). So with charlieplexing you are going to be able to address 20 endpoints. (where each endpoint might consist of multiple LEDs)
But beware. You CAN address 20 endpoints but you CANNOT light every combination simultaneouly. You will have to work out if there is a constellation that allows you to light all lights you want in the same time or you will have to use one of the timers to toggle between different lights. I don't know how well it works thou.
I have managed to use a timer on an 8MHz device to drive 4 LEDs at 400Hz directly without charlieplexing and not using PWM. So I assume it will be possible but might be flickering.
It would definitively be easier. I always recommend to stick to things that are well known and widely used. That would fit your ATmega32U4.

Make sure you layout your LEDs and think how you want to address them and if it makes sense to join multiple LEDs to one pin and toggle them at once.


You are printing the unprintable.

Do you think it should print:

~0581,34{

or

0x7E 0x00 0x05 0x08 0x01 0x44 0x33 0x04 0x7B

What you will get is

tilde
null
enquiry
backspace
start of heading
comma
three
end of transmission
open brace

I think you can call

Serial.print(stringy[i], HEX);

To see the number you put in come out.


You check if power is 1, but it will never be 1. Instead it will be 1<<5 or 32. Better use:

if(Power != 0){
  PORTB |= (1 << PORTB3);      //set high
}
else{
  PORTB &= ~(1 << PORTB3);  // set  low
}


Two pots controlling 2 servos -- odd behavior

I have no idea whats wrong with your system, but this might help you diagnose it.

#include <Servo.h>

static const size_t MaxServos = 2;              // The number of pots and servos attached
const int servoPins[MaxServos] = {9, 8};        // The pins that the servos are controlled through
const int potpins[MaxServos] = {A0, A1};        // analog pin used to connect the potentiometer
Servo myservo[MaxServos];                       // create servo object to control a servo

void setup ()
{
    for (size_t index = 0; index < MaxServos; ++index)
    {
        myservo[index].attach (servoPins[index]);
    }
}

void loop ()
{
    for (size_t index = 0; index < MaxServos; ++index)
    {
        readAndSet (potpins[index], myservo[index]);
    }
    delay (15);                           // waits for the servo to get there - might want to multiply a value by the number of degrees turned to give a better value.
}

// \brief   Read the specified analog pin and set the server proportionally
// \param   The analog pin that the pot is connected to.
// \param   The servo that will be moved
void readAndSet (const int& pin, Servo& servo)
{
    const int value = analogRead (pin);            // reads the value of the potentiometer (value between 0 and 1023)
    const int mappedValue = map (value, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
    servo.write (mappedValue);                  // sets the servo position according to the scaled value
}

I have refactored your code to eliminate the duplication.  This means you will get more test coverage and you should find the bug quicker.  You could add a Serial print statement to the readAndSet function to ensure that you are passing and calculating the right values, but I suspect you are.

There appears to be nothing wrong with the code, so is it possible that there is some hardware limitation?  Is there a short between the lines that causes the pot on A1 to be bypassed?


Is analogWrite() inferior to writing directly into registers?

analogWrite() is already PWM, Arduino doesn't produce a true analog signal
Motors tend to draw a lot of current so you might want to control the motor with a MOSFET then connect your power supply directly to the motor. PWM will still work in that case, you just need to connect the output pin to the gate pin of the MOSFET
If you want more of an assurance when working with motors, try buying a motor shield. You current problem, speed problem and many will be resolved. It also makes it easy to control multiple motors.


I don't know my arse from my elbow when it comes to electrical engineering and all that so I have a couple of questions. 1. Do I need to have a background in engineering to use an Arduino.

The answer to your first question: it depends on what you want to achieve, and how much time you are willing to spend stuck.

A bit of electrical/electronic background can help you a lot.  Basics such as Ohm's, Kirchhoff's.  Semiconductor devices (diodes, transistors, OpAmps).  It's very useful to understand what kinds of test&measurement equipment exists and how it can be used.

You can pursue C++ for 6 months 1-2 hours a day.  You can pursue electrical knowledge in the same way as well.  A solid book like "The Art of Electronics" will help you a lot (doesn't have to be the latest edition).

Then you can pursue more exciting things: sensors (for example).


Connecting ESP8266 with Arduino Uno - WiFi shield not present

You can program and upload code to ESP8266 using Arduino programming environment, reusing code and libraries with small changes. Check https://github.com/esp8266/Arduino for more information.

For most tasks ESP8266 may substitute Arduino board completely. It has more flash, more RAM and integrated WiFi, and is faster (80MHz).


If you want to use esp-01 over SoftwareSerial, you must set the AT firmware's default baud rate to 9600 baud. The default baud rate of AT firmware is 115200 baud. SoftwareSerial can't work at this speed.
To change the baud rate you must have a way to communicate with AT firmware at the default baud rate of 115200 baud. You can use the USB adapter of the Uno. Upload BareMinimal sketch from Examples to Uno to make it silent and connect the esp-01 to RX and TX pins of the Uno.
Connect RX to RX and TX to TX to have the cross connection to USB of the Uno. Then connect from Serial Monitor to esp-01 at 115200 with "Both line end characters" set. Try some basic AT commands and then still at 115200 baud send the command to change the default baud rate AT+UART_DEF=9600,8,1,0,0

In setup() in sketch begin for SoftwareSerial is missing. Add  esp8266.begin(9600);

Uno pin 11 is RX of software serial, pin 10 is TX. The RX pin 11 must connect to TX pin of esp-01. Same applies for TX pin 10. It must connect to RX pin of the esp-01.
On the Fritzing schema on Uno pin 11 is green wire and on esp-01 TX is green wire. But the green wire is on sides of the level converter not on the same position. The conclusion is that you have RX connected to RX not to TX. Switch wires on best at level converter.

The 3.3 V pin of some Uno clones can't supply enough current for WiFi operations of the esp8266. You need to convert to 3.3 V from Uno 5 V pin or use a separate 3.3 V power source for the esp-01.


Arduino UNO R3 as flight control plus brushless motor driver

Since so many things are being done in each cycle the phase change of the brushless motor might not be fast enough and this might hamper the motor speed? Or is the arduino fast enough to handle all this and it won't affect the speed noticeably.

This is very much an engineering question. How would one go about answering this?

One method is do a worst-case execution time measurement. Another method is to use control theory and estimate the minimum control frequency for the system (or sub-systems).

Let us assume (for this argument) that the required update frequency is 50 Hz (20 ms cycle time). That gives approx. 320.000 instructions (AVR @ 16 Hz) per control cycle.

The algorithm sketch above in your question is basically dominated by the time to receive the message. This depends on a number of factors; PLL start up, write message from AVR to NRF, transmission frequency, coding, etc, but also message loss and retransmission/acknowledgement. With 2Mbps and 5 byte address, 32 byte payload, and 2 byte checksum the transmission time is at least 300-400 us plus approx 100-200 us for the AVR/SPI to NRF communication. A total of 400-600 us which is well under the 20 ms.

What other design considerations are there? Motor interference on the communication, antenna design, range, protocol design, etc.

Cheers!


SIM800L starts sending garbage values to Arduino after random interval

I believe GSM modules needs about 2A current for few operations. One of them is calling. Are you providing proer current?


How can Arduino know Wire.available() is true or false?

The simple answer is that the Arduino Wire library has an internal buffer, and it can bring in characters and have them sitting there ready for you to pick them up.

It can also sense a total disconnect because of the way it uses both data pins to establish communications.  It is more like a current loop than a simple one-is-transmit-and-the-other-is-receive.  If it disconnects the Arduino knows it is not available.

Kudos on going to the documentation, by the way.


How can I increase the torque or speed of the stepper motor with Arduino

To increase torque of 28BYJ-48 you have to perform a simple mod (cup one path on the PCB) to change it from unipolar to bipolar and then use it with an H-bridge like the A4988 or the DRV8825 driver.

Sources:

https://ardufocus.com/howto/28byj-48-bipolar-hw-mod/
https://coeleveld.com/wp-content/uploads/2016/10/Modifying-a-28BYJ-48-step-motor-from-unipolar-to-bipolar.pdf
https://everythingsmarthome.co.uk/howto/converting-the-28byj-48-stepper-motor-for-more-torque/
http://www.jangeox.be/2013/10/change-unipolar-28byj-48-to-bipolar.html
https://www.youtube.com/watch?v=hkxnQIKybiI
https://www.youtube.com/watch?v=jHLyJbNgcDo


Why does this Arduino Pro Mini use a capacitor on the DTR reset line?

Most USB to serial chips set the DTR to LOW on connecting, but it keeps it LOW.

This would reset the arduino, but since the DTR never goes HIGH the Arduino will never get out of this reset state, and not run your code.

The capacitor will AC couple the signal. The the DTR goes low, the other side of the capacitor will go LOW too, but the pull-up resistor will slowly charge the capacitor, till the reset pin is HIGH again.

So it will convert a LOW transition to a LOW pulse.


How to transmit serial data from laptop USB out to Teensy?

Your second option is the easiest.

  a usb to ttl adapter cable to go straight to the Teensy LC, but I read somewhere that the serial UART with Arduino is different in some way

Without seeing what you read, perhaps they were just talking about the fact that the Arduino is not "true" RS-232, it's only at TTL (or 3.3V) levels.

  and wasn't sure if the serial communication coming through the usb to ttl cable would be compatible with the Teensy.

It should be compatible, especially since you note that the Teeny is 5V-tolerant.

  I was looking at one of these cables at sparkfun, and I think I would connect the TXD from the cable to the RX on the Teensy, the RXD from the cable to the TX on the Teensy, and the GND cable to a ground on the Teensy.

That's it in a nutshell!


Debugging a Nordic MCU (feather NRF52) using Segger J-Link

I haven't tried this, but OpenOCD supports both the nRF52 and the JLink.  Something like (on Linux):

openocd -f /usr/share/openocd/scripts/interface/jlink.cfg -f /usr/share/openocd/scripts/target/nrf52.cfg

might start OpenOCD.

You can then connect with (nRF52 flavour of) gdb (arm-none-eabi-gdb).

You can find information about using gdb with OpenOCD here and here.


Does the loop function work after being woken up from deep sleep? YES
loop function isn't magical.  its just a function that gets called over and over.  In other words, if it gets called once, it can be called again except if

it did something to deactivate itself
never reached the end

during that first call.  Check that you are not activating some sort of state inside the loop or going into a blocking call awaiting a signal that is never sent.
For good measure, make sure to reset all your variables to their expected states - expecting something to be 0 or set via the original definition may be insufficient.  This is something that occurs on a power reset so if reset is making it work again, thats a likely culprit.  Use a bare minimum of code in the loop for debug so you can figure it out.


Arduino Bluetooth connection with Android

You'll probably find that you are not supplying enough power to operate the Arduino and the components attached to the Arduino. Your current (Amps) draw is most likely higher than your external power supply can output.

I had this problem when using a 9v battery to power an Arduino with an XBee chip and some LEDs attached. The 9v would be able to power the kit for a while but would then not output enough current to power the Arduino. In the end I had to scrap a few LEDs.

You need to find out how much current your Arduino and its components are using and use a suitable power supply that can output enough current to power your Arduino.

Also remember when you send and receive a packet out of a Bluetooth radio - more current is required than when the Bluetooth radio is idle.


setting a dc motor to work for a fixed amount of time

There are two possibilities:
Easy way (but with limitations)
I see a delay of 200 (ms)… So if you want to have it working for a minute, than use 60,000.
If 60,000 is not accepted (maybe the input argument is a signed integer, having a max value of 32,767), than use a for loop and do a delay of a second for 60 times.
This solution will make it not respond within those 60 seconds to another left or right command.
Update: See comment of JRobert, 60,000 can be used without a problem.
Prevent a delay
If you want to respond to a left/right command WHILE the motor moving in these 60 seconds, you have to store the time (with millis) in a variable, and check against the time to know when to switch off the motor.
See command of Duncan C. This is very similar to the 'Blink without Delay' sketch which can be found here.
(Actually, there is a third way using interrupts, but I assume the second solution is best in your case, and is responsive enough considering the tasks you want to do with the Arduino.)


I had the same problem using this sensor. The solution was to connect

VCC -> 5V
GND -> GND
SCL -> A5 (SCL)
SDA -> A4 (SDA)
DNC -x Not connected
GN2 -> GND
XSH -> 5V
INT -x Not connected

And then to use the code mentioned here by Ted Meyers. I used Nano with ATmega328P and Arduino IDE 1.8.5.

CODE:

#include <Wire.h>

#define VL53L0X_REG_IDENTIFICATION_MODEL_ID         0xc0
#define VL53L0X_REG_IDENTIFICATION_REVISION_ID      0xc2
#define VL53L0X_REG_PRE_RANGE_CONFIG_VCSEL_PERIOD   0x50
#define VL53L0X_REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD 0x70
#define VL53L0X_REG_SYSRANGE_START                  0x00
#define VL53L0X_REG_RESULT_INTERRUPT_STATUS         0x13
#define VL53L0X_REG_RESULT_RANGE_STATUS             0x14
#define address 0x29

byte gbuf[16];

void setup() {
  // put your setup code here, to run once:
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
  Serial.println("VLX53LOX test started.");
}

void loop() {
  Serial.println("----- START TEST ----");
  test();
  Serial.println("----- END TEST ----");
  Serial.println("");
  delay(4000);
}

void test() {
  byte val1 = read_byte_data_at(VL53L0X_REG_IDENTIFICATION_REVISION_ID);
  Serial.print("Revision ID: "); Serial.println(val1);

  val1 = read_byte_data_at(VL53L0X_REG_IDENTIFICATION_MODEL_ID);
  Serial.print("Device ID: "); Serial.println(val1);

  val1 = read_byte_data_at(VL53L0X_REG_PRE_RANGE_CONFIG_VCSEL_PERIOD);
  Serial.print("PRE_RANGE_CONFIG_VCSEL_PERIOD="); Serial.println(val1);
  Serial.print(" decode: "); Serial.println(VL53L0X_decode_vcsel_period(val1));

  val1 = read_byte_data_at(VL53L0X_REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD);
  Serial.print("FINAL_RANGE_CONFIG_VCSEL_PERIOD="); Serial.println(val1);
  Serial.print(" decode: "); Serial.println(VL53L0X_decode_vcsel_period(val1));

  write_byte_data_at(VL53L0X_REG_SYSRANGE_START, 0x01);

  byte val = 0;
  int cnt = 0;
  while (cnt < 100) { // 1 second waiting time max
    delay(10);
    val = read_byte_data_at(VL53L0X_REG_RESULT_RANGE_STATUS);
    if (val & 0x01) break;
    cnt++;
  }
  if (val & 0x01) Serial.println("ready"); else Serial.println("not ready");

  read_block_data_at(0x14, 12);
  uint16_t acnt = makeuint16(gbuf[7], gbuf[6]);
  uint16_t scnt = makeuint16(gbuf[9], gbuf[8]);
  uint16_t dist = makeuint16(gbuf[11], gbuf[10]);
  byte DeviceRangeStatusInternal = ((gbuf[0] & 0x78) >> 3);

  Serial.print("ambient count: "); Serial.println(acnt);
  Serial.print("signal count: ");  Serial.println(scnt);
  Serial.print("distance ");       Serial.println(dist);
  Serial.print("status: ");        Serial.println(DeviceRangeStatusInternal);
}

uint16_t bswap(byte b[]) {
  // Big Endian unsigned short to little endian unsigned short
  uint16_t val = ((b[0] << 8) & b[1]);
  return val;
}

uint16_t makeuint16(int lsb, int msb) {
    return ((msb & 0xFF) << 8) | (lsb & 0xFF);
}

void write_byte_data(byte data) {
  Wire.beginTransmission(address);
  Wire.write(data);
  Wire.endTransmission();
}

void write_byte_data_at(byte reg, byte data) {
  // write data word at address and register
  Wire.beginTransmission(address);
  Wire.write(reg);
  Wire.write(data);
  Wire.endTransmission();
}

void write_word_data_at(byte reg, uint16_t data) {
  // write data word at address and register
  byte b0 = (data &0xFF);
  byte b1 = ((data >> 8) && 0xFF);

  Wire.beginTransmission(address);
  Wire.write(reg);
  Wire.write(b0);
  Wire.write(b1);
  Wire.endTransmission();
}

byte read_byte_data() {
  Wire.requestFrom(address, 1);
  while (Wire.available() < 1) delay(1);
  byte b = Wire.read();
  return b;
}

byte read_byte_data_at(byte reg) {
  //write_byte_data((byte)0x00);
  write_byte_data(reg);
  Wire.requestFrom(address, 1);
  while (Wire.available() < 1) delay(1);
  byte b = Wire.read();
  return b;
}

uint16_t read_word_data_at(byte reg) {
  write_byte_data(reg);
  Wire.requestFrom(address, 2);
  while (Wire.available() < 2) delay(1);
  gbuf[0] = Wire.read();
  gbuf[1] = Wire.read();
  return bswap(gbuf);
}

void read_block_data_at(byte reg, int sz) {
  int i = 0;
  write_byte_data(reg);
  Wire.requestFrom(address, sz);
  for (i=0; i<sz; i++) {
    while (Wire.available() < 1) delay(1);
    gbuf[i] = Wire.read();
  }
}

uint16_t VL53L0X_decode_vcsel_period(short vcsel_period_reg) {
  // Converts the encoded VCSEL period register value into the real
  // period in PLL clocks
  uint16_t vcsel_period_pclks = (vcsel_period_reg + 1) << 1;
  return vcsel_period_pclks;
}


You noted that your goal is to determine whether or not a vehicle is in motion. Because you are trying an IMU, I assume the device that needs to know this is on-board the vehicle.

There are many complicated ways to know this, such as using the acceleration data from the IMU to perform Inertial Dead Reckoning, this has the problem of temporal drift. A GPS has the issue of needing it's speed data to be filtered a bit to get rid of high-speed spikes.

But -- if you just need to know if the vehicle is moving or not, and if the vehicle has wheels, you can use an light detector, such as an IR emitter and IR receiver pair, along with a slitted disc attached to the wheel, and simply count when the last time the receiver was activated -- if beyond some threshold of time, then you assume the wheel is not turning, and thus that the vehicle is not moving. Or perhaps just use a light sensor and paint white and dark patterns on the wheel.

Or put a magnet on the wheel and place a hall effect sensor (magnet sensor) near where the magnet will pass. Count the pulses from the hall effect sensor.

If the vehicle is not a wheel-based vehicle, then you may have to rely on GPS or some other method, however.


Esp8266 firmware update with uno "chip sync error"

I run the same problem too and took me countless hours to figure this error out. The problem seems the Baud rate starts at 115200 while the COM port is set to 9600. What I did is I checked the Device Manager and find the COM port, right clicked to properties and to the Port Settings Tab, I changed the Baud Rate to 115200 and flash the firmware again. And it works!


Yes, i made a mistake... The arduino board should be powered by a 7-12V power supply to support high current from 5V pinout in order to power the sensor card... I'm very lucky, my sensor is not broken. I have powered it with 5V and it works fine!!! Thanks


Problem with sending a POST request using the WiFiEsp library

Your problem is the content you are sending. While this format works well e. g. in Python libraries, this library seems to have a problem with it.
I solved it this way, when I happened to face this problem:

//all your other code, including the remaining HTTP-Request
String content = "{\"temperature\":\""+String(value)+"\"}";
client.println("Content-Length: 16"); //insert, well, your content length
client.println(content);


7805 powered Atmega328 Stops working when input of 7805 exceeds 7volts

It looks like the reason for the MCU drawing high current is operating the LEDs in half a dozen optical isolators without current-limiting resistors.  The part number of your isolators apparently is PC817, for which the suggested LED current is 5 to 20 mA at about 1.2 to 1.4 forward volts.  But if you don't limit the current, they are likely to draw 50 to 100 mA each when turned on.  Add a series resistor, say 220 to 330 Ω, in series with each isolator.

At this point, it's possible you may have damaged your ATmega328 by overheating it, due to drawing too much current from its outputs.  You probably should run some tests with simple sketches to see if they all work ok.

Note, it probably would make sense to use a buck regulator rather than a linear regulator in the 12 V environment.  MP1584-based buck regulator boards (“Mini DC 4.5~28V to DC 3.3V MP1584 3A Step-down Converter Regulator Module”), about 2x2 cm, are about a dollar on ebay and handle 2 amps typically.


Arduino Yun - Sensor Data logging to MYSQL on External Server

Yes, you can do that using python as well as other languages, or you can use Temboo: there's an example bundled with the Arduino IDE, it's called "SendDataToMySQL"


Arduino Uno + Jaguar Speed Controller + CIM Motor (12V DC)

I searched for the library you're using and the arduino website mentions :

  0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement

From this we can take that the value 90 is not perfectly in the middle of the speed range therefore 10 points under 90 won't necessarily be equivalent to 10 points above 90.
My only advice is to try and find the equivalence point yourself by trail and error.
Even though 90 seems to cause no movement, try 89 or 91 see if they also have the result and so on.

Or simply try different values to get same speeds in different directions, it's ok if you use different values (away from 90) for the two different directions :P.

Gd Luck


What does the datasheet information for a switch mean?

A reed switch like this will not require any minimum voltage. It should work quite happily down to millivolt levels. If you want to switch on an LED from a 5V supply that is switched by the reed switch you will need a resistor that limits the current to no more than
20mA. The forward voltage drop over a red LED is around 2V so your resistor will drop 3V which means it needs to be at least about 150 ohms.


How to make timed loops after switch / case?

Create a new variable to hold the state of whether or not you are in autoClose mode:

uint8_t inAutoClose=0;

Then, add a line in your switch statement to set that flag when you enter that state, but not call the function if you were already in that state:

case 10:
  //automatic close
  Serial.println("A Close1");
  digitalWrite(gear1ClosePin, OFF);
  digitalWrite(gear1OpenPin, OFF);
  if (!inAutoClose) {
    inAutoClose = 1;
    t.enable(autoClose);
    autoClose();
  }
  break;

Add a line in your other switch branches to clear that flag:

case 1:
  //manually close
  inAutoClose = 0;
  [...]

If you want autoClose() to be called every 10 seconds repeatedly as the "idle" state, then you need to clear inAutoClose (set it to zero) at the end of every 10 second period. How and where you do that depends on other factors you haven't shown, like what autoClose() does, or what the timer you enable does.

Side note: avoid naming your timer name (autoClose) and your function name autoClose() the same! Does your code compile that way? It ought to throw an error.

ANSWER 2 (based on comments)

Your auto-close state is described as

  Turns on for 10 seconds, after that off for 10 seconds.

This can be accomplished with a similar structure to what you have now, with a few changes. (These are my suggestions, but by no means the best or worst way.)

Edit your open and close functions:

void Open1() {
  digitalWrite(gear1OpenPin, ON);
  if (isAutoOpen) {
    t.setTimeout(10000UL, Close1); // Sets a timer to call closer in 10s
   }
}

void close1() {
  digitalWrite(gearClosePin, ON);
  if (isAutoOpen) {
    t.setTimeout(10000UL, Open1); // Sets a timer to call opener in 10s
  }
}

When you call either Open1() or Close1(), if your auto-open flag is set, then 10s later, the opposite function is called, and this keeps chaining together, every 10s.

Whenever it's time to stop this, you clear the isAutoOpen flag and disable the timers. You may wish to keep track of the timer ID that is created with the setTimeout() function, so you can disable it at any time to avoid the system going through the cycle one more time after you clear the flag.


char printDigits(int digits){

You are telling the compiler you will return one character.

 char a[3];

a is three characters. Thus the declaration doesn't match.

You could change the declaration to:

char * printDigits(int digits){

But even that would be bad because a would go out of scope after the function returns.

 char a[3];

That's a little short for putting an integer into. An integer might be 5 characters, plus possibly a minus sign, and you need a trailing "null" at the end. Seven bytes would be safer.

The simplest way of doing what you seem to be wanting is:

void setup() {
  Serial.begin (115200);
  testCounter(3);
}

void loop() {
}

char testCounter(int countx){
  char a[15];
  sprintf (a, "COUNTER: %02d", countx);
  Serial.println (a);
}

Also, here:

  if(digits < 10) {
    strcpy(a, "0");
    sprintf(a,"%d",digits);
  } else {

That won't work because you are putting "0" into a and then overwriting it with sprintf.

  printDigits function return char, so... strcat should be work. But why still error?

Look at the prototype for strcat:

http://www.cplusplus.com/reference/cstring/strcat/

It expects char * not char. They are different things. One is a pointer, one isn't.


How can I make a garage door laser sensor?

I would recommend using laser and LDR. This will be very efficient and will not cause any problem due to light or ultrasonic deflecting. It will be precise by mm if you do thing right way. I made a simple porject back in 2005 using laser, LDR and relay.

Here what you need to do.

Get a laser, any laser will work. www.ebay.com/itm/6mm-650nm-DC-5V-5mW-Mini-Laser-Dot-shaped-Diode-Module-WL-Red-Copper-Head-Tube-/291089398593?pt=LH_DefaultDomain_2&hash=item43c647bb41

Get a PhotoResgister www.ebay.com/itm/Reliable-Hot-New-20-PCS-Photoresistor-GL5528-LDR-Photo-Resistors-Light-Dependent-/161434780484?pt=LH_DefaultDomain_2&hash=item2596434344

Put ldr in the dark box and drill a hole in it so that no other light can enter 2mm diameter hole will work.

Connect the LRD to your board. Fire laser and change status of indicator led by the value of ldr.

Check this link for refrence www.instructables.com/id/Arduino-Laser-Tripwire/?ALLSTEPS


All voltage directed to pin 3 when multiple pins are set to out put

It is probably a dead chip. Try getting a new ATmega chip for the Arduino (easily found online for ~$5) and see if that fixes it.


Making a composite waveform using a single TIMER interrupt

Woo, solved it.  My ISR code was completely wrong.  Works using:

ISR(TIMER2_COMPA_vect)
{
  if (timer2_signal_toggle_count != 0)
  {
    // toggle the pin
    if(signal_state == 1)
        *timer2_pin_port ^= timer2_pin_mask;

    if (timer2_toggle_count > 0)
      timer2_toggle_count--;
    else
    {
        TIMSK2 &= ~(1 << OCIE2A);                 // disable the interrupt
        *timer2_pin_port &= ~(timer2_pin_mask);   // keep pin low after stop
    }
     timer2_signal_toggle_count --;
  }
  else
  {
    timer2_signal_toggle_count = signal_cycle_count;
    timer2_toggle_count --;
    if(signal_state == 1)
    {
        signal_state = 0;
        *timer2_pin_port &= ~(timer2_pin_mask);
        //*timer2_pin_port ^= timer2_pin_mask;
    }
    else
    {
        signal_state = 1;
        *timer2_pin_port ^= timer2_pin_mask;
    }
  }
}

I was trying to just AND the signal state into the original pin state, which was completely the wrong thing to do.


According to the highlighted part of Due schematics it'd be better to connect 3.3V to the AREF pin as there might be some significantly big resistor between AREF and 3.3V source. So it might not be needed but one never knows.


ESP32 Arduino Bluetooth Serial does not reconnect after disconnecting

Nothing wrong with your code, I've the exact same issue as you have. It bothers me whole week long and fortunately, we (along with my colleague) accidentally figured that was caused by Windows 10, weird right? We don't believe it at very beginning either, but after several back-N-forth testing, it just like that. When we upload exact same code from another older computer with Windows 7 OS, it just works no matter how many time we connect/disconnect or even "QUIT" the APP without make it disconnect properly, its been able to be reconnect no problem. But once we use new computer with Windows 10 OS to upload the code, it can only be connected for first time, then stop broadcasting (or advertising).
The arduino official website in IDE download page also has a notice message "IMPORTANT: This app performs with core functionality on Windows 10 S but some limited plugins do not work. We are working with Microsoft on a fix.", hope this information helps.


HX711 Load Cell application strange behaviour

1) Put your power source on an oscilloscope and check it. I assume what's happening is you don't have a clean sine, and the power fluctuates, whereas power from a PC USB port is usually very well regulated. This may be causing issues in your sensor due to under/over voltage at a minuscule level.

2) Because you're pushing your sensors to the edge of their capabilities, you're going to have to work around them, so the normal scenario's don't really offer much help, as they are usually based on working within the middle ground of capabilities.

You said that factoring based on low load vs high load created unreliable  variances in your measurements, i would personally suggest calibrating not for max load, nor min load, but 2/3 of max, or 1/3 max, and see if that stabilizes you, or at least gets you somewhere to the middle of the road where your differences are nominal, or something you can live with.


Why is my LCD 16*2 is not displaying any characters, although all the wiring is correct?

Check out this tutorial on Adafruit. It will walk you through setting it up. In the tutorial they change the pins, which I believe is the issue here. Here is a snippet.

And change your pins:

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);


Just use a single 1ms timer interrupt and count them. Every 10 interrupts do both things.
void interruptHandler() {
   counter++;

   // do things that happen every 1ms

   if(counter == 10) {
      // do things that happen every 10ms
      counter = 0;
   }
}


While condition with & bitwise of PINx read

SPI transmitt is started by writing one Byte into SPDR. And this code won't return from SPI_MasterTransmit function before it's complete. Transmitt completition is anounced by setting SPIF by hardware (and if SPI interrupt and global interrupts are enabled, it'll run also ISR and clear that flag).

If you write into SPDR before transmission is completed you'll corrupt current "transaction", so you have to wait until it's complete before another write.

Bitwise & is used for bit masking. Bits in the result are set if bits at corresponding positions in arguments are both set:

0b00110011
         &
0b00100001
        ==
0b00100001

So if bit at position SPIF is not set, it will loop again and when it's set, it exits the loop, as there is inverted logic.

( SPSR     & (1<<SPIF))                    !(SPRS &(1<<SPIF))
0b0xxxxxxx & 0b10000000 == 0b00000000  =>  !0b00000000 == true
0b1xxxxxxx & 0b10000000 == 0b10000000  =>  !0b10000000 == false


Can I hook up two micros to one GPS module?

You are quite wrong. The answer is not "it depends", but "yes".

You can have any number of devices listening to (receiving) the transmitted data. You can only have one device sending anything back to whatever it is that is broadcasting the data if you need to configure it in any way. That shouldn't be a problem of course if you have one main controller that does that configuration and everything else is just a passive listener.  Just be sure that you don't connect the transmit pins of the passive listeners to anything (unless you want to use them for a completely unrelated purpose to transmit serial data to something else).

The only caveat is that each device you add as a listener will increase the load on the GPS's transmit pin and eventually the slew rate will become too slow and the signal will become distorted. If this ever becomes an issue reducing the baud rate can combat it to a certain extent. For serial though you would need quite a lot of devices for it to become an issue. Two devices certainly won't ever be an issue.


Read a String from serial to debug the AT commands sent to my GPS shield

if (Serial.available() > 1) is wrong. Always use if (Serial.available()) in such cases. Also it seems you are communicating with the GPS shield using Hardware Serial. However, the Arduino also uses the same serial port for communicating with the PC via the USB connection. So what you have basically is:

Arduino TX, PC RX and GPS RX are all connected
Arduino RX, PC TX and GPS TX are all connected

So anything the Arduino writes to the Serial port using Serial.println() is received by both the PC and the GPS shield. And the other hand, responses from the GPS shield and commands sent from the serial monitor all arrive at the same Arduino pin. So when you use Serial.read(), assuming you used the serial monitor to send the command, you will end up receiving your own command (like some sort of echo), and according to your program, you use Serial.println() to send the command again which is received by both PC and GPS shield, with the GPS shield responding to the same command again. All undesirable.

TLDR; use SoftwareSerial instead for the GPS shield. Connect the GPS shield TX to pin 2 and its RX to pin 3 and use this code:

    #include <SoftwareSerial.h>

    SoftwareSerial gps(2,3);   // pin 2 = RX, pin 3 = TX

    void setup(){
        Serial.begin(57600);
        gps.begin(57600);    // change to your baud rate, if not auto-baud
    }

    void loop(){
        while (Serial.available())     //used to send commands from PC
            gps.write(Serial.read());   // to gps
        while (gps.available())        // used to read responses from gps
            Serial.write(gps.read());  // to PC
    }

So the Arduino forwards everything it receives from the PC monitor (commands) to the shield and sends everything it receives from the shield (responses) to the PC to be displayed in the serial monitor.


Java NetBeans sending value and receiving value from Arduino

You are writing a number as a single byte and expect it as a string on the other end.

Replace

val = Serial.parseInt();

with

val = Serial.read();


Buttons for LED strip only work when held down

It's a software issue.  You are basically saying "If this button is currently pressed down then run this sequence once", rather than "If this button has transitioned from OFF to ON then set my current sequence to X"

You need to learn about the Finite State Machine and about switching from one state to another (or one selected sequence to another) when a button changes state not when it is in a state.

So basically the whole logic of your program is flawed and needs re-working.


Atmega328p - PCB ISP pins for bootloader and sketch upload

Realistically, you should design ATmega boards to support both ISP and bootloader pins.  The logic is simple:

Unless you buy pre-programmed chips, or have a programming fixture, you will need ISP either to load the firmware itself, or to load a bootloader.
Even if you plan to use only ISP for programming, it is still worth providing external connections to the UART pins for interacting with firmware during development; generally with ATmega-based Arduinos you do not have a breakpoint debugger, so debug messages on serial are your primary visibility into what is happening.
You should wire the reset line to somewhere that you can manipulate it, so you don't have to power cycle your firmware every time you want to restart it in testing.

Once you have done all that, you end up with support for both ISP and UART bootloader - regardless if you plan to use them both or not.


This is basic algebra 1.
Say steps / degree = 5
So write that as 2 fractions:
steps   5
----- = -
degree  1

Then take the reciprocal of both sides:
degrees   1
------- = -
step      5


Can I use this board to control multiple vibration motors?

Not directly, no.  Those boards are designed to generate a low power PWM signal for passing to a servo with a built-in controller. To use that output directly with a motor you will need to add a transistor to each output to control the motor.

simulate this circuit – Schematic created using CircuitLab


Uno pin connection: Atmega16u2 & ATmega328P

You could use from PB1 to PB3 from 16u2 (SCK, MOSI, MISO) wich are exposed to its ICSP.
Add a wire from one of them to your atmega328 :)


Why does it say "Servo" does not name a type

Your include statement seems to be incomplete; add "Servo.h" to your include to make it look like this:

#include "Servo.h"

Without including "Servo.h", the compiler doesn't know what a servo is, and thus "Servo does not name a type".


(By googling) I figured out the problem and a work-around. But not an executable solution. The problem seems to be that the RF module is not properly initialised when the device is powered on or awakes from reset.

Sadly there seems to be no manual mode to switch on the RF module.

However, I found a workaround. First I made the connection to enable deep sleep, for that, we need to tie the RST pin to D0/GPIO 16 on the ESP8266.

Then I added the following code to setup

extern "C" {
  #include "user_interface.h"
}

void setup(){
  if (resetInfo->reason != REASON_DEEP_SLEEP_AWAKE) {

      ESP.deepSleep(10, WAKE_RF_DEFAULT)
  }

Basically whenever the system comes into setup from something else than deep sleep, the system goes to deep sleep and when powering back on the RF module is enabled.


The code shown in two previous answers is problematic.

For example, in Look Alterno's code, Serial.println("R") will trigger an R response.  The while(!Serial.available()); construct will wait for the first byte of the response.  Then responseR = Serial.read(); will read one byte.  Next, Serial.println("O") will attempt to trigger an O response.  The second while(!Serial.available()); will wait for a byte to be available, which should happen when the second byte of the R response arrives.  Then responseO = Serial.read() will read that byte.

In ratchet freak's code, each quarter second bytesToReadFromR and bytesToReadFromO are set to 8.  In the next several passes through loop(), if(bytesToReadFromR) and if(bytesToReadFromO) are satisfied, so while(bytesToReadFromR && Serial.available()) and while(bytesToReadFromO && Serial.available()) will be controlled by whether a character is available.  At 9600 bps, about one character per millisecond will become available, so most of the time we are just spinning through loop() dozens of times per millisecond, waiting for characters.  The if statement for bytesToReadFromR has a slightly higher chance of catching fresh characters, but which buffer (responseR or responseO) gets any given character still is left to chance.

Instead of the code previously shown, consider something like the following:

enum { dataBytes = 8, interval=250 };

float getResult (char trigger) {
  union { byte d[dataBytes], float f[2] } u;
  byte rin=0;
  Serial.print(trigger);
  while (rin < dataBytes) {
    if(Serial.available())
      u.d[rin++] = Serial.read();
  }
  return u.f[0];        // Assumes bytes in forward order
}

unsigned long prevMillis = millis();
float RValue, OValue;

void loop() {
  if(millis() - prevMillis >= interval) {
    prevMillis = millis();
    RValue = getResult ('R');
    OValue = getResult ('O');
    // put code here to consume the results
    // ...
  }
}

Note, this code will get stuck if too-few characters arrive from the R&O device, or if some characters get lost for any reason.  One could add a timeout to the loop in getResult(); it could check for millis() - prevMillis >= interval and if so, break the loop and return a NAN.

Note, this code assumes the byte-order of floats from the R&O device matches that of the Arduino.  That will be so if both are big-endian, or if both are little-endian.  If they differ, store bytes in reverse order into the u.d array, and return u.f[1] instead of u.f[0].

Note, union is a C / C++ technique for accessing data multiple ways.  The declaration union { byte d[dataBytes], float f[2] } u says that u is a structure where the array d starts at the same address as the array f.  Thus, the float u.f[0] corresponds to the first four bytes of u.d, and u.f[1] to the next four.

Note, if the R&O device requires an end-of-line character, change  Serial.print(trigger) to Serial.println(trigger).


Yes, it is possible.

Your code doesn't show any sign of board powering on and initialization.

SIM900 has some LED that show status - make sure you are connected to GSM network.

Please check this tutorial: https://www.youtube.com/watch?v=RUGV_64lQX8


Using the ATMega328, from an Arduino UNO in a Standalone configuration, and bootloader - I am really lost

So do I understand you correctly that you want to lift the ATmega328 IC from the Uno board and use it on a breadboard? That strikes me as an unnecessarily risky proposition just to save a dollar or two for a separate ATmega328p.

Second, you technically might not have to write a new boot loader to the chip, if you don’t intend to reprogram it while it’s on the breadboard, but you definitely need different fuse settings, and the two changes are closely related in the Arduino IDE.

Third, bootloaders on ATmega are incapable of modifying themselves, so if you want to write a new bootloader, you always need a programmer (which can e.g. be your Arduino UNO running the ArduinoISP sketch or ScratchMonkey); I don’t think your single-microcontroller idea would work.

For mass production, you’d just use a programmer. Bootloaders tend not to be used for this, which can lead to situations like this year’s mishap at SparkFun


Lots of errors in your code. Mine is basically the same that @frarugi87's answer.

I only have to add: when reading serial, wait for the end of line ('\r' and/or '\n') to know when you have all your data, so you don't depend on length (which can be corrupted).

Edit (on Majeko's comment)

String code, rs1, rs2, rs3, readString;
void setup()
{
  Serial.begin(9600);
  Serial.println("Serial ready!");
}

void loop()
{
  static bool inData = true;

  while (Serial.available()) {
    char c = (char) Serial.read();

    if (c != '\r' && c != '\n') {
      readString += c;
      inData = true;
    }
    else {
      if (inData) {
        rs1 = readString.substring(0, 3); //034
        rs2 = readString.substring(3, 6); //000
        rs3 = readString.substring(6, 9); //017
        code = rs1 + rs2 + rs3;
        Serial.println(code);

        if (code.equals("034000017")) {
          Serial.println("OK");
        }
        readString = "";
        inData = false;
      }
    }
  }
}

This code works for any configuration of line ending ('\r', '\n' or '\r\n').

It doesn't test for length (or validity or timeout); it's left as an exercise to the reader :-)

I hope it shows how code grows when making it robust in all scenarios.


Do I need a relay to control a monitor's power with an Arduino?

It's always better to use MOSFET as a switch (or relay) like this:

It can handle loads up to 24V, 5A. The load is powered from an external supply. It is based on a IRF520 Mosfet and cost 0.55 a piece in Aliexpress. Search "Arduino IRF520 module"

You need one Arduino pin to switch on/off the load.

It's very handy and provide posts for power input/output.

I understand that you will still power the monitor from the wall, replacing only the original switch with Arduino. Otherwise, you will need a bigger relay


...I have read that on low voltage I have to use 8Mhz crytstal...

Technically you can run anywhere below 13Mhz or so, so you have lots of choice.

You may also be able to use the prescaler to divide the clock by 2, either by hoping the ATmega can run the short time at 16MHz, or by programming the CKDIV8 fuse to start it at 2MHz.

  ...do I have to take the chip out to reflash with the programmer again...

If you move to a frequency within spec with either a clock change or prescaler use, yes. The bootloader and Arduino libraries expect a 16MHz clock, so you will have to rebuild the bootloader with the new clock rate, and sketches that use delay() et alia as well as the intrinsic delay functions will also need to be rebuilt.

  What will happen if I do not change the oscillator and leave it on 16MHZ ceramic?

It may work, it may not.


How come `MyClass.MyStaticMethod()` doesn't work, but `Serial.begin()` does?

. is used to call a method on a class instance whereas :: is used to call a static method within a class itself.

There is no Serial class - Serial is merely an instance of the HardwareSerial class.

#if defined(UBRRH) && defined(UBRRL)
  HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);
#else
  HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
#endif

If you want to use . then you have to instantiate your class and not use a static method:

class MyClass {
    static void myStaticMethod() {
    }
    void myMethod() {
    }
};

MyClass Fred;

// ...

Fred.myMethod();
MyClass::myStaticMethod();


Is your servo the modified 360 degree type with no position feedback (meaning the internal feedback potentiometer has been disabled)?


The READY signal is open-collector. It will therefore require a pullup-resistor. Test circuit in datasheet shows a 2 kohm resistor. You could try with that. Alternatively use the internal pullup resistor on the input pin but this may be too large (weak).

Cheers!


How to program arduino for ethernet with only usb cable

You can do the programming of the Arduino through the USB cable, but in order to test and operate the program, you'll need an Ethernet shield and a cable to connect that to the LAN.


Adapt Dynamixel library to different shields

You are setting the baudrate to 57.6K however, you need to communicate with the Dynamixel at the baudrate it is set to. I believe the Dynamixel comes with a preset baudrate of 1Mbs. The first thing thing I would do is to change your 57.6K to 1Mbs and try that. This is assuming the ID is actually 1 (also a default)

Here are two links for info on Arduino baud rates and Dynamixel serial communications.

Controlling AX-12 Servos

How high of a baud rate can I go (without errors)?


It seems this was planned for the Adafruit BMP280 library but not implemented. Looking at Adafruit_BMP280.h we see commented code that has a method seaLevelForAltitude():
/*
class Adafruit_BMP280_Unified : public Adafruit_Sensor
{
  public:
    Adafruit_BMP280_Unified(int32_t sensorID = -1);

    bool  begin(uint8_t addr = BMP280_ADDRESS, uint8_t chipid = BMP280_CHIPID);
    void  getTemperature(float *temp);
    void  getPressure(float *pressure);
    float pressureToAltitude(float seaLevel, float atmospheric, float temp);
    float seaLevelForAltitude(float altitude, float atmospheric, float temp);
    void  getEvent(sensors_event_t*);
    void  getSensor(sensor_t*);

  private:
    uint8_t   _i2c_addr;
    int32_t   _sensorID;
};

*/

In another library, BMP280-arduino-library, I found a function that seems to work:
double BMP280::sealevel(double P, double A)
// Given a pressure P (mb) taken at a specific altitude (meters),
// return the equivalent pressure (mb) at sea level.
// This produces pressure readings that can be used for weather measurements.
{
    return(P/pow(1-(A/44330.0),5.255));
}

First, I just copied that function into my code (without the class name), due to the friendly pizza license. Later I switched to that library and it also worked fine.


How to control segments with SevSeg library

You can't with that library. The author has not provided any public methods that will do the job.

There are private methods (segmentOn and segmentOff) that might be usable, but you would have to modify the library to be able to access them.


The Arduino Blink example uses delay() to pause the Arduino in a specific state, so that for a specific amount of milliseconds the device will keep the blinkPin HIGH or LOW.

Instead of using a delay(), you should use millis(). The main advantage of millis() over delay() is that it does not interrupt the code. When you call a delay() the whole code pauses, nothing can be done during those milliseconds. But millis() doesn't work that way. You also don't call it the same way as delay().

What millis() does is that it stores a timer value into an unsigned long. At a later point in time you can substract a new millis() from your previously stored millis in the unsigned long. The result is a difference in time between each millis() in milliseconds.

Now, instead of using only one unsigned long, we use two different ones: one for each LED. Now you can log a time interval, independently, for each LED. Furthermore, if you apply the logic of millis() for keeping the LEDs on or off, you don't have to interrupt the code with delay() functions. This means, that regardless of each LEDs state (HIGH or LOW), the timer keeps running, keeps logging and thus can control both LEDs simultaneously.

To give you a bit more information on millis(), below are some references that will get you started in how to implement. If you have more questions, just comment on this answer :)

millis() reference on the Arduino website
Blink without Delay example


Send AND Receive through i2c / set Arduino as master AND slave

The I2C protocol is both read and write. Master/Slave depends on who initiates the communication. Typically the master will issue a read command to the slave to retrieve the results.

Cheers!


How to use a Bi-color matrix led 8x8 with 24 pins?

Take a closer look at the device schematic diagram, which I copy below. It will tell you how each of the LEDs are wired. For example, the green LED on the upper-left corner (which I marked with a green circle) has its anode (positive terminal) wired to pin 5, while its cathode (negative terminal) is wired to pin 1. Can you see that?

To light up that LED (green LED on the upper-left corner), you must apply voltage (with limited current), to pins 1 (-) and 5 (+). If you wanted to light up the red LED at the same position instead, you should apply voltage to pins 1 (-) and 20 (+).

To light up all LEDs of a given color, you'll have to connect pins 1, 2, 3, 4, 21, 22, 23 and 24 to the negative terminal of your power supply. These are the LED common anodes. They are called common because they are shared among each pair of red and green LEDs. If you choose to use the red LEDs, you'll also have to wire pins 13 through 20 to your positive supply. On the other hand, if you pick green, you'll wire pins 5 through 12. These are the LED cathodes.

Don't forget to wire a current limiting resistor in series with each LED.


Compiling with -flto and -nostartfiles results in no program at all

As @MaximilanGerhardt wrote in his comment. LTO was optimizing away too much of the code. Usual programs start with the interrupt vector table that in case of a regular reset or startup point to the main function. That is why the compiler knows that main has an entry point and is used. The actual program starts at the table.

Removing  the interrupt vector table with -nostartfiles causes the compiler not to know that main is used at all and optimizes it away.

To give the compiler a hint __attribute__((used)) has to be placed at all methods that have to stay and there is no code path leading to them otherwise.


Failed to boot VL53L0X: VL53L0X Error: -6

I was facing same issue, now my problem is solved here.
This problem mostly occurs when we apply a power supply to the MCU that has capacitors at its output. This type of power supply's rising voltage is like you can see the image:

If you look at the data sheets of MCUs, you see that most MCUs can work at 1.8V to 5.5V. Here the rising voltage is slow; the MCU starts working at 1.8V and send signals to VL53L0x, but the sensor doesn't work at 1.8V.
So, what you need to do is add some delay (first power supply gets stable then start communication with sensor) in your code to avoid this issue. Do not add delay in the loop; it will affect the working of the MCU, where exactly you need to add delay. Code modifications are in the video below:
https://youtu.be/QEiNbTB8nNE
or you just can search on Youtube: How to fix VL53L0X error


Arduino Uno's Timer maximum frequency using Timer Compare Interrupt, not Timer Output Pins (e.g. OC0A)

How can one explain that using this code I get this toggle frequency on the digital pin ?

Code takes time to execute. Your ISR, when compiled, looks like:
ISR(TIMER0_COMPA_vect)
{
 124:   1f 92           push    r1
 126:   0f 92           push    r0
 128:   0f b6           in  r0, 0x3f    ; 63
 12a:   0f 92           push    r0
 12c:   11 24           eor r1, r1
 12e:   8f 93           push    r24
 130:   9f 93           push    r25
    PORTB ^= 1 << 1;  // Toggle D9; this allows to measure the toggle frequency, however this could be replaced by some code to generate a custom binary signal
 132:   85 b1           in  r24, 0x05   ; 5
 134:   92 e0           ldi r25, 0x02   ; 2
 136:   89 27           eor r24, r25
 138:   85 b9           out 0x05, r24   ; 5
}
 13a:   9f 91           pop r25
 13c:   8f 91           pop r24
 13e:   0f 90           pop r0
 140:   0f be           out 0x3f, r0    ; 63
 142:   0f 90           pop r0
 144:   1f 90           pop r1
 146:   18 95           reti

That's 18 assembly instructions, each needing between 1 and 4 clock cycles to execute.  Referencing the datasheet you can count the exact cycles needed and sum them up, yielding 31 clock cycles.
Toggling at maximum speed that would be 16MHz / 31 = 516kHz.
And then you have the rest of the code running between each call to the interrupt, so it's slower than that.

How can I generate a custom binary signal over a digital pin at the highest possible frequency ?

By not using interrupts, and writing a tight loop in assembly language.


Ops, I just realized it's the compiler working it's magic. I never used t, thus the compiler said "Wtf is this guy doing, this t is useless and I'll remove it!". When I used t I got sensible results.


Welcome to SE.

digitalWrite() takes a few microseconds to execute as well. There is also some overhead around the delayMicroseconds() function.

I you need exactly 500 kHz, you would want to consider using a timer.
You can read up on how to set one up in the microcontrollers datasheet.

Unfortunately, I don't have access to an Arduino Leonardo, but here is an example code for the ATmega328P. The register names will be different, but you should be able to adapt the code to fit your Arduino.

// 500 kHz frequency

void setup() {
  cli();                 //Disable interrupt during setup
  TCCR2A = 0;
  TCCR2B = 0;

  TCCR2B |= (1 << CS20); //Enable timer without prescaler
  OCR2A = 15;            //Do interrupt TIMER2_COMPA after reaching this counter value
  TIMSK2 |= (1 << 1);    //Enable TIMER2_COMPA interrupt

  DDRD |= (1 << PORTD3); //Set Digital Pin 3 as Output Pin
  sei();                 //Enable interrupts again
}

ISR(TIMER2_COMPA_vect) { //If the counter has reached the point where the output needs to be low
  TCNT2 = 0;
  PIND |= (1 << PORTD3); //Toggle Digital Pin 3
}

void loop() {
  //your looping code here
}

Explanation:
TIMER2 is an 8-bit timer, which means it will always count from 0 to 255, regardless of what the CPU is doing.

Normally, it counts up at the Arduino's clock frequency, like 16 MHz.

When the counter hits 15, a special code is immediately executed, called an "Interrupt Service Routine". In this code, we reset the timer and change the state of your outpin pin, resulting in a 500 kHz square wave on that pin.

We count to 15 since there are 16 steps in between "0" where the counter begins and 15, where we reset it.

16'000'000 Hz / 1 (no prescaler) / 16 (counter) / 2 = 500 kHz

The divisor of 2 comes from the fact that we need to change the pin state twice for every full square of the output signal.


How to detect water presence with only 2 wires

Since all you have is 2 bare wires, the water simply forms a resistor between them.

You can use it as part of a resistive divider, with a fixed resistor between your analog input and +3.3V.  The resistance between the wires will change from infinite (dry) to something much lower (wet) and the reading you get from the ADC will depict that.

You will need to experiment with different resistances in order to get reasonable values, but start with 10kΩ, or 100kΩ.  If you use a very high resistance (in the order of 1MΩ or more) you may even be able to use it like a simple switch and connect it to a digital input.

Be warned, though, that this method will cause a small amount of electrolysis, causing one electrode to be eroded away and the other to gain extra material.  For this reason it can be good to connect the resistor to a GPIO pin instead of directly to +3.3V and switch the GPIO pin HIGH when you want to do a reading (to provide power) and LOW (or INPUT) when at other times (to remove power).  This will greatly increase the lifetime of your water sensor.


Cannot get HC-12 to function with Arduino Pro Micro clone

Solution to problem is as follows:
 For the Arduino Pro Micro [as for the Leonardo], Serial1 must be used instead of a SoftwareSerial specification, e.g.,

SoftwareSerial HC12(HC12TxdPin, HC12RxdPin).

Code is to be modified by changing HC12.available() to Serial1.available().  The same holds true for the reads and writes.
Pins are to be wired such that the HC-12 RXD pin connects to the Pro Micro TXD pin, and the HC-12 TXD pin connects to the Pro Micro RXD pin.
My thanks to @mico for providing the reference that explains it all.


I've read you post a couple of times and I get the impression you would like this board to work, so here are some quick check to try and find the fault.

You need a bread board
An arduino
A 200-300 ohm resistor.
Some wires. About 6 hands :)

Connect the board ground to the breadboard.  Then connect the to the resistor.  Then connect that to the power supply ground.

Take the positive off the power supply and touch it to the LED1 pin and check LED1 lights up.  Repeat with 2 and 3.

Switch every thing off

Connect the Positive to the Vcc connection of the board.
Connect a wire between Arduino A0 and "Sinal Analog"

Load this sketch

   void setup() {
       Serial.begin(9600);
    }
   void loop() {
       Serial.println(analogRead(A0));
       delay(250);
   }

When you cover the LDR it should read a lower number when you shine a light on it should read a higher number.

Turn everything off again, and if you have a multi meter test the resistance of the resistor on the board it should be 300 ohms, but I can't remember which way to read the bands and it might be 10K ohms, which would be a problem.

If anything doesn't work then they can all be fixed for a few cents and you don't need to worry about the discolouration.

Hope that helps you.


Why can I measure two pins simultaneously?

You can test it easily by calling the function twice directly after each other. If the first time a true is returned and the second time a false, the state is internally reset.

But probably because after you call the fell function, the internal state is reset, so after the call not a new fell has been happened.

So store the return value of the fell and rose functions and use those instead.

Update:

I'm not sure if this is the actual implementation but I found for fell/rose and see this:

bool Bounce::rose()
{
    return ( state & _BV(DEBOUNCED_STATE) ) && ( state & _BV(STATE_CHANGED));
}

bool Bounce::fell()
{
    return !( state & _BV(DEBOUNCED_STATE) ) && ( state & _BV(STATE_CHANGED));
}

So as long as the state has not changed it returns false (which is similar/equal as 'resetting the internal state'. Except this reset is done at a different location (but checked in the fell and rose function).

Update:

See remarks from gre_gor below


Using an Arduino to rotate a DC motor once a minute (edited)

The best way would be to check the datasheet: https://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf and set an interrupt on one of the timer.
Example code of this application can be found on this stack here : How to make 1 second delay more accurate?
Another way of doing it if you don't need to do anything between rotation would be to wait by just waiting using delay in a for loop. Be aware that this is less precise than interrupts driven wait.
https://www.arduino.cc/reference/en/language/functions/time/delay/
edit : if you want to complete one full rotation every 60s
int i = 0;
while(1) {
  i++;
  delay(1000);
    if( i == 60){
    doFullRotation();
    i = 0;
    }
}


Cool question! ;-) Instead of a fixed timer, I would build in some (so-called) hysteresis, which means turning refrigeration on above a certain temperature (say 4 °C) but only turning off when the temperature has dropped again to a temperature well below that (say 3 °C). This ensures the temperature stays within set limits while at the same time preventing fast cycling. You don’t need any timers for this and it will work in any situation (even when it’s very hot or very cold outside of the fridge). This is how commercial thermostats work.
If you really need to ensure the compressor cools enough between cycles, you just need to start a timer when it turns off, and not turn on again before it expires. Look at examples like BlinkWithoutDelay for some coding ideas.


How do I even out Infared distance sensor readings?

Averaging is a very good technique for improving noisy data, provided
you have a “nice” noise. “Nice” meaning that you never get “atypical”
data points, i.e. the error of any given data point is of the order of
the “typical” error amplitude. If you have for instance
additive white Gaussian
noise, then
it can be shown that averaging is in some way the “best” way to clean
your data.

However, if you have big sporadic errors, then averaging is not a good
solution. This is because you will have to average a lot of samples
in order to smoothen out a single big error... and the more samples you
average, the more chances you have to get another huge error that will
ruin your average. Of course, averaging will somewhat improve things,
and it is better than no smoothing at all, but there are better options.

The solutions to this problem lye in the realm of robust
statistics. It may look
like hairy math, but there is actually a very simple smoothing filter
that is far more robust than the average: it's called the
median. The idea is quite simple:
you sort your list of samples from smallest to largest, then you pick
the one sample that ends right in the middle of the sorted list. Unlike
the average, this filter is completely insensitive to samples carrying
huge errors, as long as the majority of samples are reasonable.

Here is an implementation of a simple moving-median filter based on the
standard libc’s qsort(). It assumes samples have int type, but you
can change it to whatever numeric type you want. You can also change the
filter length: longer lengths provide more robustness against series of
consecutive bad samples, at the cost of more filter delay, more memory,
and more processing time.

/*
 * Comparison function for qsort(): return an integer "less than, equal
 * to, or greater than zero if the first argument is considered to be
 * respectively less than, equal to, or greater than the second."
 */
int compare(const void *pa, const void *pb) {
    int a = *(int *)pa;
    int b = *(int *)pb;
    return a<b ? -1 : a>b ? +1 : 0;
}

#define FILTER_LENGTH 11  // length of the median filter, should be odd

/*
 * Input: raw sample.
 * Ouput: filtered sample.
 */
int median_filter(int data) {
    static int input_buffer[FILTER_LENGTH];
    static int input_index;
    int sorted_buffer[FILTER_LENGTH];

    // Store the current data point.
    input_buffer[input_index] = data;
    if (++input_index >= FILTER_LENGTH) input_index = 0;

    // Sort a copy of the input buffer.
    for (int i = 0; i < FILTER_LENGTH; i++)
        sorted_buffer[i] = input_buffer[i];
    qsort(sorted_buffer, FILTER_LENGTH, sizeof *sorted_buffer, compare);

    // Return median.
    return sorted_buffer[FILTER_LENGTH/2];
}

As I did not explicitly initialize the filter memory, this will output
zeros the few first times it is called. I encourage you to try this
filter and compare against an exponential moving average, and only then
decide which works best for you.