We cannot know, if your python code also has a problem. But your Arduino code will send the series of "V" only once.
You are using this while loop:
while(counter < maxnum)

in there you are incrementing the variable counter. But after you left the while loop, you are never resetting counter to zero. So the next time, counter is still equal to maxnum. Thus the while loop will not run again. To solve that, insert
counter = 0;

directly after your while loop. Though, for such loops its normally easier to just use a for loop.

Also you might have a second problem. Currently the code waits for Serial data to be received. When something is received, the code will enter the
if(Serial.available() > 0)

statement. But this will stay true, unless you are actually reading the data. Currently the code inside the if statement will be executed on every loop() interation forever. So if you are applying the above fix to the first problem, the code will send "V" forever after you send the first byte to the Arduino. To actually only react to data being received, you need to read the data from the buffer - even if you are throwing the data away:
Serial.read();

What is the difference when an arduino has been unplugged vs when a serial port connection was closed?

For the Arduino itself? Nearly none. Reopening the serial connection will cause the Arduino to reset. The code then starts again from its beginning. Thats also what happens, when you power cycle (replugging) the Arduino. I think there are some little details, where both differ, but that certainly is not the problem here.
For the computer, replugging means, that the USB device (the USB-to-Serial chip on the Arduino to be precise) gets disconnected and again connected. That can lead to the OS allocating a different com-port/device-file for it, than before. Though that doesn't directly do something with the Arduino code (apart from the mentioned power cycle with reset).
For resetting (preserved from comment of OP):

I found that by setting DTR to 0 then 1, then 0 again, right before closing the port, the arduino resets.


Your question is vague so I have made some assumptions, I hope they are right.

The first is I have assumed you are relatively in experienced at programming, I hope that's right otherwise the rest of this may seem patronising.

You have a number of LEDs arranged in a grid (lets say 3x3 to make life easy).
You are asking is there an alternative to doing this:

// Step 1
digitalWrite (LED1, HIGH);
digitalWrite (LED4, HIGH);
digitalWrite (LED8, HIGH);
delay (100);
digitalWrite (LED1, LOW);
digitalWrite (LED4, LOW);
digitalWrite (LED8, LOW);
// Step 2
// And so on...

Yes there are, and there are many, I think this is probably going to be the easiest to start with.

Coding the data in a 2D array.

An array is a fixed length list of values of the same type.  One obvious use for an array is to hold the pin numbers for you LEDS, rather than having LED0 through to LED8.

#define LED0 2
#define LED1 3
// and so on

Alternative array version

//  Define the number of elements in the array
#define MaxLEDs 9
// Define the array
const int LEDPins[MaxLEDs] = {2, 3, 4, 5, 6, 7, 8, 9, 10};

I have declared the array as const because the values in it aren't going to change.  The array is going to hold integers (because that's what digitalWrite() takes as a pin number) and there are 9 of them.  Rather than use the literal 9 I have defined a constant because I know that value is going to be used elsewhere in the code and this means it is easier to change the number of LEDs.

So how does this help you?  Well you can define an array of 'steps' and each step has a list of which LEDs are switched on.  As your code loops through the steps it turns the specified LEDs, waits and then turns them off.  The simplest way to encode the data would be for each 'step' element to be an array of Boolean values (each true value indicates a light that should be on during this step).  I have chosen Booleans because it will use the least amount of space, which is always an issue on an Arduino.  Depending on the number of steps and LEDs you may need to look at alternative storage methods, like just the LEDs that are on, but it will do for now.

const bool theSteps[MaxSteps][MaxLEDs] =
{
    {false, false, false, false, false, false, false, false, false}
  , {false, true , false, false, true , false, true , false, false}
  , {false, false, true , true , false, false, false, true , false}
  , {true , false, false, false, false, true , true , false, false}
};

You still have to code the data within the program, but its much smaller

//  Define the number of elements in the array
#define MaxLEDs 9
// Define the array
const int LEDPins[MaxLEDs] = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };

const bool theSteps[MaxSteps][MaxLEDs] =
{
    { false, false, false, false, false, false, false, false, false }
    ,{ false, true , false, false, true , false, true , false, false }
    ,{ false, false, true , true , false, false, false, true , false }
    ,{ true , false, false, false, false, true , true , false, false }
};

#define StepDelay 100

void setup()
{
}

void loop()
{
    for (int onOff = 0; onOff < 2; ++onOff) // Turns the LED on and off
    {
        for (int step = 0; step < MaxSteps; ++step)
        {
            for (int led = 0; led < MaxLEDs; ++led)
            {
                if (theSteps[step][led])  // If the LED should be on
                {
                    digitalWrite(LEDPins[led], (onOff < 1) ? HIGH : LOW);
                }
            }
        }
        if (onOff < 1)
            {
                  delay(StepDelay);
            }
    }
}

I'm afraid I haven't tested any of this code (it might not even compile) but the theory is right and it should give you a shove in the right direction.


Unexpected negative values from abs() function inline with analogRead

abs() is defined in Arduino.h as a macro:

 #define abs(x) ((x)>0?(x):-(x))

A macro does not evaluate in the same way as a function.

 sensor = abs(analogRead(A0) - 512);

This statement will be expanded at compile-time to:

 sensor = ((analogRead(A0) - 512)>0?(analogRead(A0) - 512):-(analogRead(A0) - 512));

Now the "error" is easy to understand. The analog pin is read twice. The "error" can be avoided by adding the following line first in your sketch:

#undef abs

This will remove the macro abs() and the standard library function will be used instead.

Cheers!


how can I upload a hex file to an arduino uno?

I use a standalone programmer that uploads a .hex file from an SD card via the ICSP interface.


Fixed.
My router is ancient and does not support WPA.  As of ESP8266WiFi library Version 2.5.0, WPA is is the preferred mode.  The solution is to get a better router, or add WiFi.enableInsecureWEP(); before calling WiFi.begin().

WiFi.enableInsecureWEP();
WiFi.begin(wifi_ssid, wifi_password);


No. It uses pin-change interrupts to trigger reception, and both reception and transmission use calibrated delay loops.  However, interrupts are disabled during both transmission and reception so that the calibrated delay loops remain always the precise length - so if you do anything with any other interrupts they will not work at the same time as SoftwareSerial.


How to conect multiple output pin from sensors to a single digital pin on a arduino

If the ICs output 5V and your Arduino is 3.3V, you can simply use one voltage divider at the Arduinos pin to divide the voltage down to 3.3V.

But there is still one important thing to connect them safely: You have to check, if the outputs of the ICs are driven actively high, when no fault occured, or if they simply use a pullup resistor internally.

A pin, that is actively driven high, does not have an overcurrent protection. So, if one IC would pull it's pin to low and the others are still high, a high current would flow between them, potentially destroying them. In that case you need current limiting resistors in series with the ICs (directly at the ICs, so that the resistors are between them).

On the other side, if the ICs output a high level through a pullup resistor, you are safe to connect them directly, as there can only flow a very little current through the pullup resistors. Often such a situation is called Open-Drain (passive high level through pullup resistors, active low level by driving the pin to low through a MOSFET, like used in a digital output pin). In that case you don't need the current limiting resistors.

EDIT: The datasheet of the ICs, that you linked to states that the fault output is an

  Active-low open-drain output

Also the example circuit shows an external pullup resistor. That means, that the fault pin is internally connected to a MOSFET, which will connect the pin to ground in case of a fault. Otherwise the pin is floating. The external pullup resistor will pull the pin state to a high level, when the MOSFET is not activated. This is good for you, since you can now simply use 1 resistor (one resistor is enough for all ICs), to pull the level up to 3.3V. Then you directly have the correct level for your Arduino and you don't need a voltage divider.


Step 1: I would load NodeMCU on you ESP8266: https://github.com/nodemcu/nodemcu-firmware

Step 2: Connect to your home router or make an ap on one of your ESP and connect them... use the api: https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en over serial connection

Step 3: write a TCP server:

srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
  conn:on("receive",function(conn,payload)
    print(payload) //This payload will be send to your arduino over soft serial
    conn:send("<h1> Hello, NodeMCU!!! </h1>")
  end)
  conn:on("sent",function(conn) conn:close() end)
end)

Step 4: write a TCP client:

suc = false;
function sendData( host, pathData )
    suc = false;
    print("GoSending!");
    -- A simple http client
    conn=net.createConnection(net.TCP, 0)
    conn:on("receive", function(conn, payload)
        if(string.find(payload, "200 OK")~=nil) then
            suc = true;
            print("AllDone")
        else
            suc = false;
        end
    end)
    conn:on("connection", function(c)
        print("connected");
        conn:send("GET /".. pathData .." HTTP/1.1\r\nHost: ".. host .."\r\n"
            .."Connection: keep-alive\r\nAccept: */*\r\n\r\n")
        end)
    conn:on("disconnection", function()
        if(suc==false) then
            print("ErrorSending")
        end
    end)
    conn:on("reconnection", function() print("reconnection") end )
    conn:connect(80,host)
end

Step 5: Connect your esp boards with software serial to the arduino

Step 6: write (from board 1) to softserial to esp1: sendData( hostIP, yourData)

Step: 7 Parse the Data on sofserial read on the second arduino

Step 8: DONE!

EDIT:

Ok more infos on step 6.
If you got your script running on your esp, you can call functions by sending the function name with parameters over your serial connection.
So, this is some example code for your ardoino if you got the script from above:

SoftwareSerial wifi(3, 2); // RX, TX

//at some time in your programm
//Build up your string that will be send over serial
String i1 = "sendData(\"ipFromTheServer\", \"send.php?d=";
String i2 = i1+dataToSend;
String i3 = i2 +"\");";
wifi.println(i3);

This will call the sendData function on you esp. this will call the send.php on a Server... you can put a server up on an other esp and call it (dont have to be a php page)

More infos on step 7.
the script on top will always print all incoming data. So you just have to read serial data on wifi:

if (wifi.available())
    Serial.write(wifi.read()); //this will print all inc data to your arduino console (serial) parse this data!

Info: I've build this on my own... dont know if this is best practice :)


Arduino IDE doesn't pick up serial ports

The MAC / Arduino install instructions appear to be here.

If your Arduino (possibly a NodeMCU 1.0 version board) is using the CP210x chip set there appears to be a download page here.

If your Arduino (possibly a NodeMCU 0.9 version board) is using the ch340g, ch34g or ch34x chip set there appears to be an effort to create a Mac OS X driver here.

The install instructions from that github page are as follows:

  Installation

Unplug any CH34* devices.
Unload the old drivers if running:
    sudo kextunload /Library/Extensions/usbserial.kext
    sudo kextunload /System/Library/Extensions/usb.kext
Remove the old driver by issuing one of the following commands (depending on your installation):
    sudo rm -rf /System/Library/Extensions/usb.kext
    sudo rm -rf /Library/Extensions/usbserial.kext
Double-click on the CH34x_Install_V1.5.pkg file and install (no need to reboot)
Instead of rebooting, you can force quit Installer after it completes.
Load the new driver:
    sudo kextload /Library/Extensions/usbserial.kext
Plug in your device. It should now be listed under the /dev directory. Examples:
    /dev/cu.wchusbserial1410
    /dev/tty.wchusbserial14210 (driver version 1.5)


I've looked at the data sheet for this and I think it is the wrong choice of device for a beginner.  Can I suggest that you start by looking at a relatively simple DPI interfaced device, such as a sensor or RTC.  This will teach you the basics of sending commands via the Wire library.  You might even get the hang of it just by looking at existing libraries.

I can't find a library, so you are going to need to write your own.  The library will need a begin function which initialises you class and a write and read function, which write and read from an address.

void begin(void);
uint8_t read(const uint8_t& address);
void write (const uint8_t& address, const uint8_t& bytesOfData, const uint8_t* pData);

You will need to flesh those functions out, but that's it.  If you want to make you library more useable read the datasheet and create wrapper functions for each of the registers that can be accessed.

// This instruction requires 10 buts spread over two bytes.
void writeFrequencyOffset (const uint8_t& highByte, const uint8_t& lowByte)
{
  write (0x73, lowByte);
  write (0x74, highByte);
}

The process of creating friendly wrappers is a tedious operations, just reading the data sheet and translating that into code.


How to use RS-232 sheild as software serial port?

GND => GND 5V => 5V Digital Pin 2 => 232RXD Digital Pin 3 => 232TXD

A better choice of board would be the Leonardo, since you could connect such a shield and use the USB port right out of the box. However, since you have the Uno, there is a solution.

From Arduino:

  The SoftwareSerial library has been developed to allow serial communication on other digital pins of the Arduino, using software to replicate the functionality (hence the name "SoftwareSerial"). It is possible to have multiple software serial ports with speeds up to 115200 bps. A parameter enables inverted signaling for devices which require that protocol.

It then goes on to reccomend the library AltSoftSerial.

Here is some example code from the link above:

#include <AltSoftSerial.h>

AltSoftSerial altSerial;

void setup() {
  Serial.begin(9600);
  Serial.println("AltSoftSerial Test Begin");
  altSerial.begin(9600);
  altSerial.println("Hello World");
}

void loop() {
  char c;

  if (Serial.available()) {
    c = Serial.read();
    altSerial.print(c);
  }
  if (altSerial.available()) {
    c = altSerial.read();
    Serial.print(c);
  }
}

It acts like a standard serial port, only you declare the connection as a variable first. This code is written for a board with an additional serial port, like you have.

All is good, except for one problem:

The problem is the shield is wired to connect to pins 0 and 1: the ones used by the USB adapter. The AltSoftSerial library uses pins 8 for TX and 9 for RX. (Note: You cannot use PWM on pin 10 on the Uno... it should still work as a digital pin.) In that case you would not attach the shield by plugging it into the Arduino, and you would wire it like this:

  GND => GND | 5V => 5V | Digital Pin 8 => 232RXD pin 0 on the shield headers | Digital Pin 9 => 232TXD 1 on the shield headers

So then, you would be manually wiring the shield to the Arduino with jumpers. As long as it doesn't connect to any other Arduino pins I'm not aware of (it shouldn't besides maybe 13 for a LED or something like that), it should function like it would stacked and using pins 0 and 1.

Note: (Obviously) You cannot connect anything to the headers on the shield (You cannot connect to pin 5 and get a signal).


Programming "Arduino" code to AT90S8515?

Theoretically yes, once you write a core (1.5.x/1.6.x) for it. I'm not sure if the IDE has a configuration for the STK500, but it should be easy enough to add (since avrdude already supports it).


ld.exe:linker_script.ld:138 cannot move location counter backwards | ArduinoFFT Error

Short Version
The short answer is that you've exhausted RAM.
These two arrays alone:
const uint16_t samples = 16128;
double vImag[samples] = {0};
double double_buffer[16384] = {};

...are occupying (16128 + 16384) * 8 == 260096 bytes of memory.  There's only 262144 bytes of RAM in entirety.
The way the linker script is set up at least 1024 bytes are reserved for the stack, and there is no doubt at least another kByte in use somewhere.  In the Mbed OS and Arduino core files if nothing else.
As for why it fails only when you call Compute, that comes down to the compiler optimizer discovering that one (perhaps both) of your arrays are not actually used and so not entering into the mix when the linker is run.
Details
In theory, you should have gotten a somewhat nicer and easier to understand message from an ASSERT in the linker script:
ASSERT(. <= (ORIGIN(RAM) + LENGTH(RAM) - 1024), "heap region overflowed into stack");

So, you should have seen an error "heap region overflowed into stack" on your screen instead, which is maybe not the easiest thing for an Arduino user to decipher, but heap and stack are terms likely to be recognizable as memory-related sooner or later.
However, the linker executable shipped with the current version 1.3.2 of the Arduino core for Mbed ignores ASSERT statements completely; I have tested this (and tested my understanding of my test using an amd64 linker).  Presumably, there's a build option for the linker or a command-line or configuration file option that controls that, but I haven't found it yet.  In any case, it ignores a helpful ASSERT and instead proceeds to fail on line 138 mentioned in the error message:
 . = ORIGIN(RAM) + LENGTH(RAM) - 1024;

You can see it involves the same expression, just without a useful message if something goes wrong.  The "location counter" in the message is a linker related term that roughly means "where the next thing will be placed in memory" as it cobbles together your final executable from separately compiled chunks.  You've used so much RAM in your program that the location counter has been pushed past where the linker script wants to place the __HeapLimit symbol, 1K from the end of the MCU's RAM.  The location counter is supposed to increase monotonically.  So, evaluating this expression results in an erroneous attempt to "move location counter backwards".


Using a scrolling text in OLED Adafruit_SSD1305

The SSD1305 hardware apparently does include scrolling support (SDD1305 datasheet - see section 10) but apparently the Adafruit driver didn't implement it. But The SSD1306 looks so similar to the SSD1305, that if the SSD1306 software driver won't work with it "out of the box" (worth a try!), you could probably compare the two software drivers and back-implement that feature into the the 1305 driver yourself.


DC Motor doesn't turn and a beep sound is made, also there is a burning smell

Alright, I finally realized that RPM value was too low. It has to be at least 150 for my case.


How can I power an Arduino Nano with a LiPo battery, preferably 3.7v

In short: not reliably.  The Arduino Nano expects either a 5V regulated supply or a 6-20V unregulated supply (https://www.arduino.cc/en/Main/ArduinoBoardNano).  Even if you plugged it in and it worked initially, the battery voltage will decrease gradually as it discharges (LiPo cells can drop as low as ~3.2V), making it more and more unreliable.  You'd technically be overclocking the processor, since the Nano runs at 16 MHz and the datasheet for the microcontroller requires at least a 4.5V supply to run above 10 MHz.

A safer solution would be to use a 2S LiPo battery (~7.4V), which would be plenty to supply the regulated input pin (VIN).  On the other hand, if you're set on using a 3.7V LiPo, other Arduino boards (like certain versions of the Pro Mini) run at 3.3V.

As for your second question, 3.7V is plenty to power a few LEDs so long as they are connected in parallel (or to separate pins).  The only thing you need to be aware of is current draw--more current means shorter battery life.  For example, if your circuit draws 100 mA total from the battery, and your battery is specified at 500 mAh, you will get approximately (500 / 100) = 5 hours of battery life.


The volatage level on the IO pin needs to change (from low to high and vice versa), only then can the microcontroller detect a button press. Without another connection to the button, IO2 is simply floating (unconnected).

There are two methods to implement this: external pull-up or external pull-down resistors and internal pull-up resistors (both methods are described for example in this tutorial).

I prefer the internal pull-up resitor method. You need to connect the second pin of the button to GND. Then change your setup code to

pinMode(buttonPin, INPUT_PULLUP);

If the button is not pressed, the internal pull up resistor inside the microcontroller pulls IO2 to +5V and a digitalRead(buttonPin) returns HIGH. When you press the button, IO2 is pulled to GND and digitalRead(buttonPin) returns LOW.

So in your case you need to check for a LOW reading, because you want the LEDs to blink when the button is pressed.

(Btw. you can replace the while loop with an if, since the loop() function is already executed in an infinite loop.)


In this example your missing a semi-colin after int buttonPin = 2, and your if statement should probably look like this
if (buttonValue == HIGH){
  digitalWrite(lightpin, HIGH);
}//red

else{
  digitalWrite(lightpin, LOW);//red
}//red/*

Also if you go into the examples in the Arduino IDE, under "digital", this sketch is called button.


How to Sort a String with Number by Ascending

As Michel Keijzers points out, qsort is the standard sorting function
from the libc. Now, since your numbers can start with either two or
three digits, you can not sort them lexicographically, because if you
did so 111 would sort before 82. Instead I suggest to:

parse the start of the strings as integers
compare the integers
if the integers are equal, then sort the strings lexicographically.

The simplest way to parse the strings into integers is atoi(). Unlike
functions like strtol(), atoi() does no error checking, but it is
good enough if you know for sure that the strings have the right format.

Here is the comparison function:

int compare(const void *a, const void *b)
{
    // Get the strings.
    const char *sa = *(const char * const *) a;
    const char *sb = *(const char * const *) b;

    // First, compare the numeric prefixes.
    int ia = atoi(sa);
    int ib = atoi(sb);
    if (ia < ib) return -1;
    if (ia > ib) return +1;

    // If equal, compare the strings lexicographically.
    return strcmp(sa, sb);
}

And here is an example on how to use it:

#define STR_COUNT 3
const char *strings[STR_COUNT] = { "112:AAAA", "82:FFFF", "111:EEEE" };
qsort(strings, STR_COUNT, sizeof strings[0], compare);

Now the array of strings is sorted as ("82:FFFF", "111:EEEE",
"112:AAAA").


Pins 9,10,11 should be working off TIMER 1 which all use the same pre-scaler, so I dont know how 9 and 10 can have one frequency, and 11 have a different frequency.

Unless D11 is configured as OC0A instead of OC1C, which means that it will work off timer 0.

TCCR0A &= ~(_BV(COM0A1) | _BV(COM0A0));
TCCR1A |= _BV(COM1C1) | _BV(COM1C0);
 ...
OCR1C = ...;


The max() “function” is actually a macro defined in Arduino.h as

#define max(a,b) ((a)>(b)?(a):(b))

This expands in your code into something like

buttons_pressed = random(0, N_OF_BUTTONS) > n_of_buttons_pressed) ? \
                  random(0, N_OF_BUTTONS) : n_of_buttons_pressed

The problem with the macro is that it evaluates at least one of its
arguments twice. In this case, if the test is true, the variable
buttons_pressed gets assigned another pseudo-random number.

The way around this is to store the pseudo-random number in a variable,
to avoid random() being evaluated twice:

int pseudo_random = random(0, N_OF_BUTTONS);
buttons_pressed = max(pseudo_random, n_of_buttons_pressed);


Arduino TFMini Lidar sensors and speaker

I don't know why the three of them don't work together.

I already answered that question in my answer to your previous question.

why I'm using this calculation in my code and why if I removed it the lidar will not give me any measurement?

That code part is reading the data from the first SoftwareSerial interface. If you don't read this data (by removing this code part) you are not reading any data from the TFMini, thus you don't have any measurement. If you want measurements from the lidar sensor, don't remove the code part, that actually reads the measurements.
Besides that I will explain the complete function here in comments to the code. Before that, you should understand what the static keyword means here. Normal variables, that get declared inside a function, (aka local variables) will get destroyed, when the code reaches the end of the function. Variables marked with the keyword static will continue to exist and hold their value also after the function ended. They act a lot like global variables, though their namespace is local to the function (thus you can declare other variables with that name in other parts of your code).
void getTFminiData(int* distance, int* strength) {
  static char i = 0; // this counter variable denotes the position of the next to be received byte in the buffer rx.
  char j = 0; // temporary counter variable
  int checksum = 0; // will be used to calculate the checksum, so that it can be compared to the one send with the data
  static int rx[9]; // this is the receive buffer, where the received data will be put

  if (TFMiniOne.available()) { // When data is available on the serial interface, read one byte
    // Serial.println( "tfmini serial available" );
    // read one byte into the current position in the buffer
    rx[i] = TFMiniOne.read();

    // A valid message starts with two bytes of the value 0x59, so we restart, if the current message doesn't have that. (checking the first two bytes with these two if statements)
    if (rx[0] != 0x59) {
      i = 0;
    } else if (i == 1 && rx[1] != 0x59) {
      i = 0;
    } else if (i == 8) { // if we received 9 bytes (positions 0 to 8 in the buffer), the message is complete --> process it

      // Calculating the checksum by adding all bytes together
      for (j = 0; j < 8; j++) {
        checksum += rx[j];
      }

      // Comparing the calculated checksum with the last byte, that was received, (which is the checksum)
      // as the checksum is only one byte, we calculate the modulo with 256, thus only leaving the number range 0-255.
      if (rx[8] == (checksum % 256)) {
        // The checksums are equal, so the data is valid and we can proceed
        // The values for distance and strength have two bytes. Thus we need to put these bytes together into one value.
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }

      // reset the counter, since we have a full message and can now receive the next message
      i = 0;
    } else {
      // increment the counter variable to the next position, if we are currently receiving the bytes of a valid message
      i++;
    }
  }
}

I hope this makes the code clearer. As already said the my previous answer, it doesn't make much sense, to first use the TFMini library (declaring the corresponding objects) and then doing the communication yourself. I would suggest, that you look closer into the TFMini library. Try the examples, that surely come with the library. Use the libraries functions to communicate with the sensors. That will make it way easier for you, since the library will do the communications for you.


Serial input values only working for very short seconds

If you add Serial.println(on_time); right after int on_time = (Serial.parseInt() * 1000); you will see the problem. Once you enter the number 33 for example, the integer value printed is -32536. The Allowed data type for delay() is unsigned long, so the negative number is causing a problem.

Using Serial.println() judiciously can be very helpful when you are trying to debug a sketch.


Optmizing print code when writing to file, and reducing print time

First of all, the only difference between the two parts of the "if" statement is that, the first time, it prints the header. Instead of that code, you could do this:

//(Include the top part of the code here...)
dcounter++;
if (dcounter=1){
    Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
    Data.println(Header);
}
Data.print(strutcDate + "  ");
Data.print(strutcTime + "  ");
Data.print(strgpsStatus + "  ");
Data.print(strmodeIndicator + "  ");
Data.print(strlatitude + "  ");
Data.print(strlongitude + "  ");
Data.print(strspeedOverGnd + "  ");
Data.print(strcourseOverGnd + "  ");
Data.print(t);
Data.print("  ");
Data.print(f);
Data.print("  ");
Data.print(h);
Data.print("  ");
Data.print(hi);
Data.print("  ");
Data.print(press_pKa);
Data.print("  ");
Data.println(str);
Data.close();

Like already mentioned, you can append strings with the + operator. This would be the final code then:

//(Include the top part of the code here...)
dcounter++;
if (dcounter=1){
    Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
    Data.println(Header);
}
Data.println(strutcDate + " " + strutcTime + "  " + strgpsStatus + "  " + strmodeIndicator + "  " + strlatitude + "  " + strlongitude + "  " + strspeedOverGnd + "  " + strcourseOverGnd + "  " + t + "  " + f + "  " + h + "  " + hi + "  " + press_pKa + "  " + str);
Data.close();

FYI, it doesn't seem like you should close the stream every iteration at the end since you only open it the first time.


Arduino, problem with interrupt and SSD1306 OLED

Your problem is (most likely) that you are doing everything from an interrupt. That is not only bad practice, but on Arduinos it is generally impossible.
On small microcontrollers you typically only have one interrupt priority (occasionally two). That means that only one interrupt can run at a time, and if an interrupt is running then no other interrupt can interrupt it.
So anything that relies on interrupts to operate can never be used inside an interrupt service routine, or it will never function.
That includes things like delay() and, depending on the implementation, such things as Wire (I2C) and SPI.
Instead your ISR really should be as short as possible. It should at most do any short calculations and store results, and then indicate (through the use of a semaphore) to the main thread that it should do some work.
The simplest "fix" to your problem would be to move visadisplay() into loop() and in isr() simply set a bool flag when there is data to display. Your loop() then checks that flag and, if set, resets it and calls visadisplay().
Also, you don't need to detach and re-attach the interrupt all the time - if the ISR is running then interrupts can't happen anyway.
// ... snip ...
volatile bool doDisplay = false;

void isr()          //interrupt service routine
{
  Vinkel = 0;
  StartTid = millis();
  CalcTid = SlutTid;

  PulsTid = (StartTid - SlutTid);
  HastighetPerferi = (omkrets/PulsTid);
  SlutTid = StartTid;
  Rpm = ((HastighetPerferi/(omkrets/1000)* 60)/2);  //Calculate speed

  doDisplay = true; // Signal to the main thread there's data to display
}

// ... snip ...

void loop() {
    if (doDisplay) {       // If there is something to display
        doDisplay = false; // then clear the flag for next time
        visadisplay();     // and display the data.
    }
}


Querying streaming sensor data on the Arduino board

It sounds like you are after my Average library:

https://github.com/MajenkoLibraries/Average

It allows you to store a rolling set of data where you get to "push" values into it and the oldest one drops off the end. (It's implemented internally using a circular buffer).

You can then do various forms of analysis on the data - get the mean average, the mode average, calculate the standard deviation, find the maximum and minimum values of the set, and even access individual entries within the set.

It's a fully templated library, so you can use it with any numerical data type (float, double, int, long, etc).


Reading/writing to Arduino GPIO pins from raw C code

In theses cases you are right, using register address is the way to read/write data from/to digital pins.
In the case you use analog input, the process is similar but you have to follow some procedures before getting the value of the data.

GPIO REGISTERS

For AVR micro-controllers these registers are:
DDRn – Data Direction Register
PORTn – Port Output data Register
PINn – Port Input Register
n- Indicates the port name i.e. A, B, C & D
If you have arduino board and want to use these pins, look for mapping pictures about arduino and avr pins.

The following is an example from the Arduino website.

DDRD is the direction register for Port D (Arduino digital pins 0-7). The bits in this register control whether the pins in PORTD are configured as inputs or outputs so, for example:

DDRD = B11111110; // sets Arduino pins 1 to 7 as outputs, pin 0 as input
DDRD = DDRD | B11111100; // this is safer as it sets pins 2 to 7 as outputs
                         // without changing the value of pins 0 & 1, which are RX & TX

See the bitwise operators reference pages and The Bitmath Tutorial in the Playground

PORTD is the register for the state of the outputs. For example;

PORTD = B10101000; // sets digital pins 7,5,3 HIGH

You will only see 5 volts on these pins however if the pins have been set as outputs either by using the DDRD register directly or by using the  pinMode() function.

For analog read

You just need to include the headers and start using the registers. They hold the equivalent hexadecimal values for your microcontroller. And the procedure is described in the datasheet. All you have to do is to translate it to code.

// this code scans ADC1 for an analog signal upon request, using 8Mhz processor clock

#include <avr/io.h>
#include <stdint.h>       // needed for uint8_t

int ADCsingleREAD(uint8_t adctouse)
{
    int ADCval;

    ADMUX = adctouse;        // use #1 ADC
    ADMUX |= (1 << REFS0);   // use AVcc as the reference
    ADMUX &= ~(1 << ADLAR);  // clear for 10 bit resolution

    // 128 prescale for 8Mhz
    ADCSRA |= (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);

    ADCSRA |= (1 << ADEN);    // Enable the ADC
    ADCSRA |= (1 << ADSC);    // Start the ADC conversion

    while(ADCSRA & (1 << ADSC)); // waits for the ADC to finish

    ADCval = ADCL;
    ADCval = (ADCH << 8) + ADCval; // ADCH is read so ADC can be updated again

    return ADCval;
}

int main(void)
{
    int ADCvalue;

    while (1)
    {
        ADCvalue = ADCsingleREAD(1);
        // ADCvalue now contains an 10bit ADC read
    }
}

For more information about analog read, see this.


Use distance sensor to trigger LED strip and stay on while the person is in range

if (inches <= 38)

That You might want to change. Try using "while(inches <= 38)" and moving sensor calculations to that loop. When ever the distance stays less than You want the light should stay on.


Problem with uploading LUFA MassStorage .hex file to Leonardo

Cannot say for sure, but if you was able to flash something, then loose functionality, but was still able to flash it back, then there is possibility, that you flashed the application part (with would-be-bootloder code), not the bootloader part (and the old bootloder in bootloader part then enabled you to flash back something sensibe).

bootloader is resposible for saving application in memory in process of flashing and running the application after that, or in case you just connect the board and do not start flashing it just after (maybe software/transmit) reset.

if you save bootloader to application part of memory, it is highly possible, that it would not do anything good, as the original bootloader would still run first and setup your board and the application (with new bootloader code) would try something futile (and maybe have bad addresses already, as it is suppose to be runned in bootloader place, not in application).

There are two parts of flash memory in arduino - one for application, other for bootloader and they have different use, even if they are just different parts of one big flash area. So make sure, what you actually updated and how was the hex compiled (for which address)


Porting Arduino code to AVR/C++ input not working?

During the creation of this question I found out the answer... Though I wanted to share it with you guys for later reference.
It has been quite a time since I have worked with AVR.

You should read pins from PINx

You should set pins in PORTx

Set DDRx to 1 for OUTPUT and to 0 for INPUT

^ This is fun because PIC/Microchip MCU's use 1 for input and 0 for output.

See code below:

#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>

#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clear_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define isset_bit(Y,bit_x) (Y&(1<<bit_x))
#define toggle_bit(Y,bit_x) (Y^=(1<<bit_x))

int main( ){
    DDRB = 0xFF;
    DDRD = 0x00;

    while(1){
        if((PIND&(1<<PD5))){
            set_bit(PORTB,PB5);
        }else{
            clear_bit(PORTB,PB5);
        }
    }
}


Multiple node network communication over I²C

It sounds (after discussion) like what you are after is actually a mesh of multiple peer to peer devices.  That is, lots of devices, each one has multiple dedicated communication links each directly going to another device.

If you had enough UART ports you could create individual UART links between nodes. The bets Arduinos only have a handful of those, and the UNO only one.  So that's not really practical.

You could possibly do it with SPI if you wanted to put a lot of work in to developing a decent control protocol to go along with it.  Something along the lines of BUSRQ/BUSACK signalling:

BUSRQ: Signalling line pulled HIGH by resistor. All nodes INPUT.
BUSACK: Signalling line pulled HIGH by resistor. All nodes OPEN-DRAIN & LOW.
SS: Direct 1:1 GPIO links between nodes - all pulled HIGH. All nodes INPUT.

Node 1                   Node 2                  Node X
RELEASE BUSACK
DRIVE BUSRQ (OD Low)     Sees BUSRQ fall         Sees BUSRQ fall
                         RELEASE BUSACK          (could be busy...)
                                                 RELEASE BUSACK
Sees BUSACK rise
DRIVE BUSACK
SS Node 2 LOW            Sees SS go LOW
Send SPI data            Receives SPI data
SS Node 2 INPUT          Sees SS go HIGH
RELEASE BUSRQ                                    Sees BUSRQ rise
                         Sees BUSRQ rise         Drive BUSACK
                         Drive BUSACK

Only once all nodes have released BUSACK will the requesting node be able to send any data, and once a node has released BUSACK it knows that it must never send any data.  The requesting node has basically locked the bus from other nodes accessing it.

It's not perfect, and doesn't handle multiple devices requesting the bus at the same moment, but it does prevent one device trying to send while another is actively sending.


Which pin of the ESP8266 chip can be used as I²S output?

I uses GPIOs 2, 3, and 15. You only have GPIO2 available, and that's also one half of the UART interface.  Also you usually need to generate a "master" clock (usually something like 256x the bit clock) for oversampling. So you can't with that module.

  Which ESP chip would be the best choice for this purpose?

ESP32, without a shadow of a doubt.

  I know about the MAX98357A which is used to convert digital I²S data to analog. But, for stereo output I need to use 2 of those. Is there any alternative to this chip which supports stereo output by default?

Yes, there are plenty. The search term you want is "CODEC". Personally I use the TLV320DAC3101.

You never use two separate mono CODECs for stereo, since I²S is a (normally) stereo protocol for connecting to a stereo CODEC. Reliably splitting a stereo I²S stream into two mono ones is not easy.

  I have found many tutorials which shows how to play audio from SD card of ESP8266. But, how can I stream audio over standard WiFi connection?

By implementing a suitable protocol, and that depends entirely on what your audio is and how it is generated.


Problem receiving CAN messages using arduino, MCP2515 CAN module and multiprotocol radio shield

The compiler is saying it can't find the header files. The part of the path ../arduino-api/ is suspicious.

It may be because the header files are expected to be somewhere else, or their is a small error which has had a knock on effect.

1 - Find arduinoMultiprotocol.h
Put its full path into the include statement, e.g.

    #include "C:\Users\user\Documents\Arduino\libraries\arduinoCANBUS\wibble\arduinoMultiprotocol.h"

If that is still broken, but a new error is printed, copy the error. If the error doesn't change, then make a backup copy of every file you can find containing #include <arduinoMultiprotocol.h> and edit it to contain the full path. It looks like starting with arduinocan.cpp is a good place to start.

2 - If that doesn't fix the error, create an empty sketch, including all those headers, e.g.

    #include <arduinoCAN.h>
    #include <arduinoClasses.h>
    #include <arduinoMultiprotocol.h>
    #include <arduinoUART.h>
    #include <arduinoUtils.h>
    #include <Wire.h>
    #include <SPI.h>

    void setup() { }

    void loop() { }

Compile and copy the error message.
Move the #include <arduinoMultiprotocol.h> a bit later in the sequence of #includes. If the error changes copy that for later, and record which sequence changed it.

3 - Change #include <arduinoMultiprotocol.h> in that empty sketch
to the full path (as in step 1). If that doesn't fix it, copy that error message.

If you still need help, please update your question with the results of those tests.


Will this sketch eventually fail because of integer limit issue?

No, the sketches will not fail or work incorrectly. The Arduino "delay()" function calls the "micros()" function for timing. The "micros()" function uses the Atmel's TIMER0 clock and waits for 1000 microseconds (1 milliseconds) each iteration. The TIMER0 overflows about every 70 minutes, but the program code used in the "delay()" function handles that overflow correctly.


Optimizing code to use less Flash Memory and SRAM

What you can do in addition to the items you mentioned:

SRAM reduction

Use the smallest amount of data type for integers, e.g. use an 8 bit data type instead of the default integer, this saves you one byte for every variable. See remark below about types. I made my own types (if not existing) for int32_t, uint32_t, int16_t, uint16_t, int8_t and uint8_t and always use the smallest possible.
Use unsigned instead of signed for types that cannot be negative. This might save you one byte if you can prevent using an unsigned byte instead of a signed int because a value can be in range [128..255]. The same for unsigned int instead of signed long.
Use bit fields if you use multiple booleans inside a struct or class. Make sure the bit fields are declared consecutively.
Pack data in smart structures ... I.e. if you have two variables, where one can be 0..7 and another can also be 0..7, store this together using bit fields (in combination with boolean to bit field above).
Prevents float/doubles (see KIIV's comment below), instead:
Instead of using a float, multiply the value by the needed accuracy and store it in an integer (if you don't need high accuracy and it fits in the integer type).
In case you need a lot of strings to be stored, and those strings do not have characters above 128, you can save 1 bit per byte, of course this means quite some programming work to handle 7 bits 'ASCII' characters.
The same, if you have to store a lot of values that can be e.g. 0 to 50, you can use 6 bits instead of 8 bits; you cannot use bit fields, but you can make a smart array and program your own get/set functions to access the 6 bit values.
If you use libraries which declare big buffers, try to minimize those buffers, this might cause to copy them and manually change them yourself.
Prevent your own buffers to be made global, instead use them as a local variable temporarily when you need them. If you have two of such buffers, you don't have both buffers allocated at the same time; note however, that during execution, that buffer still needs space (so you have to calculate or make a guess/estimation what the maximum stack size will be).

Flash Reduction

Don't use duplicated code blocks, but make functions with parameters to differ between the differences of the duplicated code.
Instead of lookup tables, create a function that calculates it (if possible). Of course the gain depends on the length of the lookup table and the length of the function.
Instead of debugging strings, use numbers.

Both SRAM/Flash Reduction

Split your application over multiple MCUs, of course this adds some kind of communication protocol (UART, I2C, SPI).


Can Only Upload Arduino Sketch Once to Custom Mega2560 Board

Your RESET circuit is wrong.

You have no pullup resistor on the RESET pin of the ATMega3560.
You have an extraneous pulldown resistor on the D7 pin of the 16U2.

That means your 16U2 will not be able to trigger a reset of the ATMega2560 to run the bootloader.
Remove the pulldown on D7 of the 16U2 and add a 10kΩ pullup to the RESET pin of the ATMega2560. Without that pullup:

The chip may not run properly as RESET is floating (it may have an internal pullup, I can't recall)
The capacitor linking the 16U2 D7 and RESET of the ATMega2560 won't be able to generate a proper reset pulse. This will be exacerbated by the 1kΩ pulldown.

On the Mega2560 reference schematic RN1A is the pullup in question.


Controlling ceiling fan speed using Arduino

Or is it something completely different?

fairly easy to do.

approach 1 is phase based, like a typical dimmer. your arduino needs to detect zero crossing and control a triac. fairly common.

approach 2 is simpler but less common: put a mosfet inside a bridge so it can control an ac load. apply pwm to the mosfet and you are done.


Reading updated serial data from ESP8266

Thank you everyone I had to just clear the response string every time.

I have just added response = ""; after the Serial.print(currentLikes);


Your code is currently written as blocking, so we can leave it that way and add another blocking nested loop. Let's take the colorWipeUP() function as example:

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

You go through all leds, lighting them up one after another with the provided color, delaying between the LEDs. The brightness of an LED is controlled by the overall RGB value. If you just multiply the RGB components red, green and blue with a number between 0 and 1, you (mostly) keep the color and only control the brightness. For example like this:

void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 0; i < NUM_LEDS; i++) {
    for(uint8_t brightness = 0; brightness <= 100; brightness++){
      setPixel(i, red*brightness/100, green*brightness/100, blue*brightness/100);
      FastLED.show();
      delay(fadeDelay);
    }
    delay(SpeedDelay);
  }
}

For every LED we are now going from zero brightness to 100% brightness in a loop, showing each individual step on the LED strip.  fadeDelay determines, how fast this fade in should be. You will have to tune both delays to fit your expectations. You can use the same principle for the wipe down.

You may be asking yourself, why I count from 0 to 100 and then dividing by 100 instead of directly counting from 0 to 1 in steps of 0.01. I've done this, because on AVR based microcontrollers you don't have native floating point calculations. This means, that every floating point calculation needs many instructions to execute (because the floating point math is implemented in software instead of hardware). Here I'm counting with integers and when calculating the brightness also only integer math is involved (dividing by 100 is an integer division, which will automatically cut all digits after the decimal point. We don't need them).

Note: With 300 LEDs, the call to FastLED.show() will take some time. I haven't tested the code, but depending on your needs the fading might be too slow, even when you remove the delay call. Then you can simply increase the increment of the for loop, for example to use 10 steps instead of 100:

for(uint8_t brightness=0; brightness<100; brightness+=10)

  something like a fade over 10 LEDs

For this I would use a totally different approach. If you view it mathematically, the brightness of each LED is a function of position and time. So we can implement a function much like a mathematical function, that returns the brightness for a given position and a given time. As I understood, you want the a function, that is first constantly zero, then it grows linearly with time and position and then it is constantly full brighntess. We can count the time from the moment, that the sensor is triggered, where we then start with zero brightness and let it rise linearly. Something like this:

int fadeBrightness(int position, unsigned long time){
    int brightness = m_p*position+m_t*time;
    if(brightness > 100) return 100;
    if(brightness < 0) return 0;
    return brightness;
}

m_p and m_t are constants, that you would need to define and fine tune. For fading over 10 LEDs, m_p has to be -10. time is provided as milliseconds. I'm currently not sure about the value of m_t, but you can simply try some values and use one that's fitting.

Then in your colorWipeUP() function you can loop through all LEDs and set their pixel just like in the code above, but this time you use the newly created function.

void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  unsigned long timestamp = millis();
  while(millis()-timestamp < duration){
    for (uint16_t i = 0; i < NUM_LEDS; i++) {
      setPixel(i, red*fadeBrightness(i, millis()-timestamp)/100, green*fadeBrightness(i, millis()-timestamp)/100, blue*fadeBrightness(i, millis()-timestamp)/100);
    }
    FastLED.show();
  }
}

You need to define the duration according to how long the fading will take with your m_t. If you set it longer, the loop will just loop longer, holding the brightness at 100%.

In the function we first create a timestamp from the millis() function. Then we loop, while the duration of the effect hasn't passed. In each while loop iteration, we set the color components of each LED pixel with the brightness according to our fadeBrightness() function. Then we show this on the LED strip. The function is constantly updating the strip at max speed. The actual speed of the animation is determined by the fadeBrightness() function.

This version is also blocking code, but it can easily be transformed to non-blocking code, that you would call repeatedly until the animation is done.


Arduino ADC Reference Voltage if it is Battery Powered

... won't the ADC reference voltage constantly be dropping with the battery?

Yes, which is why you either use or measure an internal bandgap reference instead.

Use the analogReference() function to select a reference appropriate for the board in use. Note that you will need to use a voltage divider to reduce the battery voltage to a value below that of the selected reference if you wish to measure it.

To measure the bandgap voltage instead (using AVCC as a reference and working "backwards") you will need to set MUX[3:0] in ADMUX to 0b1110 and then perform an ADC reading directly (set ADSC in ADCSRA and wait until it resets, then read from ADC[H:L]).

As always, see the MCU datasheet for details.


avr/io.h No such file or directory error when compiling using avr-gcc

I’m guessing you started with the toolchain Arduino put on your machine.

Try explicitly including the header files on the include path with the -I switch.

avr-gcc -mmcu=atmega328p -I /path/to/avr/include -o main.out main.c

Just search for the io.h file. It should be somewhere close by to where you found the compiler.


Does lowering arduino analog reference increase precision in measuring low voltage?

The former, i.e precision would now be 1/1023 but the accuracy of the AD converter is 4 / 1024 or 1 part in 256  i.e. 0.25%.

Also be aware that the internal reference voltages themselves are not very accurate :

DEFAULT: depends on your computer power supply USB2  Vbus = 4.4V - 5.25V, Vint 1 = 1.1V  actually 1.0 -- 1.2V, Vint 2 = 2.56V  actually 2.4 -- 2.8V


Can the arduino be recognized if the usb chip is broken?

It depends on the exact arduino product. An Arduino Uno has a USB programmer chip, that then programs the AtMega 328 Chip. If the programmer is broken, it will likely not register any device when you plug in an arduino uno to your PC.

if the micro-controller is dead, but the programmer is operational, you will get a device in your device manager, but not be able to reprogram the micro controller.

If both the programmer, and the micro-controller are broken, then figuting that out could be difficult. The AVR microcontrolers support other programing methods, and the AtMega 328 IC, supports DebugWire. you could attempt to reprogram the MCU out side of the programmer, if you thought the programmer, was defective.

Here is a great article on using DeBugWire.
https://awtfy.com/2010/02/21/modify-an-arduino-for-debugwire/

another nifty trick I learned, is to take your Digital MultiMeter, set it to diode test, or continuity. then, measure between the ground pin, and the positive voltage pins on the MCU.  If you get a shot, the chip is busted. You will expect to get roughly 0.7Volts, although an OL reading might indicate more about your multi-meter, than the MCU.

Other Arduino devices, that have integrated USB programing, may behave differently. Features of the specific MCU dictate how it can be debugged. You might want to read the datasheet for a specific MCU if you're having trouble.


What you're doing wrong is that you're using the wrong compiler. That syntax is for CodeVision or mikroC, but the Arduino IDE uses GCC. Which follows global standards rather than making syntax up.


Can I reuse crystal frequency of Arduino?

Yes but you need to know what you are doing.  You will need a clock driver and possibly a clock receiver depending on the devices you select.  Then you need to modify both boards voiding any possible warranty.

The best answer is NO!


How to access variables by variable? (I.e. variable variables?)

No, you can't do that sort of thing. That sort of thing is only possible on interpreted languages where the name of the variables is seen at runtime.  In compiled languages you can't see the variable names (they no longer exist) so you can't access them by name like that.

Instead you need to either store your variables in a simple array and access them by index, or create an array of "key/value" pairs (simplest to use an array of a struct) and iterate it looking for the right key to match with your input.  Or, if there aren't too many inputs, simply use a switch to select different values:

int getval(char input) {
    switch (input) {
        case 'a': return 17;
        case 'b': return 42;
        case 'c': return 50;
        default: return 0;
    }
}


Not able to find right library for MPU9250

In the Arduino IDE, click on SKETCH > INCLUDE LIBRARY > MANAGE LIBRARIES.

Then, search for 9250, select the SparkFun one, and click INSTALL.

Finally, from the examples, choose the MPU9250BasicAHRS_I2C.


Most efficient method to turn a gear extremely slowly?

Steppers require current - and power, due to I^2*R losses) to hold a position. Power off, they free-wheel. What kind of efficiency do you need? A stepper might not be the most power efficient.

An escapement permits or causes a gear to index one position and prevents it turning any farther. In a clock, it permits a weight-driven or spring-driven shaft to index. You'll probably want one that drives the shaft as well, probably with a solenoid.

Another option that comes to mind and doesn't need an Arduino, is a clock motor. Gear down the hour hand 2:1 and you're done. Find a 24-hour clock motor and even that gearing will have been done for you.


Can't upload to Arduino Mini via Arduino USB 2 Serial Converter

The Arduino USB 2 Serial converter was defect (even though brand new). I bought a cheaper (7 Euro) FTDI to USB and I can now upload.


Have you read the Servo library page?

The library support upto 12 servos outputs. You can use any pin you want.

The library disables analogWrite() (PWM) functionality on pins 9 and 10.


loop() either stops working, or lcd stops working | buttons don't work

The buttons will send a LOW signal when pressed if they are set with pinMode INPUT_PULLUP.

The issue with currentNumber not displaying is that after you clear the screen with the 'for' loop, you need to reset the cursor to position 0,1 with lcd.setCursor(0,1); . Otherwise, the numbers are printing out of view.

If I add lcd.setCursor(0,1); just above each line with lcd.print(currentNumber); , I think the code has the behavior you're looking for.

Edit from the person who asked the question:
 You also have to add a delay of around 150-200, or else one push will count as many.


How can I scan for a HIGH signal on digitalRead during the main loop, while running other things?

Simplify, and show your setup code.

First, do you have a pinMode call in your setup function:

void setup() {
  pinMode(A15, INPUT_PULLUP);
  Serial.begin(115200);
}

Then use test code like this:

void loop() {
   if (digitalRead(A15) == HIGH) {
      Serial.println("Pin A15 is HIGH");
   } else {
      Serial.println("Pin A15 is LOW");
   }
}

Connect your A15 pin directly to ground with a jumper and run the sketch above. Open the serial monitor and see what is output. It should be LOW. Then disconnect the jumper and check again. It should now be HIGH. Finally, connect the jumper between A15 and +5V and check the output again. It should still show HIGH.

That lets you troubleshoot just the software piece. Once you get that working, connect pin A15 to the remote Arduino's output pin and try again.


This relay is designed to operate on 5V.

Most commonly this will come from the Uno's 5v pin.

If you want to externally power the relay itself then make sure to connect the +5 to the Vcc on the relay board and the - lead to the GND on the relay board.

Uno's GND must also be connected to the GND on the relay so the Digital outputs from the Uno will properly control the IN1 and IN2 inputs to the relay board.

The Uno has multiple GND connections so it makes the most sense to connect the - to one of them then another to the relay.

Note that the Uno's 9V Vcc external power comes in through the barrel connector on the Uno itself. The Uno will pass power through its internal regulator to provide 5v at the appropriate connection.

If you are switching external devices that run on 120V it would be on the screw-terminal side of the board only.

  To prevent accidental activation of the relays, note that this particular board is ACTIVE-LOW which means that as you initialize the output pins you should first set them HIGH so setting the pinMode will not default to LOW which would trigger the relay.

In the setup() section, using pins D5 and D6 as an example:

digitalWrite(5,HIGH); pinMode(5,OUTPUT);
digitalWrite(6,HIGH); pinmode(6,OUTPUT);


Use Arduino pro micro to program pro mini?

I don't know if it will still work but I will suggest you this.
As arduino micro is Leonardo compatible and you r two arduino minis are based on atmega328. You should be able to use the tutorial posted above to use micro as programmer for the two mini.
Hope that helped.


Connecting the grounds together is required since without that there would be no circuit for the current to flow through.  Take this simple block diagram for instance:

In the top diagram there are two complete circuits - the green one (Arduino's 5V power) and the blue one (device's 12V power).  The communication between the Arduino and the Device can't happen because there is no circuit (red).

In the bottom diagram the red circuit has been completed by joining the grounds together.  That means that the current has some way to get back to where it came from (which current always has to do) so the signals you send can actually get through.

To avoid having to connect the grounds together you need something called Galvanic Isolation.  This involves using some method that is not electricity to connect the two circuits together.  That could be using light in the form of an opto-coupler, or magnetism in the form of a transformer, or even something even more physical like a relay.  In that situation you have an arrangement like this:

The ground connection that was part of the red circuit above has now been sliced in half (red and orange now) and the isolation device is responsible for passing the signal from one side to the other.

Galvanic isolation is highly desirable when:

You are controlling a different type of current (e.g., using DC to switch AC)
You are working with voltages considerably higher than your drive voltage (e.g., switching mains)
You have different ground potentials (e.g., you have a long distance connection)


How to on/off light dimmer using another pin?

Finally I find out solution. Here, I detect when switch becomes pressed instead of  button is pressed. So, for that I used StateChangeDetection. So while loop just removed from code. And I made function to perform dimmer and vise versa operation.
k
So, now I'm able to ON/OFF the PWM pin. And also vary PWM pin. Thanks everyone for your effort.

Here, it's my full code.

const int buttonPin1 = 2;
const int buttonPin2 = 3;
const int buttonPin3 = 4;

const int pwmPin = 9;

const int onOffPin = 10;

int buttonState1 = 0;
int lastButtonState1 = 0;

int buttonState2 = 0;
int lastButtonState2 = 0;

int buttonState3 = 0;
int lastButtonState3 = 0;

int buttonPushCounter = 0;

int onOffCounter = 0;

void setup()
{
   pinMode(buttonPin1, INPUT);
   pinMode(buttonPin1, INPUT);

   pinMode(pwmPin, OUTPUT);

   pinMode(onOffPin, OUTPUT);

   Serial.begin(9600);
}

void loop()
{
   buttonState3 = digitalRead(buttonPin3);

   if(buttonState3 != lastButtonState3)
   {
     if(buttonState3 == HIGH)
     {
       onOffCounter++;
       Serial.println("Button 3 on");
       Serial.print("number of button 3 pushes:  ");
       Serial.println(onOffCounter);
     }
     else
     {
       Serial.println("Button 3 off");
     }
     delay(50);
   }

   lastButtonState3 = buttonState3;

   if(onOffCounter % 2 == 0)
   {
     Serial.println("Switch is OFF");

     analogWrite(pwmPin, 0);
   }
   else
   {
      PWM_fun();

      Serial.println("Switch is ON");
   }
}

void PWM_fun()
{
  buttonState1 = digitalRead(buttonPin1);

  if (buttonState1 != lastButtonState1)
  {
    if (buttonState1 == HIGH)
    {
      buttonPushCounter++;
      Serial.println("Button 1 on");
      Serial.print("number of button 1 pushes:  ");
      Serial.println(buttonPushCounter);

      if(buttonPushCounter > 4)
      {
         buttonPushCounter = 4;
      }
    }
    else
    {
      Serial.println("Button 1 off");
    }
    delay(50);
  }

  lastButtonState1 = buttonState1;

  buttonState2 = digitalRead(buttonPin2);

  if(buttonState2 != lastButtonState2)
  {
    if(buttonState2 == HIGH)
    {
      buttonPushCounter--;
      Serial.println("Button 2 on");
      Serial.print("number of button 2 pushes:  ");
      Serial.println(buttonPushCounter);

      if(buttonPushCounter < 0)
      {
         buttonPushCounter = 0;
      }
    }
    else
    {
      Serial.println("Button 2 off");
    }
    delay(50);
  }

  lastButtonState2 = buttonState2;

  switch (buttonPushCounter)
  {
      case 0:
              analogWrite(pwmPin, 0);
      break;

      case 1:
              analogWrite(pwmPin, 64);
      break;

      case 2:
              analogWrite(pwmPin, 128);
      break;

      case 3:
              analogWrite(pwmPin, 192);
      break;

      case 4:
              analogWrite(pwmPin, 255);
      break;
  }
}


Can I program a 20MHz Attiny85 with the 8MHz Internal Clock option in the Arduino Software?

I think you have the wrong end of the stick here. The Attiny85 is not a chip that comes in different speed versions. The datasheet mentions that it can run at 20 MHz. That doesn't mean you can buy a "20 MHz version". By selecting the appropriate clock option in fuses you can run at 20 MHz (or higher). From the datasheet:

  High Frequency PLL Clock

  There is an internal PLL that provides nominally 64 MHz clock rate locked to the RC Oscillator for the use of the Peripheral Timer/Counter1 and for the system clock source.

  I believe these to be pre-set from the factory for the various clock options - but will it matter when I try to program them with the Arduino software?

That list is weird, it doesn't specifically say they are pre-set to any speed. Personally I would regard that list as meaning that the higher speed ones are manufactured to better tolerances, if indeed it means anything at all.

Maybe when they manufacture them they do a quick test at various speeds, and ones that don't run at 20 MHz are put into a different batch.

The datasheet specifies the default clock settings, it would be weird if Atmel made them with different settings unless you placed a massive order.

As for programming them, by default they don't come with a bootloader, so you would need to use ICSP programming anyway. You would need (in any case) something like the AVRISP device (which connects via USB to your computer, and the other end goes to your chip to be programmed). Or you can make up something like my AVR hex programmer which lets you put a hex file from the IDE onto a MicroSD card, and then use that to program the ATtiny85.

In all of these cases you can change the fuses to do what you want, including the clock options you prefer.

There is a board you can buy which is a pre-made gadget using the code I mention above, where you just press a button and the chip is programmed, which would be helpful if you are doing a lot of them.


ESP8266 Stops Working After A While (Unknown Problem)

I have had the "stops after a while" too and it turned out to be heap memory consumption and fragmentation that caused not having enough stack and heap space any more.

My solution: check the heap from time to time (in loop) and reboot the node when it comes down to a practical limit.

Alternate: avoid using the String type and other Heap usages.


If a condition is ever met I want to run a loop permanently

This may be unrelated to the actual question but... your Morse timings
are completely messed up. The standard timings are:

element         duration
------------------------
dot                 1
dash                3
interelement gap    1
intercharacter gap  3
interword gap       7

where the time unit is the duration of a dot. A correctly timed SOS can
be implemented as follows:

const uint32_t DOT_TIME = 150;  // 8 words per minute

void dot() {
    digitalWrite(2, HIGH);
    delay(1 * DOT_TIME);
    digitalWrite(2, LOW);
    delay(1 * DOT_TIME);
}

void dash() {
    digitalWrite(2, HIGH);
    delay(3 * DOT_TIME);
    digitalWrite(2, LOW);
    delay(1 * DOT_TIME);
}

void send_sos() {
    dot(); dot(); dot();
    dash(); dash(); dash();
    dot(); dot(); dot();
    delay(6 * DOT_TIME);  // interword gap
}

Notice that there are no intercharacter gaps within SOS, as this is a
procedural signal, transmitted with no letter boundaries. It
is not a three-letter word. The last delay is written as
6 * DOT_TIME as there is already a one DOT_TIME delay at the end of
the function dot().


How do I know when filter coffee machine is finished by using any sensor?

Just two ideas, both non-invasive:
The machine moves water from the reservoir at the back to the coffeepot at the front of the machine, so its weight distribution will change while making coffee.
If you put a thin pressure pad (like this one, or something similar) under the whole machine at the back you should see the pressure at that point become smaller while coffee is being made.
If the effect isn't pronounced enough, you could make the whole machine tilt forward while making coffee by putting a narrow and thin strip of plastic under its centre from left to right so it can swivel forward and back just a little depending on the location of the bulk of the water.
If the pressure on the pressure pad at the back stops dropping, the coffee is ready. You can also detect when the coffee can is empty again this way, or maybe even how many cups of coffee are still available in the coffee can.
Or maybe you could detect with a contact microphone when the machine goes silent, assuming it makes sufficient noise when making coffee. Mine does.


Wire.requestFrom(kClockAddress, 7); // request seven bytes of data

Just because you request 7 bytes doesn't necessarily mean you get them. I suggest before reading the date and time you set all those variables to something invalid (like 0xFF). Then after reading, if you get 0xFF in any of them, ignore the entire lot.

  we are sending a start bit again, when we never sent a stop bit previosuly. ... Does this sound reasonable

Not really, because I2C doesn't have start and stop bits, it has start condition and stop condition which are specific changes to SDA and SCL which don't happen at any other times. See I2C for a description. I would be checking the data for validity, as I said. There is no other way of knowing for sure that a transmission wasn't interrupted. If you request 7 bytes of data, the library tells you that you got 7, even if you did not. However if it cannot even find the target device, it returns 0 as the number of bytes (you aren't testing for that anyway).

The very least you should do is test for a valid connection, eg.

if (Wire.requestFrom(kClockAddress, 7) == 7)
  {
  // read the data
  }

That at least confirms that the clock chip responded in some way. Not checking error returns from function calls, where documented, is not wise.

Similarly when you send your command.

  Wire.endTransmission();

That should be:

if (Wire.endTransmission() != 0)
  {
  // handle error here
  return;
  }

You have no tests in your code for either the sending or receiving to be working. And then you are unconditionally using the resulting time values. That's like opening a file, and reading it, without checking if the file exists.


How to Implement Simple, Quick HMAC on Arduino

I ended finding a Arduino library called Spritz which can be found here:
https://github.com/abderraouf-adjal/ArduinoSpritzCipher

Also, for anyone else who comes across this task, here is a very simple Hashed Message Authentication Code (HMAC) example I scrapped together:
https://github.com/zach-king/ArduinoStash/blob/master/src/Spritz_HMAC/Spritz_HMAC.ino

This library supports encryption as well, which is nice, but not needed in my case.

--EDIT--
The SpritzCipher library was actually too slow (about a 50% reduction in network speed) so I must try a different approach. I have found a MD5 library for Arduino which I will try next:
https://github.com/tzikis/ArduinoMD5


How do I send an arduino PIN state to a local PC using the ethernet connection?

The simplest method is to set up a web server on your PC.  You haven't mentioned what OS you run (which is kind of critical), so looking into WAMP or LAMP ("Windows/Apache/MySQL/PHP", or "Linux/Apache/MySQL/PHP") is probably your best option.

Once you have a working web server you can pretty much use verbatim the Ethernet examples for connecting to a remote website ("Web Client").  That website would be your local PC address, and you send whatever parameters you want.

You then write a small PHP script (or whatever language you program your chosen web server in) to accept that web request and process it accordingly.

In general you never need to explicitly send the IP address since it is encapsulated as part of the actual socket connection information and is generally made available through various means to your web page (see $_SERVER in PHP for example).

If you want to get more "low level" and lighter weight then you would most likely be looking at writing a UDP server on your computer which receives UDP requests from the Arduinos and processes them as needed.  The content of a UDP request is entirely up to you, but programming a server for dealing with it is beyond the scope of an answer here - suffice it to say there are plenty of resources online available for all the major operating systems and programming languages on how to write UDP servers.


When you send 'buf', how do you know that buf[0] is transmitted first and buf[1] is transmitted second ? Not long ago a bug in Wire library was fixed and it is now allowed to use multiple Wire.send() in the requestEvent() function. I suggest to send two bytes in sendSensor() in the Slave without using the 'buf'.

When you request the Slave addres, you send 0x55. That is not the Slave address. Do you receive 0x55 ?

It is not needed to remove pullup resistors from the analog input pins. It is also not needed to set the pinMode for those pins. You can use analogRead() without something else.

Did you connect the GNDs ? And did you connect SDA to SDA and also SCL to SCL. Which Arduino boards do you use ? Do you know that you can start the Arduino IDE twice, each connected to a board and each with its own serial monitor. That way you can work on both sketches at the same time.
As soon as the Slave is running with Wire.begin(8), the Master can run a i2c_scanner and it should find I2C address 8. That is the first test to verify that the I2C bus is working.


Even this is quite old, to help others as well:

As you already did, pin 13 (output enable, active low) to ground and pin 10 (master reset, active LOW) to HIGH, to disable reset.


NODEMCU 1.0 HX711 Load cell reading weird text

Try D1 instead of D3. D3 is io 0, a boot configuration pin with pull-up on board.


externally powering the Arduino questions

I am guessing that you are thinking of dividing down the battery voltage from 7.2V down to 7.2*(4.7)/(4.7+1.5) = 5.5V. This is generally a bad idea for a few reasons.

The battery voltage will not be a constant 7.2V. When they are fully charged it could be even higher. As they discharge they could drop significantly and your Arduino POR (power-on-reset) circuit would potentially shut the board down before the batteries are fully discharged
The batterys' internal resistance would probably drop the output voltage considerably once the resistors try to draw 1A of current. It might even collapse the voltage to some unusable value.
Even if the battery internal resistance is very low and even if the Arduino is not drawing much power (or even off) you will always be drawing ~1A of current from the batteries. This will rapidly drain your batteries and will also heat them up from their internal resistance. Not to mention your external resistors better be able to handle > 5W or so. Conclusion: lots of unnecessary heat and power loss.

To answer your other question, assuming the servo is low power and the Arduino power supply is up, you could power it from the Arduino 5V supply (not your batteries).

If you need to use batteries to power an Arduino, I would highly recommend a power regulator to produce a stable output voltage to power your Arduino.


Reading sensor data, massaging it and performing operation based on transformed data

Here's a back-of-envelope sketch, off the top of my head:

Conveyor belt driven by stepper motor, controlled by the Arduino.  Each step is a known distance.

Bottles are either of exactly two heights, at random.  Two beam break sensors, one to determine where a bottle starts and one to determine whether it's tall or short.

Some sort of valve to control the water flow - I presume you have some idea how this can be controlled.  I don't, but washing machines have electrically-controlled valves so something broadly along those lines.  Controllable on/off by the Arduino.

Software on the Arduino steps the motor until it sees the start of a bottle (first beam broken).  Then uses second beam to determine whether the bottle is large or small.

Arduino switches on the water valve (outlet positioned exactly right to be above the bottle) for either 2s or 4s accoriding to bottle size, then off again.   (Water pressure and flow rate regulated independently, perhaps fed from a header tank).

Arduino steps motor more until it sees another bottle.

No string concatenation in there, nor sorting of lists or need for a Raspberry Pi.  It's not clear to me why you'd need those things for the application described.

I'm not aware that you can program the Arduino in Python unfortunately.  Someone may know better.  C isn't hard though - get an Arduino and some LEDs or whatever, go through some tutorials, you'll get the hang of it.


Arduino : send data via satellite (or other solutions ? without GSM)

My two cents: A possibility might be LoRaWAN on the 2.4GHz spectrum, for which there are also satellites in orbit.
The LoRaWAN ("Long Range Wide-Area-Network") protocol is based on a chirp-spread-spectrum (CSS) modulation and has a very high range.
I've used LoRaWAN before but not on 2.4GHz or with a satelitte, so I can't comment on the practical feasibility. However, there are some materials from The Things Conference (by The Things Network, a leading developer of LoRa network servers).

https://www.youtube.com/watch?v=iwocSYupdIQ
https://www.youtube.com/watch?v=jlNyBDxpKUw
https://enterpriseiotinsights.com/20190618/channels/news/lora-shoots-for-75pc-of-iot-market
https://enterpriseiotinsights.com/20200130/channels/news/lorawan-enters-2-4gh-plus-satellite-boost-network-sharing-embedded-security
https://www.semtech.com/company/press/semtech-and-swarm-deliver-satellite-communications-with-lora

Also maybe other modules that can talk to the Iridium satellites suite you better. Sparkfun has a few

https://www.sparkfun.com/products/13745
https://www.sparkfun.com/products/16394


First off I cannot say much about the library that you are using I have't tried that one yet as for the shield i have some of those and there are two versions of them check your PIN outs on them the cs pin is either on d9 or d10

the other thing is make sure that you are in the right operation mode ie. Normal and maybe give this library a try I have had lots of success with this one:
https://github.com/coryjfowler/MCP_CAN_lib

as for the baud rate I have tried all types of ways of getting the right baud rate for certain vehicles but the best remains start small and step it up till you get the one that gives you reply

make sure that you ground the Arduino to the car as well it works without that but sometimes it does nothing If you are using the OBDII cable it should be grounded by default


How to stop Arduino from drawing power through USB

If you provide power to the Arduino through Vin this will disconnect USB power through the MOSFET switch.


I/O expander with i2c interface vs Multiplexer

The MCP23017 gives you 16 extra real IO pins. Each one has facilities such as pull-up resistors, change notification interrupts, etc - the kind of things that you expect from real IO pins. You can read and write to all of the pins.

A multiplexer though just feeds signals through to the existing pins. They're pretty dumb. Only the signal that is currently fed through can have anything done to it. So only one signal can have a value written on it or read from, and pullup resistors and interrupts are non-existent.

However the CD4067 can be used with signals other than digital - as such they are good at being a multiplexer to the analog inputs, something an IO expander can never do. You could, though, use an I2C ADC chip for that.

For high speed IO control you really want to be using the MCP23S17 instead of the MCP23017. It uses SPI instead of I2C and thus is much faster to control.


What is a faster alternative to parseInt()?

The annoying thing about parseInt() is not its speed, it's the fact
that it relies on a timeout. If the timeout is too long, it slows you
down. If it's too short, it may induce errors.

A safer way to parse the sort of messages you are using is to buffer all
the incoming characters until you find a carriage return, then parse the
whole line. For example:

// Just echo the messages with a different separator.
void parse(char *buffer)
{
    char *s = strtok(buffer, ",");
    int x = atoi(s);
    s = strtok(NULL, ",");
    int y = atoi(s);
    Serial.print(x);
    Serial.print(':');
    Serial.println(y);
}

void loop()
{
    static char buffer[BUFFER_SZ];
    static size_t lg = 0;
    while (Serial.available()) {
        char c = Serial.read();
        if (c == '\r') {        // carriage return
            buffer[lg] = '\0';  // terminate the string
            parse(buffer);
            lg = 0;             // get ready for next message
        }
        else if (lg < BUFFER_SZ - 1) {
            buffer[lg++] = c;
        }
    }
}

Note that you should add some error checking when you call strtok().


Only pins that support PWM support analogWrite() fully. 3, 5, 6, 9, 10, and 11 do. The rest do not.


The back light of the LCD is just an LED connected through a resistors on the A (15) and K (16) pins on the display. The LED doesn't require an external resistor since according to the datasheet there is a build in resistor on the board itself. If you aren't using any external resistors and applying a constant voltage of 5V and the screen is still dim than this means that the led is most likely dead and you would need to replace the back light panel.

If you are talking about the contrasts of the display. Than I would recommend you to hook up the contrast pin to a PWM pin on the Arduino and by using analogWite to tune the display in order to get the desired value of contrast.


Serial.println(): Where is the text printed?

The IDE on your computer has a menu item under the tools menu called "Serial Monitor." On my Mac, at least, it is indeed a black area under the source editor for the current sketch.

It won't work unless you call the Serial.begin() function in your setup method before the first Serial.print()/println()/write() function call.

Something like this:

//Set up the serial port @ 9600 baud for display back to the computer
Serial.begin(9600);
delay(25);
Serial.println("Hello world!":);


Communicating Arduino with Intel Galileo

You could use SPI/I2C as interface between Arduino and Galileo.
They are better than plain serial.


ESP8266 NodeMCU 3v3 current for fingerprint sensor

Be careful using Vin on the NodeMCU for 3.3V devices! If you are powering it by 5V USB power, this Vin pin will probably have something like 4.76V on that pin. The circuit diagram shows that Vusb is connected to Vin with just a schottky diode, which drops the current about .34 volts and provides some noise isolation from the Vusb supply. If you connected a 3.3V device to this pin at 4.76V, you may have damaged your component.
You'd have to check the datasheet or documentation for the fingerprint module, but it sounds like the fingerprint module will only draw 60-70mA when it's given 3.3 volts. Datasheets often provide application examples and may specify that you do need additional resistors, capacitors, etc. The refrain in cases like this is always read the datasheet.
If your NodeMCU datasheet says it can provide 400mA then it should certainly be able to provide the 60-70mA that the fingerprint sensor needs. I've powered an ESP8266 by connecting its Vin pin to the Vin of another NodeMCU and they seem fairly happy together, although there tends to be quite a bit of noise on the Vin pin.


Arduino split comma separated serial stream

The reference article, that you linked to, is about sending data over Serial, not about reading.
You can use the strtok() function, which can split a character buffer into tokens based on a delimiting character (the comma in your case).
First you have a buffer, where your Serial message in saved (I'm not covering the actual receiving/reading of the Serial data here, because there are tons of tutorials on the web):
char buffer[] = "1,2.3,4,0x56";

Then you can get the first token:
char *token1 = strtok(buffer, ",");

token1 is a pointer to the start of the token. strtok() replaces the found delimiter (which you specify with the second parameter) with a null character. That means, that token1 points to a null terminated C string with only the first token in it (Keep in mind that the buffer is changed with that, so it does not make any sense to try printing buffer after you used strtok()). Note, that this does not create a new buffer. It simply points to a specific place inside buffer.
You could also directly process it, for example convert it to an integer:
int token1_value = atoi(strtok(buffer, ",");

To get the next token, you simply again call strtok(), but now you provide NULL instead of buffer in the first parameter. That tells strtok(), that you still want to process the same buffer from the last execution.
float token2_value = atof(strtok(NULL, ",");

You can now do this, until no token is left unprocessed in the buffer. In that case strtok() returns NULL.
char *token = strtok(NULL, ",");
while(token != NULL){
    Serial.println(token);
    token = strtok(NULL, ",");
}

Have a look at the C++ reference for strtok(). It also includes an online editor, where you can run the provided example and play with it.


Have a look at the first several links from googling for Arduino and my Beaglebone black through SPI.  Here are a few comments on those first few links:

• SPI - Beaglebone Black Master Arduino Uno Slave (forum.arduino.cc topic 446924.0) – This page asks your question in more detail, and includes Beaglebone master code and Arduino Slave code.  However, the poster makes an egregious error in the Arduino code by saying Serial.println("SPI"); within the SPI interrupt service routine.

• Communicate Beaglebone Black and Arduino via SPI
(ulasdikme.com) – This page addresses your question in rather more detail, and apparently shows working code.  It also explains how to enable SPI in the Beaglebone device tree.  Note, this poster too makes an egregious error in the Arduino code by saying Serial.println(c); within the SPI interrupt service routine.

• SPI communication: BeagleBone Black (as Master) to 4 Arduinos (as Slaves) (adurthi.com) – This page covers level shifting and device tree setup and provides ok code.  It seems to cover BeagleBone concerns nicely, and has ok Arduino code as well.

One or two of the above also make reference to Nick Gammon's excellent SPI pages:

• SPI - Serial Peripheral Interface - for Arduino (gammon.com.au forum id=10892) – This page is where you should start if you have questions about how SPI works.  After you are familiar with SPI basics, scroll down to the “How to make an SPI slave” heading, and set up the master-slave example with two Arduinos.  When you have that working, you can substitute or add a BeagleBone as master.  Other code examples further down the page include  “How to get a response from a slave”, slave SS pin interrupt examples, SPI via USART, speed settings, SPI on ATtinys, sending data structures, and (under the heading “SPI under IDE 1.6.0 and later”), exegesis of SPI library methods.

• Debugging using SPI/I2C and a second processor (gammon.com.au forum id=11329) – This page illustrates master-slave communication between two Arduinos, using one as a slave to forward information sent from a system being debugged.  Also illustrates use of I2C for similar purpose.  Note, Debugging The Arduino With The SPI Interface Instead Of Serial.println() (utopiamechanicus.com) is a follow-on article, by another author, about this debugging technique.


Controlling servo with IR led and photodiode

Yes that is possible.

Start by googling for the two halves of your project separately. Find a project, example or tutorial which controls a servo. Get it working. Understand it.  Then find one which deals with a sensor similar to the one you want to use, get it working, understand it.

Then you'll have everything you need to get your project up and running.


The Arduino Uno uses the Atmel Atmega328p microcontroller, which only has one debug option, DebugWire.  There are a few tools that can work with it, but the least expensive and most commonly available is the AVR Dragon.

You can use AVR Studio 6 for this.  You can use the .elf file file produced during the Arduino build process directly, but setting up the debugger is a little easier if you port the Arduino program to the AVR Studio.  It's not difficult, but there are a lot of little pieces to deal with.  There are guides online to help you through this.


Can I use GSM and Data Logger Shield at the same time on one Arduino?

It depends, but high likely yes.

The sensors, GSM and Data Logger may use the I2C, SPI, analog pins or UART (last not likely).

For I2C, the Arduino can handle many of such devices, because it is part of the protocol.

For SPI it is similar, although some cheap SD card reader for Arduino are notorious not being compatible with other SPI devices. And the Arduino has only one SPI port (but can handle many SPI devices, as long as they all are capable to allow other SPI devices).

For analog pins, these are likely only used by sensors, the Arduino has 5. But there are some ways to use more sensors by polling, using multiplexers etc.


You are correct and that was the second part of the problem. The first part was that my code wasn't always retrieving every byte and this was hanging up the OnReceive function. Once I fixed that bug I found something very close to what you mentioned. On rapid device writes my handler routine didn't finish fast enough and thus could miss updates. What I did was to streamline the routine to take minimum time and that worked as the sending processor needed time between updates itself. In testing this works fine, what I did was to toggle a port pin and look at the I2C bus and that pin and could verify I was cleared out of the routine before the next update could come in. If it was close I would have gone to assembly for that routine but it turned out ok in this case. Thank you for your analysis!


Master doesn't receive the correct values in a master/slave SPI link

In slave, command is always 0. You problably meant:

void loop(void) {
    command = (digitalRead(SS) == HIGH ? 0 : 1);
}

and at ISR:

ISR (SPI_STC_vect) {

    byte input = SPDR;
    byte output = 0;

    if (command) {

        switch (input) {

            case 'a':
                //...
                break;

            case 'z':
                //...
                break;
        }
    }

     // send data back
     SPDR = output;
}

As a best practice, avoid to implement the logic within the ISR and use global volatile variables to pass state changes to the code in the main loop. Probably you will have to implement a circular buffer to receive from and send to the SPI bus...


As you have already found out, add -fexceptions to the compiler flags. This can be done by modifying the platform.txt of your Arduino IDE installation.

See https://github.com/arduino/ArduinoCore-avr/blob/master/platform.txt#L28. There is -fno-exceptions defined, so you have to remove that, too.


Why does Ethernet.begin() require a MAC address when WiFi.begin() doesn't?

The flip answer would be "because it doesn't need it…"

I think what is going on is that older Ethernet shields did not have a MAC address and it was necessary for the code to set one (and I would guess that on at least some of them you can still set the MAC address, overriding the one that is on the sticker).

WiFi cards, I would guess, are newer and the MAC address is always there, so there is no need to require you to assign it.


My Arduino freezes if power removed from the HMI

It seems that Software Serial is waiting for "high" on RX

Only a hardware solution comes to my mind

simulate this circuit – Schematic created using CircuitLab

This way Arduino RX will be released on HMI power loss

Later edit

You can also use the watchdog timer to unfreeze your code when unresponsive. It will reset the Arduino if wdt_reset() is not called in a given amount of time and you can make the cleaning you need before using Software Serial again. Here is a useful tutorial.


Need help with an Arduino project using a RTC and LEDs

Use the SQW pin on the DS3231 or DS1307 to create 1sec pulse, read it on your Arduino. There are very good libraries are available (like RTClib from adafruit).


How can I address the NodeMCU from the website?

You can't. The NodeMcu is behind the phone, behind a router, behind a gateway of the operator etc. It can access the Internet over the infrastructure routing it out, but is not visible from the Internet.

  Does the NodeMCU need to be a server or just a client?

The device should be a client and open the communication to the server by sending a request and renewing the connection if it times out. You can use WebSockets or MQTT or similar framework.


What is the maximum of bits that an Arduino can read on the digital input, which model in the Arduino range can read the most bits?

A digital input is by nature binary (i.e. a single bit). The answer to your question is therefore one bit per digital input.

The total number of digital inputs depends on the board. It ranges from Arduino Micro (which has fewest less with than 10) to Arduino Mega which has the most with more than 60).

Another possible interpretation of your question is the resolution of an analog pin (ADC). The AVR has max 10 bit resolution.

Cheers!


Serial.println Sensor Value and text in one line

You just do two Serial prints:

Serial.print("POT value ");
Serial.println(sensorValue);

The .print prints without moving to a new line, the .println moves to a new line.

If you want to be more fancy and don't mind the processing and memory overhead, you can use snprintf to format the string:

char temp[15];
snprintf(temp, 15, "POT value %4d", sensorValue);
Serial.println(temp);

You can read more about sprintf and formatting here:

http://www.cplusplus.com/reference/cstdio/snprintf/ (function parameters)
http://www.cplusplus.com/reference/cstdio/printf/ (formatting options)

Note that there is no floating point support in the standard library for the Arduino - so you can't use %f etc.


When the Arduino is in reset mode are the digital pins high impedance?

From the ATMEGAxx8 datasheet...

11.1 Resetting the AVR
... The I/O ports of the AVR are immediately reset to their initial state
when a reset source goes active. This does not require any clock
source to be running.

(bold added)
Looking over the register descriptions for the Data Direction Registers, all bits have an initial value of 0, corresponding to high impedance input.
...so it is safe to assume that all IO pins will be in a high impedance state a very short time after the RESET pin goes low.
Caveats:

The clamping diodes are in-circuit even when pins are in high impedance state, so current will flow if the voltage on the pin is higher than Vcc or lower than Ground (at least until the diode blows up!).

Some Arduino pins are connected to other things besides just the pin on the MPU. For example, digital pin 13 is connected to ground though a resistor and diode, so current will flow into it if you connect a voltage higher than the threshold for the diode. On the Uno there are also resistors on the RX and TX pins connected to the serial communications link, so current can flow there too.

The MISO pin can inadvertently become an output while RESET is held low if the Programming Enable command ($AC $53 xx yy) is transmitted over the MOSI & SCK lines. This process is described in App Note AVR910.


HC-12 modules stopped receiving, cannot understand why

For what it's worth, I manage to make them working again by playing a bit with the settings of both modules.

Using a simple test sketch I issued some AT commands to both modules; I had already tried setting them to the DEFAULT setup with AT+DEFAULT, but that was fruitless. I decided to left the mode as is (FU3), same for the serial rate (B9600), but I tried switching channel so I set both modules with AT+C002.

That did the trick, maybe was some sort of external interference, or a lack of precision in the channel settings - I just know that's a week now they've been communicating just fine and that's what matters.

So, if they fail to communicate, first try to adjust their settings, don't assume the DEFAULT ones are surely working.


non asssign variable using by for in loop() can remeber last value. what happen here?

I think you missed a compiler warning (I did, too!) - notice that you are using 'd' uninitialized. On each re-entry to the loop() function, loop()'s stack will be in the same place in memory. The for-loop doesn't initialize 'd', but the boot loader did zero RAM for your first run. 'd' happens to occupy the same memory location on each entry to loop(), so the old value (just before reset) is still in place. Since the for-loop didn't re-initialize it... :)
The fix is:
for (int d=0; d <= 32767; d++) {

Update:
That begs the question: Why did your run fail as expected, while my run appeared to execute normally? My guess is different bootloaders, one that does, and one that doesn't, initialize SRAM on a reset that doesn't result in an upload.


Can I connect 220V AC supply to Node MCU (or any arduino)pin D1 and D3 while node MCDU is power off?

No, never! 220V is way way way too much for a microcontroller. The Uno runs on 5V, the ESP8266 on 3.3V. You should never connect any more voltage than that to the microcontroller. Also you must not connect a negative voltage to the microcontroller pins.

Besides the voltage difference: You should also not connect a voltage to the pins of a microcontroller, while the microcontroller itself is turned off (meaning that it does not have the necessary supply voltage). In that case a parasite current would run through the clamping diodes, which powers the microncontroller, until the diodes get blown.

As an important side note: Don't do anything with mains power (like 220V AC), until you really know, what you are doing!!! One error and it can kill you !!!