Can't make Wee serial WiFi work with Arduino Uno

A look at https://github.com/itead/ITEADLIB_Arduino_WeeESP8266/blob/master/ESP8266.h shows that when you pass a SoftwareSerial object to the ESP8266 constructor, a default baud rate of 9600 is also passed to it. Also, the library source file shows that, in the constructor, the begin() method of the SoftwareSerial object you passed (myserial) is called with 9600 baud. Thus, this line in your code:

    mySerial.begin(115200);

is a duplicate, albeit one with a different baud rate, thus rendering the constructor's call of mySerial.begin() useless, since your call comes after the constructor's. If you are certain that 115200 is the right baud rate for the hardware, then you should get rid of the line above and instead pass the baud rate to the constructor like this:

    ESP8266 wifi(mySerial, 115200);

Replace 115200 with any baud rate you discover to be the right one for the AT commands. You also need to uncomment the line in ESP8266.h in your library:

    //#define ESP8266_USE_SOFTWARE_SERIAL

and then save, since you are using SoftwareSerial to communicate with the module.


It certainly looks like the INT pin of the RTC can kill the whole unit. Bit of a FUBAR on their part I would say.

  Is it a viable idea to try and burn a new bootloader ?

If the problem is that INT pin then you won't be able to replace the bootloader, and even if you did it wouldn't fix the problem.

  Is there a simpler way to reset the state of the device?

It looks like you will have to make a hardware modification - cut the connection between /INT and /RESET on the board - if you can identify which track that might be - or use a soldering iron to heat and lift the /INT pin of the RTC chip, which might be easier, depending on what the chip is (they are amazingly short on information).

  What did I even do wrong ?

Probably nothing serious - it's the design that is at fault. Anything that has the potential to completely cripple a system like that without even trying is just idiotic.


There are two devices on an Arduino board than need a clock source:

The ATMega328 / ATMega2560 main MCU (16MHz)
The USB interface.

The USB interface crystal speed depends on what device is used on your board. Genuine Arduino boards use an ATMega16U2 which uses a 16MHz crystal.  Cheap Chinese clones use a CH340G which takes a 12MHz crystal.

Note that normally it's one crystal and one ceramic resonator.  USB requires very precise timing, so a crystal is used for that. The main MCU doesn't need quite such precise timing, so a cheaper (and less accurate) ceramic resonator is used.


Asynchronous function calls in Arduino sketch

Yes and no. You're kinda vague on what you want to do. I've made this into a few different sections (mainly focused on reading sensor data... it applies to everything but that's the context I'm using):

Threads

AFAIK all Arduinos only have one core (they can do one thing at once). For most Arduino boards, hardware multithreading isn't supported. However, there are ways to implement software multithreading. The approach by AsheeshR wouldn't work well for functions that take a long time to complete (i.e. something in a library that takes a while, or a delay) because it would get jammed up by those instructions, but it would work well for short functions like pinMode(). The Protothreads library listed there might be better at this, but I don't really know.

It'd be hard to orchestrate this with HTTP, especially since you have to make

Delays

A common way for a sketch to stall is the use of a delay. This can be solved by using, in the main loop, a if statement and the millis() function that returns a time (not a clock time, but rather the time since the Arduino started). You could also do a loop within the loop to poll sensor data.

The millis() approach wouldn't work well with things that cause the whole program to stall (i.e. more delays or loops that last a noticeable amount of time). Note that 100ms IIRC is the general maximum time to make a UI not seem laggy.

Interrupts

Interrupts are a great way to keep things almost asynchronous. They run a short piece of code (that you specify) every time a pin state changes. It breaks from the loop(), and goes back where it left off once the "ISR" has been ran. I don't have much time to explain how to do this, but a quick Google search will yield a lot of results.

As far as you example, the threading section would be the most applicable. This topic is pretty vague, so you'll have to experiment with a few things and find something that works.


Your code is completely wrong in almost every respect.

#define char incomingByte; //Defines incomingByte

That line means that the compiler will substitute incomingByte; whenever it sees char.

#define char sendBack = K;

Now it will substitute sendBack = K; when it sees char.

#define char ?;

Now it will substitute ?; when it sees char.

#define pollTime;

I don't know what you are thinking here. If you are trying to declare a variable you have to give a type, like this:

int pollTime;

bool running = true;

void setup() {
Serial.begin(9600); //Set data rate.
}
void loop() {

Those lines are OK.

for(Serial.available() > 0;)  { //Gets you the number of bytes that are available to be read from the serial port.

You don't want the semicolon there. A for loop is not written like that. You possibly mean while, ie.

while(Serial.available() > 0)

pollTime = delayMicroseconds(200); // Sets a poll time of 200 microseconds.

That is doing nothing of the sort. It is delaying 200 µs, it isn't setting anything.

incomingByte  = Serial.read();

That line is OK, assuming you declared incomingByte like this, and not the way you did:

char incomingByte;

if(incomingByte = ?) {

That needs to be in single quotes, as you are comparing a character. Also you compare with == not = ie.

if(incomingByte == '?') {

Serial.print(sendBack);

It looks from your earlier code you mean:

Serial.print('K');

  }
 }
}

These lines look OK.

I suggest you read a beginners page about C programming. This is just pure guesswork what you are doing here. For one thing, read up on how #define works. Here is one page: https://www.techonthenet.com/c_language/constants/create_define.php. And another: http://www.cprogramming.com/reference/preprocessor/define.html


Anyone have the Maplin N97DG bluetooth shield working?

I've just got mine working, in about 3 hours.

The first example I've never got working. The SAT+RESET worked first time... and I was then able to pair.

An easier module is the HC-05. That by default goes straight to discovery mode, and makes things alot easier.

I have more success with the serial monitor in Arduino studio, rather than X-CTU.

The point of the sheild is to prototype, or the shield you have to use in your production project. If you are doing the former, then there is little point in using the shield as you would have to change the code to fit the hardware.

It seems a thorough product, probably too involved.


I see that resistance is decreasing with bigger pressure. Will there be almost 0 ohm resistance?

The harder the force, the lower the resistance. Sparkfun has a datasheet attached that shows the following graph:

Notice how both axis of the graph are logrithmic. This means that the resistance will never reach 0 ohms. However it will get close. At 10 Kg (22 lb) the resistance is about 250 ohms.

  What would happen if I'd create pressure about 100kg?

The datasheet has the following to say for weight above the 10 Kg mark:

  At the high force end of the dynamic range, the response deviates from the power-law behavior, and eventually saturates to a point where increases in force yield little or no decrease in resistance. Under these conditions of Figure 2 [ie. the graph above], this saturation force is beyond 10 kg. The saturation point is more a function of pressure than force. The saturation pressure of a typical FSR is on the order of 100 to 200 psi. For the data shown in Figures 2, 3 and 4, the actual measured pressure range is 0 to 175 psi (0 to 22 lbs applied over 0.125 in^2). Forces higher than the saturation force can be measured by spreading the force over a greater area; the overall pressure is then kept below the saturation point, and dynamic response is maintained. However, the converse of this effect is also true, smaller actuators will saturate FSRs earlier in the dynamic range, since the saturation point is reached at a lower force.

In summary, the weight applied can go over 10 Kg providing that weight is spread over the sensing area. The larger FSRs (such as this one) are better suited for this purpose as they have a larger area for which to spread the pressure.

Note: It is quite possible that with 100 Kg you could irreversibly damage the FSR, particularly if the weight isn't spread over the sensor area.

Measuring an analog voltage from the sensor is possible so that it can be fed into one of the analog pins of the Arduino. This Adafruit page has a nice table at the bottom showing the analog voltage that you get when you put the sensor in a voltage divider network (ie. in series) with a 10K ohm resistor.


How to convert the 0-5V to a 4-20mA current loop?

If all you need is analog 4-20mA loop transmitter, then you need an op-amp, the transistors that its output drives, a sense resistor, and a few other resistors. Note that these are at least 1% resistors. This needs to be built on a printed circuit board, not a solderless breadboard.  Two of my coworkers at Maxim Integrated wrote an applications note about a 4-20mA current-loop transmitter: http://www.maximintegrated.com/en/app-notes/index.mvp/id/5610  see this figure:

Since you are already using a PWM (hopefully with an RC low-pass filter), you just need everything after the DAC output. (Performance will not be as good with an Arduino PWM as it would be with a 16-bit voltage-output DAC, but the general idea would still work.) For your purpose, you can also ignore all of the stuff about the HART modem -- that's an extra feature for sending digital information along the same loop. Only relevant if your PLC receiver was expecting it.

There are also numerous prebuilt 4-20mA transmitter boards available, this has been around many decades in the industrial control market. Since Maxim Integrated makes precision DAC chips, we don't make reference designs that take 0-5V (especially from a PWM!) and convert to 4-20mA -- but we do sell reference design boards that include the DAC. Such as our Monterey system board (MAXREFDES15#). http://www.maximintegrated.com/en/app-notes/index.mvp/id/5683

There's also a 4-20mA Current-Loop Transmitter from ti.com, XTR117: http://www.ti.com/lit/ds/symlink/xtr117.pdf

There's also a board from mikroElektronika, MIKROE-1296 (available through mouser.com) that uses an Analog Devices DAC (through SPI interface) to drive the 4-20mA transmit circuit. Again, this is an idea that's been around many decades, so a search for 4-20mA transmitter should yield lots of useful information.

So your best bet is probably to purchase one of these prebuilt 4-20mA transmitter boards, which most likely will include its own precision DAC. You'll have to modify your Arduino code to drive the SPI interface, specific to whichever DAC you end up using. Or, if you really want to use the PWM to drive 4-20mA (at reduced performance), be sure to at least use an RC low-pass filter to get it as close as possible to a stable DC level.


How to send messages to multiple numbers using Arduino uno & SIM800 module?

@nilesh just add some delay between two massege

I modified your code check it

const int Main1 = 8;
const int Main2 = 9;
const int Store1 = 7;
const int Store2 = 10;
bool i = false;
bool j = false;
bool k = false;
bool l = false;

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

  pinMode(Main1, INPUT);
  pinMode(Main2, INPUT);
  pinMode(Store1, INPUT);
  pinMode(Store2, INPUT);

  digitalWrite(Main1, LOW);
  digitalWrite(Main2, LOW);
  digitalWrite(Store1, LOW);
  digitalWrite(Store2, LOW);

  delay(1000);
}
void loop()

{
  sensor1();
  sensor2();
}
void sensor1()
{
  if (digitalRead(Main1) == HIGH && digitalRead(Main2) == LOW && i == false)

  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-----------");// first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate closed");
    Serial.write(0x1A);
    delay(5000);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-----------");// Second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate closed");
    Serial.write(0x1A);
    delay(1000);
    i = true;
    j = false;

  }
  if (digitalRead(Main2) == HIGH && digitalRead(Main1) == LOW && j == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91---------------");//first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate Open");
    Serial.write(0x1A);
    delay(5000);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91--------------"); second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate Open");
    Serial.write(0x1A);
    delay(1000);
    j = true;
    i = false;
  }
}
void sensor2()
{
  if (digitalRead(Store1) == HIGH && digitalRead(Store2) == LOW && k == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
   Serial.print("+91-----------");// first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is closed");
    Serial.write(0x1A);
    delay(10000);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-----------");// second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Closed");
    Serial.write(0x1A);
    delay(1000);
    k = true;
    l = false;
  }
  if (digitalRead(Store2) == HIGH && digitalRead(Store1) == LOW && l == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
   Serial.print("+91-----------");// first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Open");
    Serial.write(0x1A);
    delay(5000);
    Serial.print("AT+CMGS=\"");
   Serial.print("+91-----------");// Second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Open");
    Serial.write(0x1A);
    delay(1000);
    l = true;
    k = false;
  }
}

thanks

bhupendra.sinkar727@gmail.com


How can I concatenate these two values as a string?

You can use the c function sprintf(, , ...)
The char array has to be big enough to hold your text plus a null to terminate the string.

#include <Arduino.h>

void setup() {
  Serial.begin(115200);
  delay(1000);
  char out[20];
  sprintf(out, "Device-%08X",ESP.getChipId()); // %08X\n formats the hex and pads with 0s.

  Serial.println(out);
}

void loop() {}

Output:

Device-005D4D9D


Arduino software won't open in Mac OSX 10.10.1

Download and install the Apple version of Java (6): http://support.apple.com/kb/DL1572

If you need Java 8 SDK for some reason, the two can coexist because the Arduino IDE will explicitly ask for the (Apple Version) of Java 1.6 using 'JavaApplicationStub':

$ ./JavaApplicationStub
[JavaAppLauncher] Requested [1.5*], launching in [1.6] instead.
Experimental:  JNI_OnLoad called.
Stable Library
=========================================
Native lib Version = RXTX-2.1-7
Java lib Version   = RXTX-2.1-7

Note however that if you have both Apple Java and Oracle installed, running 'java' or 'javac' form the command line will run the Oracle version.

$ java -version
java version "1.8.0_25"

If you need to switch the 'command line' version, change the symlinks in:

/System/Library/Frameworks/JavaVM.framework/Versions/

'JavaApplicationStub' will use the Apple version located in /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java.

As such, 'normal' java programs will generally use the Oracle version, while applications running in your browser or using JavaApplicationStub explicitly (like Arduino) will use the 'Apple' version.


Ribbon sensor resistance slowly drops when released

The Adafruit website says this:

There is a nominal 10K resistance across the two outer leads. The middle pin resistance with respect to either of the outer pins changes depending on where on the strip one presses. When no pressure is applied, the middle pin floats, so be sure to use some sort of weak pullup, such as 100K ohm.

To use Connect one side pin to ground via a 10K resistor in series. Connect the other side pin to your Vcc power line (3V, 5V etc) via a different 10K resistor in series. Then read the analog voltage on the center pin. It will range from 1/3 Vcc to 2/3 Vcc . Do not connect to Ground and Power directly!

Here is a diagram of how I would connect it to a 5V Arduino Uno.


Need to power Arduino Mega 2560 with 3.3V

Have you considered maybe using the Iteaduino MEGA2560?

The Iteaduino MEGA2560
uses the same ATmega2560 processor as the Arduino Mega 2560,
but is physically much smaller, the size of a Arduino UNO.
It has a switch to run the ATmega2560 at 3.3 V, so its I/O pins can be directly connected to 3.3 V modules.
It breaks out all the GPIO pins of the ATmega2560,
so it actually has more I/O on its connectors than the Arduino Mega 2560.

If I'm reading this right, the Iteaduino schematics and a typical Iteaduino features list
seems to say it already has a 16 MHz crystal.


Can't connect to my ESP32 board via serial

The issue is that the Serial port on the ESP32-WROOM setup is not like like on the Arduino. It seems that the initialisation will 'miss' the USB enumeration after reboot.

To fix this add a delay in your setup() function of 10 to 15-seconds before initialising the serial.

For example:

void setup() {
  delay(10000);
  Serial.begin(115200);

  Serial.println("Setting up Access Point...");
  .
  .
  .


Multiplexing is the answer.

If you want to, as an example, light up only LEDS 1, 3 and 4, you will:

activate line A
activate line X
de-activate line X
de-activate lines A and B (yes, B was not active)
activate line A and B
activate line Y
de-activate line Y
de-activate lines A and B
start again from top

Do this so that the loop takes less than 10 milliseconds and you are actually refreshing the entire matrix at 100Hz, fast enough to trick the eyes of any human being as if the LEDs 1,3 and 4 are lighted up at the same time: persistence of vision is your friend.


Arrays in C are fixed. sizeof() will always give the amount of allocated memory for the array.

Instead, you should be using strlen() to get the number of characters up to (but not including) the terminating NULL character at the end of the string.

ScrollingMsg.SetText ((unsigned char *) TxtDemo, strlen(TxtDemo));

Make sure that you have enough space in your initial array to store the longest string you will want to send - it will not grow beyond your initial allocation. Also be sure to get the NULL character at the end of your valid text. It's too easy to forget you need to insert that after your last received character.


What kind of a sim card is required for sim800 module?

The SIM interface complies with the GSM Phase 1 specification and the new GSM Phase 2+ specification for FAST 64 kbps SIM card. Both 1.8V and 3.0V SIM card
are supported. The SIM interface is powered from an internal regulator in the module.

For more details see here and here. And remember "Google is your friend".

Cheers!


Programming other Atmel chips(excluding Atmega 328 and 168)

Since you say:

  Excluding the Atmega 328 and 168.

I'm going to assume that you already understand the general process for using your Nano as an ISP.

The Arduino IDE includes the Arduino AVR Boards hardware package which provides hardware definitions for specific configurations of:

ATmega328P
ATmega168
ATmega2560
ATmega1280
ATmega32U4
ATmega8

If your hardware matches the configuration of one of the Arduino AVR Boards then you only need to select that board from the Tools > Board menu.

It is also possible to program many other Atmel microcontrollers or alternative configurations of the microcontrollers included with the Arduino AVR Boards hardware package with your Nano but you will first need to install the 3rd party hardware package that contains the definitions for the part you want to program. You can find a fairly comprehensive list of these hardware packages here:

https://github.com/arduino/Arduino/wiki/Unofficial-list-of-3rd-party-boards-support-urls

Once you have found the hardware package that contains the necessary definitions you will need to install it. For this you have two options:

Boards Manager

The easiest installation option Boards Manager. Most Arduino hardware packages allow this type of installation (and certainly all of them on the above list):

Copy the Boards Manager package index URL.
File > Preferences > Additional Boards Manager URLs > paste URL > OK
Tools > Board > Boards Manager
Wait for downloads to complete.
Scroll down until you see the entry for the hardware package you want to install. Click on it.
Click "Install".
Wait for installation to finish.
Click "Close"

Manual Installation

Another option is to manually install the hardware package. For a simple package this would involve:

Download the hardware package
Copy the contents of the downloaded file to {sketchbook folder}/hardware. You can find the location of your sketchbook folder at File > Preferences > Sketchbook location.
Restart the Arduino IDE if it's running

After installation you will only need to select the correct board from the Tools > Boards menu. In some cases selecting a board may also add custom menu items to the Tools menu that can be used to adjust the configuration of the board (part, clock, BOD, etc.).

  using Arduino Nano as a Arduino ISP

Note that the correct term is Arduino as ISP. There is a programmer named ArduinoISP that is completely different from the Arduino as ISP. The confusion is increased by the sketch used on the Arduino as ISP being named ArduinoISP.


Grounding for arduino, measuring phase controllled 240V

your circuit will work, and can be simplified a little bit further. But it will work.

it is safer to use isolation, however. there are multiple ways to go about doing it.

the key here is to detect zero crossing, and start counting from there.


Need help with my code for my project using an Arduino Uno and Processing

You asked for (emphasis mine):

  [...] But once the input goes low, it will save the time OFF (stop)
  on the same line.

That's hard. What if several other inputs have gone HIGH in the
meanwhile? You will have to somehow rewind part of the file, then add
the stop time, the add again the subsequent lines...

You probably do not want to do all this on an Arduino. Especially
considering that the Arduino has no concept of file, unless you add an
SD card and the appropriate library. And it has no concept of time of
day, unless you add an RTC and the appropriate library. I would suggest
you go the easy path:

have the Arduino tell your computer through the Serial port whenever
one of those inputs changes state
write a program in your computer (with processing or whatever) that
reads this information and formats it the way you want.

For the first part, I suggest the following:

/*
 * Tell us when some pins change state.
 */

const int CHANNELS = 4;
const uint8_t pins[CHANNELS] = {8, 9, 10, 11};

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

void loop()
{
    static int states[CHANNELS];
    for (int i = 0; i < CHANNELS; i++) {
        int state = digitalRead(pins[i]);
        if (state != states[i]) {  // input changed state
            Serial.print("channel ");
            Serial.print(i);
            Serial.print(" going ");
            Serial.println(state ? "HIGH" : "LOW");
            states[i] = state;  // record new state
        }
    }
}

The output will be something like

channel 2 going HIGH
channel 1 going HIGH
channel 2 going LOW
...

For the second part, well, that's not an Arduino-related question
anymore!


Mic input and Speaker output using arduino

Microphone input is easy (ADC). Speaker output is easy (PWM). Both have many, many examples strewn across the Internet.

What happens in between is not, and will require external components. You will need at the very least somewhere to store the samples between record and playback. Investigate SPI SRAM large enough to store all the required samples at your chosen sample rate (8 kS/s should be high enough for human speech).


Good voltage and resistor value for string of LEDs

Since the relation between voltage and power is quadratic, the obvious answer is "as little as possible".

Allowing for 3% variance in VF gives us just under 13V, so that is a reasonable starting point. Solving for R gives 22ohms, a E24 value. This will result in a 8.8mW loss, which even a 0201 resistor can handle.


MIT "happy board" like shield for arduino

It sounds like you're looking for the Board of Education Shield (for Arduino)

  Key Features:

  17 row x 2 column breadboard for convenient circuit-building
  Headers for power (Vin, 5 V, 3.3 V) Ground, Digital I/O and Analog In
  are brought adjacent to the breadboard
  Onboard 5 V regulator supplies up to 1 A, great for robotics and
  animatronics applications
  Onboard 3.3 V regulator supplies up to 200 mA for project circuits and
  accessories, such as XBee modules
  4 servo ports with power selection jumper for regulated 5 V or Vin
  (Arduino's supply voltage)
  3-position power switch for power header only or power header + servo
  ports     Board reset button resets the Arduino
  Supply indicator LEDs for breadboard and servo power


The b prefix in Python 3 just means that it is a bytes literal. It's not part of the output, that's just telling you the type.

The \r\n is a common Carriage-Return and Newline line-ending characters. You can remove that from your string by calling strip().

Since these are floating-point numbers being returned, I'm guessing you're going to want to use them in some way after they are read, too:

import serial

ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
   value = float(ser.readline().strip())
   print('New value is {0:0.2f}'.format(value))

See also:

What does the 'b' character do in front of a string literal?


If-statement matches but doesn't give a result

The Arduino IDE uses the C and C++ programming languages.

Some string comparison basics using C:

In the C programming language, a string can be thought of as an array of 8 bit values.  One way to compare two strings is to compare each 8 bit value and consider the strings different (not equal) upon finding the first not-matching 8 bit value.  Here is an example from programmingsimplified.com:

int compare_strings(char a[], char b[])
{
   int c = 0;

   while (a[c] == b[c]) {
      if (a[c] == '\0' || b[c] == '\0')
         break;
      c++;
   }

   if (a[c] == '\0' && b[c] == '\0')
      return 0;
   else
      return -1;
}

There is a common function called strcmp() which can be used instead.  Here is another example from the same web page which uses strcmp():

#include <stdio.h>
#include <string.h>

int main()
{
   char a[100], b[100];

   printf("Enter a string\n");
   gets(a);

   printf("Enter a string\n");
   gets(b);

   if (strcmp(a,b) == 0)
      printf("The strings are equal.\n");
   else
      printf("The strings are not equal.\n");

   return 0;
}

Note that in both cases the array of strings is assumed to end with a NULL or zero value byte.  If you do not wish to follow this format you can use an alternate version of the function called strncmp() where the number of characters to be compared is passed along with pointers to the 2 strings.

Some string comparison options using C++:

There are C++ ways to compare 2 strings which make coding Arduino Sketches easier.  But C++ string manipulation usually requires more RAM.  And RAM is usually in short supply on inexpensive embedded processors.

As the code in the question is written using type String we can explore that approach. And, as there is some concern the strings may have unexpected trailing characters, we will continue to check only the necessary number of characters. In this slightly modified code example from geeksforgeeks.org string s1 is compared with string s2.  But only the first 6 characters are compared:

void compareOperation(string s1, string s2)
{
    // Compares 5 characters from index number 3 of s2 with s1
    if((s2.compare(0, 6, s1)) == 0)
        cout << "Here, "<< s1 << " are " << s2;

    else
        cout << "Strings didn't match ";
}

The number 6 was chosen because "yellow" contains 6 printable characters.  In this way, we can avoid the uncertainty of what character(s) follow the characters that make up "yellow" as received from the serial port.


How do functions outside of void loop work?

The setup() and loop() functions are unusual because they are called automatically for you by the Arduino code. No other functions behave this way.

Generally speaking, a function will never run unless you explicitly call it yourself (e.g. from within setup() or loop()), or instruct another part of the program to call it. (There are other ways to execute functions, but that usually involves some very advanced tinkering which is best avoided.)

For example, pinMode() is a function just like any other. It only runs when you actually put something like pinMode(3, INPUT) in your code. At that point, it runs once, finishes, and then the calling function carries on from where it left off (they never run in parallel).

The example code you've posted is quite interesting. Look at these lines in setup():

Wire.onReceive(receiveData);
Wire.onRequest(sendData);

These lines are telling the Wire object to call receiveData() and sendData() in response to I2C events. It does this by passing function pointers which are stored and used by Wire.

I'd recommend searching for information about C/C++ function pointers online if you want to learn more about this. You may also be interested to explore Arduino's attachInterrupt() function.


How to use relay shield to control dc motor speed and direction?

Using a mechanical relay to control the speed is not a good idea. But you can control the directions.

I prefer you to use Solid state relays (SSR) to do this. Arrange 4 SSR as Hbridge and Use PWM to control the speed.

refer this

or you can use the devices like this which has direction control as well.


Update class attribute with attachInterrupt

You've run into a classic trap.  There are a couple of things to think about.  First off, if this is a singleton class (as in there will only ever be one instance) then you can just have a non-member function that you use with attachInterrupt and have that function just call the member function you want.  Normally what I would do would be to create the instance in the .cpp and put an extern declaration for it in the header so that it can just be used without creating it.  Look at how Serial works for an example.  Then put all the configuration type stuff into a begin or init method to call from setup.  That way the non-member function for the interrupt can be part of the header and the user never has to see or mess with it and it feels like it's part of the class.

If this is not a singleton class and you might one day have several instances of this in one program then you have to start asking yourself how will the interrupt know which instance to act upon.


The Absolute Maximum is 40mA per pin, but you shouldn't go even close to that; max. 20mA per pin is about where you want to be. Total current (all pins) shouldn't exceed 200mA.
Only you know what current your "fairly small" motors pull, but you may have fried a few IO pins.
Also, you need flyback (or maybe bidirectional TVS) diodes and a few capacitors on your motors to keep noise and inductive kick-back away from your pins. Motor driver modules often have these installed, but your Arduino pins don't. Inductive kick-back can easily kill IO pins also.


Arduino Mega PWM - 100ms Period - SSR and Heater

I'd suggest using the TimerOne library.

Call Timer1.initialize(10000) in setup.
Then call Timer1.pwm(pin, duty); in your loop. Where pin is 11, 12, or 13 for the MEGA, and duty is between 0 and 1023.


Use server.arg results as a function parameter?

server.arg stores get the parameter as a string, so I am not sure what needs to be done.

The parameter needs to be converted to an uint32_t (and then to a CRGB or CHSV struct). The simplest way is to use the C library function strtoul

uint32_t color = strtoul(arg, NULL, 16);

This can be improved so that it checks that a number was scanned, etc.

Cheers!


Sending NEC IR signals makes LED strip blink

32 kHz seems to be the winner. Now all my codes work! Damn, if I only had read that ONE SITE that showed it haha.


It apparently is true that “RTTI (run-time type information) is disabled with the fno-rtti compiler flag”; however, looking at compiler.c.flags and compiler.cpp.flags in platform.txt, no fno-rtti compiler flag is set, suggesting that gcc sets it by default.

One way to turn off fno-rtti is adding a -frtti flag into the appropriate flags string in platform.txt.  As a side effect, this will affect all sketches subsequently compiled, rather than only those that need dynamic casts.

Note, on a microcontroller, a more-appropriate way to deal with the problem is getting rid of the need for dynamic casts, via function overloading.

Edit 1: On Linux, typical file paths to platform.txt are like /opt/arduino-1.6.3/hardware/arduino/avr/platform.txt or /opt/arduino-1.8.0/hardware/arduino/avr/platform.txt.  I don't know the location on OSX.  However, a command like locate *avr/platform.txt should reveal its location.  (If locate is a new install on your system, first run updatedb, which may take a while.)


Leading Zeroes on Arduino Ethernet MAC Address

Writing this in case someone in the future might be interested.
The values passed in the Ethernet library is correct. The last value, 0x01 must be 1 and is written correctly, 0x01 in the registers of the W5500 inside the Ethernet shield.
Where I've got it wrong is how I pass the MAC address to the server. I'm basically creating a string for a json message. In there, I've put %02x to make sure that zeroes are padded.


Do I need to power off the Arduino board before doing something?

It is not safe, as you may accidentally connect some points, which should not be connected and destroy Arduino and/or any other part of circuit. typically legs of resistors/LEDs tends to touch other legs near them, when you are putting it in - and if it is powered, magical smoke can happened easily.

Even if you do not this kind of mistake, not everything can be put in random order without risc of damage.

So everytime you change something with circuit, disconnect power source/USB first. And if you have big capacitors anywhere, you better make sure, they are discharged too.

You switch on the board, when the building is done and you want to program it, or use the already present program.


Control LED strip IR controller using Arduino

I tried to do the same thing with hooking up an IR LED on a Raspberry Pi. It worked pretty well but the chip on the receiver board could not take fast switchings. I ended up doing my own PCB.

The problem is that the chips run at voltages higher than you would use for an ESP8266 or Arduino. This will be the biggest problem if you want to supply it with the voltages available on the board.

I think the safest thing is to see if you can simulate IR input by just connecting to GND and OUT of the IR receiver port.


EDIT this answer explains how you can put a Arduino between a (1 ppm pin per channel) RC receiver and a RC receptor. This allows for smart features (like autonomous control with RC overrule, or sensor based corrections,..)
It seems it is not the question of op.

What you want is easy but there are some pitfalls.
I can make a long story short by these links

http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with.html
http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with_20.html
http://rcarduino.blogspot.com/2012/04/how-to-read-multiple-rc-channels-draft.html

if you are serious about RC this may be of your interest to
http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with_25.html

I also converted this info in a library you can find here:
https://github.com/jantje/ArduinoLibraries/tree/master/RCLib

And for stackexchange policy here the hightlights.
If I look at the picture you added you have a 6 channel ppm receiver. Each ppm channel you want to read must be connected to a interrupt enabled pin of your arduino (The drawbacks of software enabled interrupt pin is another discussion).
The high time of the ppm tells how high or low your lever is on the remote control.
You can then have arduino do with this info what you want. For instance use the servo library to generate a ppm signal out to servo's and ppm driven motors.


MegaCore ATmega2560 PB7 activation randomly at boot

PB7 is pin 13. That's the traditional LED pin.
The bootloader blinks that LED to indicate it's active.
If you want other behaviour then you will have to compile your own version of the bootloader that doesn't blink the LED.


https://learn.adafruit.com/

and

http://makezine.com/

have a lot of projects

there's also a book called Exploring Arduino by Jeremy Blum :D

Have fun!! (:


Can I use and external power supply and USB at the same time on my Arduino?

Yes, you can simultaneously connect external power supply and USB. As explained in one of the answers, that you linked, the Arduino chooses it's power input through the supplied voltage on Vin/barrel jack. Vin has no direct connection to the VUSB, so the USB port will not get any voltage from the external supply, thus it does not get damaged.
BUT: Your thinking is wrong. Clearly your LEDs need more than 500mA. This current should never flow through the Arduino. You can easily fry the protection diode or the voltage regulator (which is an inefficient linear regulator), if you connect all the LEDs to the 5V pin. One GPIO pin can only provide about 20mA (40mA at absolute max, you should stay below 20mA) and only 100mA through all GPIOs together. They are not made to provide power, but for switching.
Instead you should connect the LEDs outside of the Arduino to the power supply. If you want to use the specified 9V power supply, you need to buy a buck switching voltage regulator, which gets the voltage down to 5V for you. Make sure, that this regulator is rated for a current significantly higher, than what you need.
How to control the LED then? That depends on your LEDs. If you just have some bare LEDs, you could use a transistor to switch the higher voltage from the Arduino. If you have a plain LED strip you can also use a transistor. Best use a MOSFET for this. If you have an addressable LED strip, just connect the power lines to the 5V output of your new switching regulator and the data line to the Arduino.


NRF24L01+ scanning and connecting to wifi hotspots or creating one

It does seem possible, check out this thread on Arduino forums, where cpixip worked directly with the NRF24 SPI interface to accomplish that.

Here is the code he published, in case the link won't be available:

#include <SPI.h>

// Poor Man's Wireless 2.4GHz Scanner
//
// uses an nRF24L01p connected to an Arduino
//
// Cables are:
//     SS       -> 10
//     MOSI     -> 11
//     MISO     -> 12
//     SCK      -> 13
//
// and CE       ->  9
//
// created March 2011 by Rolf Henkel
//

#define CE  9

// Array to hold Channel data
#define CHANNELS  64
int channel[CHANNELS];

// greyscale mapping
int  line;
char grey[] = " .:-=+*aRW";

// nRF24L01P registers we need
#define _NRF24_CONFIG      0x00
#define _NRF24_EN_AA       0x01
#define _NRF24_RF_CH       0x05
#define _NRF24_RF_SETUP    0x06
#define _NRF24_RPD         0x09

// get the value of a nRF24L01p register
byte getRegister(byte r)
{
 byte c;

 PORTB &=~_BV(2);
 c = SPI.transfer(r&0x1F);
 c = SPI.transfer(0);
 PORTB |= _BV(2);

 return(c);
}

// set the value of a nRF24L01p register
void setRegister(byte r, byte v)
{
 PORTB &=~_BV(2);
 SPI.transfer((r&0x1F)|0x20);
 SPI.transfer(v);
 PORTB |= _BV(2);
}

// power up the nRF24L01p chip
void powerUp(void)
{
 setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)|0x02);
 delayMicroseconds(130);
}

// switch nRF24L01p off
void powerDown(void)
{
 setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)&~0x02);
}

// enable RX
void enable(void)
{
   PORTB |= _BV(1);
}

// disable RX
void disable(void)
{
   PORTB &=~_BV(1);
}

// setup RX-Mode of nRF24L01p
void setRX(void)
{
 setRegister(_NRF24_CONFIG,getRegister(_NRF24_CONFIG)|0x01);
 enable();
 // this is slightly shorter than
 // the recommended delay of 130 usec
 // - but it works for me and speeds things up a little...
 delayMicroseconds(100);
}

// scanning all channels in the 2.4GHz band
void scanChannels(void)
{
 disable();
 for( int j=0 ; j<200  ; j++)
 {
   for( int i=0 ; i<CHANNELS ; i++)
   {
     // select a new channel
     setRegister(_NRF24_RF_CH,(128*i)/CHANNELS);

     // switch on RX
     setRX();

     // wait enough for RX-things to settle
     delayMicroseconds(40);

     // this is actually the point where the RPD-flag
     // is set, when CE goes low
     disable();

     // read out RPD flag; set to 1 if
     // received power > -64dBm
     if( getRegister(_NRF24_RPD)>0 )   channel[i]++;
   }
 }
}

// outputs channel data as a simple grey map
void outputChannels(void)
{
 int norm = 0;

 // find the maximal count in channel array
 for( int i=0 ; i<CHANNELS ; i++)
   if( channel[i]>norm ) norm = channel[i];

 // now output the data
 Serial.print('|');
 for( int i=0 ; i<CHANNELS ; i++)
 {
   int pos;

   // calculate grey value position
   if( norm!=0 ) pos = (channel[i]*10)/norm;
   else          pos = 0;

   // boost low values
   if( pos==0 && channel[i]>0 ) pos++;

   // clamp large values
   if( pos>9 ) pos = 9;

   // print it out
   Serial.print(grey[pos]);
   channel[i] = 0;
 }

 // indicate overall power
 Serial.print("| ");
 Serial.println(norm);
}

// give a visual reference between WLAN-channels and displayed data
void printChannels(void)
{
 // output approximate positions of WLAN-channels
 Serial.println(">      1 2  3 4  5  6 7 8  9 10 11 12 13  14                     <");
}

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

 Serial.println("Starting Poor Man's Wireless 2.4GHz Scanner ...");
 Serial.println();

 // Channel Layout
 // 0         1         2         3         4         5         6
 // 0123456789012345678901234567890123456789012345678901234567890123
 //       1 2  3 4  5  6 7 8  9 10 11 12 13  14                     |
 //
 Serial.println("Channel Layout");
 printChannels();

 // Setup SPI
 SPI.begin();
 SPI.setDataMode(SPI_MODE0);
 SPI.setClockDivider(SPI_CLOCK_DIV2);
 SPI.setBitOrder(MSBFIRST);

 // Activate Chip Enable
 pinMode(CE,OUTPUT);
 disable();

 // now start receiver
 powerUp();

 // switch off Shockburst
 setRegister(_NRF24_EN_AA,0x0);

 // make sure RF-section is set properly
 // - just write default value...
 setRegister(_NRF24_RF_SETUP,0x0F);

 // reset line counter
 line = 0;
}

void loop()
{
 // do the scan
 scanChannels();

 // output the result
 outputChannels();

 // output WLAN-channel reference every 12th line
 if( line++>12 )
 {
   printChannels();
   line = 0;
 }
}

The pinout seems to match the NRF24 library pinout.
Please note that it seems this project does not implement the WiFi stack, but only check a high enough signal ( > -64dBm) for a given channel.

In order to create a WiFi hotspot, implementing the 802.11 stack is inevitable, and it seems like the Arduino core chip (atmega328) is not suitable for implementing it using software and bit-banging, so a dedicated hardware will be necessary.


How can I loop for a set amount of time when a condition is met?

You have two major issues here:

void loop() {
  // put your main code here, to run repeatedly:
  int sensorState = digitalRead(lightSensor);

  switch(sensorState)
  {
  case 1:
    while (sensorState == 1)
    {
      if(stopTime-startTime<=myDesiredTime && sensorState == 1)
      {
        runBuzzer();
        stopTime=millis();
      }
    }
  }
}

The first is that you never re-read sensorState. The second is that you are comparing stopTime before setting a value to it. Try re-arranging like this:

void loop() {
  // put your main code here, to run repeatedly:
  int sensorState = digitalRead(lightSensor);

  switch(sensorState)
  {
  case 1:
    while (sensorState == 1)
    {
      stopTime=millis();
      if(stopTime - startTime <= myDesiredTime)
      {
        runBuzzer();
      }
    sensorState = digitalRead(lightSensor);  // read sensorState again
    }
  }
}

  In your example, the buzzer does not sound when the light has been switch on and then back off again.

Good point. Well, we can simplify somewhat:

void loop() {

  if (digitalRead(lightSensor) == HIGH)
    {
    startTime = millis ();  // remember when we started
    while (digitalRead(lightSensor) == HIGH &&
           millis () - startTime <= myDesiredTime)
      {
      runBuzzer();
      }  // end of while switch still closed and time not up
    while (digitalRead(lightSensor) == HIGH) { } // wait for sensor go to LOW
    delay (200);  // debounce
    }    // end of switch being closed
}      // end of loop


When does the ADC start reading again in interupt mode?

Your answer is correct. The ADC does indeed keep going independently of
what the ISR does. There is, however, a point I would like to make
clearer. You asked:

  My question is does the ADC start the new reading as soon as I have
  read the ADCH register or does it wait for the code inside the
  interrupt to finish?

The ADC starts a new reading as soon as it is done taking the previous
one, irrespective of whether you read ADCH or not. When your ISR
starts, the ADC is already busy making the following conversion. This
guarantees a steady conversion rate, at one A/D conversion every
13 ADC clock cycles exactly.

As a side note, you can read the result with

int val = ADC;

No need to read the bytes separately unless you are using a very ancient
version of gcc that does not know how to read a 16-bit register.


how to read all line except the first line?

Why don't you do reads for the first line, ignore them and start the while thus:

while (myFile.available() && (myFile.read() != '\n') {}; // Empty while body
while (myFile.available()) {
  Serial.write(myFile.read());
}


Arduino Uno rev 3 - what are the additional 2x3 set of pins for?

The ICSP pins have two functions:

For programming the ATMega328P directly using a hardware programmer (In Circuit Serial Programmimg)
SPI connections for shields in a standard place.

They are used for SPI because different boards have the SPI pins on the main headers in different locations. All boards should have this 6-pin block in the same place though meaning that shields can then work with more boards.

On the Uno they share the same physical connections as digital pins 11-13 plus reset and power.

JP2 and the other 6-pin block are connected to the USB interface chip (ATMega16U2). The 6 pin block provide ICSP for programming that chip. The other 4 (unpopulated) pins connect to GPIO pins on that same chip. They can be used for anything you like if you replace the firmware on the USB chip.

For now ignore those two pin groups. They aren't really anything to do with the Arduino side of things, only the USB interface.

You can find all this on the official Uno schematic which is on the official Uno product page: https://www.arduino.cc/en/Main/ArduinoBoardUno


Flash an ESC Through Serial USB without Arduino Interrupting the Signal

I can offer general advice without reference to specific implementations.

By driving the Arduino pins when it is powered off you are potentially exceeding it's maximum rated specifications for voltage on any ping, and possibly for current into a pin, and you risk damaging it.
When the Arduino is powered down its Vdd pin and power supply rail will be at about 0.0 volts and will be loaded to ground by power supply capacitors and various other items connected to Vdd - including the OUTPUT of the Vdd voltage regulator in many cases.
Each Arduino pin is connected to the Vdd rail by a body / protection diode. To drive the pin high you must also raise Vdd to high-1 diode drop and must drive the Vdd rail load from your signal line via the body diode.
If your programmer has the ability to do this there is a reasonable chance that you may damage the body diode. For extra points, a very capable signal input MIGHT damage the Arduino's voltage regulator and possibly other on board devices - but I'd think that to be unlikely.

The technically best solution is to disconnect the Arduino's relevant pins when programming. As you obviously would rather not do that, then ...

Probable solution: If you power on the Arduino and run a program which ensures that the relevant pins are set to input mode then it should work as required. IF the Arduino default program sets the relevant pins to inputs then just powering it on should suffice, but odds are that the serial port pins are not both configured as inputs.
If the Arduino has a USB to serial port IC or other devices connected to the pins in question then you will need to also ensure that they do not load the pin excessively and that they will not be damaged by programming signals. eg if you were trying to drive the Arduinos serial RX_in pin which was connected to the TX_out pin of a USB-Serial IC then the programmer would be attempting to drive the USB-serial output pin and this must be dealt with in some way.

Checklist:

Is there something else connected to this pin.

If so

What state is it in during ESC programming
Will it be damaged by programming
Will it affect programming.
What action is thus needed.


Assuming a GPIO pins outputs 5V, and you need 20 mA (0.02A), why not use a resistor of 250 ohm?

V = I * R <=>
5 = 0.02 * R <=>
R = 5 / 0.02 = 250 ohm

For 4 mA you use a resistor of 5 = 0.004 * R <=> R = 5 / 0.004 = 1,250 ohm

If you want it from the same GPIO pin, you can use also a trick:

Take a LED from a GPIO which you control by PWM
Tie a photosensor against the LED and put tape around both the LED and the photosensor
The photosensor will have a certain resistance (you can control it by the LED)
Run your circuit needing a current from 4-20mA through that photosensor.


I recommend writing your own in C++.  Arduino works well with C++ as it is written in C.  You can focus on getting the asynchronous behavior to do what you need instead of writing drivers.  I don't think it will take any longer to learn enough C++ to make this work than it will to learn to use, and possibly fix, a library. Your C++ knowledge will be much more generally useful than knowing a specific library.

Igor points out the advantages of going to a real time operating system.  I agree and think that, if you want to work on robots long term, you should go with an RTOS and get away from Arduino. Working with C++ and Arduino is one way to get started.


Communication between two arduinos over wifi esp8266

The simplest solution is to turn on Access Point Mode on one of Wifi modules. and the other one has to be set to Station Mode in order to connect to the first one.

In case you want to add a router, just set both ESP8266 modules to Station Mode and connect them to the router.

Also, I would recommend replacing the Original Firware (AT firmware) of ESP8266 with NodeMCU Firmware. It uses lua language to write programs directly to ESP8266 which means that you can even make 2 ESP8266 modules talk with each other without even using Arduino.


Is parity check hardware only or can I read it? ( Arduino Mega )

This came up a while back on the Arduino Forum - talking about Asynchronous SeaTalk.

I made a modified version of HardwareSerial which can be downloaded from http://gammon.com.au/Arduino/HardwareSerial9bit.zip

Changes are:

The internal buffers have been changed from 8-bit characters to 16-bit characters (to hold the 9th bit). Thus the buffers double in size.
There is a new argument to the Serial.begin() function, which is a boolean, whether or not you want 9-bit mode. It defaults to false.
There is a new function Serial.write9bit (). This takes an unsigned int argument, letting you supply a character with the 9th bit set. I didn't want to change the existing write function because it is used in the Print class.
The read function, which already returns an int, now will return the 9th bit where required.

Example code:

void setup ()
{
 Serial.begin (115200);  // debugging prints
 Serial1.begin (115200, true);  // 9 bit mode
 Serial2.begin (115200, true);  // 9 bit mode
 Serial.println ("--- starting ---");
}  // end of setup

int i;

void loop ()
{

 Serial1.write9bit (i++);  // send another byte

 // display incoming on Serial2
 if (Serial2.available ())
   Serial.println ((int) Serial2.read (), HEX);

 // check if we have sent all possible characters
 if (i >= 0x200)
   {
   delay (100);
   while (Serial2.available ())
     Serial.println ((int) Serial2.read (), HEX);
   delay (5000);
   i = 0;
   }  // end of sent 512 bytes
}  // end of loop

As Ignacio Vazquez-Abrams said, the hardware supports this 9-bit mode natively, it just takes a bit of fiddling around to make it work.

Because of the way that hardware serial is integrated into the IDE it is, unfortunately, necessary to find your existing files:

HardwareSerial.cpp
HardwareSerial.h

... and replace them with the ones in the download.

Note that this is for version 1.0.1 of the IDE. No guarantees are given that this will work with other versions. This was written a while back, I'm not sure what changes have been made to HardwareSerial in the meantime.

The actual changes are here: http://gammon.com.au/Arduino/hardwareSerial_diffs.txt

You could use those to guide your implementation on more recent versions, if the file download does not work "as is".


I have downloaded the library but not sure what went wrong

Your problem is, that you haven't installed the Adafruit_Sensor.h, which is a dependency of Adafruits DHT library. The README on Github for the DHT library also states this:

  You must have the following Arduino libraries installed to use this
  class:

Adafruit Unified Sensor Library

You can find the Adafruit_Sensor.h here at Github. Install it in your libraries folder. You can refer to the answer from per1234 for instructions on installing libraries.

--

The second part in your error output is not really an error. As others stated before, the IDE only tells you, which version of the DHT library it uses. If you want to have multiple version in your libraries folder, you will have to make sure, that you always use the correct one. If they are identical, you can delete one of them, if you want to. The outcome would not be any different, except for that the IDE doesn't have to tell you, which library it uses.


Nano resets or freezes on calling a function

Your problem is not due to memory shortage, but because you are erroneously using pointers.

Even with your fix you are doing the same mistake, you are just not incurring into the same problem by luck as you are not addressing anything new after the bad definition of your variable msgBuff.

Putting all that into simple terms, you should change your code and probably read some articles on C pointers as it looks like you have a Java background (like me).

Your issue is in the char msgBuff[]=""; statement which should be moved after the the call to obtain the payload size and turned into char msgBuff[RFlen];:

int RFlen=radio.getDynamicPayloadSize();
char msgBuff[RFlen];
delay(10);
radio.read(&msgBuff, RFlen);


When I open a COM port some pins on Arduino Uno goes low for about 2 seconds

What you see is expected: that's because opening the USB connection to the UNO will automatically trigger a reset of the ATmega chip of the board, hence your sketch will be executed from scratch, ie setup() will be called again then your loop() repeatedly.

Hence what you observe in detail:

open USB connection from PC
open USB connection on Arduino UNO
UNO USB chip (an ATmega16u2) triggers a RESET of the MCU (an ATmega328P-PU)
On reset, the MCU sets all pins to INPUT, i.e. high impedence, hence no voltage can be measured on any pin
Then the bootloader starts, performs some intialization and starts your sketch
Your sketch executes first setup(), so your pin is put in OUTPUT mode and set to HIGH: its voltage is thus measurable (5V)
your sketch loop() gets executed "forever" i.e.until a new reset or power supply disconnection


My question is, can I just split the power from the wall-wart providing 5v_reg directly to the 5V pin on the Arduino Micro and 5v_reg to the LEDs Vss?

Yes. As long as it is a clean regulated 5V supply.

  It it necessary to use extra bypass capacitors in this case?

No.


Arduino or Raspberry? Self Balancing robot

This depends on the type of screen you want to interface. An Arduino UNO can with big effort interface a VGA signal with very low resolution and only few colors. Better are little screens (like small OLED screens or small LCD displays with integrated controller). Using a more capable Arduino (like the Mega) can extent the capabilities of your project. The RaspberryPi has of course big display capabilities (like 1080p over HDMI).

There is also another side to the problem: A self balancing robot needs to control its motors very fast (changing the direction fastly depending in sensor input). A RaspberryPi is in principle a computer, not a microcontroller. Programs in it don't have a garanteed time of execution, so especially under high load the program might have to wait for its turn, effectively destabilizing the robot. For these real time fast applications a simple microcontroller is fitted better.

Since you also want wireless control you might be interested in using an ESP (WLAN) as a microcontroller.

All in all you should use a microcontroller for driving the balancing logic and motor control. Depending in your needs you can either use only this microcontroller to do all the other things too or connect another board as a master (eg over I2C vor SPI) which tells the microcontroller what to do. For this a raspberryPi is good.

If you provide more information about the concrete target capabilities you might get a better answer. The scope of your project is too open for clear answers.


Which Timer can I use on the Arduino/Genuino Micro?

Only Timer0 is used for millis and micros, just as with the Arduino Uno and Mega 2560.

Timer0 is used in "wiring.c".
That same file is used for the Uno, Mega 2560, Leonardo and Micro. The differences for the Leonardo is the pin numbers in "pins_arduino.h".

If you don't use PWM output with analogWrite, then you can use all of the other timers. The timers are set to certain values in the function init (also in wiring.c). But you can ignore that if you never use analogWrite.


Looking for learning resources to teach the "principles" rather than "follow this" projects

Welcome to the Arduino world!

First I'd like to try to answer your question: (This explanation does not apply to his situation as explained in the comments, but, I guess, it's a fun and useful read so I'll leave it here)

  "You'll also need to add a 10k ohm resistor from ground to the switch pin that connects to the Arduino [...] it connects the pin to ground when the switch is open so it reads LOW when there is no voltage coming in through the switch". I understand that in principle I think, but why is it 10kohm, why do we have to connect it using a resistor when the switch is open, etc. (I see that we have to have a complete circuit and I'm assuming it is because the 10kohm is a "default" branch of most resistance with nothing else connected?)

I haven't seen your circuit but I think I know the deal here. The author is basically telling you to create a pull-down circuit. What this does is, what it says. It pulls down the voltage on arduino pin to GND. Now, why would you want to do that? I think because in your project, the author was reading analog values from that pin. He wants the pin pulled down because otherwise when the switch is open, the pin would be floating i.e. not connected to anything. Floating pin means that you will get random analog readings from that pin. Basically, if you don't connect that pin to any source/sink, it will act as an antenna. You will get noise. (You can actually use this to create random numbers for your arduino!)

Now, about that 10kOhm resistor: Its depends on two things. First, if you put a low value resistor, then you will draw lots of current from the supply to the ground when the switch is closed. You normally don't want that, why spend energy more than you have to? So, you pick any big resistor that you can possibly pick. But how big can you really put there? This depends on the analog read pin's current consumption. Whenever you do an ADC (analog to digital conversion) a.k.a analog read, your pin sinks/supplies tiny amounts of current and samples it to determine voltage. Atmel datasheet says that:

As you can see, the good guys in Atmel already did some tests and determined that with the current Atmega328p (Arduino-UNO chip) chip, a source of 10kOhm internal resistance is sampled the best. (When you open the switch, the 10kOhm resistor is basically a 0V source with 10kOhm internal resistance)So basically, I guess, that's why the author used 10kOhm. Could you have used 20kOhm instead? Of course...

Now about the electronics book thing. The best practice with electronics is to both read and do. So, whatever book you pick, make sure it has examples and explanations that you can try. Don't buy a highly theoretical book with lots of math and physics. Don't use a simple do-this do-that book either. I can't provide you a single good book, because that's not how I prefer to learn. But I might have some good suggestions for you if you prefer to study like this as well:

Learn the basics or R,L,C. Study filters, energy, their differential equations etc. Any book, website will do.
Use software and simulate theoretical/explanatory circuits. LTSpice is best. For bigger projects, something like MATLAB is better.

If you do that, you'll gain some insights on how things actually work.

Move on to transistors: BJT, MOSFET etc. What are they and how they behave?
Combine transistors and R,L,C to create some digital-analog circuits. How do you make a RAM cell? Can you make an arithmatic logic unit?

At this point, you should be comfortable with most elements of electronics.

Since you started with arduino, study RISC/CISC architechture. What actually is a microcontroller?
Since you know software, try using assembly code to turn on and off some leds. This is where you meet software and hardware at the lowest possibly level you can.
Try to make your own microcontroller using FPGA! (I've done this -it was a simple and not-so-useful CPU but nevertheless it provided insight. You can invent your own assembly language!!)

At this point you should be able to understand most basic arduino projects.

Read atmega datasheets.
Read Transistor, motor driver IC etc. any driver datasheet and search the terms on google. What do they mean?

After that you can do this:

Pick a project, and do it from scratch. Without, copying any circuits from the internet. Can you place atmega chip to work stand alone, away from arduino board? Can you use that and make for example a BLDC driver?
Pick a project and ask stackexchange. (Well, obviously). There are some really brilliant people here that are willing to help. Personally, I feel I'm learning better if I try to answer other peoples questions and ask questions.

I guess the downside/upside is you never stop learning. Electronics combined with software is a huge area of expertise.

So I wish you Good luck!


Serial Monitor shows a continuous "word salad" without a loop

The ESP8266WiFi.h is for running on an ESP8266 host, but your are trying to use it on an Arduino Uno. This caused the crash of your sketch on Arduino Uno.
Based on the connection diagram you provided, you are using the ESP-01 as an wifi-shield and the ESP-01 by default is having an AT commands firmware. In order to use the ESP-01 as a wifi shield, you need an library like WiFiEspAT.


A byte can only contain values from 0 to 255 (including).

So my guess it works for values until 255.

You should use a different type, e.g. unsigned int or unsigned short.

for (unsigned short i = len; i < 250; i++) buffer[i] = '#';     // pad with #

Also, I advise to use a constant or define for the buffer size, now you have 3 values (512, 500 and 250 in the loop, I assume they should be based on the same value).

About the char*: Looking at StreamReadBytesUntil, it seems that the parameter wants a char* instead of a byte* (which is more or less the same), but it's better to cast to show the parameter is of type char* since that is high likely the exact type (but the official Arduino documentation does not show the parameter types sadly).


There are some 10pin adapter boards floating around. See e.g.
nrf24l01 (8pin) + adapter board (10pin) oops?

Their pinout looks to be the following.


Using Serial Plotter with Visual Studio Code

Without very specialized software that can create two new devices with the correct "teeing" policy, it's not going to be possible.  Only one program can open a serial port at a time (certainly and have it get anything intelligible out of it...)

I would suggest you may want to add a second serial port.  Use an FT232 adaptor to communicate on another serial connection (or a SoftwareSerial connection at a pinch) for your debugging information.  You really want a board with more than one serial port for this - or a board with a native USB for programming and a hardware serial port for data communication.

Another alternative is to ditch the serial for programming altogether and program your board through a dedicated programmer, thus leaving your serial port free for data communication.


That delay statement totally defeats the purposes of your millis code.  If you want to enforce a minimum off time then you'll have to do that with millis as well.  Using millis in this way requires that you allow the loop function to repeat many thousands of times per second.  As written you only allow the loop function to run through once every eleven and a half days.


Servo motors won't work with motor controller

See Servo.cpp:

  Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached.
   Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four.

Also Servo Library reference

  On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

You are using pins 9 and 10 for your motors.

analogWrite uses PWM, the servo library uses PWM, you have a conflict of resources here.


NRF24 CE and CSN connections without I/O pins easily accessible

No, you really do need the CE pin for both TX and RX modes.  See the following excerpts from the nRF24L01 datasheet.  They work practically the same for nRF24L01+:


Distance from Arduino UNO to LCD: How far?

The actual distance depends highly on several other factors:

Wire thickness / current carrying capacity / resistance
RFI (Radio Frequency Interference) environment
Data rate that you write to the LCD (Maybe you are using an I2C or SPI backpack)

In general, even 5 meters is probably going to work if you use sufficient wiring, but try it and see.

You may also need to add shielding to mitigate RFI.


What are some "must-have" sensors or shields for an Arduino robot or motor?

It largely depends on your interests but since you've mentioned robotics, a motor shield, motor power supply, and one or a couple of hobby servos or DC motors will get you started on learning about controlling mechanical motion. You may be able salvage a DC motor from something else, like the vibrator motor from a dead cell phone.

If you want to start inexpensively, a few LEDs and a ~200 Ohm resistor for each one, and a couple of light or temperature sensors will give you plenty to play with. It's amazing how much real-world data you can collect and infer from a couple of well placed temperature sensors.

LM34 and LM35 are inexpensive and easy to use analog thermo-sensors that read directly in 0.01 Volts / degree (Fahrenheit and Celsius respectively), so only minimal arithmetic conversion is required (because along the way, you'll learn about Analog to Digital conversion, too).

Get some experience with those simple parts, and the coding to make them useful, and you'll have a much better idea of what you want to do next and what you'll need to acquire to do it.


Using INT2/3 on Arduino Micro (Atmega32u4)

You problem isn't with your pins or code, but with debouncing the signals. I've changed the "func()" method to read:

void func()
{
  static uint32_t lastChange = 0; // Note millis() don't change inside ISR, but can be read
  if (millis() - lastChange > 100)
  {
    state = !state;
  }
  lastChange = millis(); // Set new value
}

which will ignore spurious interrupts if they occur within 100ms of each other. This solves the issue that you are seeing, I've tested it on an Arduino Micro I have lying around.


Arduino powered from motor shield and USB issue

Looking at pictures of the Elegoo Mega 2560 they use a "hash fill" for the pour on the tab of the regulator, not a solid fill, and zero vias to another dissipation layer on the reverse. While this may look more funky it provides only a fraction of the heat dissipation of a solid double-layer fill, meaning the regulator is more likely to overheat. Also because this is a Chinese clone the component quality will be lower (cheaper) meaning the regulator probably doesn't have proper thermal overload protection.

So it gets too hot too easily, and pop your Arduino is dead as the regulator fails "short" and 12V gets pumped directly into the rest of your Arduino.

Byebye Arduino, and byebye computer (fortunately temporarily in the case of your computer).


Arduino calculator: I'm struggling to write a sketch which parses inputted characters

Characters in a char[] variable may be encoded in ASCII or Unicode. You will want to convert them to numbers in this case. Consider subtracting the ascii value of one less than 0 from each char to get the number. Edit: @Matt informed me that 0 is the lowest ASCII number. As he suggested, you can subtract the character '0' from the digit to get the value. You want to specially handle any addition, division, or other operator symbols.

Then you can treat each number like a digit in a number. If you can break up the array of numbers by the operators, you can successively attach the operands to the operators. Keep in mind that each number to the left is a power of ten (assuming this is how it's implemented. This is called Endianess.)

If you post code I may be able to help further.


Thermosensor Error - 'Wire' does not name type?

You've goofed up your braces and none of that code is in loop(). Look at the braces in the code and make the appropriate corrections.


Will there be any pin interference in this Project?

possibly you will face problems with current drain and timing. There is no ready made solution. You have to get a bit farther by yourself and come back with detailed descriptions of your problems.
check on other threads (google) the issues with driving directly a coil. There are plenty of explanations why you need to be careful about it.
you should at least try to do the math yourself, then ask for verification. Try to calculate the power requirements of each component (average, maximum, peak) and add them up for every scenario. The you can report your finding and ask for confirmation/advice.
Sure you can, there are plenty of solutions available, but you have to define your requirements and constraints. Then it's easy to pick one solution (or at least google for it).
Just try to include them in the project and compile them. It's fast and you will get the answer immediately. There are ways to optimize things, but first you should assess if it's needed.

All in all, to get more help, you should show more in detail what you have already done, what are your concerns and why.


Sorry, but I'm not 100% sure of what you are trying to do, I don't understand 'both imu the' in your question.  I think you are trying to use two identical boards at the same time.  (If not tell me so I can edit my answer)

You will need to modify the library so the begin function takes a parameter.
That parameter for MPU9250_DMP::begin then identifies the address of the device, this will need passing to Wire.begin() I think (you'll need to check the Wire.begin() function, I can't).

That should let you create two different instances of the class.

MPU9250_DMP apple;
MPU9250_DMP banana;
apple.begin(0x68);
banana.begin(0x69);


How to access multiple SPI interfaces on Arduino

Assuming you just want to connect two SPI slave devices to the SPI bus and use them in a mutually exclusive way under software control, with the Arduino as the master, then you just need to make sure you use a different pin for the slave select (SS) on each SPI device.

When you want to talk to one slave, you hold its SS low and drive the other high. Do the opposite to talk to the other slave.

There are some devils in the detail using multiple slaves, and these are explained in more depth here, but in general, it's quite common and OK to use more than one SPI device as a slave.

This blog post will give you more information and is a good place to start reading.


CS5211AGP wireless RF transmitter (433MHZ) address decoding problem

I am looking at mine, wich address is 01212012, acording to a sticker in a side. I can see in mine jumpers as follows (starting from A0): -HLHL-HL-H-H where - means no jumper. Based on my sticker I can see that 0 is equivalent to NO-JUMPER, 1 is H and 2 is L. By watching yours I can tell that your code is 21111002.
The other 4 jumpers is what I don-t understand, but if I change any of them, my alarm no longer detects any change.
Hope this helps...
Regards.


Arduino Mega 2560 multiple slave via SPI

Any you like. There's nothing magic about them, as long as you have the main SS pin as an output to ensure the SPI port is in master mode.


How to get variable from callback function?

Callback functions are usually void and don't return real data, because they are called by some type of event handling system, like the mentioned library. As this is calling the callback function, not you, it does not make much sense to return data from it. To get that return value, you would need to change the library for every bit of data, that you want. Thus return values of callback functions are either void or some message to the event handling system (for example to make the event system send down the event to the next possible handler).
But you can use global variables to get the data from the callback. Define a global variable for the value, that you want to extract, and inside the callback function set that variable. Then at other places in your code you can use that global variable.
The library, that you linked, seems to handle the event in the main code and not in interrupts. So you are safe to just use the global variables as you like.
Though to be complete: When interrupts are involved and you change global variables inside an interrupt service routine, you need to be very careful. Single byte variables are not problem, but with multi-byte variables you can get scrambled data, as the interrupt might occur in the middle of processing that variable. Then you need to introduce a critical section, where interrupts are disabled for a very short time.


Using a L2938D Motor Driver Module. (Not IC, Module)

While no one can tell you exactly how to connect that board without having its documentation or the board in hand to examine visually or with an ohm-meter, it is quite likely that by leaving the "12v" terminal unconnected, no power is being provided to the motor side of the circuit.

It kind of looks like there is a voltage regulator on board, so it may be that it will even provide 5v on that terminal when given something 7 volts (or so) or higher on the "12v" terminal - again, we cannot know without details of your exact board.

The L293 is an old and low-performing chip, with internal losses that mean  that to achieve 5 volts across a motor, you will need to supply very nearly 7 volts to the chip.  The difference gets wasted as heat.


First, did the Arduino continue to respond and operate after you smelled the burning?

Just because there isn't smoke doesn't mean you didn't kill something on the board.

If your Arduino is not responding, there are two possibilites I can think of:

Your port is not working so simply switch to a different USB port
Somehow your laptop must have sent a large amount of amps/volts to the circuit and burned it out. If you have a multimeter you can use the sound setting to test whether or not wires are burned out, and if your nifty with an iron/heat gun, you can replace the part. Or you could buy a new one.

If the connection is good, you will hear a small beep. Oh, and these things don't work if there's a resistor in the way.


Connection of a DS18B20 on a Arduino pro mini

I finally made it work, thx @domen.

I looked at the other part of the schematic and found I was using the wrong pin - I have two LDO and the one I was using was deactivated for sensor.

Thanks all for your help.


Your code compiles, but as Gerben said, the printf won't do anything in its current state, as no output handlers are defined for it. Why go to all that trouble when you can do this?

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

void loop()
  {
  uint16_t adc_value;
  adc_value = analogRead (0);
  Serial.println (adc_value);
  delay (100);  // stop output spamming your monitor
  }

You could conceivably make printf work by following the tutorial here: http://playground.arduino.cc/Main/Printf

However I don't really see the point, when what I posted is much easier.

  If performance is an issue, you might want to use the "advanced" code.

That "advanced" code above doesn't give you any more performance, because is still blocks. You can do a non-blocking version easily and readably enough:

const byte adcPin = 0;  // A0

bool working;

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

  ADCSRA =  bit (ADEN);   // turn ADC on
  ADCSRA |= bit (ADPS0) |  bit (ADPS1) | bit (ADPS2);  // Prescaler of 128
  ADMUX =   bit (REFS0) | (adcPin & 0x07);  // AVcc
  }  // end of setup

void loop ()
  {
  if (!working)
    {
    bitSet (ADCSRA, ADSC);  // start a conversion
    working = true;
    }

  // the ADC clears the bit when done
  if (bit_is_clear(ADCSRA, ADSC))
    {
    int value = ADC;  // read result
    working = false;
    Serial.println (value);
    delay (500);
    }

  // do other stuff here

  }  // end of loop

Now that code (which admittedly fiddles with the registers) doesn't block so you could be doing other things during the conversion. I don't see any reason you wouldn't use that on a commercial product.

See ADC conversion on the Arduino (analogRead) for more details.


Cool, an UBEC is indeed a smart choice for powering a SIM900.
I could get away with a small switching power supply and just putting in a big capacitor (since the sim900 only draws high current in very short peaks).

But, the limiting factor in this case would be the 6AA batteries. Your UBEC may be able to supply 5A's but those AA's may not.

Also, look up "transient response" (related) according to the related article, you can have an 20A power supply, but still have the voltage drop out when the sim900 starts to transmit. This is because your supply needs to be able to deliver the required 2A in a very short period of time, so basically if your supply can't go from 100ma to 2A fast enough, it'll dip.

I suggest finding a more optimal source as AA's and adding a "big ass capacitor" close to the sim900's input.


First of all no protective circuit is needed in order to connect an arduino with an SSR. SSR input is isolated from the load.
Now answering your question you better go with an inverter, forget the SSR, and let arduino control the inverter. Using DOs from an arduino you can command the inverter to start/stop the motor or change the motor direction. Using an AO e.g provided by a DAC like MCP4921 you can control the motor RPM, too. There are a lot of inverters available for different loads and also different controls (Manual, Digital/Analog, Serial)


How do I prevent Arduino from running on startup?

The Leonardo should wait a couple of seconds after resetting to see if a new sketch arrives.

Power off the board completely (remove the USB cable).
Hold down the Reset button, and keep it held down (or, run a jumper wire from the RESET pin to the GND pin). This stops the problem sketch from starting.
Still holding down Reset, reconnect the USB cable.
Start uploading a sketch that does not have this problem (eg. Blink)
Once the IDE reports "Uploading" release the Reset button (or remove the jumper wire).


Measure movement distance - not sure what sensor?

The sensor to use is an accelerometer. The principle is easy: measure the acceleration, perform a double integration and you have the distance (after the first integration you have the velocity).

The problem is that, because of the double integration, small errors in the acceleration signal lead to big errors in the calculated distance. For example: an error e in the acceleration leads to an error e.t2 in the distance (where t stands for time). For this reason al sorts of filters are used often in combination with gyroscopes and/or gravity sensors. The signals from the gyroscopes and/or gravity sensors are used for the low frequency signals (long term) and te signals from the accelerometer(s) for the high frequency signals (short variations). That's why you find these sensors often combined in one package (for example the BNO055 form Robot Electronics https://robot-electronics.co.uk/bno055.html).

It is a complicated and highly mathematical area of science. In fact you want to do the same thing as fitness trackers do (and I think you are striving to a higher accuracy than they) - and there are not many that do really well.

P.S. Robot Electronics also sell a tilt compensated compass board with this BNO055 chip: the CMPS12 (https://robot-electronics.co.uk/cmps12-tilt-compensated-magnetic-compass.html). With this board you can read out absolute and relative positions straight away without any calculations.


I need to change this code to start the section of code when the switch is on and not when the switch is released

You should provide a description of your hardware setup as part of your question, as well as a clearer statement of your problem.

Are you saying that your code is backwards, and is acting like the button is pressed when its not, and like it's been released when you press it?

You probably have your button set up as INPUT_PULLUP, and wired to connect the pin to ground. That's a pretty typical setup. In that case the button pin reads as LOW when it's pressed and HIGH when it's not pressed. Just changed your if statement to:

//                         vvv
if (digitalRead(BUTTON) == LOW)
//                         ^^^


Advice on cabling, packaging and connectors for 12v light project

generic DC connector advice:

avoid the use of connectors which connect serially, like headphone jacks. you make strange combinations while plugging in

avoid connectors which do not latch, like headphone jacks

in a system like yours, with stages and signal processing in between, use different connectors for each phase, so you can not get it wrong

use connectors that can not be connected backwards for DC. I prefer:

Hopkins 47965 2-Pole Flat Extension for raw solar power.Not because    it's a great connector, but because it's common in low power solar

Anderson Power Poles for regulated DC power. you can secure them
together with a tie wrap; you can't connect them backwards without
doing things that are obviously counter intuitive.
Fuel injection    connectors from Autozone for signal wires. they got
a million of    them, they are made for DC at useful current levels
Trailer    connectors for multiple lead serious power.
XLR connectors can be    found from 3 to 6 pins, and you can't jam a
5 pin into a 6 pin, so    you can't cross connnect

keep things dummy proof.


data integrity when interrupts are too fast

54000 interruptions per second [...] is way too fast for my arduino
  uno

Your test is probably flawed. My Uno does handle that interrupt rate
with no issues. See my test code below.

  my arduino is able to handle only about 2050 interrupts per second

You are probably doing something wrong, like blocking interrupts for too
long, or using a library that does so.

  What surprises me, is that tickACount and tickBCount have
  different values!

As previously stated in comments, this is not the case. Instead, the
counters have been incremented while you were printing them.

  And according to the documentation, volatile only makes sense for 8bit
  values.

Either the documentation is grossly wrong, or (most likely) you have
misread it.

  From what I read, interrupts cannot be interrupted.

This is indeed the default behavior. You could change it, by issuing
interrupts() within the interrupt handler, or by declaring an ISR as

ISR(XXX_vect, ISR_NOBLOCK)
{
    ...
}

but that is seldom done.

Below is my test code. I used Timer 2 to generate a square wave on
pin 3, which is both a PWM pin (OC2B) and an interrupt pin (INT1).
The PWM frequency is about 54.054 kHz.

const uint32_t PRINT_PERIOD = 1e6;  // print counts every second

struct TickCounts {
    uint32_t tickA;
    uint32_t tickB;
};

volatile TickCounts rawCounts;

void myInterrupt() {
    rawCounts.tickA++;
    rawCounts.tickB++;
}

// Atomically read both counts.
static TickCounts getCounts() {
    TickCounts counts;
    noInterrupts();
    counts.tickA = rawCounts.tickA;
    counts.tickB = rawCounts.tickB;
    interrupts();
    return counts;
}

void setup() {
    // PWM at 54 kHz on OC2B = PD3 = INT1
    DDRD  |= _BV(PD3);    // pin PD3 as output
    OCR2A  = 37 - 1;      // period = 37 * 0.5 us = 18.5 us
    OCR2B  = 37/2 - 1;    // duty cycle ~ 50%
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // mode 7: fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(WGM22)   // ditto
           | _BV(CS21);   // clock at F_CPU/8 = 2 MHz

    Serial.begin(9600);
    attachInterrupt(1, myInterrupt, RISING);
}

void loop() {
    static uint32_t last_time_printed;
    if (micros() - last_time_printed >= PRINT_PERIOD) {
        last_time_printed += PRINT_PERIOD;
        TickCounts counts = getCounts();
        Serial.print(counts.tickA);
        Serial.print(" ");
        Serial.println(counts.tickB);
    }
}

And here is the output:

54053 54053
108107 108107
162161 162161
216215 216215
270269 270269
324324 324324
378377 378377
432431 432431
486485 486485
540539 540539
...


16 X 2 LCD display blank with Arduino Uno

It is most likely that I wasn't providing enough power to the arduino, and or had the potentiometer set to the wrong point. according to this post, you shouldn't run the arduino and display off of USB, because it may not actually be providing 5 volts. So I plugged it into the wall using a DC adapter. It now works.


Is EEPROM's location relocated on sketch compile?

The EEPROM is a completely separate part of the silicon inside the chip. It has no address of its own.

You are making a fundamental error in what you are doing, though - you cannot directly store the contents of strings by looking at the addresses of those strings. The data in them is dynamically allocated in RAM and is completely separate from the object. You will have to come up with a different way to store your data.


How to store incoming serial string in arduino?

Actually I can see what I think may be an issue with your code.

 while(Serial.available() || !begin)

This isn't right.  If there is no data available in the serial buffer but the first { hasn't been seen then go and read the non-existent data anyway?

Rather than try and explain what I mean in multiple comments I have put it all together and this is what I think your loop should be this:

/// This is un-compiled code, so you might have to fix some little issues.
/// bool begin = false;         // True when the initial { has been seen

void loop()
{
  while (finished == false)
  {
    if (Serial.available())
    {
      const char in = Serial.read();
      if (in == '{')
      {
        response = "";  // Blank the string
        begin = true;
      }
      if (begin)
      {
        response += (in); // Only write if within the {}
      }
      if (in == '}')
      {
        begin = false;   // Prevent any chars between } and { leaking through.
        lcd.setCursor(0, 0);
        lcd.print(response);
      }
    }
    delay(1);
  }

  delay(500); // Not sure what will happen if you send multiple {} to the LCD too fast.
}


How to make BLE data accessible to a particular app?

In general terms, you could simply require a client to authenticate first. This would require a bit of a deviation from the example you linked to (which actually only handles reading of the characteristic) to handle multiple connections and their state, but it should be pretty straightforward.

The Arduino BLE library seems to lack sending quite a bit of information via the callbacks, so you just know there's a connect or disconnect or a write to a characteristic, and not which devices did. This means you won't be able to handle multiple connections at the same time, but making sure you reset your authentication state whenever you receive a connect or disconnect should be enough to prevent anyone but your own client from "talking" to your device.


One problem in your original code is that you are only storing the current state of the buttons if they are pressed.  The next problem is that you are looping through all your brightness values when a button is pressed giving you your "fades all the way up in one go" problem.

This would be my replacement for your loop() code:

loop()
{
    int currentButtonStateA = digitalRead(buttonApin);
    if (currentButtonStateA != lastButtonStateA && currentButtonStateA == LOW)
    {
        currentBrightness += BRIGHTNESS_INCREMENT;  // BRIGHTNESS_INCREMENT is defined at the top of the file with #define BRIGHTNESS_INCREMENT 25
        if (currentBrightness > MAX_BRIGHTNESS)     // MAX_BRIGHTNESS is defined at the top of the file with #define MAX_BRIGHTNESS 255
        {
            currentBrightness = MAX_BRIGHTNESS;
        }
    }
    lastButtonStateA = currentButtonStateA;

    int currentButtonStateB = digitalRead(buttonBpin);
    if (currentButtonStateB != lastButtonStateB && currentButtonStateB == LOW)
    {
        currentBrightness -= BRIGHTNESS_INCREMENT;
        if (currentBrightness < MIN_BRIGHTNESS)     // MIN_BRIGHTNESS is defined at the top of the file with #define MAX_BRIGHTNESS 0
        {
            currentBrightness = MIN_BRIGHTNESS;
        }
    }
    lastButtonStateB = currentButtonStateB;

    analogWrite(ledPin, currentBrightness);
}

Hopefully this is pretty self explanatory.  The current button A state is read and stored in a local variable.  If it is different to the previous state and it is low, the current brightness is incremented and capped at a maximum value.  Next the current button state is stored as the previous state ready for the next run through the loop.

Similar actions are performed for the B button, but with a decrement rather than an increment.  Finally the LED brightness is set regardless of whether any buttons have been pressed.

You do not need to store your current button states (buttonStateA) or your counts for the number of button presses (buttonPushCounterA - which you never referenced anyway) or your ms value so could get rid of those global variables.  You need a new global variable at the top of your file for currentBrightness (int currentBrightness = 0;).

You have used variables to store various non-changing numeric values, such as "maxBright = 255;" which is good practise, but is better (particularly with Arduino development) to use #define macros instead, such as "#define MAX_BRIGHTNESS 255".

The reason for this is that variables take up memory when the code is running - something that an Arduino Uno doesn't have a lot of, whereas a #define takes up no memory - the compiler uses it as a "search and replace" before compiling your code.


Ok, this is the solution for me:

remove all old drivers:

sudo rm -rf /Library/Extensions/usbserial.kext
sudo rm -rf /System/Library/Extensions/usb.kext

Now reboot the computer.

And then (very important, because it took me 10 cables to find the right one) use a fully connected cable ;-)

Now I have these ports:

/dev/cu.wchusbserial1410
/dev/cu.usbserial-1410


You can use tft.rect(x,y,width,height) to clear only a portion of the screen. Make sure to set tft.fill before calling it.


Arduino Zero to Arduino Zero SPI configuration

A zero has the same number of IO pins then a UNO, they use the same header layout. So I believe you want to use the chips on a self made PCB. (?)

Based on this, I think a second SAMD21 is not the best solution.

They are easily connectable as they use the same Voltage. I used the SPI lib on a zero, so yes, I think its programmable with Arduino techniques. And you can use a CS pin of your choice. The SPI lib uses Arduino header files for the selected platform. So the MCU clock speed shouldn't be a problem.

But you have to program the master and the slave and maintain this firmware. An MCP23(s/0)17 is ready to use.

Two MCP23S17 (QFN packages) don't take that much space.

SAMD21 is capable of driving max. 3.6 V; MCP can handle 5.5 V. (But if you want to use 5V you have to level shift the connection between your Arduino zero and the MCP.

And adding two more MCP23S17 is way easier that adding a third SAMD21, when even the old firmware must be reprogrammed.

A MCP23S17 can drive and sink 25 mA on each pin.

A SAMD21 can handle 14 mA source current and 19.5 mA sink current per IO cluster (there are 6 clusters each of them has between 2 and 16 pins).

On the other hand, if you are sure, you don't need more than 3.6 volts and ~1 mA per pin and the number of the additional IO pins is enough, there is no reason not to use a second SAMD21.

If you need capacitive  touch pins, or more I2S ports or other capabilities of the SAMD21, then the second SAMD21 is even the better choice.

Have you seen the Arduino DUE? It has all the features of a zero and way more IO pins (54) and 12 analog inputs and 2 real analog outputs.


How to use and retrieve data file from AT command in Arduino D1 Mini Wemos (With esp8266)

The command is documented in the ESP8266 AT Command Reference, with a non-PDF option at https://room-15.github.io/blog/2015/03/26/esp8266-at-command-reference/#AT+CWLAP

The response from the AT+CWLAP is a series of lines listing available access points, and for each, you are given their encryption method, SSID, RSSI, MAC, and the channel (or frequency offset and a calibration value).

It would be up to the you to parse the resulting strings to obtain the APs, sort by signal strength, and decide what to do with that information.

EDIT:

Because you are using the Arduino environment/core to write code for the ESP8266, you won't be able to use the AT command set. The AT Commands are available when the ESP8266 has the EspressIF firmware loaded to it, and thus the ESP8266 module is intended to be a peripheral device to some other controller; contrast with your use, where the ESP8266 is the only controller, with the WiFi ability baked in.

In this case, you will need to examine the features of the Arduino ESP8266 core, especially the ESP8266WiFi library, which gives an example sketch for scanning the available WiFi networks.


Guide to code for multitasking and non blocking timers

It is not really clear what you want here...

If you want to execute things in a certain time, then take a look at http://playground.arduino.cc/Code/Scheduler

Or, if you want more than just that (multiple tasks, preemptive multitasking) https://launchpad.net/arduos (arduOS can also just serve to run things in a certain time, but without having to use a function all the time)

While OOP MIGHT take more program memory, an object without virtual functions only takes the RAM the variables in it take (if you have a byte (1 byte) and an int (2 bytes) in an object it would take 3 bytes)

On the AVR-architecture (the one most Arduinos use) the program is directly executed from a flash-memory and only the variables are in the RAM

The if-state-handling you are doing there can be done easier using arrays like:

typedef void(*handler)(void)
handler stateHandlers[STATES] = {&handle1, &handle2, &handle3 ...
// handle? are functions without the () !
void handleState(int state)
{
    if(state >= STATES)
        return;
    stateHandlers[state]();
}

Obviously, you can also use arrays to store the states of the LEDs.

Also note that HIGH is just 1 and LOW is 0, so technically a bit would be enough to store the states.


int led = 1;

You do know that pins 0 and 1 are the serial port don't you?

Take your pick.... Either use pin 1 for the LED OR use pin 1 for the serial connection.  You can't do both!

As it says in the manual:

  In addition, some pins have specialized functions:

  Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data. These pins are connected to the corresponding pins of the ATmega8U2 USB-to-TTL Serial chip.


NEMA17 and DRV8825 200 steps give only half revolution

See page 33 of the DRV8825 datasheet https://www.ti.com/lit/ds/symlink/drv8825.pdf.

DRV8255 moves the stepper on a rising edge in the signal.

That requires the signal to go low, then high.

That is two cycles of your program.

Add two lines to your code so that it is output low, delay 10, output high, delay 10