Converting c string to integer to unsigned char

Not sure if or why you want to convert char* to int, but if you need to, there are atoi(), atol(), strtol(), strtoul() to consider, or rolling your own function.
Pros and cons are discussed here. Main thing to note is that atoi() and atol() have no error handling, but if the char* you feed them is completely under control and predictable, that need not be a problem.
BTW I would try to get the websocket to send the correct single bytes instead of string representations of numbers, if at all possible.


Blinking 2 LED having input from serial monitor

@Juraj was on the right track however the end-of-line characters for example may not be buffered and the problem could continue.

The correct approach is the wait for the end-of-line character specifically.  Let's take the easy way out and use Serial.readStringUntil

#define EOL_CHAR '\n'

void setup() {
  Serial.begin(9600);
  pinMode(REDledpin,OUTPUT);
  pinMode(YELledpin,OUTPUT);

  Serial.println("How much voltage you want to apply to the red LED (0-255)?");
  while(Serial.available()==0){}
  redintensity= Serial.parseInt();

  Serial.readStringUntil(EOL_CHAR); // clear serial buffer to end of line character

  Serial.println("How much voltage you want to apply to the yellow LED (0-255)?");
  while(Serial.available()==0){}
  yellowintensity = Serial.parseInt();

}

This all depends on what you're Serial Monitor is sending as a new line; it could be CR (\r), LF (\n) or CRLF (\r\n), so change the EOL_CHAR value accordingly depending on your serial monitor setup.


Conncet Bluetoth module HC-05 to Arduino Uno Using UART Usb to enter in AT command

By using SoftSerial you can connect the HC-05 module to another pin than D0 and D1. Example connect HC-05 to D2 and D3 and define SoftSerial to use D2 and D3.

---------                        -----------                        ------
| HC-05 +---(SoftSerial)---(D2/3)+ Arduino +(D0/1)---(Serial USB)---+ PC |
---------                        -----------                        ------


Answering my own question - a bit of a walk of shame here.
I had disabled the internal TIMER0_OVF_vect in the arduino core code, so that I could write my own (for another project). I wrapped in in an #if 0 so I could go and bring it back when I needed it.
Today, I learned that the atmega interrupts aren't filled with an IRET by default, but instead hit the reset vector, resetting the board. Anything I compiled on this library would reset whenever TIMER0 overflowed, because my ifdefs didn't cover the TIMSK setting in the arduino core either
The "Serial.println isn't exiting" was actually "the board is resetting before it can complete" and explains why faster bauds could print more data.
Not much smarter than hairless apes, sometimes.


How to reprogram Arduino if USB port is already in use?

https://digistump.com/wiki/digispark/tutorials/connectingpro
It is suggested that in order to upload using the Arduino IDE you must:

Add the repository http://digistump.com/package_digistump_index.json in Preferences > Additional Boards Manager URLs
Install Digistump from the boards manager.
select the DigiSpark in Tools > Boards.
Then this is perhaps the important bit "You do not need to plug in your Digispark Pro before invoking upload"   So hit upload before connecting the Digispark.
Then connect the Digispark when prompted by the Arduino IDE.


HM-10 send and receive data and checking received value

The first issue, I am checking if c equals "hi" and if it does then display said hi.

This is not how you compare:

  if (c.equals('hi')) {

Single quotes indicate a single (or multi-byte) character.  A character string (lower-case) is enclosed by double quotes:

  if (c == "hi") {

But it's better to avoid the String class (more info here).

To eliminate the String class, use char arrays instead (aka "C strings") and accumulate characters until the newline is received.  There are many, many C string functions for manipulating and searching.  In this specific case, you would use strcmp or strstr for comparison:

#include <AltSoftSerial.h>

AltSoftSerial bluetooth; // pin 8 is RX, pin 9 is TX

char btResponse[ 20 ];
uint8_t count;
const uint8_t BT_MAX = sizeof(btResponse);

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

  Serial.println("PC Side Connected");
  bluetooth.begin(9600);

  bluetooth.println("Bluetooth Side Connected");
  bluetooth.println("AT"); // just a check
}

void loop()
{
  if (bluetooth.available()) {
    // Read what is sent back from the BT module
    char c = bluetooth.read();

    if (c == '\n') {
      btResponse[ count ] = '\0'; // NUL-terminate the character array

      // Use C string functions to parse the response

      if (strcmp( btResponse, "hi" ) == 0) {
        Serial.println("only said hi");

      } else if (strstr( btResponse, "hi" ) != nullptr) {
        Serial.println("said hi, among other things...");

      }

      // And if there is a comma in there somewhere, display all comma-separated fields
      if (strchr( btResponse, ',' ) != nullptr) {
        uint8_t fieldNumber = 0;

        char *field = strtok( btResponse, "," );
        while (field != nullptr) {

          Serial.print( "Field " );
          Serial.print( fieldNumber );
          Serial.print( " = " );
          Serial.println( field );

          // Some fields might be numbers.  Parse them into integers.
          if ( isdigit( field[0] ) ) {
            int value = atoi( field );
            Serial.print( "  value = " );
            Serial.println( value );
          }

          // get next field
          field = strtok( nullptr, "," );
          fieldNumber++;
        }
      }

      // Reset the counter to receive another response
      count = 0;

    } else if (c >= ' ') {
      // Accumulate another non-control char, if there's room
      if (count < BT_MAX-1) {
        btResponse[ count++ ] = c;
      }
    }
  }

  if (Serial.available()) {
    // Send data to Bluetooth module
    bluetooth.write( Serial.read() );
  }
}

Notice that it shows how to use strtok to break the response string into individual fields, if a comma character is somewhere in the line.  For example, entering this:

hi,123,456

... produces this output:

said hi, among other things...
Field 0 = hi
Field 1 = 123
  value = 123
Field 2 = 456
  value = 456

It also uses AltSoftSerial for the BT connection.  SoftwareSerial is very inefficient, and it cannot send and receive at the same time.  It will lose received data while it is transmitting to the BT.  This can also interfere with other parts of your sketch or other libraries.

This answer has a good summary of the alternatives and how to select one.  Since you are already using pins 8 & 9, it would be easy to switch to the AltSoftSerial library.  All of the mentioned libraries are available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.


Upload Assembly to AVR on a breadboard using Arduino as ISP

Try uploading the blink sketch to the standalone atmega328 first.

Once you get that to work you can get the right command form the console (after enabling verbose output, in the settings).


getting error 'Serial' was not declared in this scope

I learned that I needed to include Arduino.h header file

apart from that I learned .ino files and .cpp files is that the .ino files transparently include particle.h for you.

The other difference is that .ino files generate forward declarations for you. This is necessary when you’ve implemented a function later in the file than when you’ve first used it. For example, if you pass the function to something like Particle.subscribe in setup() but you’ve implemented it farther down the file.


As KIIV mentioned you need to do the math:

Use this online voltage divider calculator to calculate your maximum input.

Keep in mind you shouldn't exceed Arduino 5V.
Use a multimeter to measure the resistors actual resistance.
Do the math for your example assuming R1 is exactly 100K and R2 10K you have to multiple the voltage by 11.
remember any error is going to multiple by 11 too, so make sure the first reading is accurate/stable.

ADS1115 is actually 15bit which will give you resolution of 32768, with default PGA setting you get:
6.144 / 32768 = 0.0001875V per bit.

Voltage = (your ADC reading) * 0.0001875V;
Voltage = Voltage * 11;

Take a look at This question/answer to see how I did reduced Arduino ADC noise, some steps can be done for ADS1115 as well.


Powering an Arduino Mini Pro using a CR2032 battery as a remote control

You should take a look at ATmega328P datasheet

  On page 2, it says: Six Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, Standby, and Extended Standby

These are the modes which can be used to put Arduino Pro Mini in stand-by. You can search for them at datasheet and choose the only that better applies to you. To learn more about sleep mode and other methods to save battery, you can take a look at this source: Arduino Low Power - How To Run ATmega328P For a Year On Coin Cell Battery

On the datasheet of battery, you should pay attention at its charge:

  Typical Capacity: 240 mAh (to 2.0 volts)

This means that from 3 to 2 Volts, it relases 240 mAh. This is the charge you can expect to use. Using the consumptions rates you posted above

NRF24L01: 10 mA per second (low-ball)
ATmega328P: 5 mA per second (low-ball)
CR2032: 240 mAh
Time: 240mAh/(10mA + 5mA) = 16 hours

Which is not so much. To increase this autonomy, the link I posted above is quite useful because it will show you alternatives like removing the voltage regulator that will reduce drastically your consumption. Now, if you feel really adventurous, you may take a look at how to underclock your board: Arduino pro mini @ 1MHz - 1.8V. This is a very efficient way to save power where clock frequency is not a must.

EDIT after comments:

The 16 hours were computed using 5mA for the Arduino (which is a value for power consumption that can be expected on active mode) and 10mA for the NRF24L01. You have to estimate a sleep mode consumption for both and a percentage of time in sleep mode if you want to estimate an autonomy. At the link I sent you about sleep mode there are some tables with power consumption in different configurations.

ATmega328P can run with a minumum of 1.8 Volts, while nRF24L01+ can while with a minimum of 1.9V - see datasheet. So probably you are going to have a little bit more than 240mAh to work with. Your battery won't have 3v all the time. It is going to start with 3V (maybe a litte bit more) and gradually reduces it voltage as the charge is provided to the circuit. Once the voltage goes bellow 1.9V, nRF24L01+ won't be guaranteed to work properly.

Definitely, to sleep the Pro Mini, just waking it up when using, is the right way to design this circuit. According to this reference I posted above, power consumption for Arduino should be 0.90 mA. At the item 5.1 of nRF24L01+ datasheet, it is described that it consumes 0.32mA at standby mode II. If you sleep the Pro Mini for, let's say, 90% of the time, without removing leds or voltage regulators, you can estimate that

t = 240mAh * (0.1/(5mA+10mA) + (0.9/(0.9mA+0.32mA)) = 178.65 hours

If you use strategies to reduce Arduino power consumption, like the ones I send you above, you can increase this time. You will also save power if you change nRF24L01+ from standby mode 2 to standby mode 1. Check the database to see which one fit your needs.


Accessing multiplexed I2C and UART pins of STM32F103 in arduino IDE

In order to use two different peripherals on the same pins, you have to initialize I2C and de-intialize UART when using I2C and doing the opposite when using UART.

It’s not possible to initialize two different peripherlas on the same pins, concurrently.


Inside Mastermachine(), Todo is a copy whatever is passed as its paramter. Even if you make a global named Todo, it will be 'hidden' by the parameter of the same name. That parameter goes out of scope - disappears - when Mastermachine() exits, including any changes made to it within the function.

There are a few choices to accomplish what you want to do, but the easiest is probably to make a global Todo and get rid of the parameter Todo in Mastermachine(); i.e., make it void Mastermachine(void). Then the name Todo inside the function will refer to the global by that name.


Since no one has posted an answer, and I finally found one myself. Ground pin 10 for 6 seconds.


Serial.println() prints the value of one expression. The expression you passed it was `("Test " + index++).

In C/C++ a character literal such as "Test " evaluates to the memory address its first character. Adding 1 to that address gives the address of the next (or 2nd) character. Adding 2 to it gives the address of the 3rd character, and so on.

To get what you were expecting, the value of the literal, AND the value of the index, you would write:

Serial.print("Test ");
Serial.println(index++);

If you had created a String variable with the value "Test ", then the String expression, ("Test " + index++) would have been evaluated differently: The "+" operator would have concatenated the String "Text ", with the String equivalent of the current value of "index"; but that isn't the way a character literal is treated. There is a C++ String library among the Arduino libraries but it's use is not recommended because Strings get reallocated and copied when they get concatenated, resulting in excessive memory use, and the Arduino has very little memory.


Uploading to atmega328 over serial with arduino bootloader running at 2MHz

Unprogram the CKDIV8 fuse and add the following to the sketch instead, near the beginning:

#include <avr/power.h>

void setprescaler(void) __attribute__ ((naked)) \
  __attribute__ ((section(".init1")));

void setprescaler(void)
{
  clock_prescale_set(clock_div_8);
}

This will do essentially the same thing as the fuse, but won't interfere with the bootloader.


Multiple shields on one Arduino/Linker base shield

I would recommend looking up the power consumption specs on the datasheets for each shield. Then determine whether the current used by all of the shields exceeds the limits for any given pin and for the board as a whole. I highly recommend the following article: http://www.ruggedcircuits.com/10-ways-to-destroy-an-arduino/


Is there a away to transmit sensor signal over RF without Arduino?

You don't have to use a $30 Arduino. You can make a "breadboard" one for a few dollars, like this:

$5 for the chip and a couple of dollars for a couple of capacitors and resistors.

Add to that a NRF24L01 transceiver like this:

Available from eBay for around $1 each. You need two, as you need to transmit from one and receive from another.

So the whole thing could be done for under $10.

  Something that could work for considerable duration with a small tablet like battery?

See Power saving techniques for microprocessors


Arduino Uno with ESP8266 Wifi transceiver or ESP8266 NodeMCU board?

In my opinion, it is more desirable to program the ESP8266 directly. I'm always shivering when I see a Uno (ab)using the ESP8266 as a WiFi bridge when the ESP8266 already has everything needed for the project. Of course, this is highly project specific.

Advantages of programming an ESP8266 directly:

you learn about a new MCU and architecture (XTensa vs AVR)
you learn to use a new Arduino Core (Arduino-ESP8266)
ESP8266 is way more powerful than the Arduino Uno

80MHz (overclockable to 160MHz) vs 16 MHz
~40kB free RAM at startup vs 2 kB
4 MB Flash vs 32kB
can use an RTOS like FreeRTOS
Flash can be used as filesystem (e.g. for a HTTP(S) server)
==> we can build way more complex projects

WiFi radio and stack directly on the processor, no need to get information via a serial bridge

higher speed, more direct control over sockets etc.

you can try out other frameworks and languages, such as

Micropython
esp-open-rtos
the NodeMCU firwmare (Lua language)
Espressif's NON-RTOS / RTOS SDKs

easier to move to its big brother, the ESP32 (Dual-Core XTensa LX6 @ 240MHz, WiFi + BT, 4MB Flash, 520kB RAM (+4MB PSRAM optional), tons of peripherals and accelerators) for even more complex projects

Disadvantages:

only 1 ADC input (vs. 6) with a voltage range of 0 to 1.0V (unlike the normal 5V range on the Uno)

remedy: external ADCs via I2C / SPI (e.g. MCP3008)

3.3V device, must be careful when connecting to existing 5V devices or shields

remedy: logic level shifters, voltage regulators

less number of available digital GPIO pins (9 vs 13)

remedy: external GPIO expanders via I2C/SPI (e.g. PCF8574, MCP23017)

In summary, I think a good way of acquiring a better skillset is to try to explore and program a new board directly vs programming the old board and slapping the new one on top over serial. I hope this gave a rough overview of why an ESP8266 might be better (or worse) for a certain project.


using seek() in Arduino to go to the end of a variable-sized file

You can only seek to an absolute position from the start of the file.  Fortunately there is the size() method that can tell you where the end is, though.

file.seek(file.size());


What are the differences between the 1.0.x and 1.6.x IDEs?

I think Arduino's version history is a bit confusing. I'm not an expert but I think this explanation will help. First let's note that version 1.6 was released 2015.02.09. However, back in 2012, version 1.5 BETA was created and it remained in beta for several years. Meanwhile, the 1.0.X version evolved independently here's an excerpt from the changelog

ARDUINO 1.0.6 - 2014.09.16
ARDUINO 1.0.5-r2 - 2014.01.08
ARDUINO 1.0.5 - 2013.05.15
ARDUINO 1.0.4 - 2013.03.11
ARDUINO 1.0.3 - 2012.12.10
ARDUINO 1.0.2 - 2012.11.05

So you can see that 1.0.6 isn't as old as one may think. Many vendors probably chose not to develop their products against the 1.5 version (or branch) because of its beta status. 1.5 being in beta for as long as it did lends to a confusing version history. I did get the impression that LightBlue Bean is working on compatibility with 1.6.x because their getting started page mentions

  Download and extract the Arduino app, version 1.0.5. We currently do not support newer versions of the Arduino IDE.


Serial question : Going from Mega to Uno

Arduino UNO only has one hardware UART, hence only one Serial available, which is linked to USB, but you could still use it for something else by connecting directly to D0 & D1.

However, if you need 2 separate, independent, UART then go for SoftwareSerial for the second one.

Now, if you need to connect 2 devices, one to exclusively get data from, the other exclusively to send data to, then you can use just one UART, i.e. Serial for both devices, as long as both links work at the same speed and settings (parity...)

Also you must ensure that USB won't receive anything otherwise you would get it and confuse it with input from the first device.

The non USB device providing input to the Uno should be connected to D0 (RX).


Risks of ftdi_eeprom? - TX always high after flashing

The ftdi_eeprom utility re-writes the entire EEPROM, not just the selected bits you have chosen.  That includes the "CBUS" pin configurations.

You need to check on the Nano's schematic which LED is connected to which CBUSx pin on the FTDI and set it accordingly.  You do that in your config using:

cbus0=TXLED
cbus1=RXLED

for example.

Possible settings for the CBUS pins are:

TXDEN
PWREN
RXLED
TXLED
TXRXLED
SLEEP
CLK48
CLK24
CLK12
CLK6
IO_MODE
BITBANG_WR
BITBANG_RD
SPECIAL

Except CBUS4 which only has the functions:

TXDEN
PWRON
RXLED
TXLED
TX_RX_LED
SLEEP
CLK48
CLK24
CLK12
CLK6

There is a chance that your pre-packages version of ftdi_eeprom doesn't support those settings, so you will need to download and compile the latest version from source from here: https://github.com/legege/libftdi

Also during testing I accidentally changed the VID of one of my boards thus rendering it unresponsive.  I did that by omitting the 0x from the VID and PID numbers.  Extreme care should be exercised using thin utility.  I have submitted a patch to allow the specification of a default VID for recovery from such situations.


Weird behavior (Couldn't pull the pin LOW)

You are creating a pointer variable, not a normal variable.

That pointer variable is, until told otherwise, pointing at address 0x00.  It covers 4 bytes.

Addresses 0x00 to 0x1F are the internal CPU registers R0 to R31.  Your pointer variable points to R0 plus three more addresses above it (a long is 4 bytes in total).

So when you write to your pointer you are directly writing to CPU registers R0, R1, R2 and R3.

According to the AVR-GCC ABI:

R0 is the scratch register
R1 is the zero register
R2 & R3 are general purpose (call-saved) registers.

So if you write 255 to your pointer variable you are doing:

R0 = 255
R1 = 0
R2 = 0
R3 = 0

And that's no big deal: some things may go a little awry, but nothing major.

However, writing 256 results in:

R0 = 0
R1 = 1
R2 = 0
R3 = 0

The big thing here is that the zero register R1 is now 1, not zero.  The ABI states:

  R1 always contains zero. During an insn the content might be destroyed, e.g. by a MUL instruction that uses R0/R1 as implicit output register. If an insn destroys R1, the insn must restore R1 to zero afterwards. This register must be saved in ISR prologues and must then be set to zero because R1 might contain values other than zero. The ISR epilogue restores the value. In inline assembler you can use __zero_reg__ for the zero register.

So R1 must be zero except for a brief moment when you use it for something else.  Since you're setting it to 1 and leaving it as one, any other operations that then rely on that register being zero will have a hard time knowing just what they are doing.

Having a "zero" register is a common thing. There are many times (especially in a RISC architecture) when you want the number zero - and having a register that is guaranteed to always be zero saves a lot of time. For instance, in MIPS the register $0 is hard-wired to be zero and can never change.  AVR doesn't have that luxury, but the GCC compiler imposes the rule for R1 which you have to abide by - since there are huge amounts of library code and other auto-generated code that rely on that register being zero.

So when it's set to one, all gloves are off, and no one can ever really know just what is happening - you'd have to disassemble the code (or get an intermediate listing out of the compiler) to see just what is using R1, and work out what the effect of that being 1 instead of 0 would be.

As an example, digitalWrite has this:

        if (val == LOW) {
 370:   11 11     cpse r17, r1
 372:   05 c0     rjmp .+10          ; 0x37e <digitalWrite+0x50>

That's "COMPARE SKIP IF EQUAL".  It's looking at the value you pass (val) to see if it's equal to zero - by using R1 as the zero value. But if R1 isn't zero then it will never know that what you passed as LOW is LOW - instead it would find HIGH as LOW, since HIGH is 1 and R1 is 1.  So you've basically swapped HIGH and LOW over as far as digitalWrite is concerned.

There are also places where the number 255 is wanted.  This is easy to generate with "eor r1,r1" - exclusive-or of the zero register. EOR turns bits off that are on and on that are off - so zero becomes 255. Except if zero is actually 1, you end up with 254 not 255, and more strange things happen.


How do I correctly use enum within a class?

I see two separate issues here.

First of all your enum isn't available as a variable.
By declaring it as a private type within your class the enum can't be used outside of that class.

This forces a user of that class to handle unintended calls like (attention, bug):

CandleRack(255);

which can make code harder to read (and debugging more difficult, since it wouldn't be detected by the compiler).

Second of all you try to directly assign a byte value to an enum type. This will be rejected by the compiler and/or cause runtime errors later (depending on compiler settings).

I recommend that you declare the enum type so that it is accessible directly via the header file:

.h

enum CandleRackStatus {
    inactive = 0,
    candlesOn = 1,
    rewardAnimation = 2,
    tweetArrived = 3,
    partyMode = 4,
};

class CandleRack
{
  public:

    CandleRack(CandleRackStatus candleRackStatus);
    ~CandleRack();
    void begin();
    void pushButton();
    void selectRandomCandle();
    void turnOnCandle(byte candlePosition);
    void burnCandlesForMs();
    void fadeOutCandle(byte candlePosition);

  private:
    Bounce *_debouncePushButton;
    CandleRackStatus _candleRackStatus;
    byte _pushButtonPin;
    byte _candlePosition;
    byte _candleStatus[NUM_LEDS];
    elapsedMillis _candleTimeElapsed[NUM_LEDS];
    unsigned int _candleOnForMs;
};

Now you can instantiate your class while using the correct enum type as the parameter.

.ino

CandleRack MyCandleRack(CandleRackStatus::inactive);

Within your implementation you can now directly store the constructor parameter in the private variable, the compiler will make sure it's always of the correct enum type:

.cpp

CandleRack::CandleRack(CandleRackStatus candleRackStatus) {
    _candleRackStatus = candleRackStatus;
    // rest of your initialisiation goes here
}

As an added bonus, there's the possibility to use a couple of C++ language features that will make your implementation easier:

a default parameter value
an initializer (list)

.h

class
{
  public:
    CandleRack(CandleRackStatus candleRackStatus = CandleRackStatus::inactive);
    // [...]
}

.cpp

CandleRack::CandleRack(CandleRackStatus candleRackStatus) : _candleRackStatus(candleRackStatus) {
    // rest of your initializiation goes here
}


Is it possible to run Python embedded in Arduino?

You can use other kind of board called MicroPython

But yes, is possible using some kind of TX-RX Python class...


How to solve Atmega 16A Serial write (println) hang with Arduino Uno firmware?

Unfortunately you can't just simply upload the Arduino bootloader and expect it to work. The ATmega16 is not the same as the ATmega328. One quick look at the datasheet will already explain why this is not working. The UDR(USART data register) is at 0xC6 on the 328, while it's at 0x2B at the Atmega328. So the ATmega16 will look at the location where the 328 stores the received data and will not find it. This could explain the hang, but I expect that other things like UART setup will have gone wrong before you get to the receiving of data.

If you want serial communication with the ATmega16, try programming it directly in C with the AVR libraries and without the Arduino extensions. That will make it harder to figure out.


Formula for current through shift register

It's just N×IL+IQ where N is the number of LEDs, IL is the current through each LED and IQ is the current the shift register needs to operate (quiescent current).

The current through each LED is just (VIN - VLED) ÷ R, where VIN is 5V, VLED is the forward voltage drop of the LED, and R is the value of your resistor.

So you can combine it to be a single formula, if all your LEDs are the same and your resistors are the same, to:

IT = N × ((VIN - VLED) ÷ R) + IQ


Draw polygon on LCD from GPS latitude and longitude

Over a small area lat and long are just simple Y and X coordinates respectively.

Dynamic scaling of the points is a very simple matter.  All you need to do is work out the range of each dimension - so subtract the lowest latitude from the highest, and the lowest longitude from the highest.

That gives the full X and Y dimension of your area. Then just divide those by the dimensions of your screen.  That gives you a scaling factor for each direction.

For each point, subtract the lowest longitude and latitude, and divide by the scaling factor for each direction.

If you want to be more fancy and retain the aspect ratio then you just need to work out which of the two scaling factors will allow all the polygon to remain on the screen - that is, divide and offset all your points by one factor, then by the other, and pick the smallest factor where all the points are within the area of your screen.


Whether you compile manually with a Makefile (or Arduino-Builder) or in the IDE, the end result is a HEX file.  This is a text file describing the data to load into the flash memory.

You then use avrdude to install it into the Arduino - either from the IDE or by running it manually (or specifying it in your Makefile, etc).

A Makefile doesn't produce an executable. A Makefile is merely a recipe - a set of instructions - telling the make program which programs to run (gcc, avr-gcc, etc) and in what order (and with what flags) to compile your code.

There are many Arduino Makefile projects out there that do it all for you.


The ST7735 TFT uses SPI to communicate. That can never be particularly fast.

At 160x128 pixels with 16-bit colour depth that gives you 327680 bits that you need to transfer just for the colour data.  On top of that you have 88 bits to set up a drawing window (11 bytes of "set X coordinate and width" [5 bytes], "set Y coordinate and height" [5 bytes] and "start drawing" [1 byte]).

That's a total of 327768 bits that you need to transfer.

Now the transferring of that data is at the mercy of the SPI clock speed. How fast that can go depends on what the ST7735 can work at and the quality of your wiring (if it's a shield you can almost discount the wiring).  Assuming you can operate at the maximum 8MHz that the Arduino can run SPI at (which is probable) then you get:

8,000,000
---------   =  24.4 frames per second
 327768

That is the absolute maximum theoretical speed, and doesn't take into account any work done by the Arduino to actually send the data. The SPI library is completely blocking in its operation and each pixel has to be sent separately as one blocking transaction. So you can expect about half that rate in reality, if not less, while it loops around and sends each pixel, then blocks waiting for the pixel to be sent.

And of course that's assuming running at the maximum speed. In reality that probably isn't happening. Libraries that use SPI often choose the "lowest common denominator" for their SPI speed (if they actively choose a speed at all) so that the library "just works" in the majority of cases. So the speed the library is running at will most likely be considerably lower than the actual maximum speed you could run at.

For example, if it runs at 1MHz instead of 8MHz then you will get about 3 frames per second (which is more like what you are describing).

So examine your chosen library and see what it does in the way of configuring the SPI speed. If it doesn't do anything then consider adding code to increase the speed. If it does then consider increasing the speed it operates at (see the SPI library reference for more details).

TBH, though, a small Arduino is seldom a good choice to control a TFT screen. At the bare minimum you really need a chip with far more memory so you can draw graphics "off-screen" in a framebuffer, and then use DMA to transfer that off-screen buffer to the TFT screen over a 16-bit parallel connection at high speed while leaving the CPU free to do other jobs.  Or even better a microcontroller with a built-in TFT controller to directly generate the correct drive signals for a TFT panel and store the whole screen image in internal RAM.


Is it really programmable withut any TTL/ICSP/FTDI extention?

Only if you use an ATTiny chip that has the "Micronucleus" bootloader already installed.

  If so, is it possible to program other AVR chip (Attiny/Atmega) with simple codes directly via USB...?

Some can, but most need a bootloader installing. The ATMega32U4, for example, has a "DFU" mode, which is essentially a bootloader in ROM, that you can use directly over USB.  In general, though, the answer is "Not without installing an appropriate bootloader with some hardware programmer first".


Lowest latency triggering multiple Arduinos using NRF24L01+

Yes, that should work, however also think about the following issues:

What if one (or more) camera does not receive the signal? You might need to add an ACK signal, but of course this will reduce the latency (a lot). If you don't want an ACK signal
To prevent an ACK, you can send the signal many times (and cameras who already processed the signal not react for a fixed amount of time). Of course it will received by the other cameras (at least) 283 us later.
If reliability is important, you could try using a less high speed, the latency will go up, but reality too.

Also you probably can fire the cameras even faster, if you first send the address bytes (4 bytes). And than send the shoot signal which can be in principle 1 bit. You can use one of the bits for that in case 128 cameras would suffice. Or send one byte extra which contains the signal to shoot.


There won't be a really complete list, since there are many many tools, that one could use for an electronics/Arduino laboratory. Also low budget is relative, so you might wanna choose out of the below list based on your real budget and the actual price of the parts at your place. Also consider, that many tools can be bought very cheap, but these tools are often bad, which means, that you most likely will buy a better replacement product later (buying cheap means buying twice). Still a low budget can absolutely justify buying cheap at first (some bad tools is better than no tool).
Note: I will use Euro as currency here (as I'm from Germany), which can about be used interchangeably for US Dollar. Your mileage may vary.

Breadboards: For working with Arduinos you wanna first build your circuits on a breadboard for testing. You should at least get one. I've seen 3-Packs of breadboards on platforms like amazon for about 12€.

Jumper-Wires (male-male/male-female): These wires with attached dupont jacks will make it easier to prototype on breadboards.

Colored Wire spools: I have a few spools with 4 different colors of 0.2mm² wire. You can use these for your PCBs and for breadboards. The different colors help to color code your wires for better overview. They cost a few € each.

Multimeter: A simple multimeter, that can measure voltage, current and resistance and in best case has a continuity check mode. This is a very important base tool for all electronics. I think most multimeters from 15€ up would be ok.

Pliers and Wire cutter: These are good for pressing and for cutting things. If you train a bit, you can even use the wire cutter for removing the isolation at the end of your wires. Technically a proper wire stripper is better, but I think using a wire cutter for the low budget start is totally ok. A wire cutter can go as cheap as 10-15€ for a decent one.

Soldering iron: Don't buy one of these soldering irons, that go directly into the mains. Buy a little soldering station with basic temperature control and integrated holder and a sponge for cleaning the tip. It should also have the possibility to change the tip (when you need a smaller/bigger tip or when your tip is no good anymore). A few years ago I got one of these for about 15€. Going a bit higher will benefit you with a better solder station.

Solder wire: You need to buy the actual solder. You should buy a spool of solder wire with integrated flux. Though most little spools have that. Depending on the exact solder wire it can be useful to also buy some flux (I'm currently using a flux pen), if the solder isn't flowing good enough.

Third hand with magnifying glass: When soldering it is sometimes helpful, when you can put a part into a clamp (like the third hand) and then use your hands for soldering iron and solder wire. The magnifying glass (which is also hold by the third hand) can help with small parts and inspection of your soldering work. It often costs only a few €, but getting up a bit can give you better durability and stability.

Perfboard: To build PCBs yourself you can most easily use perfboards. That are simple boards with solder pads for through-hole components. You can solder the components to the and then connect the pads via solder/wires. These are available with each pad not connected to anything else, or already connected like on a breadboard (I use these ones, like in this answer), or in stripes,... Building better PCBs would involve a more complicated process with chemicals or sending the PCB files to a manufacturer.

Heat shrink tubing/sleeves for wires and cables: To isolate wires, you might want to get correspondingly sizes heat shrink tube. They slide onto the to-isolate place and then get heated with a heat gun or a lighter. They shrink down and so enclose the part for isolation.

Oscilloscope: This is normally one of the most expensive tools. A decent oscilloscope can cost 250€ and up (into infinity). But you can sometimes get the big old oscilloscopes second hand (for example from ebay) as others upgrade to a digital oscilloscope. Or you can buy an USB oscilloscope, which works with your PC. I got one of these for about 50€. Or there are simple kits for standalone oscilloscopes (with limited capabilities) for 35€ and up. An oscilloscope is important for analyzing analog signals.

Logic Analyser: This is used to analyze digital signals. Standalone logic analyzers are expensive, but you can get a USB version for about 10€. The opensource software sigrok can then be used to interface the logic analyser. This tools is really really useful in relation to its low price. For example: You can use it as debug tools by setting pins inside your code at special places. That gives a better view on the temporal code flow than the typical Serial output.

Hot glue gun: Seems pretty basic, but I really often use my hot glue gun. You can fix things, protect them, build a supporting structure,... They only cost a few € plus a few for the glue sticks.

Scalpel and box cutter: Cutting things is also important and these two are good at it. They only cost a few € and have interchangeable blades. Especially a fresh scalpel blade can make the cutting of light materials really smooth.

That's about, what I can think of currently.


Did you try removing the 0x indicator? If I remember correctly the incoming signals are raw, e.g. 2E3A06C0, even though the script requires the 0x indicator on the send routines.

Alternatively, you'd need to rewrite, but you could try this IR Library and code, which I found has much better documentation and data analysis options on the receiving side: https://github.com/cyborg5/IRLib/


The problem is that you're touching the foil.

The "capacitive sensing" used in that library is crude at best.

If you read the Arduino Playground page for the Capacitive Sensing Library it discusses a lot of the problems with the library, including grounding.  Make sure that the Arduino is properly grounded, or provide your own ground plane under the foil sensors.

Also they talk about the value of resistor and the sensitivity.  With a 10MΩ resistor you get sensing at (supposedly) 4-6cm from the foil.  That's the value you're seeing as you remove your finger.  While you're touching the foil it's just having a complete brain haemorrhage and can't work out what is going on (completely unable to charge the pin since you are leeching off all the current).  For "absolute touch" it recommends no more than 1MΩ.

Of course, as I mentioned, that method is rather crude.  To do it properly you need to:

Discharge an analog input pin through a MOSFET to ground (low impedance).
Apply a constant current (typically 50µA is used but varies depending on ADC characteristics) to the analog input for a fixed amount of time.
Remove the current and measure the voltage on the ADC input.
Repeat.

More modern MCUs have this kind of functionality built in, in the form of a "CTMU" - Charge Time Measurement Unit.  If you want to have anything more than "there's someone vaguely in the vicinity of the sensor" then I would suggest switching to a more modern MCU and doing it properly, or employing a specific CTMU chip as an external device.

Also, the sensor should be comprised of three parts - a ground plane, a sensor plane (connected to the ADC) and a dielectric layer between them.  The sensor should also be insulated from direct touch.


Is it bad coding practice to design a buffer using pointers?

Don't bother with malloc unless you need to. If you explicitly define your buffer before hand then you can use avr-size to check your SRAM usage.

Also the C compiler automatically adds code to initialise global variables to 0, so you don't need ring_init if your define the array explicitly. See https://stackoverflow.com/questions/2218254/variable-initialization-in-c for initialisation comments. Even if buffer was filled with non-zeros it wouldn't matter because it should be written to before being read from.

If you change the ring buffer from chars to ints, etc. you will have to change memset, as it assumes chars.

Will MAX_BUFFER_SIZE change? If not, you could put the buffer in ring_t.


read data from controller via RS485 Modbus rtu Arduino

I can't say if this is your problem or not but I don't like this bit of code:

   RS485Serial.write(request, sizeof(request));

   digitalWrite(Pin13LED, LOW);
   delay(10);
   digitalWrite(SSerialTxControl, RS485Receive);

You're sending the request then waiting 10ms and switching to receive mode.  That might be enough of a delay, but it's hard to say (best case, 960Bps at 9600 baud gives about 1ms per byte, which is 8ms for the request, but with software serial it may not be that simple).

Instead you should be using the flush method of the Stream class to wait for the data to be transmitted:

   RS485Serial.write(request, sizeof(request));

   digitalWrite(Pin13LED, LOW);
   RS485Serial.flush();
   digitalWrite(SSerialTxControl, RS485Receive);


Arduino + 4051 -> noise on certain 4051 pins

I have a post about that chip at 74HC4051 multiplexer / demultiplexer.

I made up the circuit shown on my page above with modifications as described below:

I moved the A/B/C and O/I pins to match your code.

A is the low-order bit so pin 11 on the 74HC4051 should go to D2 on the Arduino.

74HC4051  Arduino   Meaning
    11       D2        A
    10       D3        B
     9       D4        C
     3       A2        O/I

I put a pot on I/O0 (pin 13 on the 74HC4051) and randomly set the other pins to +5 V or Gnd, as shown.

In setup() I added:

Serial.begin (115200);

I also modified it to automatically sequence through all 8 possible ports, and then stop after 1000 iterations to stop flooding the USB port on my computer. Code is:

int r0 = 0;      //value of select pin at the 4051 (s0)
int r1 = 0;      //value of select pin at the 4051 (s1)
int r2 = 0;      //value of select pin at the 4051 (s2)
int which = 0;   //which y pin we are selecting
int val;

void setup() {
  Serial.begin (115200);
  pinMode(A2, INPUT);       // mux1 input
  pinMode(2, OUTPUT);    // s0
  pinMode(3, OUTPUT);    // s1
  pinMode(4, OUTPUT);    // s2
}  // end of setup

unsigned long counter;

void loop () {

  // select the bit
  r0 = bitRead(which, 0);
  r1 = bitRead(which, 1);
  r2 = bitRead(which, 2);    // use this with arduino 0013 (and newer     versions)

  digitalWrite(2, r0);
  digitalWrite(3, r1);
  digitalWrite(4, r2);

  //Either read or write the multiplexed pin here
  // refactor, this should be digitalWrite with millis or something
  val = analogRead(A2);     // MUX ouputs here

  Serial.print("sensor number ");
  Serial.print(which);
  Serial.print('\t');
  Serial.print("val is ");
  Serial.println(val);

  delay(2);

  if (++which > 7)
    which = 0;

  if (++counter >= 1000)
    {
    Serial.flush ();
    exit (1);
    }
}  // end of loop

The output from your sketch was as expected:

sensor number 0 val is 781
sensor number 1 val is 0
sensor number 2 val is 1023
sensor number 3 val is 1023
sensor number 4 val is 0
sensor number 5 val is 0
sensor number 6 val is 0
sensor number 7 val is 1023

I suggest you check that your wiring agrees with mine.


Is it possible to have an array of int arrays?

Yes you can have arrays inside arrays.

The array would be declared as:

int arrayName [ x ][ y ];

where x is the number of rows and y is the number of columns.

The example below declares and initializes a 2D array with 3 rows and 10 columns:

int myArray[3][10] = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
                       { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 },
                       { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 } };

To access the value of 27 (and save it into myValue):

myValue = myArray[2][6];


Do some arduino pins give signals when the controller starts?

Most Arduino boards come with a bootloader of some form.  This bootloader may do things with IO pins. However apart from that, no, nothing else happens to any IO pins.

The bootloader may:

Flash pin 13 (built in LED)
Configure and communicate on pins 0/1 (UART)

With no bootloader then absolutely nothing happens on any IO pins.


I'd guess it's in the if(packetsize) logic -- if you get a packetsize of zero, you still try to read into a zero-size buffer and who knows what would happen.  Move the read inside the if(){...}

See https://www.arduino.cc/en/Reference/EthernetUDPRead

Also, you want to limit the reading to the UDP_TX_PACKET_MAX_SIZE size of the buffer, not to the size of the packet.

Update: The UDP_TX_PACKET_MAX_SIZE is only used in the user code, and nowhere else within the Ethernet Library.  You could use a larger buffer if you need to by defining and allocating a larger buffer and specifying its size in  EthernetUDP.read()  (see https://www.arduino.cc/en/Reference/EthernetUDPRead).


There is a lengthy discussion about this on the Arduino Forum. As I understand it, the input impedance is only important if you are sampling a rapidly varying signal, as it takes a finite time to charge the sample/hold capacitor. However your potentiometer would not vary rapidly (certainly not in the order of thousands of herz). Thus I don't think the potentiometer resistance will be particularly important, particularly if you are not changing the analog inputs (eg. from one channel to another). The continuous current through the 10k pot would be 0.5 mA.

If you are worried about power, then rather than connecting the +5V side directly to 5V, connect it to an output pin, which you can bring high when you want to take a measurement, and make low at other times. That reduces the power through the pot, since there won't be a voltage potential. You might allow a few microseconds for the reading to stabilize when you need to take one.

  So the lower the pot resistance, the faster response time? Also I will constantly always be taking a measurement

No, I don't think this is an issue. The "response time" is really the time taken to do the ADC calculation (nominally 104 µs if you don't fiddle with the registers).

See ADC conversion on the Arduino (analogRead). As mentioned on that page you can speed up the measurement by changing the ADC prescaler. However even with a prescaler of 128 you get 9615 conversions per second. I doubt you can turn the pot fast enough for this to be a meaningful issue.

Regardless of the response time, the issue here is accuracy. Will a lower pot value give more accurate results? Well, I doubt it. The ADC effectively copies the analog input into a 14 pF capacitor (the "sample and hold" capacitor) which it then tests against the reference voltage divided up in various ways.

The input impedance would be relevant if you were sampling a high-frequency input. On the page I linked I sampled a 4 kHz sine wave and got good results. You just won't be turning the pot that fast (4000 times a second).

  I'm still unsure with how potentiometer resistance affects the data ...

If you keep sampling the same ADC input (eg. A0) then I think the sample and hold capacitor can be charging in the background (while your code is doing other things).

But even if that were not the case, the datasheet says the sample and hold operation takes place 1.5 ADC cycles after the conversion starts. So at 16 MHz clock rate, and a prescaler of 128 for the ADC clock, this means we have:

128 * 62.5 ns * 1.5 = 12 µs

Now since the datasheet says the sample-and-hold capacitor is 14 pF, and the time taken to (almost fully) charge a capacitor is reckoned to be:

5 * R * C

Given R = 110k and C = 14e-12 (14 pF) then it will take:

5 * 110000 * 14e-12 = 7.7 µs

I quoted 110k because the datasheet mentions a resistance of 1 to 100k in series with the capacitor, plus the 10k impedance they recommend.

This means the capacitor will charge within the 12 µs it has available. Bump R up to 1e6 (1 megohm) and the calculation now gives:

5 * (100e3 + 1e6) * 14e-12 = 77 µs

This exceeds the 12 µs quoted for the sample-and-hold.

This is why, I suggest, that for fast-changing signals they recommend a lower input impedance.

However if I am correct that the sample-and-hold capacitor is normally connected to the ADC input, then that 77 µs can be spread over the time you deal with the calculation. Still, that is quite a few clock cycles. :)

My recommendation is to stick with 10k or so potentiometer (as recommended by the datasheet) and use my earlier suggestion of connecting the 5V side of the pot to an output pin instead of continually having it connected to the +5V signal. That way you only need to "power" the pot when you actually need to take a reading. However you can see that a 20k pot (or even 50k) will probably still be in an acceptable range for an accurate conversion.

For example, a 50k pot could charge the capacitor in:

5 * 150000 * 14e-12 = 10.5 µs

I would also be cautious about a 1 megohm pot because then slight variances in other things (eg. heat on the wire, nearby noise) could swamp the reading from it.

  Wait, sorry do I need to half my potentiometers' resistance if I'm using two analog inputs?

No, because the multiplexer chooses one input at a time (the others are effectively out of circuit).

However if you are choosing between two pots (to measure two) then the resistance becomes more relevant. As I showed, with a high value pot it takes longer to charge the capacitor, so if you read A0 and then immediately afterwards A1, you don't want a lengthy charging time for the capacitor, because that would give erroneous readings.


Error Uploading Arduino Sketch to Arduino Pro Mini

It's your COM port or your board selection.

I often use the Pro Mini and an Uno and when I forget to change either the COM port or the board to which I have to upload the sketch to, that error message happens.


How to convert 0-5v inverted serial to 0-3.3v non-inverted serial

I think you're looking for an inverting amplifier. This can be done with either a BJT or a MOSFET (assuming your input is enough to turn the MOSFET on). Here's an example with a BJT:

simulate this circuit – Schematic created using CircuitLab

The output range is independent of the input and is defined by the supply voltage.


How to connect an LED to Arduino LilyPad Mp3

You might try connecting the anode side of your LEDs through a current limiting resistor to the positive side of the supply.  Then connecting the cathode side of the LED to the switched pin on the Arduino LilyPad Mp3.  So, in this diagram:

...that would be the pads where the switches are connected.

The current limiting resistor depends on the specifications of the LED.  Check the voltage and current required to light the LED.  Subtract the voltage needed from your supply voltage.  Then use the V=IR equation and solve for R.  That is, V = the voltage difference between your supply and what is needed by the LED and I is the current (probably in milliamps, so watch your math!) that the LED needs to light up properly.  You will probably need small current limiting resistors somewhere around between 100 and 800 ohms.

Added later...

Thanks to @Gerben we have a diagram of what I was describing:

In Gerben's diagram he has used the regulated 3 volt output of the Arduino LilyPad Mp3.  We can double check all the pin labels using a diagram from Sparkfun:

You should be able to repeat this circuit for each switch.  Sparkfun has an LED tutorial here.  But I'm not very happy with their guess approach when picking out a current limiting resistor.  Ah, this tutorial is much more to the point.

So, if we assume the LEDs you are using need 3mA @ 3V (remember to use values for YOUR LEDs!) and use this equation (Vs = supply voltage and Vf = LED voltage):

...then we set it up like (3 - 3) / (0.03) which is zero.  That's because I was using LEDs that work at 3 volts.  But if I used LEDs that worked at 3mA at 1.8V then I need... (3 - 1.8) / (0.03) = 40 ohm resistors.  Or there about. As most resistor values are on a log scale I suspect there should be a 47 ohm available.


According to (MG996R)'s datasheet
You must connect a 6 volts - 2.5 amps power supply for it's best performance (max. Torque)
Maximum voltage of this servomotor is 6 volts
And be careful, exceeding that voltage can be cause of some damage to it's control board
Try 6 volts 2.5 amps power supply and if doesn't work maybe your servomotor's control-board is damaged by over-voltage.


How to connect MPU6050 to arduino using only digital pins

The MPU6050 communicates over I2C. I2C uses clock line SCL and data line SDA. I2C pins on Uno are pins A4 and A5.
This is because the ATmega328p MCU used on Uno has the I2C peripheral on the same pins. It has nothing to do with the DAC function of the pins.

Alternatively MPU6050 can communicate over SPI. This are pins 11, 12, 13 on Uno and one more pin for CS. Pin 10 must be output while ATmega328p is SPI master so it is recommended to use it as CS for the SPI slave device.   EDIT Sorry, only MPU6000 has SPI.


Detect movement on moving robot? PIR Sensor

Basically you have a robot and sensors that can detect movement.
There is one caveat though. For the PIR sensors to (non false-positive) detect motion, they have to be stationary (as far as I know).

So with only these PIR sensors it's unlikely that you can track something well.
Tracking something would be done best by using a range/proximity sensor.

The image below, seems to be a cute robot, with eyes.
You could take 3 sensors and place them under an angle (one forward, one forward/left and one forward/right) [picture 2]. Or just have one that rotates (will be more difficult) [picture 1].

You would want the robot to start following anything that comes close (or when one of the sensors sees a difference in distance. And then the robot will try to keep that distance, brake when he gets closer, drive when he gets further.

If that's working, you can implement the sensors at the side, that if suddenly he loses track of the object/person, he'll adjust his alignment so that the middle sensor sees it again. This could also be done by simpler sensors [picture 3]

When the robot gets to close, and the other object doesn't try to run for quite a time, you can make him check for another target. (With a PIR or by rotating and stopping rotating to check range/pir)

I believe this solution is more applicable as with only PIR sensors, as it's usefull to know the range when you're following something. You don't want to bash into it.


RFID + LCD + Arduino Mega 2560 = RFID not printing correctly

OK i fixed it. It is now this :

#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#include <LiquidCrystal.h>

Servo myservo;  //creates servo to control

const int rs = 44, en = 45, d4 = 46, d5 = 47, d6 = 49, d7 = 48;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int R=3;
int G=8;
int B=6;

void setup()
{
  lcd.begin(16, 2);
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  Serial.println("Place your card near reader");
  lcd.print("Place your card");
  lcd.setCursor(0, 1);
  lcd.print("Near reader");
  lcd.setCursor(0, 0);
  myservo.attach(7);//attatches servo to pin 7
  myservo.write(179);
}
void loop()
{
  analogWrite(B, 255);
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  lcd.clear();
  Serial.print("UID tag :");
  lcd.print("ID:");
  byte letter;
  String content= "";
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     lcd.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     lcd.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "4F 60 3C D9") //change here the UID of the card/cards that you want to give access
  {
    delay(5000);
    lcd.clear();
    Serial.println("Scanning Database");
    lcd.print("Scanning");
    lcd.setCursor(0, 1);
    lcd.print("Database");
    lcd.setCursor(0, 0);
    delay(5000);
    lcd.clear();
    Serial.println("Authorized access");
     lcd.print("Authorized");
    analogWrite(B, 0);
    tone(4, 900, 100);
    lcd.clear();
    Serial.println("Unlocking...");
    lcd.print("Unlocking...");
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    delay(1000);
    myservo.write(100);
    delay(15);
    Serial.println("Unlocked");
    lcd.print("Unlocked");
    delay(5000);
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 255);
    Serial.println("Relocking...");
    lcd.print("Relocking...");
    delay(1000);
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    myservo.write(179);
    delay(15);
    Serial.println("Locked");
    lcd.print("Locked");
    delay(100);
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 0);
  }else{
    delay(1000);
    lcd.clear();
    Serial.println("Scanning Database");
    lcd.print("Scanning Databas");
    delay(5000);
    lcd.clear();
    Serial.println("Access denied");
    lcd.print("Access denied");
    analogWrite(B, 0);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(100);
  }
 lcd.clear();
 Serial.println("Ready");
 lcd.print("Ready");
}

had to remove the lcd.setCursor(0, 1);
from line 57.


Arduino: How does digitalRead read a value? And what is this value?

Modern digital electronics is made from many tiny electronic components called MOSFETs (a type of transistor). They can be switched on and off using a voltage, and a very small amount of current. They use the majority of the power when they are switching on and off; the rest of the time they use virtually no power. It this very low-power capability which allows us to make complex digital electronics.

Electronically, a MOSFET looks like a tiny capacitor, which triggers a very low-power switch, on and off. Once there is charge on the MOSFETs capacitor, the switch will stay on or off.

A modern large-scale processor, for example the type of device Intel makes, contains billions of MOSFETs, but requires less than 100W, and switches billions of times/second. So we can be confident that a MOSFET can be switched using much less than 1/10,000,000W. At 5V, that means 1/50,000,000A, or 0.000,000,02A, i.e. 0.02µA.

So, the input circuit, connected to an Arduino's pin has some protection, to protect the MOSFETs from static electricity (which could damage or destroy the capacitor), then a complementary pair of MOSFETs (called N-Chanel and P-Chanel). The input voltage switches one on, and the other off. It typically requires less than a micro-amp of current, but at a voltage close to ground or 5V. See pjc50's diagram.

So an Arduino input pin, connected to the 5V end of the resistor and LED will take a tiny amount of current, for a short time, to switch on.

If that pin is connected between the LED and resistor, at some voltage less than 5V, but more than 0V, then it might not switch fully. It might not give a reliable value of digital 0 or digital 1, and might switch high and low rapidly influenced by electrical noise in the environment.


The board definition (pins_arduino.h) has this:

static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
static const uint8_t A3 = 17;
static const uint8_t A4 = 18;
static const uint8_t A5 = 19;
static const uint8_t A6 = 20;
static const uint8_t A7 = 21;

Since A0 is a constant variable equal to 14, if you assign that to a variable, it just assigns 14.

In other words:

A = 14.
B = A.
Therefore B = 14.


Change the fuses of an Arduino Uno (can an Arduino Uno change its own fuses?)

You need a programmer to burn fuses.  If you have another arduino then you can use the Arduino as ISP example sketch in the IDE.  You can't burn fuses just using the USB cable like you upload code with.  The only reason that can talk to the chip at all is because there is another chip to convert it to serial and a bootloader on the 328P to allow it to upload code via serial.


Is there an alternative to soldering to connect boards?

Yes, there are ways. There is a system called "Press Fit" where the pins have a bulge in one end of them. This grips the inside of the holes in place of soldering.

A number of companies make them, such as TE Connectivity and Positronic.

Of course, these depend on the holes being just the right size, and finding the right connectors could be tricky... so... your mileage may vary.

But nothing is better than getting someone to solder the pins for you. You could teach one of your younger relatives to solder, for example...


Wifi strength Automation . Help. Noobie here

You need to design your program using a Finite State Machine.
First start off by defining each state that your program can be in, and what is allowed to happen in each of those states.
For example:

IDLE

The only thing that is allowed to happen here is detecting the RSSI and deciding whether or not to start the engine.

IGNITION

The RSSI has got strong enough and you want to start the car. The only thing you want to do is turn on the ignition and wait a moment. Nothing more.

CRANK

Once you've waited a moment you can crank the engine. That means turning on the starter motor and waiting a moment.

RUNNING

Now the engine has started you can release the starter motor and leave the engine to idle. It's now that you want to start watching the RSSI gain.

STOP

The RSSI has dropped below your threshold, so now you can stop the engine.

IDLE

Now the engine's stopped you can go back to the start and idle looking for the RSSI to get high enough again.
These are all the states of a Finite State Machine. You move from state to state depending on different inputs or triggers.  One input is your RSSI value - or more strictly your RSSI value being above or below a threshold.  Another input is (less obviously) time. Waiting for some time to pass.
So you start in state 1. In that state all your program is doing is watching the RSSI. When that rises you move to state 2. At that point it performs whatever actions are needed (turn on the ignition) and record the time. When enough time has elapsed you move on to state 3, and do the same.
It could actually be simplified by compressing states 2 and 3 together:

Turn on ignition
Delay
Turn on starter motor
Delay
Turn off starter motor
Delay
Move to next state

You could then increase the complexity again a little (while increasing the safety) by adding extra steps when you're watching the RSSI. You can then check to see if the RSSI has been above (or below) the threshold for a certain amount of time before moving on to the next step:

IDLE - watching RSSI

If RSSI rises above threshold go to state 2.
Else stay in state 1

Record the time and keep watching the RSSI

If RSSI drops below threshold: Go back to 1.
If Enough time has passed: Go to state 3.
Else stay in state 2

Start the engine.

Go to state 4

RUNNING - watching RSSI

If RSSI falls below threshold go to state 5.

Record the time and keep watching the RSSI

If the RSSI rises above threshold: Go back to 4
If enough time has passed: go to state 6.
Else stay in state 5.

Stop the engine.

Go to state 1.

... etc ...


The concepts of HIGH and LOW, and thus the voltages associated with those concepts, apply only to logic signals.

LED drivers are not logic signals - they are constant current sinks. The voltages you are measuring are the forward voltages of the LEDs.


ESP 8266 reverse digitalWrite behaviour on which pins?

The esp8266 must have a pull-up on io 2 for boot configuration. The Wemos D1 boards put the LED in series with the pull-up resistor on io 2. This creates the 'reversed' LED behavior.

The large D1s are retired and it is hard to find a good and readable schematics. The cut out is from D1 mini schematics.


Sending values to an Arduino Yun across different networks

I have accomplished this, first by reading this article on controlling a Yun through a web-browser on the same network. From there it was a matter of allowing my Yun to be accessed externally (setting up port-forwarding on my router) and changing a few lines of code to reflect the new location reference.

All the necessary files and code are included under the heading "Project Files" in the above link and no modification is needed to get it working within the same network. That said, I had to convert the two .jpg files to .png (and change the filenames in index.html) - I don't know why they wouldn't show up in my browser.

In brief:

The Yun hosts a webpage (index.html) which contains some indicators and control inputs. These objects are linked to the 32u4 using Bridge and the REST API - nothing special. The bulk of the html code is for visual purposes, and the actual REST calls are nice and simple.

What is good is that the webpage can be accessed from anywhere with the right jiggery-pokery, and with a little more determination can be hosted from anywhere.

External Access

Once you have that working, you need to do the following to allow access externally. I tested this using my smartphone - disconnected from my home WiFi of course - to ensure the link was over the Internet, not intranet.

1) Set up port forwarding and a static IP for the Yun. This is the fundamental step if you simply want to control your Yun over the Internet. However, I can't actually tell you how to do this because I don't know what equipment you have! Information is all over Google for setting up both DHCP static IP and port forwarding.

2) Get a static IP from your ISP for your home/work, or set up a Dynamic DNS service (these people offer it free, but I've never actually needed to use an external service). Most commercial ISPs tend to dish out static IPs, but that's no guarantee that yours will.

3) Access your Yun with a browser via: http://YOUR.IP.ADD.RES:PORT/arduino/<SketchName>.

External Hosting

If you want to host the webpage on something other than the Yun, you can! You will of course need a server to host this, either your work's central server or an external hosting service. You'll need to change some more lines in the code:

1) In the Yun sketch change server.ListenOnLocalhost(); to server.noListenOnLocalhost(); - the subtle difference is the 'no', and is essential for external control. Sorry, that's incorrect without a little more explanation than is required at the moment to answer your original question.

2) In the .html file, you need to change each instance of:

server = "/arduino/<SOMETHING>";

to

server = "YOUR.IP.ADD.RES:PORT/arduino/<SOMETHING>";

If you have the REST password set to ON then you have to incorporate the username/password in there too:

server = "username:password@YOUR.IP.ADD.RES:PORT/arduino/<SOMETHING>";

There are three occurences in the original file, so be sure to catch them all.

3) When making changes to the .html file, make sure you re-upload it to the external host, not the Yun - that mistake took me hours to figure out.

A little more...

While searching for the URL of the article in the opening paragraph I found this atricle on a similar theme. It looks to have plenty of information although I haven't read it yet fully yet; I've been busy writing an answer on Stack Exchange. External Access should be no different, and if you want the 'External Hosting' version you just need to find any line that references the 'server' as "/arduino/..." and change it to "YOUR.IP.ADD.RES:PORT/arduino...".


Well, for example Arduino's delay needs interrupts to be working and as you may not know it's disabled inside of ISR handler.

Never ever use anything like while (1), delay(1000) and so on inside of ISR! And also do not reenable interrupts either! Set a simple volatile flag and use it inside of loop function instead.

Basically something like this:

constexpr int8_t button = 2;
volatile bool      flag = false;

void setFlag() {
  flag = true;
}

void setup() {
  pinMode(button, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(button), &setFlag, FALLING);
}

void loop() {
  if (flag) {
    // it's running, you can do something here

    // and you can reset the flag here either
  }
  //delay(100); // if needed
}


Multiple I2C sensors with the same address

If you're using MPU6050 IMUs, there's an easy trick: put them all on the I2C bus, and connect each IMU's AD0 pin to a separate digital pin on the Arduino[*]. When you want to read from a specific IMU, set all AD0s to HIGH, except the one you want to read to LOW. All the IMUs with AD0 set to HIGH with have an I2C address of 0x69, whereas the only one on LOW will have an address of 0x68.

If you want to read them all, you just go through a loop and set the one you want to LOW, the others to HIGH, and you're set.

[*] If you want 20 IMUs, you'd better get a Mega, or, even better, a Maple. Small form factor, quite a bit of oomph, lots of pins and flash, and some clones cost next to nothing; eg Itead sells Maple clones for 6 bucks. ElecFreaks sells them for 9 bucks. You could use the 16 pins at the bottom for the AD0s.

This trick works with any kind of I2C device that has a customizable address scheme through one or more pins. I do that with AT24Cxx EEPROMS, which have a 0x50-57 address range. When you want to have more than eight chips, setting all but one to 0x50 and one to 0x51 solves the problem pronto.

Reference: https://github.com/PaulStoffregen/FreeIMU_original/blob/master/documents/PS-MPU-6000A-00v3.4.pdf


My idea: Two light sensors on a short stick embedded in the ground. If the top sensor detects light, but the bottom one does not it means that it's daytime, and grass is long enough that it covered the bottom sensor. You will probably need several of those, because there is no guarantee that grass will actually cover the bottom sensor, and you will need to filter out random elements by testing if values don't change to much.


How to tell Arduino Uno that I pressed or released a key on PC keyboard over serial?

As mentioned by Spiked3 there are a few ways to hit the ground running with C#.

Firstly, as detailed by Majenko, you will need an application running on your PC and some code on the Arduino to interact with this. For the desktop application, the two easiest ways to get started with C# are with WinForms, or XNA/MonoGame. WinForms is targeted at Desktop application development; think legacy desktop apps. Although it is not the current defacto standard (replaced largely by WPF) it is very simple and akin to Swing in Java to use. MonoGame and XNA are targeted at video game development. The latter would be my preference as it lends itself more towards real time applications, and has a game loop much like the Arduino so it is very easy to start using. The caveat is that there is more setup involved, but you will probably find this the friendliest and best supported.

Firstly, The Code! So for the Winforms Route, We have something like this:

using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            Debug.WriteLine(" Key Up! ({0})", e.KeyCode);

            // TODO: Talk with Arduino
        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            Debug.WriteLine(" Key Press! ({0})", e.KeyChar);

            // TODO: Talk With Arduino
        }
    }
}

To get to this point, fire up a new winforms project, and open up the 'Form1' code (the default window which is added to the project) add the methods as outlined above. You will need to go to the designer afterwards and add events for on KeyPressand on KeyUp to tie these functions to the Window. You can do this by clicking the Window, then opening the Properties Panel, and then clicking the lightening bolt. You will see a list of event names; find the corresponding events (Key Press and Key Up) and associate them with these methods.

From here, you can perform some logic when a button is either pressed or released.

The monogame or XNA approach is a bit simpler to follow as there is no hidden magic; but may be more intimidating if you're not familiar with C# and the project type.

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.Diagnostics;

namespace GameName1
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;

        KeyboardState currentState;
        KeyboardState previousState;

        public Game1() : base()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            // Get state management started
            currentState = Keyboard.GetState();

            base.Initialize();
        }

        protected override void Update(GameTime gameTime)
        {
            // Listen for exit command
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            // Update the state of your keyboard object
            previousState = currentState;
            currentState = Keyboard.GetState();

            // Detect Keypress of key 'F'
            if (currentState.IsKeyDown(Keys.F) && previousState.IsKeyUp(Keys.F))
            {
                // F Key has been pressed
                Debug.WriteLine(" Key Pressed! ({0})", 'F');
                //TODO Talk to Arduino
            }

            // Detect Keyrelease of key 'F'
            if (currentState.IsKeyUp(Keys.F) && previousState.IsKeyDown(Keys.F))
            {
                // F Key has been pressed
                Debug.WriteLine(" Key Released! ({0})", 'F');
                //TODO Talk to Arduino
            }

            base.Update(gameTime);
        }
    }
}

In either case, you will need to get yourself set up first. Get a compy of Visual Studio Community from the link below, and install MonoGame if desired. Then do some C# tutorials to get comfortable in your new environment.

Visual Studio Community Edition
Mono Game
C# Tutorial
C# Mono Game Tutorial
C# WinForms Tutorial

Lastly, you will want to talk with your Arduino. This can be done by implementing a compatible Serial interface between your desktop application and your Arduino. See the tutorial below to get started!

Arduino C# Serial Tutorial

I hope this information is useful. There is a very broad range of topics mentioned here, and it may seem overwhelming at first - but C# is a very idiosyncratic language in that it permits rapid development in many different scenarios, and I think that you will find it rewarding to conquer the learning curve.


Working or functionality of pinMode(), digitalWrite() and digitalRead()

{
  pinMode(kPinLed, OUTPUT);
  pinMode(kPinBtn, INPUT_PULLUP);
}

This block of code used to define mode of Pin i.e. making pin as Output pin or Input pin.

if(digitalRead(kPinBtn) == LOW)
{

}

This block of code is used to read value from defined digital pin either High or Low. And in return will give pin state High or Low. For example if we want to make LED ON which is connected to one of digital pin of Arduino at certain condition, we will define that pin under above block of code and can read state of that pin as High or Low.

 {
   digitalWrite(kPinLed, HIGH);
 }
 else digitalWrite(kPinLed, LOW);

This block of code is used to make Pin state High or Low i.e. Under certain condition this function will make pin state either High or Low.

To learn more, visit......

PinMode Click here

DigitalRead Click here

Digital Write Click here


This seems more like an overflow issue with something than an actual delay.  If you look at the time in the log, it seems you aren't skipping seconds in the log (aka, 19:12:32.234 in two sequential log entries when you claim a delay).  I think it's an error of working with larger than 8-bit data sizes.  I know this is an old question, but I was looking for info and came upon it and figured I'd ask.


int array passed through function has wrong values only after multiple passes

You are wrongly using the new operator for your arrays. That will dynamically allocate these arrays. They are put on the heap (not the stack like local variables) and thus don't get freed automatically, when the function exits. That has to be done by your code with the delete keyword. Your code just eats up all the available memory. Thats called a memory leak.
That you need to free your dynamically created variables is not an Arduino thing; this is correct for all C/C++ code. But the limited memory on AVR based Arduinos like the Uno makes it worse.
If you do the math, one iteration of void loop() will block 432 bytes of memory (216 array elements, each of type int thus 2 byte). The 2KB of memory (which is also needed for local and global variables) is eaten up rather fast.
I don't see, why you even would use dynamically created arrays. Why not just using locally defined arrays, like in the miniCubes() function?

That said, it is also a generally bad idea to use dynamic memory allocation microcontrollers, especially those with small memory. When creating and deleting objects of different sizes (which is the main advantage of dynamic allocation), you will leave small holes in your RAM, which are too small for one of your objects to fit. At some point your RAM is completely filled with these holes, so that no more memory can be allocated for your objects to save. Thats called memory fragmentation.
On your PC that isn't a problem because of 2 reasons:

The PC has loads of RAM available, and
the OS manages the RAM, defragmenting it, if necessary.

Since microcontrollers don't have an OS managing the RAM and often very limited RAM, you need to make sure, that your RAM doesn't get fragmented too much in the runtime of your code.


Decimal numbers sent over Serial get split and sent over multiple ticks

As explained in Majenko’s comment, the serial link is not packetized: it
transmits individual bytes and nothing else. If you need to convey a
notion of “data packet”, or “full message”, you will have to devise a
way to signal the message boundaries. This is called message “framing”.

Your Arduino is sending ASCII data. In this case, the most common way to
frame messages is linewise: each message is a single line, and each line
is terminated by an “end of line” sequence. The standard end of line
sequences are CR (carriage return, i.e. 0x0d or '\r'), LF (line
feed, i.e. 0x0a or '\n'), and the pair CRLF (CR followed by LF, or
"\r\n").

Actually you are already doing that: you are using Serial.println(),
and this method automatically appends CRLF at the end of whatever it
prints. So now you just have to parse that at the other end: you put
all the incoming characters into a buffer until you see that incoming
CRLF. Then you know you have a full line, which you can report as an
entire message.

This procedure is very common and there is a standard Node.js module for
it. It once was part of the serialport module, but it seems to have
split into a separate module. It is called parser-readline, and you
would use it like this:

const Readline = require("parser-readline"),
      parser = comport.pipe(new Readline({ delimiter: "\r\n" }));

parser.on("data", data => console.log(data.toString()));

C.f. the documentation of
ReadLineParser.


What is the difference between a Hall effect sensor and an inductive one?

First they physically work differently. In the Hall effect sensor the electrons flowing through a plate will be deflected. Thus there will be a voltage perpendicular to the current, which can be measured. The voltage will be proportional to the magnetic field strengh. So you can sense a magnet, that is near the sensor, even if it doesn't move.

For the inductive sensor you have a guiding wire, that has an AC current flowing through it. This also means, that a magnetic field ist constantly building up and collapsing again around the wire. This change of magnetic field will induce an induction voltage in a nearby wire loop (the actual sensor). The frequency of that voltage is the same as of the guidance wire and the strength depends on the distance between the wires. So you are not measuring the magnetic field strength directly, but you measure how much it is changing (mathematically you differentiate).

Two different measurement methods which can be used to do the same thing. To guide a robot over a predefined course I would use the induction method (as long as the situation allows laying out wires), since it can be made less susceptible to noise. For that you can filter out all frequencies except of the used guiding frequency with a LC circuit. Or even better (though maybe not important) a lock-in amplifier. The hall sensor is an analog device, which can be very noisy.


Translating WS2812-LED-Strip-IDs when cutting up a strip to multiple parallel ones

No, there is no library.

It's just simple maths.

If all your strips are the same, then you just multiply the strip number by the number of LEDs per strip, and add the number of the LED you want in that strip.

So, assuming 10 LEDs per strip:

lednumber = 10 * strip + led;

You can make a little macro to do it for you if you like:

#define STRIP2LED(S, L) (((S) * 10) + (L))

Then you can use such things as:

// Set all LEDs on strip 3 to red
for (uint8_t i = 0; i< 10; i++) {
    leds[STRIP2LED(3, i)] = CRGB::Red;
}


Running a robot with 2 front-facing sensors, but it's stuttering

your updateDirection logic doesn't quite work the way you think it does.

after a bit of code formatting and comments it looks like this:

void updateDirection() {

    if (distanceInchR < minDistanceInch && distanceInchL < minDistanceInch) {
        if (movement != BACK) {
            backUp();
        } else if (distanceInchR < minDistanceInch) {
            //always entered if movement == BACK
            if (movement != TURNFL) {
                turnFL();
            }
        } else if (distanceInchL < minDistanceInch) {
            //never entered
            if (movement != TURNFR) {
                turnFR();
            }
        } else if (distanceInchR > minDistanceInch && distanceInchL > minDistanceInch)
            //never entered
            if (movement != FORWARD) {
                forward();
            }
        //endif distanceInchR < minDistanceInch && distanceInchL < minDistanceInch
    } else {
        // entered when distanceInchR > minDistanceInch || distanceInchL > minDistanceInch
        if (movement != STILL) {
            still();
        }
    }
}

it looks like you had a missing closing brace around the first condition. Causing the only movement functions that get called to be backUp, turnFL and still.

If we add the missing braces then it looks much better:

void updateDirection() {

    if (distanceInchR < minDistanceInch && distanceInchL < minDistanceInch) {
        if (movement != BACK) {
            backUp();
        }
    } else if (distanceInchR < minDistanceInch) {
        if (movement != TURNFL) {
            turnFL();
        }
    } else if (distanceInchL < minDistanceInch) {
        if (movement != TURNFR) {
            turnFR();
        }
    } else if (distanceInchR > minDistanceInch && distanceInchL > minDistanceInch) {
        if (movement != FORWARD) {
            forward();
        }
    } else {
        if (movement != STILL) {
            still();
        }
    }
}


Communicating between a computer and multiple Arduinos

It is very interesting project. In my opinion, i would not do like you want to control generators from one point.

Look at ZigBee and Wireless sensor network. It is possible. Do more search, also there are several books about networking.
I think that would be more efficient to control the wind turbine with an Arduino and send only data to the main computer. Main computer should do some calculations or send some main configuration data or control on/off wind turbine basis of:

2.1  Metrological data (wind speed or else);

2.2 Storage SOC(if you will store it in batteries or somewhere);

2.3 Required power of grid and etc. etc.

Arduino UNO like you said, connected to computer could do just data collection and making it compatible with computer(MatLab or whatever) and spread control data from PC to targeted Arduino.

Added links

Could not add more than 2 links due to low reputation :)

http://www.digi.com/pdf/wp_zigbeevsdigimesh.pdf , http://forum.arduino.cc/index.php?topic=105273.0


Can internal and external pull up/pull down resisters be used together?

The main risk if you use both internal and external pullup/down resistors working in opposite directions is that the input will be left at an intermediate voltage that is not guaranteed to be read as high or low. Furthermore a little noise on the input might flip a read from high to low or vice versa. There is no risk of damaging the input however


SoftwareSerial Write to return Read in Serial Monitor?

SoftwareSerial cannot talk to itself. Since it is implemented in software and not hardware it can either send or receive at one time, but not both.

Look at the code for write in SoftwareSerial:

size_t SoftwareSerial::write(uint8_t b)
{

...

  cli();  // turn off interrupts for a clean txmit

...

  // Write each of the 8 bits
  for (uint8_t i = 8; i > 0; --i)
  {
    if (b & 1) // choose bit
      *reg |= reg_mask; // send 1
    else
      *reg &= inv_mask; // send 0

    tunedDelay(delay);
    b >>= 1;
  }

...

  SREG = oldSREG; // turn interrupts back on

...

}

Since it turns interrupts off, and interrupts are needed for it to detect incoming data, therefore it cannot detect incoming data while it is sending.


Arduino Uno + SIM808 EVB 3.2.4 not working properly?

I recommend you to use AT command ..then using some kind of library. You need to dig into library for better information.
https://randomnerdtutorials.com/sim900-gsm-gprs-shield-arduino/
Go through this link....this will give you a rough idea.


Chinese CH340 Arduino Uno - Burning stand allone chip

You said:

It just need a pull-up resistor for the reset pin!


Arduino library creation - Calling library and Merging

If you consult the Arduino Library Specification's section on keywords.txt:

  A tab should be used to separate each name from the KEYWORD1/Keyword2/Literal1 identifier.

A true tab character is required, rather than spaces, as you have in your keywords.txt. It is common for text editors to be configured to add a given number of spaces when the tab key is pressed rather than a true tab character. That's great but in this case you will need to be sure that the tab character is used.

Note that the tab requirement will be relaxed in the Arduino IDE 1.9.0 release, which will also accept space(s) as a keywords separator but it's still best to use tabs for backwards compatibility since people will be using pre-1.9.0 IDE versions for years to come.


Can anyone tell me about the onboard accelerometer of LightBlue Bean?

There is a reference to the accelerometer datasheet from the Arduino Reference page


How to convert Arduino example sketch to a complete c++ project?

Basically *.ino is *.cpp without headers. So you can

rename it to *.cpp,
If you have any functions which are used before they have been defined, provide declarations for each function before its first use
#include <Arduino.h> on the top
#include <Wire.h> if you are using Wire and so on

and you have "normal" CPP file.

If you are making library this way, than you create also *.h file, where you declare all exported functions and objects and #include that file in your *.cpp as first line (than you do not need/have to forward declare any of that exported functions)

You may like to take a look at https://github.com/arduino/Arduino.git https://github.com/sudar/Arduino-Makefile and https://github.com/ladislas/bare-arduino-project

the Bare Arduino have 2 projects each using 2 libraries, so you can get inspiration there


By that photo you posted, you pretty much answered a decent part of your question. You'll need six pins for the LCD, and one or two for the button. That means that you need a total of 8 pins. That Uno pictured has 20 (analog can act as digital, too).

As far as the boards, if you feel comfortable with some extra work, I'd recommend an ATtiny. From what I can find, it seems like you can drive a LCD with a 44 or an 84 (similar, but the 84 is more powerful).

Source for image and how to program chip. I'm not going to go into the details for this method, as the link has the necessary files...

That's the smallest way to do this*, however, if you want to use a real Arduino board, then I'd recommend the Micro for a few reasons.

First of all, it has the newer ATMEGA32u4 chip, found on the Leonardo. I do not recommend the Mini because, although it's the smallest of the three, it doesn't feature on board USB. You would have to buy another adapter to program it. If you're already using a breadboard, the extra 2cm (or so) is worth not having to spend more to buy both of those components. The Nano is the equivalent of the Mini, only with USB. Also, the Nano and the Micro are roughly the same size, one a little bit longer and one a little bit wider.

However, the Nano and Micro are roughly the same as far as processing power, so I'd recommend that, if you can get one significantly cheaper, to go with that. It doesn't really matter that much.

*If you're building this on a breadboard, it won't be smaller. If you're transferring to a PCB, then you should use an ATtiny.

As far as the pot goes, I'd recommend getting a trimmer with an equivalent value. Some of them are very small, as I have one that fits on the USB connector part of my thumb drive. They need a screwdriver to adjust, but I would recommend it. I've had issues moving it from a dark room to in the sun and not being able to see it clearly. Spend the two cents and the 2 cm2 and have an opportunity to change it if needed.

For the battery, I would recommend any rechargeable battery (under ~3.5V) if and only if you add a proper chip to not waste energy in the conversion. I talked about this in this post.


How can I pulse a stepper motor whilst also wanting to handle other tasks?

Instead of delaying between pulses, loop around the main loop() function as fast as possible constantly checking the time to see if we should pulse the motor.

This means that computations can occur in the loop (so long as they are reasonably fast).

To implement this, the micros() function can be used to get an unsigned long representing the microseconds that have passed since the start of the program.

Then in each loop cycle, we need to check if the difference between the current time and the last time that we pulsed is >= the pulse delay. In which case, we send a pulse to the motor

However, instead of setting the last pulse time variable to the current time, we instead increment the last pulse variable by the delay time. This has the affect that even if we were slightly late in pulsing, we pretend that we did in fact pulse at the right time so that they do not drift over time.

This would look something like:

#define STEP_PIN  3
#define DELAY     100

uint32_t last_pulse;

void setup(){
    pinMode(STEP_PIN, OUTPUT);
    last_pulse = micros();
}

void loop(){
    //heavy computation taking time
    if (micros() - last_pulse >= DELAY){
        last_pulse += DELAY;
        digitalWrite(STEP_PIN, LOW);
        digitalWrite(STEP_PIN, HIGH);
    }
}

Note that there is a slight subtlety here in that the result from micros() and therefore the value of last_pulse will overflow after ~70 minutes. However, because we are taking a difference of two unsigned numbers, this method will still work, so long as micros() is never a whole cycle ahead of last_pulse which in practice will never be the case.


To solve this problem, you should google the error message "avrdude: stk500_recv()".  The web shows countless records where this error comes up.  The message indicates that the serial communication has malfunctioned, but incorrect driver or serial port is not the only way this can happen.

During upload, (1) Have you tried to reset the arduino, (2) ensure that the RX/TX pins are not in use?


Send out a short signal every 10 seconds to an arduino

A 555 doesn't have to generate a 50% duty cycle. Even if you do want to use a 50% duty cycle, the edge can be RC coupled into the interrupt to reduce the pulse width.

An Arduino can use a slow clock like a 32kHz watch crystal, then it's very low power indeed. This slow one can be used to wake-up your more power-hungry Arduino.

The lowest power and tidiest external solution would be to use a CD4060. These are designed to be very low power, very long period timing devices.

The correct way to do it is to use the internal Watchdog Timer to wake itself up from sleep. This uses an independent internal hardware 128kHz low power oscillator. The longest this can be programmed to wait is 8s. However, if you program it to 5s, then the Arduino can choose to do work, or go straight back to sleep again, on each interrupt.


The L293D has about a 2.6V drop on the output pins. That means for a 3V motor you need to provide about 5.6v for it to run at full speed. 5V will work, but it will run slightly slow and underpowered.
9V batteries are useless. Only any good for very low power applications like smoke alarms. They just can't provide the current you need.
Instead you need to be looking at model aircraft / drone suppliers for a "2S" battery (7.4V Li Poly / Li Ion) and a suitable 5V (or 5.6V if you can get it) UBEC (switching regulator).


What Arduino board with WiFi should I choose

I'd recommend ESP8266 (model 07) based board.

Can be programmed the same way as other Arduinos
Cheap
Enough storage for code
Fairly low power
Large community (more code examples and better library support)


Arduino UNO - analogRead() returning mixed results

The analogWrite function, despite its name, outputs PWM (pulse width modulation) which is either fully on or fully off, with varying duty cycles. If you run that through a RC network (eg. 4.7k in series and 10 µF to ground), it will smooth out the pulses and you will actually get a varying voltage.

So in your case you are measuring on or off depending on the timing. However since you are measuring between the resistor and the LED, you won't get 5V because of the voltage drop over the resistor. An LED, depending on the colour, might have a voltage drop of around 2.2V, and thus you might expect 2.8V at that junction. This is approximately what you got.

  I want to measure the Voltage of the current ...

This doesn't make any sense electrically. You are either measuring the voltage (in volts) or the current (in amps). You don't measure the "voltage of the current". I suppose you mean "the voltage at that point".

Reference

Arduino functions reference:

Reference > Language > Functions > Analog io > Analogwrite


Just a follow up in case someone else has the same problem. One solution is Nick's answer in his comment, which grabs the far addresses first in the setup, storing them in an array, and using them. I

// Each array contains 32000 values
const byte VALUES_1[] PROGMEM = { 1, 0, 1, .... 0 };
const byte VALUES_2[] PROGMEM = { 1, 1, 0, .... 0 };
const byte VALUES_3[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_4[] PROGMEM = { 1, 0, 1, .... 1 };
const byte VALUES_5[] PROGMEM = { 1, 0, 1, .... 1 };

long VALUES[] = { 0, 0, 0, 0, 0 };

const long ARR_LEN = 32000;
long index = 0;

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

  VALUES[0] = (long) pgm_get_far_address(VALUES_1);
  VALUES[1] = (long) pgm_get_far_address(VALUES_2);
  VALUES[2] = (long) pgm_get_far_address(VALUES_3);
  VALUES[3] = (long) pgm_get_far_address(VALUES_4);
  VALUES[4] = (long) pgm_get_far_address(VALUES_5);
}

byte readNextValue() {
  if (index >= 160000L) {
    return -1;
  }

  Serial.print(index);
  Serial.print(" ");

  long arr = index / ARR_LEN;
  long i = index % ARR_LEN;
  index++;

  byte j = pgm_read_byte_far(VALUES[arr] + i);
  Serial.println(j);

  return j;
}

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

This runs perfectly with all bytes correct. The better answer would be to convert the bytes into bits like everyone else was saying in order to save memory space.