Why is the atmega chip reset three times during programming?

It does it to "force" a reset.

Historically, when you open the serial port on an FTDI interface, the DTR will automatically go LOW.  However, recently FTDI decided it'd be a good idea to change their driver so that when you open the port the DTR line doesn't go low - you have to manually tell it to go low.  But this is only on the FTDI official drivers.

If you have a driver that is newer than a certain date (no idea what date) then just running avrdude by itself on an FTDI interface may not work properly since DTR isn't being lowered.

To get around that Arduino have included a forced toggling of the DTR line as part of the programming sequence to make the target board reset.

But of course, if the driver is old enough, or not the "official" FTDI driver (i.e., you're in Linux for instance) then the lowering of the DTR by avrdude works fine.

So what you are seeing there is first a brief toggle of DTR by the IDE to force a reset, then avrdude opening the port and DTR going low, then finally the IDE toggling DTR again one last time to force a final reset.

And to me that says you're either not in Windows, or you have an FTDI driver while does toggle the DTR line automatically.

I also have a feeling that avrdude may also have started including manual control of the DTR line within it - so if avrdude is new enough, even with a new FTDI driver that doesn't automatically, you will still see the repeated action of DTR.

It's what we call belt and braces.  Use every method possible to get the board to reset, so no matter what you hardware and software arrangement the board has a very good chance of being reset into the bootloader.


is it possible to convert a 328 design to use a 32U4?

Just had a quick look at the datasheets, and the main difference I see physically is the 32u4 is 44 pin package and the 328 is either 32 or 28 pin.
Also the 32U4 seems to have a lot more peripherals.

So based on that yes you will have to modify your circuit. Atmel are fairly consistant with ports and what their alternate functions are though.

eg SPI on portB, uart on portD

But you are just going to have to compare the pinouts on the datasheets see how they differ. And adjust pin connections accordingly.

Datasheets are easy to find. Good Luck!


How to write code to make the LED’s ﬂash in the following sequence?

int led_Pin_1 = 11;
int led_Pin_2 = 10;
int led_Pin_3 = 9;
int led_Pin_4 = 8;

int led_on = 0; // Start with first (led_Pin_1)

void setup() {
  pinMode(led_Pin_1, OUTPUT);
  pinMode(led_Pin_2, OUTPUT);
  pinMode(led_Pin_3, OUTPUT);
  pinMode(led_Pin_4, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(led_Pin_1, (led_on == 0) ? HIGH : LOW);
  digitalWrite(led_Pin_2, (led_on == 1) ? HIGH : LOW);
  digitalWrite(led_Pin_3, (led_on == 2) ? HIGH : LOW);
  digitalWrite(led_Pin_4, (led_on == 3) ? HIGH : LOW);
  delay(250);

  led_on = (led_on + 1) % 4;
}

led_on will start with 0 (pin 1), switching only that pin on. Some explanation:

(led_on == 0) ? HIGH : LOW

This means: if (led_on == 0), than the value will be HIGH, otherwise LOW. Resulting in only pin 1 going on, if led_on is 0, and in the next loop, only pin 2 oing on, because led_on is 1 etc.

led_on = (led_on + 1) % 4;

This increases the value of led_on, but when it reaches 4, it reverts back to 0.

I don't know about the delay times you need. I guess you want to change all LEDs at once, than wait.

You can make the 4 almost identical digitalWrite lines into a function as small improvement.

If you want to do more with the LEDs, than consider storing the leds into an array and use a for loop to iterate through them.


'Serial1' was not declared in this scope

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


read state from button to check if clicked

As you are a beginner, you seem to have some misconceptions:

Reading button state with digitalRead(): You thought something is wrong, because you thought that digitalRead() returns, if the button was pressed (thus 1 would mean pressed). But that is not directly the case. digitalRead() returns the electrical state of the corresponding pin (if the pin voltage is at ground level (0) or Vcc (supply voltage) level) (1)). This corresponds with the button depending on your wiring. I guess you copied the wiring somewhere in the internet. It shows the most common way of connecting a button. The button consists only of two contacts, which get pressed together, when you press the button. So the button can connect the pin to either ground or Vcc, but not to both. When the button is not pressed, the pin is connected to nothing, thus it is floating and the value changes erratically. This is solved with a pullup or pulldown resistor (a rather big resistor from the pin to either Vcc or ground), which sets the value of the pin, when the button is not pressed. That means, that you need 1 resistor for each button, that you want to use. The good news is: The Arduino already has internal pullup resistors, that you can activate via pinMode(pin, INPUT_PULLUP). That way you can save 1 extra component. Since it is a pullup resistor, which connects the pin with Vcc, you need to connect the button with ground.

That also gives you the inverted logic. In the end it is determined by you, what the digitalRead() value means. Think electrically about it.
Events: In Arduino programming there are not events. You are programming very much directly the hardware. There is no OS or GUI system, that would handle events for you. The program, that you write, runs command after command with a specific speed (determined by the Arduinos clock frequency; 16MHz for the Uno), pretty much linearly. Though there is one exception for that: interrupts. Microcontrollers have some peripherals build into them (ADC, communication interfaces, Timers, ...) and many of them work parallel to the main program (since their function does not need code, but is implemented in hardware). These peripherals can generate interrupts (for example to service the peripheral), which pauses the normal run of the program, runs an ISR (Interrupt Service Routine) and then returns to the main program. That is somewhat like an event, but very hardware specific and not nearly as generically usable as events on a PC.
Reading a button click: In your code you don't read the "button click", but only the state of the button. Thus you get multiple times 0 for one long enough button press. For the real click action you need to look for the transition from 1 to 0, which ideally only happens one time per button press. I write "ideally", because real life buttons bounce. In the moment of contact the value changes rapidly multiple times, until the button contacts have settled. So you need to debounce the button. You have already done basic debouncing by using delay(20) (because the button may need about that time to stabilize). You can see more sophisticated debouncing in the Bounce2 library, which is also easy to use for reading button clicks and presses.


WebSocket message with Arduino MKR 1010 using WiFiNINA and ArduinoHttpClient libraries

I needed to use port 80.

I got a hint from wikipedia:

  The communications are done over TCP port number 80 (or 443 in the case of TLS-encrypted connections), which is of benefit for those environments which block non-web Internet connections using a firewall.

https://en.wikipedia.org/wiki/WebSocket

Switched to port 80 and it works!


Simplest/best way to control a set of 8-10 PWM signals from a smartphone

HC-05 is rated to about 9m so it wouldn't necessarily meet your requirement. The ESP8266 (example of one implementation called the Node MCU) can output PWM on any of the 0-16 pins. It can easily implement a web server which would let you control your outputs via 8026.11 (wifi). It also means you don't need to build anything for the phone/ tablet/ PC just use a web browser. The duty cycle could be set through the web server on the ESP. The ESPs are around the same price as an Arduino.

I've used the HC-05 with an arduino. It works very well, though not very far. For the Android side I used app inventor which is extremely easily to use for bluetooth.


int m = 0;
...
    drawNo[m] = (char)keys;
...
    ++m;

No other references to m in your code. Therefore m keeps increasing and you are writing outside the bounds of the array drawNo, corrupting memory.


Nick O'leary published an MQTT client for Arduino.
I use it extensively.  You can find it here: http://knolleary.net/arduino-client-for-mqtt/.
Once you have established a tcpip connection you can use this library to send/receive via the MQTT protocol across a GPRS/GSM modem.  I have used it successfully on:

the Arduino GSM shield
the Seeeduino GPRS IoT panel
a Freetronics Arduino Mega connecting via ethernet to a TPLink MR3020 router


How long does my digital pulse need to be for it to be read?

As explained by Majenko's answer, you should detect the pulses from an
interrupt and print the result from the regular code. However, instead
of just setting a flag in the interrupt handler, I suggest you instead
count the pulses within the handler. This will make the handler a tiny
bit slower, which is often something you want to avoid. However, the
extra overhead is really tiny, and you gain the ability to count
not only pulses that are short but also pulses that are closely spaced.

There is, however, something to be aware of when sharing a variable
between interrupt code and regular code. If the variable cannot be read
in a single CPU instruction (which is the case of an int on an
AVR-based board), there is some risk that the value gets changed in the
middle of you reading it. To void this problem, you have to disable
interrupts when reading the variable from regular code.

Here is an implementation of this strategy highlighting this point:

const uint8_t intPin1 = 2;
const uint8_t intPin2 = 3;

// This is volatile because it is shared between interrupt context
// and regular code.
volatile unsigned int sharedCount = 0;

// Interrupt handler.
void countPulse() { sharedCount++; }

// A variable shared with interrupt context should be accessed from
// regular code with interrupts disabled, in order to avoid race
// conditions.
unsigned int getCount() {
    noInterrupts();
    unsigned int countCopy = sharedCount;
    interrupts();
    return countCopy;
}

void setup() {
    pinMode(intPin1, INPUT);
    pinMode(intPin2, INPUT);
    attachInterrupt(digitalPinToInterrupt(intPin1), countPulse, RISING);
    attachInterrupt(digitalPinToInterrupt(intPin2), countPulse, RISING);
    Serial.begin(9600);
}

void loop() {
    static unsigned int previousCount = 0;
    unsigned int count = getCount();
    if (count != previousCount) {
        Serial.println(count);
        previousCount = count;
    }
}

Note that if the pulses come very fast, you may miss printing the
value, but you will not miss counting it (up to some limit, of
course). Thus you may see non-consecutive numbers being printed.


Would this substitute for an Interrupt timer?

The whole idea is sound, but I would make a few changes:

as explained by Jot in a comment, you have to update previousMillis
inside the if statement. You have two choices:

set it to currentMillis, then OffTime will be the minimum time
between the pseudo-interrupts
increment it by a constant amount, which I would call period, then
this will be the average time between pseudo-interrupts; this is
more similar to how real timer interrupts work

add a constructor for:

making the period user-selectable
making the action of the timer user-selectable via a callback
initializing previousMillis

With those changes, the class will look like:

class Pseudo_Interrupt {
    unsigned long period;
    unsigned long previousMillis;
    void (*callback)();

public:
    Pseudo_Interrupt(void (*callback)(), unsigned long period)
        : period(period), previousMillis(millis()), callback(callback)
    { }

    void update()
    {
        if (millis() - previousMillis >= period)
        {
            callback();
            previousMillis += period;
        }
    }
};


Does flashing ESP8266/ESP-01 firmware mean uploading a new 'sketch' and why different firmware?

When using ESP as standalone microcontroller, and if I uploaded a sketch written on the Arduino IDE, does that count as 'Arduino firmware' other people are referring to?

Yes. "Firmware" is application code running on the microcontroller.

  On the Arduino IDE, uploading sketches onto the ESP8266 seems easy by just installing extra libraries from Board Manager and selecting the right board. Is this step equivalent of doing this but for different firmwares such as AT, NodeMCU and Micropython?

Yes. "Firmware" is application code running on the microcontroller.

  For the NodeMCU dev boards, is the default firmware on the module NodeMCU firmware? If I were to use the Arduino IDE to upload a sketch, does that mean I have overwritten the NodeMCU firmware with my custom 'Arduino firmware' sketch?

Yes. "Firmware" is application code running on the microcontroller.

  To the extent of my knowledge, when using NodeMCU firmware, I would need to code in LUA language using some sort of LUA IDE and if I flashed/uploaded micropython I would need to code in micropython using exclusively the Thonny IDE. And there is no way to code in micropy or LUA from the Arduino IDE.

No. The Arduino IDE is for coding in C++ with the Arduino API extensions.

  Is the reason for using other firmware is because of how the code is compiled and the language used?

The firmware is just what runs on the chip. If that firmware provides its own programming language then you can use that to execute that programming language.

If you write your own firmware in the Arduino IDE then the chip runs that firmware. If you upload the AT firmware then the chip runs the AT firmware and you can control it with AT commands. If you upload the NodeMCU Lua firmware then the chip runs the NodeMCU Lua firmware and you control it using Lua commands and scripts.


Bluetooth module(HC05) works with Arduino Uno but not with breadboard (ATmega328)

If the LED is blinking, the device is waiting to pair with another Bluetooth transceiver (your phone). Once paired, the LED will stay lit. The factory-set pairing code is usually 1234. I can't tell from the photograph how the HC-05 Rx & Tx are wired to your ATmega328, but note that it must be cross-connected; that is Rx -> Tx and Tx -> Rx.


The SD card library works by filling up a 512 byte buffer. Once full, the data is written to disk.

The flush command updates the directory listing with the correct size for the file and also updates the file allocation table. It only needs to be done once, just before you pull the card out.

While flush is doing its thing, the internal serial buffer of the Arduino is filling up with new bytes. The internal buffer is 64 bytes long so if flush takes too long, the internal buffer fills up and you lose characters. You could edit HardwareSerial.cpp in the Arduino program directory to make it say 256 bytes.

Because of this softBuffer is not needed. Simply write straight to the card and let the internal buffer handle the buffering. See https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.cpp for the Serial code.

unsigned long bytesWritten = 0;
void loop(void)
{
  while (Serial1.available())
  {
    logfile.write(Serial1.read());
    bytesWritten++;
    if(bytesWritten > BYTES_PER_FLUSH) logfile.flush();
  }
}


Because your code is all running in a while inside your loop (which is redundant - loop() loops, hence its name), and you have no delays or yield() calls, you are not giving the watchdog the required kick that it needs to stay alive.

Either remove your whiles and turn them into ifs instead, or add yeild() calls inside your while loops.


Using

byte server[] = {XX, XX, XX, XX}; //IP
if (client.connect(server,80)) {

instead of

if (client.connect("mysite.com.br",80)) {

worked


ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\test\",3000");

That line is going to fail miserably for a number of reasons:

You need to provide an IP address or domain name - NOT a URL
Even if you could provide a URL this bit 192.168.1.13\test would end up, after C escaping, as 92.168.1.13        est since \t is a TAB character.

And then on top of all that I assume you are connecting to a HTTP server, yet you aren't sending a HTTP request, you are just sending the word "test", which the HTTP server has no hope of ever understanding.

You need to formulate and send a proper HTTP request and send it to the server. I suggest you go and look at a few tutorials and maybe look up how HTTP Servers actually operate and what the protocol looks like.


Uno Wifi Rev2 Programming via Uno R3 ArduinoISP

The new generation of AVR chips created by Microchip no longer use the same ICSP protocol as the old ones. Instead they use a new protocol called updi.
You need to use a different sketch and wiring to turn your Arduino into a suitable programmer.  More information can be found here about how to do that.


See §28.2 in Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf, which explains usage of various fuse bits.

Also see engbedded.com/fusecalc, which lets you easily figure out fuse settings.  Fusecalc also tells you the strings to use as part of avrdude command strings.

Once you know the fuse settings, send them to your device via a command like

avrdude -p m32u4 -c usbasp -u -U lfuse:w:0xEF:m -U hfuse:w:0xD5:m -U efuse:w:0x07:m

or like

avrdude -p m32u4 -P $port -c arduino -u -U lfuse:w:0xEF:m -U hfuse:w:0xD5:m -U efuse:w:0x07:m

where $port represents a port name like /dev/ttyUSB0.

Note, it makes sense to read the fuses first, and put the readings into Fusecalc to see what they correspond to.  You can read the fuses via a command like

avrdude -p m32u4 -P $port -c arduino -U hfuse:r:-:i


Using Arduino Mega with multiple HC05 Modules as masters, communicating to multiple HC05 Modules as slaves, each connected to separate Arduino

Yes, this is possible. According to arduino.cc, the Arduino Mega has 4 hardware serial ports, so you can connect 3 HC-05 modules and still have 1 serial interface left. The Mega is a good choice, when you need this many serial interfaces, so at this point you don't even need SoftwareSerial. You will have to configure the HC-05 modules correctly from the master and command them to connect to the correct slave modules.

About SoftwareSerial: The serial interfaces mentioned above are "hardware" interfaces, meaning, that the itself microcontroller contains hardware, that does the main part of the receiving/transmitting by itself, without any need for code. The Serial library then only adds a bigger buffer for the data, wrapper functions to write to it and reacts to the interrupts, that come from the hardware interface. But since most microcontrollers only have a very limited number of hardware serial interfaces (often only 1 or even none), the SoftwareSerial library comes in handy. It emulates the UART protocol (which is a more professional term for the Serial interface from the Arduino world) with software (and some help from interrupts). This means, that you can use it with any pair of pins and you can even define multiple interfaces with it. But it also has drawbacks. For example: Only 1 SoftwareSerial interface can listen at once, you cannot use high baudrates, it uses interrupts, that you might need for an application.

That said, I don't think, that Bluetooth is the best way to go, if you only want to test a small number of buttons per slave. It is simply too much hassle to configure the modules and establish the connections correctly. Instead you can use 433MHz radio modules. They don't involve such a complex protocol like Bluetooth does, so it's a very simple solution. In the simplest case, you only need transmitters for the slaves and a receiver for the master. Every slave can send a short identifier, if the button was pressed. The master can then receive this data. Of course, if more than one slave sends simultaneously, the data will be garbage. But as long, as this is not a problem, you can keep it that simple.

There are many tutorials on the web, that explain how to use these modules. You can even find libraries, that are ready to use.


ADXL345 becomes 0g when plugin MicroSD Adapter using SPI

You may have the same problem as my answer in Multiple SPI device answer ... not all devices supports another SPI device on the same port

That is (one of the) reasons I use STM32 instead of Arduino, since the Arduinos have 'only' one SPI port.


Why I can't exit this while loop by reading from the Serial?

The problem is that you check inside the two functions Sparkle and GreenYellow for another serial byte. Then when it's unequal, you move back to the while loop where you wait for the next serial byte, but I think you need to use the same one to decide to go to the correct function instead of waiting for a next serial byte.
Probably the easiest is to not read serial in the while loop but check the incomingByte global variable  (containing the last read byte, and e.g. 1 initially), and ONLY in the two functions set that global variable. Then, when returning to the while loop, you check that global variable to jump to the correct function.
So you make a setup function that sets the global variable to 1 (or you do it in the initialization itself):
int incomingByte = 1; // Start with GreenYellow

Then, in the loop function, you use:
void loop()
{
       switch (incomingByte)
        {
          case '1':
            GreenYellow();
            break;

          case '2':
            Sparkle();
            break;
        }
}

If you don't want to start in either one, then use 3 values (0, 1, 2), and ONLY in the loop function read the Serial byte, but don't read it in the functions.
This way it's a bit more cleaner as it separates the LED functionality with the Serial functionality.
The result (using the last method), results in the following code (compiles, not checked).
Comments:

Used an enumeration for the mode

Split functionality of serial data, processing the mode and RGB routines

I added some initialization lines (i.e. constants) to make it compile.
#include <FastLED.h>

#define NUM_LEDS 60 // number of led present in your strip
#define LED_PIN 6
#define BRIGHTNESS 100

enum EMode
{
  ModeNone,
  ModeSparkle,
  ModeGreenYellow
};

CRGB leds[NUM_LEDS];
EMode mode;

void ParseSerialData();
void ProcessMode();
void GreenYellow();
void Sparkle();
void setPixel(int Pixel, byte red, byte green, byte blue);

void setup()
{
    Serial.begin(115200);
    delay( 1000 );
    FastLED.addLeds<WS2811, LED_PIN, EOrder::RGB>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
    FastLED.setBrightness(  BRIGHTNESS );
    mode = EMode::ModeNone;
}

void loop()
{
  ParseSerialData();
  ProcessMode();
}

void ParseSerialData()
{
  while (Serial.available() > 0)
  {
    Serial.write("Serial.available");
    char incomingByte = Serial.read();

    switch (incomingByte)
    {
    case '1':
      mode = EMode::ModeGreenYellow;
      break;

    case '2':
      mode = EMode::ModeSparkle;
      break;

    default:
      // Ignore
      break;
    }
  }
}

void ProcessMode()
{
  switch (mode)
  {
  case EMode::ModeNone:
    // Do nothing
    break;

  case EMode::ModeGreenYellow:
    GreenYellow();
    break;

  case EMode::ModeSparkle:
    Sparkle();
    break;

  default:
    // Ignore
    break;
  }
}

void Sparkle()
{
    int Pixel = random(NUM_LEDS);
    setPixel(Pixel,random(255),random(255),random(255));
    FastLED.show();
    delay(50);
    setPixel(Pixel,0,0,0);
}

void GreenYellow()
{
  for(int x =0; x< NUM_LEDS/2; x++)
  {
    leds[x]= CRGB::Green;
  }

  for(int x =NUM_LEDS/2; x< NUM_LEDS; x++)
  {
    leds[x]= CRGB::Yellow;
  }
  FastLED.show();
}

void setPixel(int Pixel, byte red, byte green, byte blue)
{
   leds[Pixel].r = red;
   leds[Pixel].g = green;
   leds[Pixel].b = blue;
   FastLED.show();
}

void setAll(byte red, byte green, byte blue)
{
  for(int i = 0; i < NUM_LEDS; i++ ) {
    setPixel(i, red, green, blue);
  }
  FastLED.show();
}


Upload sketch remotely through a serial-IP-serial connection

I've been searching through the net for some days, in order to discover how I could easily upload a sketch to an Arduino that is not phisically connected to my PC, but instead that is connected to an another one, that belongs to the same LAN. I mean:

PC1-SERVER
Arduino Uno is connected to this PC with classic USB cable.
This PC is running Ubuntu linux, and sees Arduino as a serial port /dev/ttyACM0.

PC2-CLIENT
This is the PC where I create and compile the sketch.
I want to upload the sketch to the Arduino Uno described above (so, connected to SERVER, port /dev/ttyACM0)

SOLUTION:
server-side commands:

Code:

sudo apt-get install ssh-server ser2net

sudo passwd root    (to set the root password)

sudo reboot

client-side commands (assuming 192.168.0.7 as IP address of SERVER):

Code:

ssh -L 8086:localhost:8086 root@192.168.0.7 \
'/usr/sbin/ser2net -d -C "8086:raw:600:/dev/ttyACM0:115200 NONE 1STOPBIT \
8DATABITS -XONXOFF LOCAL -RTSCTS HANGUP_WHEN_DONE "'

you can then upload sketches to arduino doing this:

Code:

avrdude -C /path/to/avrdude.conf -p atmega328p -c arduino -P net:localhost:8086 -U flash:w:/path/to/file.hex:i

NOTE:
In Eclipse, if you are using the arduino plugin, just place "net:localhost:8086" in the configuration panel, where "port:" field is required.

This solution was also posted on arduino forum.


Piezo connection causing RTC to go haywire

Add

pinMode(TONE,OUTPUT);

to setup() to fix the problem.


Including Arduino library in a Makefile for Due

Adding a library isn't as simple as just adding an include path.

You also have to identify each and every source file (or use wildcards as are used for the various sections of the core) and compile them into object files. It is then quite convenient to archive those into a library (.a) file which you can then link your sketch against (if you don't archive you will have to link all the objects files with your sketch in the linking phase).


The start and stop bit are already included as part of the UART protocol. When you send a byte it first sends the start bit, then the byte, then the stop bit. You don't need to do anything to make those bits send.

20 is actually sent as 0001010001

So your code will just be a series of Serial.write() calls for each byte you want to send.

Serial.write(1);
Serial.write(20);
Serial.write(1);
Serial.write(1);
Serial.write(0);
Serial.write(0);

Or as an array:

uint8_t data[6] = {1, 20, 1, 1, 0, 0};
Serial.write(data, 6);


You shouldn't have any issues keeping it on all the time, however, some thing to consider is any counters you may have, like the use of millis().

From the Arduino docs on millis:

  This number will overflow (go back to zero), after approximately 50 days.

So for projects that are on for long periods of time, you may not see an issue immediately but something like this could pop up and cause errors down the road.


AC ceiling fan speed control using arduino Uno R3

Controlling the speed of an AC motor is not an easy undertaking, and messing around with mains voltages if you're not experienced and know what you're doing can be fatal.

Now that's the disclaimer out of the way, on to your question.

Unlike DC, you cannot use PWM to control the average power of AC.  That is, after all, what PWM does - the on-off ratio creates a percentage of the power - but it can only be done if the incoming power is of a steady state.

For AC there are two ways of reducing the output power - either reduce the voltage, which can be done with resistors (look inside a multi-speed fan and you'll see resistors to change the speed); or chop up the AC waveform, which is a little like PWM but more specialized.

If you only want specific speeds then you could pre-define them using resistors and switch different resistor combinations in and out using relays.  It's crude, but simple, and also probably the safest option for the beginner.

If you want proper variable speed, though, then you're going to have to chop up the waveform.  The theory is quite simple:  Start where the waveform crosses 0V in either direction, with the output on, and turn it off again at some percentage of the way through the cycle.

Like PWM it's the on-off percentage that defines the output power (and thus the speed), but timing is critical - you must start the PWM sequence at 0V and it must last exactly one cycle.

A number of simple circuits work in the opposite way - they remain off until the input waveform reaches a certain point, then switch on, until they reach the zero-crossing point.  While simple, these circuits aren't good.  The reason being that the sudden rise from 0V to the "trigger" voltage when the output becomes live can cause large spikes and noise in the circuit, which can cause lights to blow etc.  It's the same effect as why bulbs most often blow when you turn them on, not when they have been running for a while - it's that very rapid rise from 0V to a high voltage which causes them to be over-stressed and blow.

So any circuit you choose should really be a proper one which turns on at 0V and turns off after a period, not turn on at a voltage and turn off at 0V.


Example with dynamic array works with uint8_t, why not with uint16_t?

I suspect you changed everything to uint16_t but did not change the malloc call to account for the 2-byte size. Original:

_tester = (uint16_t *)malloc(len);

Try changing it to

_tester = (uint16_t *)malloc(len * sizeof(uint16_t));

This will multiply len by 2 to ensure it allocates enough space for all of the data.

(Beware that if you also changed len to be uint16_t then some of those random numbers from 1..1000 will be large enough to deplete all of the memory on an Uno. But at least it doesn't seem to crash.)


`servo.attach()` paralyzing (one) motor on L298N

The Servo library uses Timer 1 to create the servo control signal. That means it can run the servo on any pin or combination of pins, and at the 50Hz speed that a servo likes best.

However, pins 9 and 10 also use Timer 1 to create the PWM signal.

It can't do both.

As soon as you start using the Servo library you lose PWM on pins 9 and 10.

So what can you do about it? Simply move your pins around to different pins. You can't use 9 and 10 for PWM, but you can use them for the servo. So put your servo on pin 10 and your right motor speed control on pin 3 and all should be happy.


If you are using Serial then you can't use pins 0 and 1 for something else as those are the hardware serialpins. Pick different pins for the Bluetooth.


Does baud rate for HC-05 Bluetooth module need to match the Serial Monitor?

No, they do not need to match.

You are talking about two separate serial port connections.

The baud rate between the HC-05 and the Arduino (BTserial) has to match.

The baud rate between the Arduino and your PC (Serial) has to match.

BTserial and Serial can use different baud rates.

An overflow problem can arise if a lot of data arrives from the HC-05 and there is not enough memory to store it until it can be forwarded to Serial.

simulate this circuit – Schematic created using CircuitLab


Adafruit Metro Mini FTDI chip overheating

Is there a way to fix this?

Yes. Undo whatever short circuit you have created with your soldering.

  Have I nuked my board?

Possibly, possibly not. Most likely the short is making the regulator go into thermal shutdown and no lasting damage has been caused. But you can't be sure.


Arduino Pro Mini comes in 3.3v and 5v versions.


How to add Attiny13 to Attiny board profile in Arduino IDE 1.6?

You can easily add entries for the ATTiny13 to the IDE, but won't show in the same listing as damelis's ATTiny cores, as he hasn't added the ATTiny13 yet.

Here is what I have found for ATTiny13 Arduino core files, working with  boards.txt, loading them into the IDE, etc.  The boards.txt is all laid out, just drop it into your personal workspace per the directions provided.

https://github.com/MCUdude/MicroCore

How to install
Boards Manager Installation
This installation method requires Arduino IDE version 1.6.4 or greater.
Open the Arduino IDE.
Open the File > Preferences menu item.
Enter the following URL in Additional Boards Manager URLs: https://mcudude.github.io/MicroCore/package_MCUdude_MicroCore_index.json
Open the Tools > Board > Boards Manager... menu item.
Wait for the platform indexes to finish downloading.
Scroll down until you see the MicroCore entry and click on it.
Note: If you are using Arduino IDE 1.6.6 then you may need to close Boards Manager and then reopen it before the MicroCore entry will appear.
Click Install.
After installation is complete close the Boards Manager window.

This will get you quite a lot of functions, configurable clock speeds, etc. The readme for this project helped me quite a lot  in understanding what is going on inside the box and how I can enable only the Arduino core functions that I want, to save space.

Microcore is based upon :
sourceforge.net/projects/ard-core13/files/latest/

And both projects have code updates as of this summer.

For other ATTiny (I'm using an ATTiny85 sometimes since for some things I ran out of space on the ATTiny13)

github.com/damellis/attiny

This will get you:
ATtiny 25 (8 pin)

ATtiny 45 (8 pin)

ATtiny 85 (8 pin)

ATtiny 24 (14 pin)

ATtiny 44 (14 pin)

ATtiny 84 (14 pin)


Use the Timer library.

You can attach up to 10 events to each Timer object you declare. That will suit your use case.


How accurate the an attiny timer function

The on-chip systemclock is not very accurate. You can calibrate it to some degree but it also depends on the temperature and load of the MCU. You will need a high quality quartz oscillator as external clock source to reduce it. But it will still have a drift. Switching from 8-bit to 16-bit won't make a difference.

In your case an RTC sounds like the way to go.


I want to reset a variable after each 1 second on an Arduino

I would do it the following way:

Use a variable declared as: unsigned long time_passed;
In the setup() section I would add the line time_passed = millis();
In the loop() section I would add the if condition:

if(millis()-time_passed > 1000) {
   time_passed = millis();
   presss = 0;
   }

I think this is still not working properly with your example, I recommend to make two changes in your code:

you have a delay of 1000 implemented, which means the cycle time of your loop is minimum 1000ms,that means you are never able to count more than 1, since your counter is resetted every loop
I cannot understand how presss = count++; should work. For proper counting I would suggest to do it this way: presss = presss + 1;
Note: max. value of your counter would be 5, since the delay in the if Statement will enable maximum 5 detections of your button within 1000ms


How does one get the correct serial port?

I had the same problem and had even fewer options under my Tools > Port menu. Looked at the user forums but most answers did not work for me. After watching a YouTube video, I fixed the problem by following its suggestion of installing the CH34X driver. There are some other suggested drivers if you search for some other related StackOverflow and StackExchange posts, but I did not test them (once the Mac-Arduino communication worked, I did not want to spend more time on this) and nor can I explain why this solution works.

I wrote a short article on this for myself. If you are interested, please take a quick look.

Best luck! :)


If the timer 0 has overflowed (TIFR0 & _BV(TOV0)) and there is at least a count of 1 in the timer count register (t & 255) then increment the local copy of the overflow count.

That overflow count is used later on to add an upper 8 bits to what is basically an 8 bit counter to turn it into a 16 bit one ((m << 8) + t).


Anyone have example code for ESP32 as media controller for Android/iPhone Media Apps

Well after I posted this question, I kept googling. Literally hours of googling at this point. Then I stumbled across this example:
https://github.com/T-vK/ESP32-BLE-Keyboard
I wrote that sketch to my ESP32, paired my iPhone and it immediately starting controlling music playback on my phone. After looking at the code, it's so simple that I'm embarrassed I couldn't figure this out on my own. In case the link goes dead, I'll paste the code here:

#include

BleKeyboard bleKeyboard;

void setup() {
  Serial.begin(115200);
  Serial.println("Starting BLE work!");
  bleKeyboard.begin();
}

void loop() {
  if(bleKeyboard.isConnected()) {
    Serial.println("Sending 'Hello world'...");
    bleKeyboard.print("Hello world");

    delay(1000);

    Serial.println("Sending Enter key...");
    bleKeyboard.write(KEY_RETURN);

    delay(1000);

    Serial.println("Sending Play/Pause media key...");
    bleKeyboard.write(KEY_MEDIA_PLAY_PAUSE);

    delay(1000);

    Serial.println("Sending Ctrl+Alt+Delete...");
    bleKeyboard.press(KEY_LEFT_CTRL);
    bleKeyboard.press(KEY_LEFT_ALT);
    bleKeyboard.press(KEY_DELETE);
    delay(100);
    bleKeyboard.releaseAll();

  }
  Serial.println("Waiting 5 seconds...");
  delay(5000);
}


How many and fast interrupt pin can handle in Uno?

You can find the number of external interrupt and pcint pins from the data sheet.

If you use interrupts, the overhead is about 20 or so ticks, or just over 1us. That gives you the minimum.

If polling, and you are lucky, 1 tick is all it takes. 1 /16th of a us.


I found the solution in modrego's answer on Arduino Ethernet Shield 2 stuck on EthernetServer::begin(). I need the Ethernet2 library for the W5500 Ethernet controller. The Ethernet library is for W5100 only.

This library is not included with the arduino.cc library(as of IDE version 1.6.12 and older, this will likely change in future versions). I had to install it. You can do this by:

Sketch > Include Library > Manager Libraries...
Type "ethernet2" in the Filter your search... field
Click on the Ethernet2 entry.
Click the Install button.
Click the Close button.

You will need to change the line:

#include <Ethernet.h>

to:

#include <Ethernet2.h>

Other files included in example sketches for the Ethernet library will need similar modifications.


Serial available doesn't work right after upload

This fails due to the typical auto-reset-on-open serial port configuration interacting with a problematic assumption made by the PC code.

The first issue means that it will typically take a few seconds between when the port is opened (unless the port is configured not to manipulate modem control signals on open) and when the usual bootloader times out, yields to the custom sketch loaded in the Arduino, and the latter becomes able to accept input and potentially respond.

The second issue is with the PC side code:

for i in range(0,4):
    str = "test string\n"
    ser.write(str)
    print ser.readline()

Assuming that import serial refers to pySerial, then because you did not specify a timeout when opening the port, the ser.readline() is an eternally blocking read.  To quote the documentation:

  Be carefully when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received.

If we look at what happens with your python program and a typical serial port configuration where modem status lines change on open, then the first thing your program does is implicitly reset the Arduino.  Next, it writes "test string\n" - but because of the reset, it writes this at the bootloader, not the sketch which is not running yet.  Finally your program eternally waits for a newline terminated reply - which it will never receive, because your sketch will not send that until it receives something from the PC, which will not send anything else until it receives the newline terminated response to its first message.

Your programs are thus stuck in a "no, after you" deadlock.

There are many potential ways to work around this.  For example, you might open the port with a timeout, wait a few seconds, and conduct this test write and attempt to read a reasonable number of times, but declare an error to the user if success is not achieved in ten or so seconds of those attempts.

Note also that the sketch may start running midway through transmission of the test string, so you will have to handle the possibility of a message with the beginning missing, either by declaring an error or discarding it and waiting for a subsequent intact one.


Electronically, should single or several ground pins be used?

There are times when you want a single ground point (star grounding), separate grounds with filters (separate analog and digital grounds, for instance), or you just don't care (99% of the time).

Regardless, this is usually a concern when you are laying out a circuit on a PCB. When you already have a PCB the grounds become a moot point because the PCB dictates how they operate.

For a module like an Arduino, unless otherwise stated, all grounds are equal and can be used for whatever whenever.


What you can do is:

opening a file (to read)
opening a new file (to write)
since a line can be long (more than arduino's memory), it's best to read it character by character, thus:
use a boolean to denote when to start removing a line (set to e.g. Remove = TRUE)
For every character you read:

If Remove is TRUE, don't write to the output file, otherwise write it
If the character is \n or \r (check how line ends are), set the boolean to False (e.g. continue writing)

Remove file to read
Rename written file


Confirm with an oscilloscope

When I connect my function generator I usually always make sure that the output is in the range 0 to 5V, with my oscilloscope. The default is probably more like ±2.5V - but I don't have an Agilent so you would have to check. Press the Ampl button to check. (Mine reads 5VPP).

You can see from the above image that we indeed have (roughly) 5VPP - and that there is a -2.56V component, which will damage the Arduino, being negative.

Add an offset

So press the Offset button and add a 2.5V DC offset. Now the voltage jumps 2.5V and is between 0 and 5V:

The scope confirms that the minimum is 80mV and the maximum is 4.96V, which is in range for an Arduino pin (assuming you are running an Arduino at 5V, which is not always the case).

Now you should be safe to experiment with different frequencies and wave-forms. Just leave the Amplitude and Offset alone. :)

Extra precautions

You could feed the function generator through an input protection circuit, just in case you absent mindedly forget to carry out the appropriate steps.

The zener diode will conduct negative voltages to ground (dissipated through the 1k resistor) and will also limit positive voltages to around 5.1V.


How can BMP180 measure a temperature too?

If you read the data sheet (on the site you point to) you see plenty of references to temperature:

  The BMP180 is designed to be connected directly to a microcontroller of a mobile device via the I 2 C
  bus. The pressure and temperature data has to be compensated by the calibration data of the
  E 2 PROM of the BMP180.

and

  The BMP180 consists of a piezo-resistive sensor, an analog to digital converter and a control unit with EEPROM and a serial I2C interface. The BMP180 delivers the uncompensated value of pressure and temperature. The E 2 PROM has stored 176 bit of individual calibration data. This is used to
  compensate offset, temperature dependence and other parameters of the sensor.

And many many more.


My counting function is not working with the text on my lcd

Change the last line to:

lcd.print("Launch in " + (millis() / 1000));

The + concatenates the string Launch in with the number that results from millis() / 1000.


You need to use connectSSL() instead of connect(). And possibly add your certificate to mkr1000 as described on Hackster


Don't do return loop(); With that you enter into a never ending recursion. No system can resist that.

See: return loop(); means "evaluate loop() and return whatever it returns". Well, loop is void; it doesn't return anything.

Even worse is the recursion problem: you call loop(), which calls CHIAMATA, which calls loop ... never ending. You blow out the stack.

I don't look any further than that. Probably there are more errors.


If you're trying to use a method of a in the global scope, that's doomed to failure. You can only call methods within functions.

If all you want is a char array with "45317" in it then just use:

char *b = "45317";

If you want to convert a string that is built at runtime into a char array, then your current method is correct - you just have to do it in the right place.


does the built-in arduino LED light up?? If yes try connecting your arduino in another uno usb port or try pressing the reset button on your arduino uno.


>=500Mhz microcontroller that works with arduino sketches?

I would guess that the Teensy 3.6 is the beefiest Arduino available right now. It runs at 180 MHz. Now clock speed is not everything. This can be illustrated by Arduino-Scheduler and context switch time for the supported boards.

Cheers!


Define preset colors using FastLed library

Your colors array should be CRGB type, not char *.

CRGB colors[] = {0x000000,0xFFFFFF,0xFF0000,0x008000,0x0000FF}; // black, white,r,g,b

For your second problem - you are overflowing the bounds of your LEDs array:

for (int i = 0; i <= NUM_LEDS; i++) {
  leds[i] = 0xFF0000;//colors[col_indx];

You are going from 0 to 10 inclusive. That's 11 iterations. There is no such array slice as leds[10], so the value you write to it ends up overwriting the next two bytes in memory - and those happen to be occupied by the variable t.


I think I just bricked my Arduino. Any ideas how?

See my answer here. A 12V battery doesn't necessarily provide you with 12V any more than a 1.5V battery provides 1.5V.

See here for example. A 12V lead-acid battery may well provide 12.7V which is out of spec for the Uno.

See the page about the Uno.

You have too much voltage going into the voltage regulator, it tries to dissipate it, it gets hot and either shuts down or fails.

I suggested in the answer above to use a buck converter to down-convert the voltage, and my answer (which was accepted) said that "it is working like butter".


Undefined reference to Class::function()

The inline modifier doesn't make a sense for methods definitions in separate cpp file. And obviously it makes the code compilable but methods aren't recognized as methods definitions and also it's not recognized as error (that's kinda weird).

Anyway, if you wan't inline methods, do it directly inside of class definition.


The mention of unknown in the output line:

Firmware Version: 0x1C = (unknown)

isn't a good sign.

Run the firmware_check example to verify that first, before trying to run other code.

The unknown is output by line 1302 of MFRC522.cpp:

    default:   Serial.println(F(" = (unknown)"));

The firmware_check example states on line 49:

  Serial.println(F("Only known versions supported"));

So, your hardware (i.e. the reader) may not be supported.

The only thing I can suggest is try another reader. Also, read the README, there maybe some thing there, or contact the author and/or raise an issue to see if you can get support for your version of the firmware (0x1C) added.


First of all a reference is just a voltage, not a range.

If you use a reference of say 5V than your analogRead(...) calls will return a 10 bit number where 0 stands for 0V and 1023 stands for 5V.

Second, the AREF pin is there for that purpose: feed your 2.5V reference to that pin and use:

analogReference(EXTERNAL);
analogRead(...);

when you want to read using the 2.5V reference (0 stands for 0V and 1023 stands for 2.5V in this case), or

analogReference(DEFAULT);
analogRead(...);

when you want to read using the 5V reference (supposing your Arduino is powered by 5V).

UPDATE

Nothing can be done at the exact same time on an Arduino/ATmega328 because it has one single processing unit. In case of analog to digital conversion you can not even perform two conversions on two pins too fast because you have only one ADC which is multiplexed (shared) among all the analog pins.

You have no choice to perform one reading, wait, then perform the other reading. You can change the voltage reference between the two conversions though, but you need to ensure the internal ADC capacitor is properly discharged: if you read a 5V line and then read a 2.5V line without discharging the internal ADC you are more than probably going to always read the maximum value.

How long you will have to wait depends on the impedance of the line you are sampling: higher the impedance, longer the time you have to wait for the ADMUX capacitor to discharge/charge up (Arduino/ATmega328 ADC is a store and sample comparator).


With the given schematic both your logic for segments and digits should be active high, so it looks like you made a mistake. Especially because you say it doesn't work anymore when you connect ground. Check that you have the right transistor and that it's connected correctly: Emitter should go to ground, collector to the display's common cathode. (Check that your displays are common cathode!)

It's not a good idea to define some version of high as low, that's only confusing. Instead name the signals:

#define DISPLAY_SEGMENT_ON HIGH
#define DISPLAY_DIGIT_ON HIGH

The image can be found at several places on the Internet, so I guess you didn't draw it. This is a common cathode display, and the transistors are NPN types. If your displays are common anode then the whole thing flips upside-down: The Ground rail becomes Vcc, and the NPN transistors should be PNP types. Then you will indeed have inverted logic, and you should define:

#define DISPLAY_SEGMENT_ON LOW
#define DISPLAY_DIGIT_ON LOW


are 3 connections necessary for a push button?

You can use the internal pullup e.g.

pinMode(inPin, INPUT_PULLUP);

Then wire your switch between pin and Gnd.


Do I need to supply the 12V connection to an HDD

Judging by my old copy of "Upgrading and repairing PCs" - which I found a quote for on Google Books - the 12V supply is for the spindle motor, and it says:

  Spindle motors, particularly on the larger form-factor drivers, can consume a great deal of 12V power.


ESP8266 cannot create TCP connections to this particular server

Not a cookie cutter answer, I did a quick test and my ESP8266 does connect to you nginx. Of course you do not accept the params from my fridge, but this is what I see in the log.

7007 :
7010 :

For online documentation and support please refer to
7012 : nginx.org.

7015 : Commercial support is available at
7018 : nginx.com.

7020 :
7022 :

Thank you for using nginx.

7024 :
7026 :
7028 : HTTP : closing connection

You should be able to see that on your side as well.

I am using letscontrolit/ESPEASY  https://github.com/letscontrolit/ESPEasy

And their code to connect looks like

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  if (!ControllerSettings.connectToHost(client))
  {
    connectionFailures++;
    addLog(LOG_LEVEL_ERROR, F("HTTP : connection failed"));
    return false;
}

  boolean connectToHost(WiFiClient &client) {
    if (!checkHostReachable(true)) {
      return false; // Host not reachable
    }
    byte retry = 2;
    bool connected = false;
    while (retry > 0 && !connected) {
      --retry;
      connected = client.connect(getIP(), Port);
      if (connected) return true;
      if (!checkHostReachable(false))
        return false;
    }
    return false;
}

I am using generic HTTP for my controller which here: https://github.com/letscontrolit/ESPEasy/blob/503fd3555e010b08b48fb2dc18290ef120005308/src/_C008.ino

You could try the connect to function to see if that works for you.


Temperature Controlled fan using arduino project regarding - LCD not displaying anything

Your constructor doesn't match your wiring:

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

You have:

RS = 7
E = 6
D4 = 5
D5 = 4
D6 = 3
D7 = 2

Yet your wiring has:

RS = 2
E = 3
D4 = 4
D5 = 5
D6 = 6
D7 = 7

I.e., completely backwards.

The constructor prototype is:

LiquidCrystal(rs, enable, d4, d5, d6, d7)

Yet you seem to have chosen to ignore (or misunderstand) that.

Instead you need to specify your pins correctly:

LiquidCrystal(2, 3, 4, 5, 6, 7);

Also, as a side note, you don't have a ground connection to that little 9V circuit off to one side - so you will never be able to control it.  Read this.


Your code is flawed in that you are waiting a fixed time, and then hoping that the entire response will arrive quickly. Personally I would send the query, and then exit the function. Test for incoming data in your main loop, and process it when it is all received. Techniques described here: http://www.gammon.com.au/serial

The whole thing should be able to be written without delay().


Problem activating HC-05 AT command mode with Arduino Uno Bluetooth shield

After 3 hours I magically solved my pretty simple problem myself. If you wired the HC-05 and arduino correctly, the module should indicate that it's in AT Mode by blinking the LED in an interval of 2 seconds. You should get response in the Serial Monitor by typing the AT commands by switching from "No line ending" to "Both NL and CR". That's about it.


5V 10A 4 channel relay to 2 lights15W light in series in 220V AC supply

You need to connect Vin from NodeMCU (Raw 5V from USB) to Vcc on the relay board.

And as stated in the comments, the relay need 5V for operating reliable.

In has the same problem, two LEDs and a resistor. To enhance it would be to replace the indicator LED (DS1-4) with a wire.

2 x LEDS á ~1.8V and a resistor á ~1.4V = 5 Volt.

1 x LED á ~1.8V and a resistor á ~1.4V = 3.2 Volt.


Arduino with WS2812 using Adafruit NeoPixel library fade in/out different patterns

To make randomly-changing colours for the whole strip, change:

void loop() {
  rgbFadeInAndOut(0, 0, 255, ledFadeTime); // Blue
}

to:

void loop() {
  rgbFadeInAndOut(random (256),
                  random (256),
                  random (256), ledFadeTime); // random colour
}

If you want to make individual pixels different colours you could set up an array of colours, randomly initialize it, and use that. Like this:

#include <Adafruit_NeoPixel.h>

int PIN = 3;
int totalLEDs = 11;
int ledFadeTime = 5;

Adafruit_NeoPixel strip = Adafruit_NeoPixel(totalLEDs, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOut(ledFadeTime);
}

void rgbFadeInAndOut(uint8_t wait) {

  uint8_t red [totalLEDs];
  uint8_t green [totalLEDs];
  uint8_t blue [totalLEDs];

  // randomly set each colour
  for (int i = 0; i < totalLEDs; i++)
    {
    red [i] = random(256);
    green [i] = random(256);
    blue [i] = random(256);
    }

  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red [i] * b/255, green [i] * b/255, blue [i] * b/255);
     }

     strip.show();
     delay(wait);
  }

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red [i] * b/255, green [i] * b/255, blue [i] * b/255);
     }
     strip.show();
     delay(wait);
  }
}


Wiring Lilypad USB + ESP8266 Serial WiFi Module

First, upload the sketch below to your Arduino. Then, try to tie RX (pin 3) and TX (pin 2) of SoftwareSerial together. Open the Serial Monitor and send some text and see if you get it back as a response.

#include <SoftwareSerial.h>
SoftwareSerial Serial1(3, 2);

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

void loop()
  {
     if (Serial1.available())
         { char c = Serial1.read() ;
           Serial.print(c);
         }
     if (Serial.available())
         {  char c = Serial.read();
            Serial1.print(c);
         }
   }

Once you get a response, then your SoftwareSerial part is working and you can then try to connect to your ESP8266.


How to programme a button per colour for a neopixel strip?

You do not really have to use an array for this, though I do agree that it's the cleanest solution.

Here is a simplified version of your code, do mind you'll still have to do the button handling yourself (by setting buttonpressed to 'true' when the button is pressed.

Also, when adding more colors to the array, you'll have to manually adjust 'totalColors'.

void setup() {
  //Color/pixel declarations based on https://learn.adafruit.com/adafruit-neopixel-uberguide/arduino-library-use
  uint32_t magenta = strip.Color(255, 0, 255);
  uint32_t greenishwhite = strip.Color(0, 64, 0, 64);

  //https://www.arduino.cc/reference/en/language/variables/data-types/array/
  uint32_t colors[] = {magenta, greenishwhite};
  unsigned char totalColors = 2;
  unsigned char currentColor = 0;
}

void loop() {
  if (buttonpressed) {
    //Change the "currentColor" index every time the button is pressed, but make it start at 0 when it reached the end.
    currentColor++;
    if (currentColor >= totalColors) {
      currentColor = 0;
    }

    //From the array of colors, pick the one with the index "currentColor" and show it.
    ledstrip.fill( colors[currentColor] , 0, strip.numPixels() - 1);
    ledstrip.show();

    buttonpressed = false; //Reset flag, so this doesn't get executed until next time button is pressed.
  }
}

You should be able to replace the first 3 lines (setting up the array) with a single:

uint32_t colors[] = {strip.Color(255, 0, 255,  strip.Color(0, 64, 0, 64)};

But I had it split up to better show the idea of the array.

Alternatively you could do:

switch(currentColor){
  case 0:
    //Color RED
  break;
  case 1:
    //Color GREEN
  break;
  case 2:
    //Color BLAUW
  break;
}


Arduino Nano 3.0 dimensions without the pins

Mini-USB-B is around 4mm tall.

Most PCBs are around 1.6mm.

The FT232RL on the bottom is 2mm (max) according to the datasheet. (voltage regulator is 1.8mm). (I'm sure about this tantalum capacitors)

So that's something around 7.6mm total height


How to use a rotary encoder on NodeMCU with Arduino code?

Different RotaryEncoders work in different ways. Mine connects the two outputs sequentially to the Gnd or + inputs, depending on the rotation direction. The resultant phase changes need to be detected and decoded by the processor.
I took your code and ran it on a LoLin NodeMCU using my 5-pin RotaryEncoder.
I connected (NodeMCU to RotaryEncoder):

D0 to Clk;
D3 to DT;
GND to GND; and
3V to +.

I ran the code, and it worked: the printed value went up when I rotated it in one direction, and down when it rotated in the other. The "bounce" was terrible though - getting just a single increment or decrement for one "detent" was difficult; I typically got 2-4.
Because of my encoder, I was able to remove the two digitalWrite(..., HIGH); lines and it continued to work. Perhaps that's what your problem is? Did you connect the + input? You mention the two switch pins: perhaps there's only one switch pin, that connects to the Gnd pin?

EDIT: The code!
So I went away and wrote a RotaryEncoder polling library, rather than the interrupt code that the original question was based on. The idea is that you can poll a rotary encoder (relatively) infrequently, and stil "catch" the transitions as it rotates. Of course this won't work if you poll it too slowly - your mileage may vary!
But here are three files:

The header and library source for the RotaryEncoder module; and
An example usage of the module.

RotaryEncoder.h:
//
// RotaryEncoder.h
//
// This library manages a Keyes KY-040 Rotary Encoder by sampling the
// appropriate pins when requested. It is NOT interrupt driven, so you'll need
// to sample often.
//
// The encoder has five pins in a 0.1" row, so you can directly plug it into
// an Arduino's data-pin sockets. The sequence of pins matches the order of
// parameters in the constructor - use ascending (or descending) numbers for
// ease.
//
// If you pass in NoPin for gnd, vcc, or sw (the switch), then that parameter
// is ignored. You'll need to organise those pins yourself! Of course, NoPin is
// not valid for dt or clk.
//

#ifndef RotaryEncoder_h
#define RotaryEncoder_h

class RotaryEncoder {

public: // Typedefs and enums

   typedef byte Pin;

   typedef signed char OptPin;

   enum Pins : OptPin {
      NoPin = -1
   }; // Pins

public: // Methods

   // Define which pins to use for the various functions.
   // If Optional Pins are "NoPin", then they won't be initialised
   RotaryEncoder(OptPin gnd, OptPin vcc, OptPin sw, Pin dt, Pin clk);

   // Start RotaryEncoder with optional maxBias (call Rebias() periodically)
   void Begin(byte maxBias=1);

   // Returns true if switch is currently pressed
   bool Switch() const;

   // Returns 0 for no change, +ve for clockwise, -ve for counter-clockwise
   int Get();

   // Call this periodically to reduce the bias
   void Rebias(int delta=1);

private: // Variables

   const OptPin gndPin;

   const OptPin vccPin;

   const OptPin swPin;

   const Pin dtPin;

   const Pin clkPin;

   byte maxBias;

   byte bias;

   bool clk;

   bool dt;

}; // RotaryEncoder

#endif // RotaryEncoder_h

RotaryEncoder.cpp:
//
// RotaryEncoder.cpp
//

#include <Arduino.h>
#include "RotaryEncoder.h"

RotaryEncoder::RotaryEncoder(OptPin gnd, OptPin vcc, OptPin sw, Pin dt, Pin clk) :
               gndPin(gnd),
               vccPin(vcc),
               swPin(sw),
               dtPin(dt),
               clkPin(clk),
               maxBias(1),
               bias(1),
               clk(false),
               dt(false) {
} // RotaryEncoder::RotaryEncoder(gnd, vcc, sw, dt, clk)

void RotaryEncoder::Begin(byte maxBias) {
   this->maxBias = maxBias;
   if (gndPin!=NoPin) {
      pinMode(gndPin, OUTPUT); // Let's power the device,
      digitalWrite(gndPin, LOW);  // Power -ve with 0
   } // if
   if (vccPin!=NoPin) {
      pinMode(vccPin, OUTPUT); // ,with both - and +
      digitalWrite(vccPin, HIGH); // Power +ve with 1
   } // if
   if (swPin!=NoPin) {
      pinMode(swPin, INPUT_PULLUP); // They pushed it!
   } // if
   pinMode(dtPin,  INPUT); // One half
   pinMode(clkPin, INPUT); // The other half
} // RotaryEncoder::Begin(maxBias)

bool RotaryEncoder::Switch() const {
   return swPin!=NoPin ?
          digitalRead(swPin)==LOW :
          false;
} // RotaryEncoder::Switch()

int RotaryEncoder::Get() {
   bool clkNew = digitalRead(clkPin);
   if (clk!=clkNew) {
      clk = clkNew; // Clock's changed; sample data
      bool dtNew = digitalRead(dtPin);
      if (dt!=dtNew) {
         dt = dtNew; // Data's changed; remember it!
         if (clk) {  // Only pay attention to Clk Low-High
            int temp = bias;
            bias = maxBias;
            if (dt) {
               return -temp;
            } // if
            else {
               return +temp;
            } // else
         } // if
      } // if
   } // if
   return 0;
} // RotaryEncoder::Get()

void RotaryEncoder::Rebias(int delta) {
   if (bias<=1) {
       return;
   } // if
   bias -= bias>delta ? delta : bias-1;
} // RotaryEncoder::Rebias()

RotaryBlinker.ino:
//
// RotaryBlinker
//
// This example changes how fast the built-in LED blinks by using the
// RotaryEncoder library.
// It starts with an intermediate value (80h).
// * If you rotate it left, it slows down (then it jumps to the fastest).
// * If you rotate it right, it speeds up (then it jumps to the slowest).
// The jumps are because there is no logic to handle wrap-around - an exercise
// for the reader!
//
// Also note that a bias feature has been included. The faster you turn the knob, the
// exponentially quicker the rate changes. This is done by setting a fast rate on
// every detent, then when the millisecond has changed it re-biases the knob lower.
//
// To handle the knob correctly, it needs to INCREASE the time interval when
// dialling LOWER - hence you'll see a negative number in the code.
//
// It also checks for the switch. If it's pressed, it simply turns the LED full on.
//

#include <RotaryEncoder.h>

// Choose pins that are convenient for the RotaryEncoder's pins
#if defined(ESP8266)

const byte LED = D5;                   // No built-in LED! Choose... this one!
const unsigned baud = 115200;
const RotaryEncoder::OptPin GND = -1; // Use GND pin
const RotaryEncoder::OptPin VCC = -1; // Use V+ pin
const RotaryEncoder::OptPin SW  =  D4; // Switch
const RotaryEncoder::Pin    DT  =  D3; // Data
const RotaryEncoder::Pin    CLK =  D2; // Clock

#elif defined(ADifferentBoard) // Put the board's definition here

// And then change these assignments
const byte LED = LED_BUILTIN;
const unsigned baud = 57600;
const RotaryEncoder::OptPin GND =  8; // Need 0V
const RotaryEncoder::OptPin VCC =  9; // Need +V
const RotaryEncoder::OptPin SW  = 10; // Switch
const RotaryEncoder::Pin    DT  = 11; // Data
const RotaryEncoder::Pin    CLK = 12; // Clock

#else // Arduino Uno default

const byte LED = LED_BUILTIN;
const unsigned baud = 57600;
const RotaryEncoder::OptPin GND =  8; // Need 0V
const RotaryEncoder::OptPin VCC =  9; // Need +V
const RotaryEncoder::OptPin SW  = 10; // Switch
const RotaryEncoder::Pin    DT  = 11; // Data
const RotaryEncoder::Pin    CLK = 12; // Clock

#endif // Boards

// Tell library which pin does what. Note Optional Pins can be -1
RotaryEncoder encoder(GND, VCC, SW, DT, CLK);

// Setup the board for these definitions
void setup() {
    Serial.begin(baud);
    pinMode(LED, OUTPUT); // Want to see it working

    encoder.Begin(10); // Start, with a re-bias of 10
} // setup()

bool ledON = false;  // Current LED state
byte repeat = 0x80;  // How quickly to restart, in ms
byte count = repeat; // Count down 'til next time!

unsigned last = 0;   // Last time millis() was recorded

void loop() {
    // Have switch override pulsing - turn it hard ON
    if (encoder.Switch()) { // Hard override!
        ledON = false; // Pretend LED is now OFF
        digitalWrite(LED, HIGH);
    } // if
    else {
        int value = encoder.Get(); // Returns positive for clockwise turn
        repeat += -value;   // We want to INCREASE time to slow down blinking
        if (value!=0) {     // Did it change?
            Serial.print(value);    // Print latest value
            Serial.print('=');
            Serial.println(repeat); // Print new result
        } // if
    } // else

    // Is it time to blink the LED again?
    unsigned latest = millis();
    if (last!=latest) {
        last = latest;
        encoder.Rebias();    // Re-bias encoder, to decelerate rotation
        if (--count==0) {    // Reached zero yet?
            ledON = !ledON;  // Yes! Toggle LED
            digitalWrite(LED, ledON ? HIGH : LOW);
            count = repeat;  // Count for next time
       } // if
    } // if
} // loop()


Max double value or NAN as a sentinel value?

This is a matter of personal preference. I like NAN because it is almost
always obvious it cannot be a valid value.

You can test for the value being NAN with
isnan().


What I am assuming is that the reason there is jitter is that
  there are other interrupts going on in the background

This seems like a reasonable assumption. Since you are not doing serial
communication, the Timer 0 interrupt is likely the only one triggering
in the background. You can disable it with:

TIMSK0 = 0;

but then all the Arduino timing functions will stop working. You will
have to #include <util/delay.h> and replace delay() with
_delay_ms(). Note that this avr-libc function only works with
compile-time constant delays. On the other hand, it is cycle-accurate
and accepts floating point delays.

  is there a way to change this priority list?

There is not, and even if this was possible, it would not be that
useful. Interrupts in the Arduino are not interruptible: if a
low-priority interrupt is running when a high-priority one triggers, the
high-priority interrupt has to wait for the currently running one to
terminate. Priorities are only relevant when the processor is about to
serve an interrupt request but has to decide which one, among several
pending requests, it will serve first.

Now, a small remark about this:

void loop() {
  PULSE1.writeMicro(40);
  PULSE2.writeMicro(40);
  PULSE3.writeMicro(40);
  PULSE4.writeMicro(40);
  delay(2);
}

There is no point in rewriting those values over and over again. If you
plan to change the code in order to make those widths non-constant, then
you have to take care to:

make the pulseLength properties (or the whole Pulse objects)
volatile
within writeMicro(), disable interrupts while changing
pulseLength.


Accelerometer MPU-6050 marks timeout in Unity

Running MPU-6050 at 57600bps seemed to be the good rate for me:

  pinMode(5,INPUT);
  Serial.begin(57600);
}

It worked for me and I found these guys for whom it was the good rate :

From MPU-6050-simple-library, specifically MPU6050_test.ino:

void setup() {
  Serial.begin(57600);
  MPU6050mgr.begin(); // Initializes IMU module
}

From Another Arduino as external i2c device for MPU6050:

void setup() {
  Wire.begin(0x1E);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(57600);           // start serial for output
}

From Library for Arduino and MPU-6050 communication:

void setup() {
  Serial.begin(57600);
  MPU6050mgr.begin(); // Initializes IMU module
}

You may also find this link useful: MPU-6050 Redux: DMP Data Fusion vs. Complementary Filter.


Is it possible for Arduino as ISP board to flash an ISP master board?

Yes, you can flash an MCU using ISP even if the MCU acts as an SPI device (be it master or slave). The programmer puts the MCU into reset mode, so at the time the sketch is uploaded, SPI will be disabled anyway.
Another thing you need to think of are the other SPI devices (the sensors or what ever the MCU controls). They can pick up the SPI signals sent by the programmer and occasionally write on the bus themselves, therefore disturb communication on the MISO line, which would be critical. There are two options to handle this:

Simply disconnect any SPI slaves during code upload
Make sure there are pullups on the CS lines so they have a defined state (they might be floating while the MCU is in reset). Some slaves might require pulldowns to be deactivated, but that's uncommon.


Arduino HC05 - AT commands won't respond

Maybe you should try a couple of different baud rates for your script? Also check that your RX/TX wires are connected in the right order. I've had some HC-05 modules where RX/TX markings on the module were reversed.


Is Arduino Mega useing one buffer or multiple buffers?

Actually there are 2 buffers per Serial hardware interface: The hardware buffer, that is 1 byte (per direction of data transfer). The Serial library then transfers this byte in an extra buffer (64 bytes big) from an ISR. Every hardware Serial interface (Serial and Serial1 to 3 on the Mega) has it's own hardware buffer.

Then the Serial library is implemented as a class. Every hardware Serial interface get's it's own instance of this class, including the 64 byte buffer.

So the hardware and the memory is completely seperated. The only thing, what they share, is the CPU time for servicing the interrupts, which is no problem, until you are doing somehting very wrong with interrupts.


I think you should better read about the String Object and don't mix this up with string as char array.


How to enable interrupt again after disabling it?

Below I am trying to disable interrupt once it got detected and enable it again when I start loop again.

not sure why you want to do that but interrupts are DISABLED in isr by hardware (unless you explicitly enable it in isr) so what you are trying to do is done for you automagically.

  But in below code I am not able to enable it.

mostly it involves enabling the respective interrupt mask, unless you want to enable / disable all interrupts.


Try SoftwareSerial rather than AltSoftSerial.

I don't see the point in these lines, I think you can remove them:

 if (Serial.available())
  {
    portOne.write(Serial.read());
  }

  I have connected directly to a pic and verified the radio I'm connecting to does indeed continue to send data.

If that is the case, that it sends data anyway, then you could just use HardwareSerial. Connect the radio to Rx (D0 on the Uno) and leave Tx unconnected. Then just read from Serial, and write to Serial. You should see the results on the Serial Monitor. (Disconnect this wire when uploading new versions of the sketch).


Arduino - manually ceate objects (e.g. WiFi library)

I am not sure, if it would save enought memory to be worth the problems (it is just few bytes, buffers are created anyway), but lets say so.
Then you need modify the library to not creating the object, as it is allocated statically and cannot be removed later (and reclaim its memory). To protect all other projects it would be probably best to use special #define to disable it only in memory critical projects - so the Wire.h should contain something like

#ifndef EXCLUDE_WIRE
extern TwoWire Wire;
#endif

and your program (critical.ino) should start with

#define EXCLUDE_WIRE
#include <Wire.h>

and then somewhere in loop / other function use

TwoWire Wire;

as local variable. If you need to call other functions with it, then you have to send its address as a parameter.

Anyway you will not save nearly any memory, as nearly all variables in TwoWire ((and namely buffers) are static and so class variables and so are common for all instacies of TwoWire and allocated automatically if there is (possibly used) any instance of TwoWire anywhere in your program.

So it would be better to create your own library to use the same functionality, but make sure, that all such variables are instance variables and properly created and released at the right time. This would also allowe for changing the buffer sizes, if needed.

As it is under LGPL 2.0+ you are legally allowed to do that (provided you fullfill all licence conditions).


sleep and wake up arduino mega according to ds3231 interrupt

First, Arduino Mega does not have an RTC (Real Time Clock) built-in. So, to program it the way you like, would mean either using a module like DS3231 or similar, or have the Mega connected to internet, with a network card module like ENC28J60 and getting the time from there. If you don't use any of those methods basing your scheduler only on the Arduino internal timer (using sleep for example) will result in program needing to set the correct time each time Arduino is powered.


Detecting an incoming 7.875 kHz pulse to use as trigger

So i figured out what the problem was, I had to detach interrupts in the interrupt routines not in my main code. So basically these changes:
void loop() {
  digitalWrite(ledPin, LOW);
  attachInterrupt(digitalPinToInterrupt(pulse1), ISR_UV1, CHANGING);

}

& in the Interrupt routines:
digitalWrite(ledPin, HIGH);      // Send high or Low dpending on the routine
detachInterrupt(digitalPinToInterrupt(pulse1));

& basically this works like a charm, & there are still issues with the timer, but that will be solved in my main code with another sensor.


ESP8266, prints ready at start but no response to AT command

Connect TX of arduino to esp8266 RX, and arduino RX to esp8266 TX.

See this link for more info.


how to break out servo.write(angle) after it reach the angle?

You change the angle in small increments until the sensor triggers:

bool closing = false;
bool openeing = false;
int angle;

void loop(){

    //read touchSensor

    if(sensorHit){
        closing  = false;
    }
    if(closing){
        if(angle <= minAngle) closing = false;
        angle -= 1;
        myservo.write(angle);

    }

    if(opening){
        if(angle >= maxAngle) opening = false;
        angle += 1;
        myservo.write(angle);

    }

}

The to start moving the grasper you set opening or closing to true. You can also add some trigger logic in the places where they get set back to false for the next movement if applicable.


The first thing I would recommend is to log into your Amazon account and contact the seller. Ask them to send you product documentation.

If the seller is not able to provide any, then you could return the product for a refund or try to figure it out how it works.

According to this document: TTL Laser

TTL modulators emit 100% of their power when a TTL "0" (0 VDC) is input and less than 5% of their power when a TTL "1" (5 VDC) is input.

gre_gor's comment about trying a simple PWM sketch sounds like an excellent place to start.


Is is possible to hook up an SD card and a GSM/GSRM module?

Yes.

But let me try to talk you through it.

Step 1 - Analysis/Requirements:
Get your requirements right, what should your system do, what functionality.
So, GSM functionalities and SD card savings (in short).
One of the requirements would be that's it on an Arduino (atmega 328P).
Any other hardware requirements?

Step 2 - Design:
Check the possibilities with the Arduino, 1 hardware serial and multiple software serial connections. One hardware SPI/I2C I believe.
SD cards often use SPI connection and GSM units most likely use serial.
So this works great. Check some tutorials on SPI and (arduino) serial.

Step 3 - Wiring up
Wire everything up, as defined in the datasheet of the devices. Cross the Rx and Tx lines. Put MISO to MISO and MOSI to MOSI accordingly.
Be sure everything has enough power (GSM modules typically draw a lot of current when sending/connecting). Usually, if you find out that two devices are attached to the same pin, there might be something wrong (unless you can declare how they're seperated or why this is the case).

Step 4 - Implement
Well, you stated you're good at programming, so I'll leave this open for you.
But mind that it's only one of the three steps, so you should look at some tutorials, it'll learn a lot faster than asking everything. Try to get a bit comfortable with your thoughts, base them on things you have learned.

  So this shouldn't be an issue? Those pins aren't shared? - user1833028

Things like this can be found in the device's datasheet and if you follow some tutorials you'll see that they're different and why.

Also, what helps for me often, is to try to seperate this 'big' project into two smaller projects.
Try to get the GSM working and after that you go for the SD card reader.


Arduino clone avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x04

Problem not solved, but I can program it with a USBASP programmer. I burned a bootloader, but the USB connection didn't work.
I am now using it without a bootloader.


Is there any way to prevent Arduino CLI from closing each time?

I would suggest working the other way around.

Start the Arduino IDE and set external editor in the Preferences (once).
Open the sketch file(s) in the Arduino IDE and VIM.
Edit the sketch file(s) in VIM.
Move to the Arduino IDE and Verify, Upload, Monitor, etc.
Repeat steps 3-4.

The alternative is to use a make based build system. An example may be found in the Cosa build system for Linux.

Cheers!

PS: VIM = any external editor such as GNU Emacs, TextEdit, etc.


How can i split an incoming data in arduino?

Scanning string formatted data can be done with sscanf (docs). It takes format strings just like printf() does, but instead of printing formatted data, it parses formatted data into the given variables.

For example,

String input = "180 0 0 0 90 90 0";
//parse input (6 integers)
int servoPositions[6];
int numScanned = sscanf (input.c_str(),"%d %d %d %d %d %d",
    &servoPositions[0], &servoPositions[1],&servoPositions[2],
    &servoPositions[3], &servoPositions[4],&servoPositions[5]);

//print positions again
Serial.println("Parsed servo positions:");

for(int i=0; i < 6; i++) {
    Serial.print("position ");
    Serial.print(i);
    Serial.print(": ");
    Serial.println(servoPositions[i]);
}

Outputs

Parsed servo positions:
position 0: 180
position 1: 0
position 2: 0
position 3: 0
position 4: 90
position 5: 90


Is it possible to put priorities between external interrupts?

Interrupts are not the right place to handle priorities. The interrupt
handlers should be as short as possible. Then the likeliness of two of
them happening at the same time is very low. And even if it happens, the
lowest-priority interrupt will only be delayed by a handful of
microseconds, which should not be a big deal.

In this case, the sensible approach is to have the interrupt handlers
set a global flag and do nothing else. Then the main program will
check the flags and do the real work, handling the priorities as needed.

Conceptually, the code could be something along these rough lines:

// Global flags.
volatile bool alarmDetected;
volatile bool shockDetected;

// Interrupt handlers.
void onAlarmInterrupt() { alarmDetected = true; }
void onShockInterrupt() { shockDetected = true; }

void loop() {
    if (shockDetected) {  // check this first!
        measureShockData();
        if (gotEnoughShockData()) {
            shockDetected = false;
            alarmDetected = false;  // ignore the alarm
            goToSleep();
        }
    } else if (alarmDetected) {
        recordSensorData();
        if (gotEnoughSensorData()) {
            alarmDetected = false;
            goToSleep();
        }
    }
}

Note that you can remove the line that ignores the alarm in case of
shock. If you do so, the alarm will be handled after all relevant
shock data has been recorded.


How do I know if I need to use a resistor in a circuit?

How can I tell if I need to use a resistor in a circuit?

You can tell because the circuit includes a resistor.

If a circuit needs a resistor the circuit diagram will include a resistor. If it doesn't, then it won't.

The circuit for connecting an LED to an Arduino consists of an Arduino, an LED and a resistor.  Because of that you know it needs a resistor. Because it says it needs a resistor.

A resistor drops a certain voltage across it when a specific current flows through it (Read up on Ohm's Law...). If you need to drop a specific voltage with a specific known current, or if you need to cause a specific current to flow with a fixed voltage, then you use a resistor for that job.

You don't just throw resistors willy-nilly into every circuit you make simply because you see one being used with an LED.

If a device says it runs off 5V and uses 300mA current then you know that you need to hook it up to a power source that is 5V. You also know that the module will use up to 300mA of current from that source, so your source has to be capable of providing at least that much current.


Board recommendations for GPRS/GSM for 'on the go'

I have a project that have the same idea that yours.

I used Ublox NEO-6M GPS Module for GPS tracking, the module cost in a range from $6 to $13 USD(it depends from where the seller ships, china o USA) in EBAY. You can connect it via UART.

For the internet I used a SIM800L V2.0 5V Wireless GSM GPRS MODULE, you can buy it from EBAY too, it cost no more than $10.00 USD, and you can connect to internet or send SMS using AT commands.

I used a combination of arduino and Raspberry pi zero, also I send the GPS data to a webserver (I pay 5dllr/month for a VPS) and then I can track using google maps.

Thats the basic information, you can use it to start working.


Do not use delay but millis().
Example:

#define BTN 2
#define MAX_MODE 1   //2 modes

const unsigned int times[] = {1000, 2000};

unsigned int time = times[0];

unsigned long btn_tm = 0;
unsigned long l_time = 0;

byte mode = 0;

void setup(){
  Serial.begin(9600);
  pinMode(BTN, INPUT);
}

void loop(){
  if(digitalRead(BTN) == 1 && millis() - btn_tm > 200){
    btn_tm = millis();
    mode ++
    if(mode > MAX_MODE) mode = 0;
    time = times[mode];
 }
  if(millis() - l_time >= time){
    l_time = millis();
    if(mode == 0) Serial.println("mode 0");
    if(mode == 1) Serial.println("mode 1");
 }
}

Read it and try it.


Voltage is only part of what a relay uses.  Check the current requirements for the relay coil/input as well.

For example the common result for "3V relay arduino" will produce results for relay MODULEs that contain something akin to a SRD-03VDC-SL-C relay (labeled on the relay itself).  Spec for the RELAY (separate search by relay part no) yields a data sheet that says the coil resistance is 25 ohms for a 3V and would use 120 mA at that voltage (25 Ohm * .120A = 3).  Note if the same coil were run on 5V it would draw 200 mA (25 Ohm * .200A = 5V).

120 mA is bloody high to be coming from a logic pin which is why the MODULE has more than just the relay.  What the MODULE likely contains is an additional gate device that takes less current that then supplies the relay (with 120mA) from another port.

You might also be looking at a solid state relay that uses less input current but generally has some slight leakage when "Off"


Callback function must be data send from server to the ESP.
Payload is the data byte sent from server.
Length is the size of data in bytes.
BTOF is basically byte to float converter which converts all the data byte received into single floating variable and return that floating point value.
ECS.write must be the function that write the value to the servo motor controller H-bridge IC. It belongs to servo library.
Value range that can be mapped into this ECS.write is between 0-180 so map function will use that will convert the floating point data received from btof function.
Basic definition of map() function:

Map function maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.

Does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired.

Note that the "lower bounds" of either range may be larger or smaller than the "upper bounds" so the map() function may be used to reverse a range of numbers.

Syntax:

map(value, fromLow, fromHigh, toLow, toHigh)

Then ECS.write(value) will write that mapped value to servor motor controller H-Bridge.


What is the best way/module to talk to an Arduino from far away (WIFI)?

The simplest option is to use GSM for the communication. Range isn't an issue, since point A isn't communicating with point B, instead point A and point B are both communicating via third party communication subsystem C which has a much greater coverage than anything you could build yourself.

I use GSM modules for communication with agricultural monitoring and control systems at remote locations. It works well, and you're pretty much guaranteed to have a signal.

For those times when GSM isn't a possibility (no signal, or the customer doesn't want the subscription cost) you really need line of sight between the two locations. Then you can use a highly directional antenna (e.g., parabolic dish or Yagi array) to extend any other suitable wireless communication signal over a long range (WiFi can reach tens of kilometres with parabolic dishes) and there are companies that specialise in that kind of equipment (such as this one that claims 8 mile range - of course you need two of them, one for each end of the link).  Of course, with some skill and determination it's possible to get incredibly long distances from WiFi. Not for your average user though...


Yes, but the nRF24L01 can only transmit one message at at time, since it only has one buffer.

So roughly speaking, for each message

Set the transmit pipe address (if different than the last one)
Send data
Wait for completion (and ack or failure, if in that mode)


How do I connect this display to an Arduino Uno

You're in for a lot of work. Everything on the PCB is useless to you, so you'd have to interface the raw panel to the Arduino.

The first matter is to remove the panel from the board. You will need to desolder all of the connections, and then solder either some sort of rigid connector or individual wires to the large ribbon connector. The only advice I can give you is "be prepared to fail".

Once you've done that, you will need to read AVR340 in order to learn how to drive the panel. Note that the Uno itself does not have enough pins to drive the panel directly, so you will need to get an I/O expander or two for this.

Did I mention that you're in for a lot of work? Well, I'm mentioning it again. Good luck though.


How to setup HC05 Module to be distinguishable

Your options are:

As you guessed, you could set the name with AT+NAME=, and only use the names matching some pattern. It would work if you're only user so you just want to ignore other BT devices, but is problematic if you're having multiple independent users (each with its different set of *HC05*s) who might be in range (you could set different pattern for each user, though).
build a database of addresses (read-only with AT+ADDR?), and only access those devices that are belonging to that user. It would avoid problem above with multiple users, but would require some logistics on your part (for example, when you sell user the app and HC05s, in the registration process you'll need to assign exactly which HC05 address that user my access. Or you might want to allow user to pick which devices are his, by having him specify specify PIN for pairing set with AT+PSWD=)
third way is to use custom Inquire Access Code instead of GIAC so only that set of devices is scanned. HC05 allows setting it with AT+IAC=. However, as it is more complex and nonstandard that (2), and you'd probably still need to registration to differentiate which user is allowed which IAC, I'd recommend you do (2) instead.


The first thing I do when I have a transceiver that doesn't work is a loopback test. This rules out a lot of potential issues like the wrong pin being used or MAX 232 not being connected correctly.

Receiving your transmission on a PC using USB to RS232 adapter (if you have one) would also be a helpful test.


The VIN port is connected to the barrel jack. It must only be used if you are powering the board through that jack.

To access the USB power just use the 5V pin - it is directly connected to the USB.

However, the USB, although the socket it is plugged into can supply more, is limited to 500mA. This is because of a 500mA auto-resetting polyfuse on the USB power input (the large gold and dark green rectangle next to the USB socket - mine has either XE05 or 503X on it depending on which way up you hold it).


How do I set up communication between the "Seeeduino Xiao" and the "Adafruit Bluefruit LE UART Friend - Bluetooth Low Energy (BLE)"?

Nevermind, I figured it out. For anyone that has this problem to:
First, use the "blueart_cmdmode" example file. Then, follow these steps:
HOW TO GET THE SEEEDUINO XIAO TO WORK WITH THIS

Make sure the "Adafruit_BluefruitLE_UART ble(Serial1, BLUEFRUIT_UART_MODE_PIN);"
line of text above the "void error" line is UNCOMMENTED. Everything else in that
block is to still be commented.

Define the pins in "BluefruitConfig.h" as such:
#define BLUEFRUIT_SWUART_RXD_PIN       6    // Required for software serial!
#define BLUEFRUIT_SWUART_TXD_PIN       7    // Required for software serial!
#define BLUEFRUIT_UART_CTS_PIN         0    // Required for software serial!
#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused

Wire the pins as defined above.

Make sure the Bluefruit is switched to "CMD" mode.


There are so many mistakes in your code. I'll do my best to correct them using comments. The code for the slaves should be as follows:

#include "Wire.h"

//
// i2c_test_01

//
// This demonstrates a master transmitting to a slave.
//

// The master transmits a value read from an analogue port.

// The slave sends the value to the serial device.
//

int inp = 0;  // input pin

const byte SlaveDeviceId = 2;

void setup() {
  Wire.begin(SlaveDeviceId);  // here the slave joins the bus, with its address as argument to begin()
  Wire.onRequest(callback);  // here you indicate what the slave should do if a bus master queries it
}

void callback() {
  int input0 = analogRead(inp);
  // Send two bytes to master
  Wire.write(input0 >> 8);
  Wire.write(input0 & 255);

  inp++;
  if (inp == 4) {
    inp = 0;
  }

}

void loop(){}

This is the master's code:

#include "Wire.h"

const byte SlaveDeviceId = 1;
const byte SlaveDeviceId2 = 2;
char inputDev = 4;  // number of devices connected to slave analog inputs

void setup() {
  Wire.begin();   // no argument here since its a master
  Serial.begin(9600);
}

//the onReceive() method is for slaves receiving from a master, so we dont use it here

void loop() {
  Serial.println("\r\nSlave 1: ");
  for (char i = 0; i < inputDev; i++){
    Wire.requestFrom(SlaveDeviceId, 2);
    delay(1);  // more than enough time for all the data to come in
    int val = Wire.read() << 8;
    val |= Wire.read() & 0xFF;
    Serial.print(val);
    Serial.print(",");
  }
  Serial.println("\r\nSlave 2: ");
  for (char i = 0; i < inputDev; i++){
    Wire.requestFrom(SlaveDeviceId2, 2);
    delay(1);  // more than enough time for all the data to come in
    int val = Wire.read() << 8;
    val |= Wire.read() & 0xFF;
    Serial.print(val);
    Serial.print(",");
  }

}


Which one are you using?
The one closest to the reset button, I believe its the native...

This is more confusing than I realized. The Due has two ports:

Programming port
For programming, the programming port is easiest to use. And you can "talk" to the serial port using Serial, like this:
void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Hello, world!");
  }  // end of setup

void loop ()
  {
  }  // end of loop

Native USB port
This lets you emulate USB devices (eg. keyboard, mice). However if you want to use it for Serial communications you need to use a different class SerialUSB like this:
void setup ()
  {
  SerialUSB.begin(115200);
  while (!SerialUSB) ; // wait for it to become ready
  SerialUSB.println ("Starting ...");
  }  // end of setup

unsigned long i;

void loop ()
  {
  SerialUSB.print ("Hello, world! Count = ");
  SerialUSB.println (++i);
  delay (1000);
  }  // end of loop

It also helps to wait for the serial port to become ready, as I did in setup. Otherwise you may miss the first 10 lines or so of serial output.


Significance of the numbers used in the manual

The range 0 - 1023 comes from the analog-to-digital converters (ADC) built-in to your Arduino. What they do is take a voltage reading (e.g. from your sensor) and compare it to the analog reference voltage (which is typically 5 volts, although it can be changed).

It converts that reading to a binary number. The ADCs on board a typical Arduino have 10 bits of precision. The maximum number you can represent with 10 binary bits is 1023. Therefore, a reading of 0V is converted to the number 0; a reading of 5V is converted to the number 1023; and so on (it handles all the in-between values too).

However, analogWrite() works quite differently. It's not actually producing a varying voltage on the output (i.e. it's not true digital-to-analog conversion). Instead, it's using Pulse Width Modulation (PWM) to do something similar.

That means it sends lots of 5V pulses on the output in quick succession. The 0 - 255 values you give it affect the duty cycle -- that is, how long each pulse is compared to the gaps between pulses. The longer the pulses are, the 'stronger' the signal is. This is very useful for applications such as controlling the brightness of an LED or the speed of a basic DC motor.

The PWM signal is controlled by timers built-in to the microcontroller. I suspect it's the capabilities of those timers which determine the input range for analogWrite().

You can get more information from the online documentation for Arduino:

http://arduino.cc/en/Reference/AnalogRead
http://arduino.cc/en/Reference/AnalogWrite


If you look up the ASCII codes for what you sent vs what was displayed, and also look at "Table 4 Correspondence between Character Codes and Character Patterns (ROM Code: A00)" in an HD44780U spec sheet, you will find hexadecimal values like the following.

e 65, V  56
l 6C, ニ C6
o 6F, θ  F2
o 6F, π  F7
r 72, &  26
d 64, B  24
and so forth.

It appears that the high nibble of what you sent is being used as the low nibble of what is displayed, and the low nibble is being used as the high, but with some bits sometimes going wrong.  Note, a space is 0x20, and the reverse of that is 0x02, which would access a character from the character-generator RAM, which will contain random bits and produce a random blob as in your picture.

If your mis-specification of display size (20, 4 vs 16, 2) isn't responsible for the problem, then maybe there is a hardware problem with the backpack you've soldered on to the LCD.  Look at it under a bright light, using a binocular parts-examination microscope if you've got one, and see if there are loose solder particles, extra solder flux, or loose solder connections on that board.  If you have an oscilloscope, check if your I2C signals are clean and have full swing.


How can I share one power supply between an arduino and servos?

You need to figure out your total current requirements. Don't guess, figure it out. What is the peak current draw of the servos? of the other components? Add everything up. If the total is within 20% of your power supply current, that may be the problem.
Also, servos tend to draw spikes of current. You might need to add a filter capacitor to the +5V rail on the Arduino to even out dips as the servos cause sags in current before the voltage regulator in your power supply can compensate. (Put the cap between +5V and ground right at the Arduino.)


Why does Arduino use USB A-B plug, instead of A to micro USB plug?

Please note that this answer is based on speculation and some common sense rather than on insider information:

If you take look at the hardware index, you'll notice that significant parts of the layout (drill holes, pin spacing, and position and type of the USB jack) haven't changed between the Arduino Extreme and the current Arduino UNO R3), while other improvements have been made. For changes between the UNO R2 and R3, please see Arduino UNO FAQ at adafruit (link provided by jfpoilpret).

It is thus reasonable to me that keeping the USB jack was a deliberate design decision: Improve if possible, but keep the layout changes to a minimum and allow for maximum backwards compaptibility.

But again, this is just the guess of a user!


Speed data logging using arduino and GPS module

According to the NeoGPS documentation for the gps_fix class, it looks like .lat and .lon are no longer part of the gps_fix class.
It looks like instead you will have to use .latitudeL and .longitudeL for high precision (Long Integer scaled by 10,000,000) GPS coordinates.
The solution would be to replace fix.lat in your code with fix.latitudeL and fix.lon with fix.longitudeL.