You're overflowing your stack due to infinite recursion.

By explicitly calling loop() you are breaking the whole call stack system. You effectively have:

loop() ->
  funca() ->
    gsmtest() ->
      loop() ->
        funca() ->
          gsmtest() ->
            etc...

Instead of>

loop() ->
    funca() ->
        gsmtest()
    <-
<-

Instead of calling loop() you should use return; to "return" back to where the function was called from.

For example:

void loop() {
    if (call == 1) {
        funca();
    }
    print("waiting..");
}

void funca() {
    if (!gsmtest()) return;
    print("calling..")
}

bool gsmtest() {
    if (test == 1) {
        print("test ok");
    } else {
        print("error");
        return false;
    }
    return true;
}


It is very simple really.

Initially the Bluetooth got paired automatically with my Android, but apparently the variable transmission was not complete.

If this is the case with your module,it will be blinking with high frequency.

So here is what I did:

Hit the RESET button on HC-05 once
Go to Android Bluetooth Settings and UNPAIR HC-05
Now Pair it again by clicking on it
You will be prompted to enter password- '1234'
Open your Bluetooth Terminal and you will find your data appearing
on Android

P.S.-A 2 Hz blinking frequency on HC-05 should signify proper connection


How to get more than the 16 Analog INs on a Arduino Mega for using like 24 piezo sensors

You can customize a controllino on their page
https://www.controllino.biz/controllino-myplc/
I just looked at it and it seems you can get 24 analog outputs.

Don't know what the cost is though.


Connecting an Arduino to a servo with an external power supply

Your question is not very concise, but I'll try to hit the main points.

I'm going with the assumption that your "Arduino" is the Sparkfun Redboard. The Redboard has a current limit of <800mA (heat management on the Redboard probably lowers this number even more), as per the LM1117 voltage regulator listed in the provided RedBoard schematic, and a minimum input voltage of 7V. You won't be able to power your Arduino with the 5V2A powerbrick. If you are powering the RedBoard through the standard USB, then it will typically be limited to 500mA.

Are you sure your servo has a no-load draw of 170mA? That's really high for a servo. If it does, then I'm assuming it's a large servo that likely has a high stall current draw, so 800mA from the Redboard's on-board regulator won't cut it, nor a USB port.

To power your servo externally, wire the servo and Redboard according to the schematic below. The power supply is indicative of your 5V 2A "wall wart". It's important to note that you need to connect the ground of the the power supply to the ground of the Arduino. For controlling the servo, check out Adafruit's servo tutorial. You will also need to provide power to your Arduino via USB or a DC barrel jack with a power brick that outputs >= 7v.


esp8266 + octocoupler relay: WDT reset when using AC current

To prevent EMI and to save the relay contacts, you could switch the relays at AC zero-crossing. Add some kind of zero-crossing detection to you project and before switching a relay, wait for a zero-crossing and then wait just before the next zero crossing (about 9500 microseconds at 50 Hz AC).

Simple is to use a current sensor to detect zero-crossing. Current AC wave should be aligned with the voltage wave, if there is no shift in power factor.


src folder in sketch structure and include library from subfolder

I could include header files in subfolder after including root header file.

#include <TB6612_Dual.h>
#include <TB6612_Dual/tb6612_dual.h>

TB6612_Dual
└── src
    ├── TB6612_Dual.h << Add this empty file.
    └── TB6612_Dual
        ├── tb6612_dual.cpp
        └── tb6612_dual.h

Examples:

utils_asukiaaa/examples/string/string.ino
utils_asukiaaa/src/utils_asukiaaa/string.h
utils_asukiaaa/src/utils_asukiaaa/string.cpp
utils_asukiaaa/src/utils_asukiaaa.h


For compiling and uploading Arduino code, you do not need Java, nor the
Arduino IDE: you need avr-gcc, avr-libc, the Arduino core library and
avrdude. With a proper Makefile, your program just needs to

system("make upload");

C.f. the tutorial Compiling Arduino sketches using
Makefile.
On an Ubuntu or other Debian-like OS, you would just
sudo apt-get install arduino-mk make to get everything you need installed.


what is the importance of the resistors that connect to push buttons ? can i replace them by wires?

They are what is known as Pull-Up resistors.  The circuit will not work if you replace them with wires.  Not only that but you will short circuit the power supply when you press a button.

Why don't you want to use resistors?

The value is not important - you could use the same value as you are using for the LED if you don't have the 10k resistors shown in the drawing.

Having said that an alternative is to leave them out and instead activate the internal pull-ups within the processor on the Arduino:

pinMode(pin, INPUT);           // set pin to input
digitalWrite(pin, HIGH);       // turn on pullup resistors


How to fix Arduino restarting when two servos are powered by an external power?

You will need to fix this on your own but I can suggest some things that you will likely need to investigate.

Evaluate what exactly causes the AVR to get reset. It is highly likely that long wires and current surges as loads are applied is causing either the GND or the VCC to the AVR to be compromised and initiating a brown out reset in the MCU.
Driving inductive loads without proper design may be putting high voltage spikes into your design that create havoc with proper software execution and/or risking serious damage to the silicon components. Make sure you take steps to eliminating such with clamp diodes, filter caps or zener diodes.
You will have to check your exact MCU data sheet but many parts have a reset reason register that your software can read to see what particular thing initiated the reset.
Lastly the most important thing is to make sure you have the proper tools for debugging problems like this. It is very common that you should have access to an oscilloscope so you can find the problems and learn how to fix them. The best way to learn how to design in a way that you avoid problems like this on the next project is to see first hand what went wrong and learn from it.


How to use the additional SPIs on Arduino Due

I think the information you are looking for can be found at https://www.arduino.cc/en/Reference/DueExtendedSPI

There are two other alternatives that I can see: if your device supports slave select (which I think they are supposed to), then you can use a different pin to select either device 1 or device 2 (or 3...).

The other options is that if you can connect the clock to only one slave at a time (again, with another pin), you should get the same result - you should be able to use a MOSFET between the Arduino's clock-out and the slave's clock-in, and hook the MOSFET's gate to a spare pin; repeat the procedure, using a separate MOSFET, connected to a different spare pin, to the second slave; then bring one or the other "spare pin" high, to select which way the clock goes. If a slave does not receive a clock, it will not listen for incoming signal. This last one I dreamed up; I don't know if it will work.


Arduino serial port reset in Serial monitor & Python

The Arduino is designed to reset when a Serial monitor or script connects to it. The best way to mitigate this would be to send the Arduino some kind of "start sending" signal when you connect to the serial port. It would then send the data when your script was ready.


Is a solenoid piston strong enough to lock a water tubling?

The pump you are looking at is to powerful for you application: 350 liters/hour, or little less than 5 ltr/min. It will fill a 250 ml glass in about 3 seconds!

The solenoid cost you $5 a piece, but you still need a valve and a way to attach solenoid, valve and tubing.

Also, your idea means liquids will get mixed inside the tubes. And nobody wants a trace of whiskey in his Vodka Screwdriver.

You must visit The Inebriator, a cocktail mixing machine. His design have one tube for every bottle pouring liquid into the glass.

As they note, they have in version 2.0

  Switching mixers from a pressurised system with valves to using pumps
  – This slows the pouring, but vastly simplifies the machine as a
  whole. We have a capacity for 16 pumps

They don't use valves, but pumps. I recomend a peristaltic pump ($7 on Aliexpress), like this:

They don't touch the fluid, easy to mount, and are a very precise delivery mechanism, like in this video https://youtu.be/GdTUIwj5ros, showing an Arduino controlling a pump to 1ml precision:


Raspberry Pi 3B+ BLE communication to Arduino Nano 33 IOT

For completeness, it appears an appropriate Python library can be installed with:
pip3 install adafruit-circuitpython-ble

The test code, used with the Arduino code 'Echo' from the ArduinoHardwareBLE library is below.  This was updated to let you choose the name of the device (here, MY_BLE)  rather than any random device that has UART capability.  It also allows you to send a small file from a few lines, with a "#" denoting a comment (first character in the line).  ESC and a return quits the program.
# Connect to an "eval()" service over BLE UART.

from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

ble = BLERadio()

uart_connection = None

def send_stuff(s):
    uart_service.write(s.encode("utf-8"))
    uart_service.write(b'\n')
    readline=uart_service.readline().decode("utf-8")
    while(len(readline)>0):
        print(readline)
        readline=uart_service.readline().decode("utf-8")

while True:

    if not uart_connection:
        print("Trying to connect...")
        print("ESC then RETURN to exit.")
        for adv in ble.start_scan(ProvideServicesAdvertisement):
            if UARTService in adv.services:
                regular_name = adv.complete_name
                if(regular_name=='MY_BLE'):
                    uart_connection = ble.connect(adv)
                    print("Connected")
                    # for some reason, we have to read a line...
                    uart_service = uart_connection[UARTService]
                    print(uart_service.readline().decode("utf-8"))
                    break
        ble.stop_scan()

    if uart_connection and uart_connection.connected:
        uart_service = uart_connection[UARTService]
        while uart_connection.connected:
            s = input("Prompt: ")
            if(len(s)>0):
                if(ord(s[0])==27):
                    print("done.")
                    exit()
                else:

                    # Check if "!" character is used; if so, send contents of a file
                    if(s[0]=="!"):
                        print("sending commands")
                        count=0
                        file1=open('commands.txt','r')
                        Lines=file1.readlines()
                        for line in Lines:
                            count=count+1
                            tmp=line.strip()
                            if(len(tmp)>0):
                                if(tmp[0]=='#'):
                                    print("comment:" + tmp)
                                else:
                                    print("Line{}: {}".format(count, tmp))
                                    send_stuff(tmp)

                    else:
                        send_stuff(s)


Can a 12V sensor connected to a 5V output signal of an Arduino Uno

My favorite solution for such an application is to use an optoisolation module. In this case, the signal can have a voltage of 12 V and the output of the optoisolation module can be connected to the input of the Arduino, where the input is configured as INPUT_PULLUP.
Example of the optoisolation module:

In this way it is possible to connect other types of sensors and switches and the solution is universal also for other development kits, e.g. with 3V3 logic.


Run different code on different type of reset in arduino nano

The MCUSR register (page 79 of the datasheet) tells you what kind of reset happened most recently. As long as the USB interface chip on your nano isn't controlling the RESET pin without the port being opened (i.e., toggling it at power up regardless of the USB state) then you could query that register to see how it reset:

if (MCUSR & (1 << 0)) { // POR
    digitalWrite(4, HIGH);
} else if (MCUSR & (1 << 1)) { // External Reset
    digitalWrite(5, HIGH);
}

However, if the USB chip does toggle the RESET pin then there is no way you can distinguish between the two resets since they are bot the same "external" reset using the RESET pin.


iterate through 8 thermocouple sensors (MAX31856)

You CAN store them in an array, but NOT in an array of pointers to characters. That is just the wrong type. Try
Adafruit_MAX31856 thermocouples[] = {TCouple1, ...}

or even ditch the first declarations and use
Adafruit_MAX31856 thermocouples[] = {
    Adafruit_MAX31856(2,11,12,13),
    Adafruit_MAX31856(3,11,12,13),
    Adafruit_MAX31856(4,11,12,13),
    ...
};

I don't have that library installed, but I tried compiling this pattern with the Bounce2 library and it works. That looks like this:
Bounce buttons[] = {
    Bounce(),
    Bounce(),
    Bounce()
};


The Neo 6M takes a bit of time to fix when first powered on. If your board is fitted with a small battery it will most probably be flat and will take an hour or two to charge up. It is there to provide charge to the EEPROM and the onboard RTC.

Also check that the leads on the battery are not shorting.

You do not get a valid data sentence out of the GPS until the RTC can sync time.

The Error message that you got from Mike Hart routine first says that there is not enough data to do a FIX and second the Date Time is not syncing.


You are doing math with 2 different types.   One is long and the other is an int.  So, eventually the long will always be lager than the int and the test will always be true.  (A 32 bit long can count up to over 2 billion.  A 16 bit int can only count up to about 32 thousand.)

Also, the method millis() is of type "unsigned long".  So change all your variables to match this type.

Also note that when the millis() timer overflows and start over your program may perform unexpectedly.  Since this rarely happens it may not concern you.


An Arduino Leonardo has native USB support. Which means that it has separate serial interfaces to the PC and to the hardware pins.

Serial is only used for the communication with the PC and is unrelated to the hardware serial pins 0 and 1. Those are exposed trough Serial1.

So, if you are using the exact same Uno sketch, that uses the hardware serial pins, it can't work on a Leonardo, because data is just sent-to/read-from the PC and not to the connected Bluetooth module connected on pins 0 an 1.


Set PWM by period? And have it variable?

I stumbled upon a solution via trial and error coupled with watching the results on an o'scope.

The best guidance came from a Stack Exchange QA. Setup isn't particularly special, however the combination of WGM bits here worked and I didn't investigate further. Of the biggest importance are the prescaler divider bits, the least three significant bits of TCCRxB. 001 means no dividing or prescaling of the clock.

It all boiled down to 4 registers and the pinMode() call. Ultimately, seven lines of code:

#define PULSE_PIN 45
void setup() {
    // IMPORTANT: Clear Timer/Counter Control Registers
    TCCR5A = 0;
    TCCR5B = 0;

    // Set Timer/Counter Control Registers
    TCCR5A = B00101001; // Phase and frequency correct PWM change at OCRA
    TCCR5B = B00010010; // least sig bits sets "carrier frequency" by dividing CPU clock
    //  Observation:
    //  TCCR5B = B00010010 and OCR5A = 16667 results in period of 16.70 mSec
    //  meaning OCR5A is period in uSec when TCCR5B = B00010010
    //  TCCR5B = B00010001 : OCR5A = 20000 results in period = 2.5 mSec 399.3Hz

    pinMode(PULSE_PIN, OUTPUT);
}

In the sketch, I watch an analog pin with a potentiometer on it and map its sweep to an effective RPM range of 950 to 9000 RPM. Hence the arbitrary range of periods I want to handle. When loop() sees the ADC change, the below code adjusts the PWM accordingly.

Note that no floating point data types are used. The magic numbers below were chosen by trial and error in a spreadsheet with values rounded to whole numbers.

void setRpm(){
    //  Getting to period in uSec from rpm the long way to keep
    //  the answer in range of the data type:
    unsigned int rpm = map(pot_adc, 0, 1023, RPM_MIN, RPM_MAX);
    unsigned long period = rpm/50;
    period = 24000/period;
    period = period*50;
    //  The trigger lasts 26°, so the PW is 26/360 * period.
    dwell = period/36;
    dwell = dwell*26;
    dwell = dwell/10;

    //  OCR5A is a counter the carrier frequency counts up to,
    //  which sets output period / frequency
    //  meaning OCR5A is period in uSec when TCCR5B = B00010010
    OCR5A = period; //  OCR5A is period in uSec when TCCR5B = B00010010
    //  OCR5B is the width of the pulse. If we used floats,
    //  we could use duty cycle * period.
    OCR5B = dwell;
}

Obviously, this code will have limitations to the range of frequencies it can handle, but the Internet has plenty of means for higher frequency PWM, especially when the desired PWM is fixed and doesn't need varying.

The most helpful way to see the control registers is as binary positions and not to rely upon macros, masks, and bit shifting. This comment block helped greatly:

 // WGM modes:
 // TCCR1A
 // Bit              7      6      5      4      3     2     1     0
 // Bit Name         COM1A1 COM1A0 COM1B1 COM1B0 ----- ----- WGM11 WGM10
 // Initial Value    0      0      0      0      0     0     0     0
 // changed to       1      1      1      1      0     0     0     1

 // TCCR1B
 // Bit            7      6      5       4        3        2        1        0
 // Bit Name       ICNC1  ICES1  -----   WGM13    WGM12    CS12     CS11     CS10
 // Initial Value  0      0      0       0        0        0        0        0
 // changed to     0      0      0       0        1        0        0        1
 // CS12,CS11,CS10 = (0,1,1) = prescaler divide by 64


How to make an Arduino USB programming circuit?

Looking at the schematic design, you need atmega8 to make a usb programming connection. Design your circuit exactly like in the schematic.You will also need bootloader for it, so use any programmer like usbasp, connect its pins to mosi, miso sck, rst,vcc,gnd and click on burn boot loader in arduino ide


Plug some of these into the Arduino headers to add extra space.

They come in different lengths and can be cut to the required number of pins.

They also come in different pin lengths.

Google long tailed pin headers.


Unlikely.

First you would need a USB shield to be able to plug it in.

Second you would have to reverse engineer and then reimplement the proprietary protocols that device uses in order to get the Arduino to control the device.


A state machine is what you want. That and to increase your preamble to two bytes, not one.  The reason being is that due to the escaping of the preamble character in the data it is impossible to have that character twice in a row. By then having it twice in a row as the preamble it is unambiguous that it is the preamble.

You should also (if needed) escape the packet size:

Serial.write(PACKET_HEADER); // Packet header for synchronization
Serial.write(PACKET_HEADER); // Packet header for synchronization
uint8_t ps = calculatePacketSize(data, XOR); // Size of packet
if(ps == ESCAPE || ps == PACKET_HEADER) {
    Serial.write(ESCAPE);
}
Serial.write(ps);
Serial.write(unitInfo);
... etc ...

You might like to abstract the escaping into a function:

void sendEscape(uint8_t c) {
    if (c == ESCAPE || c == PACKET_HEADER) Serial.write(ESCAPE);
    Serial.write(c);
}

Then you can just call:

sendEscape(calculatePacketSize(data, XOR));

etc.

Now for receiving. Implement a Finite State Machine. In that machine you have a number of states, such as look for first preamble, look for second preample, look for size, look for id, and look for data. As bytes arrive they trigger the next state.

So you start by looking for the first preamble byte. When that arrives it triggers looking for the second preamble byte - any other byte besides the second preamble byte causes the FSM to reset. If it arrives, then it triggers the reading of the packet length. And so on.

In pseudocode it may be something like:

State is idle.
If character available:
    Read character into variable C

    Select on state:
        State IDLE:
            If C is PACKET_HEADER:
                Set state to PREAMBLE
        State PREAMBLE:
            If C is PACKET_HEADER:
                Set state to GETSIZE
            Else
                Set state to IDLE
        State GETSIZE:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Store C in variable SIZE
                Clear array DATA and prepare for reception
                Reset Seen ESCAPE flag if needed
                Set state to GETID
        State GETID:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Store C in variable ID
                Reset Seen ESCAPE flag if needed
                Set state to GETDATA
        State GETDATA:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Append C to array DATA
                Decrement variable SIZE
                Reset Seen ESCAPE flag if needed
                If SIZE is 0
                    If checksum matches
                        Process packet
                    Set state to IDLE

The main thing to watch is the remembering (and subsequently forgetting) that you have just seen an ESCAPE. That way you can know if you have two ESCAPE characters in a row and you only discard the first one - the second gets handled as a real character.

The beauty of an FSM is that at any point in the sequence, if you decide that the packet is invalid (maybe the size is too big, or the sensor ID is invalid) you can just reset the FSM to the IDLE state and reset any flags/counters and you instantly start looking for a new packet.


There is no builtin way to do that but you got all the necessary tools at hand.

End of line should be signaled by a decimal 10, aka LF(Line Feed) character.
So what you do is keep reading until you encounter LF or end of file, which then is the entire line you want to read.

while (file.available() && file.peek() != 10) // peek returns the next character without incrementing the read index
    file.read();

This code does exactly that. Now you could either store the read bytes in a buffer (big enough!) right away or instead find out the number of bytes beforehand to create a precisely sized buffer afterwards and use the read(buffer, length) overload to read all bytes at once.

Please keep in mind that the LF character has to be there in order to be read. So if you are the one creating the files, be sure to place it. (most desktop text editors do that for you)

Example:

char buffer[20];
uint8_t i = 0;

while (file.available() && file.peek() != '\n' && i < 19)    // note how this also prevents the buffer from overflowing (18 max to leave space for '\0'!)
{
    buffer[i] = file.read();
    i++;
}
buffer[i + 1] = '\0';    // it is good practice to end strings with a terminating NULL character


how to use Nano instead of Uno3 to operate DC motors

It's my understanding that the Uno 3, Nano and Micro are the same in its basic form

Not exactly. The Uno and Nano use the same chip (the Atmega328p) and have the same pins broken out. The Arduino Pro Mini also uses that chip, but I think the pinout is a bit different. But mostly a code can be reused between these boards. The Arduino Micro uses an ATmega32U4, which is a different chip. Depending on the actual code, you might not be able to just reuse the code. Then you might have to change to code to use the Micros hardware.

with the motors as small as they are is it really necessary to have a motor shield or H bridges?

I would say yes. A digital output pin of an Arduino can only supply 20mA of current over longer time (absolute maximum 40mA). Even very small motors can easily exceed that. As long as you don't know the exact needed current in worst case (like stalling the motor), you should assume, that it is more than 20mA. Also a running motor generates a lot of electrical noise and the coils can induce backcurrents, that might destroy the output hardware of the Arduino pin (for that you need a flyback diode). And lastly, if you want to change the direction of the motor, you absolutely need an H-bridge. Otherwise it is only on or off.

Question is how do I wire up the Nano to do this

With H-bridges you normally need 3 pins to control the motor:

The enable pin (often marked as EN) enables or disables the motor (run or stop). You normally use analogWrite(en_pin, speed) to control the speed of the motor. It will send a PWM signal with the given duty cycle to the enable pin.
And you have 2 input pins (often marked as IN). They give you control over the direction.

IN1 to HIGH and IN2 to LOW will give you the first direction. Reversing to IN1 LOW and IN2 HIGH will give you the other direction. This will cause the H-bridge to lead the current through the motor in different directions.
Setting them to the same value will cause the motor to break (because that will short circuit the motors coil).

So you would wire 3 output pins of the Arduino to the mentioned pins on the H-bridge. It is up to you, what you want to use here. You can use a shield (which is normally the size of the Uno), you can use other ready to use motor driver boards (there are many) or you could build your own driver with a H-bridge chip and flyback diode.


Major difference between DTR signal and RTS signal?

Electrically they are both the same. The difference is what they are used for.

DTR means Data Terminal Ready and indicates that the connected device is ready to receive data.

  Data Terminal Ready (DTR) is a control signal in RS-232 serial communications, transmitted from data terminal equipment (DTE), such as a computer, to data communications equipment (DCE), for example a modem, to indicate that the terminal is ready for communications and the modem may initiate a communications channel.

RTS means Request To Send and indicates to the connected device that it wants to send data.

  The DTE asserts RTS to indicate a desire to transmit to the DCE, and in response the DCE asserts CTS to grant permission, once synchronization with the DCE at the far end is achieved.

Basically DTR is used to indicate the presence of some equipment, and RTS is one half of hardware flow control (along with CTS) to start and stop communication.

On USB communication (e.g., using FT232 USB to UART adaptor, etc) the meaning is less clear. DTR is asserted when the port is opened (usually) and RTS is most likely not asserted at all. It's at the whim of the operating system and/or the driver whether DTR is automatically asserted or not, and whether RTS is even implemented.


Serial.write(buf, len) error. How to remove an error and pass an array of bytes?

You want to send data to computer processing or print them for user to read? Functions write send raw data. To print the data to Serial monitor print and println functions are used.

There are two write functions. First sends one byte. Second sends array of bytes. There is no write function to send array of ints. You could cast the array of ints to array of bytes to send the array as raw bytes for processing on the receiving side. But then you first should perhaps send to the receiving side some control data about the data package.

  Serial.write((byte*) datos, sizeof(datos));

If you want to print numbers to Serial Monitor, the print functions have variants which take a number and convert it to string. But there is no print function to print an array of numbers. You must print them one by one in a for loop. And put some separator between them (coma, space, new line).


How many PIR Motion Sensors can I connect to my Arduino-Uno R3?

Most PIR sensors provide a simple relay output. That means they are nothing more than a switch as far as the Arduino is concerned.

You can connect hundreds of switches to an Arduino. With judicious use of diodes and a matrix arrangement you can hundreds with not many IO pins.  For example an 8x8 matrix of switches gives you 64 PIR sensors with just 16 IO pins.  For n pins you can have (n/2)² switches with a balanced (n/2 by n/2) matrix.


Why do my Hall sensor readings change when I write them to the serial port?

The 3144 requires a pull-up resistor. It only sinks when a magnet is present. It doesn't source, so the pin is floating if no magnet is present.
You can use the internal pull-up resistor by using pinMode(HALL_PIN, INPUT_PULLUP);


Disclaimer:

I've never used an ESP chip based board I know almost nothing about them. I am going to assume that it works, in software terms, like an Arduino, and base my answer on Arduino code. If the esp chip works differently, you'll need to adapt my suggestion.

Try something like this:

Connect a GPIO line between the microcontrollers. Also connect that line - through a 10K resistor - to +5V.

Have both microcontrollers set up it's GPIO as an input.

(We'll call the GPIO pin on both microcontrollers the "DHT_available" line. It will be HIGH when the DHT sensor is not being used by the other controller.)

When one of the microcontrollers wants to read the DHT11, have it check the GPIO line. If it's HIGH switch the GPIO line to an output and pull it low, then take a reading. When the reading is complete, switch the GPIO line back to an input.

If the GPIO line is LOW, wait and check again.

Alternately you could attach each of the microcontroller's GPIO lines to interrupt handlers on a rising edge. Then have the interrupt handler set the GPIO line to an output, pull it to LOW, and set a flag that means "begin reading".

Have your loop function check the "begin reading" flag, and if true, trigger a read from the DHT, and once it's complete, set the GPIO back to an input.

With the first option, each microcontroller would need to poll the "DHT_available" line continuously until it goes HIGH before beginning reading.

With the second option, as soon as one of your microcontrollers is done taking a reading, it would stop pulling the communications line LOW, the other one's rising edge interrupt would fire, and the other one would immediately begin reading.


There seems to be a big difference between the Sparkfun and the Adafruit breakouts:

Sparkfun breadkout needs 3.3V and 5V power as inputs as shown in their wiring circuit (in the first link you mentioned)
Adafruit breakout needs only 5V as input but has a 3.3V regulator on it that provides the 3.3V to all its internal circuits that need it; it also has a 3.3V pin which is an output not an input as for the Sparkfun

Hence your wiring is wrong. The expected wiring is described in Adafruit sample sketch:

// Example sketch for talking to the VCNL4000 i2c proximity/light sensor
// Written by Adafruit! Public domain.
// To use: Connect VCC to 3.3-5V (5V is best if it is available), GND to
//         ground, SCL to i2c clock (on classic arduinos, Analog 5), SDA
//         to i2c data (on classic arduinos Analog 4). The 3.3v pin is
//         an ouptut if you need 3.3V
// This sensor is 5V compliant so you can use it with 3.3 or 5V micros

In comments, VCC should read as Vin on the breakout.

Note that the comments mention SDA and SCL pins on A4 and A5 respectively, this is correct on Arduino UNO, but your wiring on the 2 leftmost pins of the digital pin header is also correct, as these pins are now replicated there on UNO and Leonardo. On Leonardo, the real pins for SDA/SCL are pins 2 and 3. If you don't have a UNO or Leonardo though, you should check where SDA and SCL can be found (that's generally described on Arduino Product page for your board).

Although wiring SDA/SCL on these 2 replicate pins is correct, I would rather recommend using A4 and A5 instead, so that you don't get the illusion that you can both use SDA/SCL and A4/A5 for something else at the same time.

This circuit uses I2C which means you should normally add pullup resistors to SDA and SCL wires; however, it seems that the Adafruit breakout already integrates them, so no problem here.

To sum up, and provided that you have a UNO or Leonardo, your wiring is correct except that you should remove the wire between both 3.3V pins.

This is shown below for UNO (I used the real pins for SDA and SCL so that you don't use them for something else later):

Arduino UNO 5V  ---> Breakout Vin
Arduino UNO GND ---> Breakout GND
Arduino UNO A4  ---> Breakout SDA
Arduino UNO A5  ---> Breakout SCL
Breakout 3.3V left unconnected

For Leonardo it would be:

Arduino Leonardo 5V  ---> Breakout Vin
Arduino Leonardo GND ---> Breakout GND
Arduino Leonardo D2  ---> Breakout SDA
Arduino Leonardo D3  ---> Breakout SCL
Breakout 3.3V left unconnected

I show you both UNO and Leonardo since you did not mention which board you use.


There are pre-made and very inexpensive Arduino RS-485 modules available on Ebay or Amazon.  Much simpler than building your own circuit.

They look like this:


One way to communicate Arduino to Arduino device is UART (and Software Serial for additional pins). For the ESP32, it seems this allows 28 TX pins using Majenko's method (in their answer). In other words, slave 28 devices.
After further research, isn't I2C the clear route to go?

With more slave devices the less times per second to talk to them all
The application needs to have all the slave devices execute commands synchronously:

At least, the slave devices need to start functioning at the same time.

How many slave Uno's/Nano's can be connected to an ESP32?

Each device on an i2c network has a 7-bit address, so a single network theoretically supports up to 128 slave devices. In practice though, the limit is much lower. i2c slave chips often support only 8 different bus addresses, no more than 8 of that chip can be attached to the same i2c network.

https://mindbleach.com/words/2012/10/23/i2c-and-device-limits
Unclear answer:

https://forum.arduino.cc/index.php?topic=159860.0
https://forum.arduino.cc/index.php?topic=367961.0


Without the ground of the teensy connected to the ground of the fan all you will be measuring is noise. Ground is required to complete the circuit between the teensy and the fan.


Using millis() to toggle an LED every 500 milliseconds

if (!(millis() % 500)) ...

There are two issues with this. The first, and most obvious, is that the
condition will be true for a full millisecond. During that millisecond
you will be toggling the LED on and off very fast. Whether you end up
doing an odd or even number of toggles is anyone's guess.

The second and less obvious problem is that millis() skips some
values. Roughly one integer every 42 is skipped over. This is because
the millis() counter is incremented once every 1024 µs, getting
24 µs late on each increment. Once all those delays add up to a
full millisecond, millis() catches up by incrementing the counter by
two milliseconds instead of one. This is why you should never condition
something on millis() having one specific value.

The almost correct solution to this problem is shown in Juraj's answer:

  if (millis() > next) ...

This is not quite correct because it fails each time millis() rolls
over back to zero. The correct solution is

static unsigned long last;
if (millis() - last >= 500) {
    last += 500;
    ...
}

Because the subtraction follows the rules of modular arithmetic, this is
guaranteed to work across the rollover events.


Difficult between atmega328 & atmega2560 when coding & compiling in a pure c

I'm the author of the MateDealer project and I never had the intention to port it to other boards than the Arduino Mega2560!

Ignacio Vazquez-Abrams is absolutely right, the Arduino Mega2560 is the only board with more than 1 serial port (Yes there is the Due and the Leonardo, but those would require major changes to the code).

The fastest way to get the code running is by using a Mega2560, but be warned, the code might be bugy as hell ;-)


NodeMCU Exception 28 - intermitent problem

Exception 28 is, according to the exception list document:

  Access to invalid address

The most common cause is trying to read or write from/to a NULL pointer.

It could be because you have debugging turned on, and that debugging is trying to print something that didn't get returned properly from another function call (the call failed) - most likely looking up a host name (hostByName()) due to your intermittent internet connection.

This may sound counter intuitive, but try turning off debugging to see if that helps reduce the number of crashes.


You can use a common ground in fact it's the normal thing to do with external circuits such as relays, servos etc


Transmit image file thougth the TX TR serial line

You cannot. The TX and RX lines are UART. UART is not USB. USB is a very complicated protocol, and you need a proper understanding of how it works. It's not a simple serial protocol like UART.

Add to that the fact that the Arduino can in no way handle the amount of data involved in video, and you're already on a non-starter.


Sending Data between two boards using SoftwareSerial

Your problem here is that you are streaming out serial data non-stop.

See my answer in this thread: What is Serial.begin(9600)?

Without having a pause, the receiver just latches onto somewhere in the middle of the data stream and tries to make sense of it, often unsuccessfully.

If you add one "character time" delay to the sender, the receiver works fine:

  altSerial.print('1');
  delay (2);

It might get the first one wrong, but now the receiver has 2 ms to resynchronize on the data stream. At 9600 baud the delay should be 1/960 (second) at least, I used twice that to be sure.


HTTP get request using Arduino Uno and ESP8266

You can use ESP8266Wifi Arduino Library.

Here an example:

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

void setup () {

  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);
    Serial.print("Connecting..");

  }

}

void loop() {

  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

    HTTPClient http;  //Declare an object of class HTTPClient

    http.begin("http://www.google.com");  //Specify request destination
    int httpCode = http.GET();     //Send the request

    if (httpCode > 0) { //Check the returning code

      String payload = http.getString();   //Get the request response payload
      Serial.println(payload);                     //Print the response payload

    }

    http.end();   //Close connection

  }

  delay(30000);    //Send a request every 30 seconds

}


Best way to power an Arduino using the Vin pin

You have a powerbank which has a USB output, right? Why not just plug a cable from that into the Arduino USB port? That will connect the 5V directly into the 5V pin of the Arduino (probably via a switching MOSFET). Then you can connect to your motor driver from the 5V pin on the Arduino (and Gnd of course). There may be some limitations on how large a motor you can drive (based on the capacity of the power bank, and to an extent also the thickness of the traces on the Arduino board).

As others have commented, Vin is not intended for that purpose (ie. to supply 5V). You should supply 7V or more to Vin to force the switching MOSFET to disconnect the USB input. In your case you don't have 7V from the powerbank.

Here is how the Uno Rev3 power system works:

The input jack (circled in blue) goes through a diode (D1) to the Vin line.

Vin then goes through the 5V voltage regulator (U1) to provide +5V.

However on the top left you see 2 x 10K resistors (RN1A and RN1B) which make a voltage divider from Vin to Gnd. This is compared to the output of the 3.3V voltage regulator by U5A op-amp (circled in red). If higher, then T1 (circled in green) will turn off, disconnecting USBVCC from the +5V line. If lower, then USBVCC is connected to +5V. The nett effect is that if Vin in greater than 6.6V (because of the voltage divider) then the circuit chooses to use Vin, otherwises it uses USBVCC (USB power).

That's why they recommend to use 7V or more into Vin.

Note that you lose around 0.7V through the diode, which is why you need something like 7.3V at the input jack to allow for the loss of the 0.7V before the op-amp compares it to 6.6V.


Unlikely. An IO pin can only provide 25mA sustained, and 40mA peak. A display is likely to require more than that. However check the datasheet for the display. If by chance it should not need more than 25mA maximum (all pixels white) then yes it may be possible.


How to send command from coordinator to router in Xbee?

In order to change the router from the coordinator, you have to create a function that run in a microcontroller that is connected to the coordinator.You can refer to this link , https://www.youtube.com/watch?v=CzH146rR-7I&t=236s


collecting & visualizing sensor data - best approach?

Several possibilities; Both at little cost, but since you have an accelerometer, I know your budget is not 0.

1) use a shield with an SD card on the arduino to log the information to a file on the SD card.  Open it later from a laptop or PC.  Hopefully it will have enough room to store data that you can ignore later for pre-flight, post-flight time.  If not, simply add some fixed delay to the start of your program (loop 5 times; wait 1 minute;)

2) some form of remote, like an XBee, or even a wireless WiFi Shield. The setup can be complicated but that would be ideal for real time visualization on a laptop at the flying site.

3) probably the easiest/least expensive - a cheap bluetooth transmitter.

eBay

This method would allow a bluetooth mobile to collect and visualize the data. This device connects to the serial lines on an arduino, (pin 0&1) and standard Serial.Write() function can be used.  Any terminal program for your mobile will be able to receive the data. You could also get fancy and write your own if you want to visualize it. You may be able to find something already existing, like this

In cases 2 & 3 you will need a way to xmit the data. I use MQTT. A protocol just for this, but it is TCP only. I also use it with JSON (eg Json for Arduino to manage the data.  You will need to find the same. Look at MQTT-SN as a possibility, or you can just write your own serialization protocol based around JSON without too much difficulty.


where to get Arduino WIFO101 library that supports WiFi.beginAP() on board MKR1000

It is AP_SimpleWebServer.ino at Github Wifi101 release 0.9.1 examples.
It builds ok by using the old definitions for .beginAP return values.
Problem is Arduino .beginAP page has example that relies on the LATEST Github WiFi101 ("0.9.1++" not released yet).
Also example AP_SimpleWebServer is missing from Arduino Wifi101 page.


Because

((PIND & (1 << 2)) != LOW)

means exactly

(PIND & 4) != 0

and that is true if PIND is 4, 5, 6, 7, 12, 13, ... (any number having 4 in it binary), so it yelds

4 != 0

Which is definitively not equal

4 == 1

BTW: in C any integer != 0 is true and 0 is false, so you can as well write:

if (PIND & (1 << 2)) PORTB |= (1 << 5); //sets pin 13 (B5 on ATMEGA 328) as HIGH


NewliquidCrystal example HelloWorld_i2c just flickers

I was able to make the example run as intended, by using a different constructor call:

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

I am not able to tell you, what these parameters and values mean. However, the documentation for this constructor is shown below (source).

/*!
    @method
    @abstract   Class constructor.
    @discussion Initializes class variables and defines the I2C address of the
    LCD. The constructor does not initialize the LCD.

    @param      lcd_Addr[in] I2C address of the IO expansion module. For I2CLCDextraIO,
    the address can be configured using the on board jumpers.
    @param      En[in] LCD En (Enable) pin connected to the IO extender module
    @param      Rw[in] LCD Rw (Read/write) pin connected to the IO extender module
    @param      Rs[in] LCD Rs (Reset) pin connected to the IO extender module
    @param      d0[in] LCD data 0 pin map on IO extender module
    @param      d1[in] LCD data 1 pin map on IO extender module
    @param      d2[in] LCD data 2 pin map on IO extender module
    @param      d3[in] LCD data 3 pin map on IO extender module
    */
   LiquidCrystal_I2C( uint8_t lcd_Addr, uint8_t En, uint8_t Rw, uint8_t Rs,
                     uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3 )
;


You are missing a second time.sleep(1). That is why the first loop executes correctly and the the LED flashed faster. Without any time.sleep() at all, the LED is going OFF/ON so fast that you cannot see it happen (may be it's just not so bright as usually).

while 1:
   for i in range(0,10):
        serialWrite(0)
   time.sleep(1)
   for i in range(0,10):
        serialWrite(1)
   time.sleep(1)


Lighted geofenced dog collar project help needed

I would suggest the following hardware for your project.

https://store.arduino.cc/arduino-mkr1000

It has an integrated wifi module. If a wifi chip is attached to chip manually it will likely loose contact or sometimes be broken during movement.

Here are some tutorials to get you started:

https://www.hackster.io/charifmahmoudi/arduino-mkr1000-getting-started-08bb4a
https://www.pubnub.com/blog/2016-08-23-remotely-configure-your-arduino-mkr1000/
http://platformio.org/lib/show/299/WiFi101

Hope this helps.


Controlling an LED using a transistor (TL188)

You should have a resistor of a few hundred ohms on the base connection of the transistor - that is, between base and pin 13.

A PNP transistor is somewhat harder to get to grips with than an NPN transistor.  Much of it does things backwards.

The operation you see seems to be completely correct when you understand how a PNP works.

With and NPN transistor a high voltage on the base turns it on and a low voltage turns it off. The opposite is true with a PNP transistor.

When you have a voltage close to or above the voltage at the emitter the transistor will be off.  That means, providing a HIGH to the base will turn it off.  A voltage on the base that is below the emitter voltage minus the threshold voltage of around 0.7V will turn the transistor on.  That means providing a LOW to the base will turn it on.

So that means that when the on-board LED is on the transistor is off, and so the LED on the transistor will be off.  When the LED on the board is off the transistor will be on, so the LED on the transistor will be on.

"But", you say, "the on-board LED doesn't turn off".  That is correct. It just gets dimmer.  That is, again, because of how the PNP transistor works.  Current (seen from the conventional sense - i.e., flowing from + to -) enters the emitter and is then split between the collector and base. The amount of current allowed to flow out of the base defines how much is allowed to flow out of the collector (in an NPN it's current into the base and collector that combine to flow out of the emitter, and the amount that is allowed to flow into the base defines how much is allowed to flow into the collector). So there will be some current flowing out of the base - which makes its way to ground both through the microcontroller's IO pin and also through the LED on board, making it glow slightly*.

*That is a little crudely put, but kind of illustrates what is going on.


An Arduino is basically a Microcontroller on a handy PCB with built-in programming interface.  It also has a simple programming environment to get you up and running quickly.

The chip on the board can be thought of as the "brain" of the system.  It's what you program and it's where you upload your software to.

  Is one Arduino device required for each Arduino project?

Yes and no.  You can't "remove" your Arduino from your project and expect it to still work - it'd be like beheading someone - they cease to function without their brain.  However you can replicate the Arduino in your system fairly easily so you don't have to embed the whole Arduino into it.  You can get a blank chip the same as is on the Arduino reasonably cheaply and program the bootloader (the serial interface for programming it) into the chip using your existing Arduino, then build a new circuit around it.  More information here:

http://www.arduino.cc/en/Main/Standalone

  Should I have to buy more then one device for each project?

That depends if your project is complex enough to warrant more than one "brain".  Using the "standalone" instructions above you could make multiple chips from one Arduino and embed them all in your one project.

  If not then how I will make that project run without Arduino?

There are other Arduino boards available that are designed to be embedded in your project.  These are much smaller than the "development" boards like the Uno etc.  They are also cheaper, being typically the absolute bare minimum you need to get you going.  These can be a great way of saving time compared to the Standalone system above, and at the same time saving money compared to using the full blown Arduino boards.  Boards include the Mini and Nano range of boards.

http://www.arduino.cc/en/Main/ArduinoBoardMini
http://www.arduino.cc/en/Main/ArduinoBoardNano


RFID does not respond after Ethernet.begin(mac, ip) initialization

The Arduino Ethernet shield uses pins 4, 10,11,12,13. You have a conflict with the RFID pins.


HC-06 Bluetooth module and slow communication

There are a few things that may be causing your issues:

The HC-06 may be a cheap knock off and may not perform to the level that you expect.
There could be an intermittent wiring fault or loose connection.
The signal strength may be causing your issue - it just can't 'hear' your data.
The antenna on the HC-06 module might be compromised in some way resulting in the loss of signal.
The data rate (baud rate) may be too high.
Your code may have blocking functions or delays that is causing you to miss the data.
The Android app may have bugs in it.
The Arduino program may have bugs in it.


Your are not explicitly initializing the variable isChanging, so the compiler sets it to 0. This means, that your code will directly go to the last else statement and cannot at any time reach the LED code, because you are not changing the variable in the else statement.

But I don't really understand, why you were using this variable in the first place. Try to use purely non-blocking code. For checking the button you can do something like this:

boolean button_pressed = false;
unsigned long button_timestamp = 0;

void loop(){
  ...
  if(!button_pressed && digitalRead(11)){
    button_pressed = true;
    button_timestamp = millis();
  }
  if(button_pressed && millis() - button_timestamp > 50){
    if(digitalRead(11)){ // real button press
      button_pressed = false;
      // check, if the middle LED is ON and act accordingly
      // or, if the game hasn't started yet, start it
    } else { // just a bounce of the button, not a real button press
      button_pressed = false;
    }
  }

  // LED CODE
  if (millis() - lastChange > 500) {
    ...
  }
}

Note, that this code will not wait for the button to be released, but reacting, when the button was held down for 50ms. You can change this value, to a one, that is more fitting your used button, but it is a good start point.

Also in your LED code, you have to replace the 500 in the millis statement with a variable, since you want to change the speed.

For handling starting the game with the same button, you can use a state variable, which contains a value of means "Game Stopped" or "Game Started".


I tested your setup with my Mega, and it worked OK after a couple of changes.

You should really set SS high first, before even making it an output. That way the pull-up is activated, and then the moment you make it output it stays high, rather than going to low, then back to high, which looks to the target like a SS pulse.
You don't need to do pinMode() calls on the other SPI pins.
Call SPI.begin() last - after setting SS high.

void setup(){

  Serial.begin(9600);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE1);

/// -----CHANGES--------
  digitalWrite(SLAVESELECT_1,HIGH); //disable device
  pinMode(SLAVESELECT_1,OUTPUT);
/// -------------

  SPI.begin();

  digitalWrite(SLAVESELECT_1,LOW); //Enable device
  SPI.transfer(0x0E);  //Send  Fstart Write Enable to Control Reg
  SPI.transfer(0x13);
  digitalWrite(SLAVESELECT_1,HIGH);

  digitalWrite(SLAVESELECT_1,LOW);
  SPI.transfer(0xC7);  //Send Frequency to Fstart one byte at a time
  SPI.transfer(0x4C);
  digitalWrite(SLAVESELECT_1,HIGH);

  ...

As you can see from the logic analyzer, the output is OK:

The numbers look right too:

Time [s], Analyzer Name, Decoded Protocol Result
-0.000001752000000,SPI,MOSI: 0x0E;  MISO: 0x00
0.000001248000000,SPI,MOSI: 0x13;  MISO: 0x00
0.000014496000000,SPI,MOSI: 0xC7;  MISO: 0x00
0.000017496000000,SPI,MOSI: 0x4C;  MISO: 0x00
0.000030744000000,SPI,MOSI: 0xD0;  MISO: 0x00
0.000033744000000,SPI,MOSI: 0x93;  MISO: 0x00
0.000046992000000,SPI,MOSI: 0x06;  MISO: 0x00
0.000049992000000,SPI,MOSI: 0x13;  MISO: 0x00
0.000063240000000,SPI,MOSI: 0x20;  MISO: 0x00
0.000066240000000,SPI,MOSI: 0x00;  MISO: 0x00
0.000079488000000,SPI,MOSI: 0x30;  MISO: 0x00
0.000082486000000,SPI,MOSI: 0x00;  MISO: 0x00
0.000095736000000,SPI,MOSI: 0x10;  MISO: 0x00
0.000098734000000,SPI,MOSI: 0x02;  MISO: 0x00
0.000111984000000,SPI,MOSI: 0x40;  MISO: 0x00
0.000114982000000,SPI,MOSI: 0xEB;  MISO: 0x00
0.000128232000000,SPI,MOSI: 0x80;  MISO: 0x00
0.000131230000000,SPI,MOSI: 0x0A;  MISO: 0x00

Try the changes to the code, and see what happens.


How to round up millis() when divided into minutes?

To round to the nearest X in fixed point arithmetic: add 1/2 X (in the base units, msec, in this case) and divide by X (again, in the base units) so:
milliseconds = (milliseconds + (30*1000L))/(60*1000L);

The addition of 1/2 X causes a carry of one whole X if the fractional X in the original quantity was 1/2 X or greater. (Likewise, if the fractional X was less than 1/2 X, no carry will result).

Integer division naturally truncates any fractional amounts, so you'll be left with the rounded integer result.


You can turn on verbose compiling.
This will show all the compiler commands used by Arduino IDE.

The ino file is converted to a .cpp file (which you can see in the verbose output). Basically the conversion is as follows:

merge all .ino files into one big .ino file with the [project].ino
file first
Add arduino.h
Add all function declarations of methods defined in the .ino files
Save as .cpp file

As to the lack of main method.
The core contains a main.cpp file which defines main in avr world this looks like

int main(void)
{
    init();

    initVariant();

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

    setup();

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

    return 0;
}


Problem solved! By taping twice the reset and holding it the second time I managed to program my board and now the arduino ide detectes it and it works as expected.

Taping and releasing the button twice did not work but holding it the second time worked for me. I am a almost complete noob in electronics for now so to me is black magic that not releasing the button did the job instead of what everyone else is suggesting.

I hope this helps a newbie sometime in the future that is frustrated with his/er bricked board


Using MMA8451 accelerometer to count steps

Change your if statement - remove ; (semicolon) from the end.

Use this:

if (event.acceleration.x >= 5)
accum = accum + 1;

Notice there is no semicolon after if statement


How to wire a small quadcopter drone with resistor and breadboard (If possible)?

You need resistors where that article puts them, otherwise you could brownout the whole thing. You may be able to get away without a PCB, at the cost of reduced stability. Find or borrow the three resistors needed for the project, and then I recommend that you order both a large pack of 1% resistors as well as a variety of PCBs when you are able to.


Arduino UNO reprogram the MEGA8u2 using external programmer

Sure you can. Solder in a 6 pin header and you can program the ATMega8U2 using any Atmel hardware programmer. It's just a standard MCU, after all.  I'm not sure how the DFU side of things works - whether it's built into the chip in ROM or not1, but if it's just a bootloader in flash your programming may wipe it out stopping DFU from working in future. Not a problem if you can't get into DFU mode anyway.

1: The DFU is firmware stored in the "boot" region of the flash. As long as you don't erase or overwrite that region of the flash DFU will still function in future. Of course, you can also re-install the DFU firmware at any time you like.


Arduino Uno R3 not working with Cytron shield GPS 53

Your GPS board supports sending the data to the USB socket on the Arduino, sending it to pins 0 and 1, or sending it to a Software Serial port.  The first two options are going to confuse the output you are getting from the Arduino, so you should probably use the Software Serial option (read the manual on how to do that).

The data that you receive on the Arduino from the software serial port will need forwarding to the USB serial port that your PC is connected to, you will have to right a program to do this, but its not a difficult program and I'm sure there are examples out there.

If you want to make this mobile, you will need a battery to power the kit and an LCD display to show your results (get one with an I2C 'backpack' it will be easier to program).

Hopefully that should give you a start.


Arduino Yun's sample "Bridge" code not working

I ended up doing two things. First I got a replacement hardware. That made the bridge code start working.

And I also changed the port from /dev/tty.usbmodem1431 to /dev/cu.usbmodem1431. As shown in the picture below. That fixed the issue with IDE getting stuck at "Uploading...".

Not sure if this fix will last.


I just used a different motor-shield and it works now, thank you all for your replies and research in this!


Burning a bootloader onto my Arduino MEGA 2560 without another arduino board, or isp board

You need a programmer (isp or Arduino board as programmer). It is not possible to burn a bootloader without it. The USBasp version 2 plus a 10 to 6 pin adapter cost about 2 dollars.


elechouse Voice recognition v3 module not responding when i send command using Access port serial tool

The module can't communicate with Serial Monitor over a USB to TTL Serial adapter. It uses binary communication. Use Arduino, Arduino library and one of the example sketches of the library to communicate with the VR module.

And read the manual.


How to connect a 240x320 37-pin TFT to an Arduino Nano?

The Nano isn't a good choice for driving that screen. You need almost all the pins of the Nano to connect to the screen alone, and there's not enough to include the touch-screen as well. And that's when you're not using the serial port of the Arduino (TX/RX pins) for communication with the PC.

You need to connect:

16 data pins
/CS pin
/RS pin
/WR pin
Optionally RD pin, or tie it to 3.3V
/RESET pin

And all those need to be level shifted to 3.3V.

You need to provide 3.3V to VCC1/2 and VCI.  The LED A connects to 5V (since it has more current capacity than the 3.3V) and each LED Kx pin through a suitable resistor (220Ω maybe) to ground.

The touchscreen needs the X- and Y- pins connecting to a digital IO pin, and the X+ and Y+ pins to analog IO pins that can also double as digital IO pins (so not A6/A7 on boards that have them).

And then you need to obtain or write the software to drive the ILI9320 through the 16-bit interface.

Driving the interface is simple enough:

Initially:

Set /CS HIGH
Set /WR HIGH
Set /RD HIGH (if not tied to 3.3V)
Set /RESET HIGH
Short delay
Set /RESET LOW
Short delay
Set /RESET HIGH

Then to transfer a group of 16-bit words:

Set /CS LOW
Set the value to write on the 16 data pins
Pulse /WR LOW then HIGH
Repeat from 2 for each word
Set /CS HIGH

Refer to the ILI9320 datasheet for how to control the chip, or use existing library code (does uTFT or u8glib support it?).

For the touch screen it's a case of setting Y- LOW and Y+ HIGH, and X- and X+ to INPUT, then reading the analog value from X+.  Repeat with X- set LOW and X+ set HIGH, and both Y set to INPUT, and read the analog value from Y+.

You can also get better results by reading multiple inverted settings:

Y- = LOW, Y+ = HIGH, X- = INPUT, Read X+.
Y- = HIGH, Y- = LOW, X- = INPUT, Read X+.
Subtract the second reading from 1023
Add the first and (modified) second reading
Divide by two.
Repeat for X-/X+ reading from Y+.

You can also take multiple readings and average them out to reduce noise and stabilise the output somewhat.

And of course on top of all that you need to find a way to connect to a 0.5mm pitch connector. Normally a 0.5mm pitch FPC socket is used, which means a PCB with one on.  You may be able to find 37 pin adaptor for it, but 37 pins isn't a common format.  Normally 50 pin is more common to accommodate a more general purpose interface including the M0-M2 pins that allow you to select the interface type, as well as an 18-bit data bus to allow full RGB6/6/6 interfacing, and even buffer-less clocking of raw display data for very high speed display updates by MCUs that support such an interface.


Yes, it is as simple as that.

However, since the pin is pulled up already you could also do this:

pinMode(pin, INPUT);
digitalWrite(pin, LOW);

// Turn off
pinMode(pin, OUTPUT);

// Turn on
pinMode(PIN, INPUT);

That then emulates an Open Drain pin which means you're not actively driving the pin when turned on, only when turned off.

Personally I prefer system that are active low not active high, and are pulled down by default (normally off) so that you don't waste power driving the pin in order to save power (it's kind of silly really) - you drive the pin to turn on and let the pin float to turn off (especially good with deep deep comatose sleep on some MCUs where the IO pins all switch off).

However the designers of this module decided otherwise, so you're stuck with driving the pin LOW to make it sleep.


Thanks again for your contributions.

I've gone ahead and decided to go with the following code. Its purpose is to turn vol up or down based on current car MPH. I choose to define brackets that cover a range of values. When one bracket ends, another begins. I've also set the previous bracket to current bracket at the end of each loop so that the application knows where it was previously, so that if it hops above or goes under a defined bracket, it does the desired action.

I've used a random generator to supply the MPH for testing purposes for now and commented out a few things that disturbed the testing process. If you'd like to critique this code to make is better, please let me know.

Note: I've also borrowed some of this code from another individual (Matthew McMillan, http://matthewcmcmillan.blogspot.com) who wanted to figure out how to convert a vehicle speed sensor wire info into MPH. I needed this code in order to make use of the vehicle's speed.

#include <SPI.h>
#include <Wire.h>

const int lightPin = 0;
const int hardwareCounterPin = 5;
const int samplePeriod = 1000; //in milliseconds
const float pulsesPerMile = 4000; // this is pulses per mile for Toyota. Other cars are different.
const float convertMph = pulsesPerMile/3600;
unsigned int count;
float mph;
unsigned int imph;
int roundedMph;
int previousMph;
int prevCount;

// Declare brackets
const int BracketA = 1;
const int BracketB = 2;
const int BracketC = 3;
const int BracketD = 4;
const int BracketE = 5;
const int BracketF = 6;

// Initialize Previous and Current Brackets
int PreviousBracket = 1;
int CurrentBracket = 1;

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

  TCCR1A = 0; //Configure hardware counter
  TCNT1 = 0;  // Reset hardware counter to zero
}

void loop() {

  /////////////////////////////////////////////////////////////
  // This uses the hardware pulse counter on the Arduino.
  // Currently it collects samples for one second.
  //
  bitSet(TCCR1B, CS12); // start counting pulses
  bitSet(TCCR1B, CS11); // Clock on rising edge
  delay(samplePeriod); // Allow pulse counter to collect for samplePeriod
  TCCR1B = 0; // stop counting
  count = TCNT1; // Store the hardware counter in a variable
  TCNT1 = 0;     // Reset hardware counter to zero
  mph = (count/convertMph)*10; // Convert pulse count into mph.
  imph = (unsigned int) mph; // Cast to integer. 10x allows retaining 10th of mph resolution.

  int x = imph / 10;
  int y = imph % 10;

  // Round to whole mile per hour
  //if(y >= 5){
  //  roundedMph = x + 1;
  //}else{
  //  roundedMph = x;
 // }

  //Code to write your own MPH for testing purposes.
  //if (Serial.available() > 0) {
                // read the incoming byte:
               // roundedMph = Serial.read();
               //}

  //If mph is less than 1mph just show 0mph.
  //Readings of 0.9mph or lower are some what erratic and can
  //occasionally be triggered by electrical noise.
  //if(x == 0){
  //  roundedMph = 0;
 // }

  roundedMph = random(1,80);

  // Don't display mph readings that are more than 50 mph higher than the
  // previous reading because it is probably a spurious reading.
  // Accelerating 50mph in one second is rocketship fast so it is probably
  // not real.
  if((roundedMph - previousMph) > 50){
    roundedMph = previousMph;
  }

  //Place the gatherered MPH value into a bracket
  //---------------------------------------------
  if(roundedMph >= 0 && roundedMph < 20) {
   CurrentBracket = BracketA;  //Value1
   Serial.println("I Choose Bracket A");
    }

  if(roundedMph >= 20 && roundedMph < 30) {
   CurrentBracket = BracketB;  //Value2
   Serial.println("I Choose Bracket B");
    }

  if(roundedMph >= 30 && roundedMph < 40) {
   CurrentBracket = BracketC;  //Value3
   Serial.println("I Choose Bracket C");
    }

  if(roundedMph >= 40 && roundedMph < 50) {
   CurrentBracket = BracketD;  //Value4
   Serial.println("I Choose Bracket D");
    }

  if(roundedMph >= 50 && roundedMph < 65) {
   CurrentBracket = BracketE;  //Value5
   Serial.println("I Choose Bracket E");
    }

  if(roundedMph >= 65) {
   CurrentBracket = BracketF;  //Value6
   Serial.println("I Choose Bracket F");
    }

 //Decide if bracket stayed the same, went up, or down.
 //---------------------------------------------------
 if(CurrentBracket == PreviousBracket) {
 //Do Nothing
 Serial.println("Nothing Changed");
 }

if(CurrentBracket > PreviousBracket) {
 //Command for Vol Up
 int VolUp;
 VolUp = CurrentBracket - PreviousBracket;
Serial.println("Volume Went Up One by ");
Serial.println(VolUp);
delay(2000); // Delay to not change Vol to fast if near threshold
}

if(CurrentBracket < PreviousBracket) {
  //Command for Vol Down
  int VolDown;
  VolDown = PreviousBracket - CurrentBracket;
 Serial.println("Volume Went Down One by ");
 Serial.println(VolDown);
 delay(2000); // Delay to not change Vol to fast if near threshold
 }
  previousMph = roundedMph; // Set previousMph for use in next loop.
  PreviousBracket = CurrentBracket; //Set PreviousBracket for use in next loop.
}


Controlling Arduino through Internet and Bluetooth

If I were you, I would separate the "hardware" from the "software". This is quite an interesting "pattern". It's used by almost every Operating System, to assure compatibility with devices all around the world.

But how?

Layers

The "OSI-model" typically describes a few layers. But to me, the most interesting part is the difference between "Host layer" and "Media layer".

Media Layer

The media layer(s) typically handle the transportation of your bits, addressing and data collision. In "the internet" you can 'simply' change from copper to glasfiber without it being noticeable in your end application (apart from being faster).

Host layer

The same for the host layers, whatever PC or network adapter you have, your program will run fine (if this abstraction/integration is done well).

Applying this

So how do we apply this? In a basic, small application.

We want our Host to not care too much about which Media(layer) it is using.
The Arduino has to be able to be configured or detect which media layer it is using.

Something like this is neccesary (this is not actual code, more pseudo code):

String messageBuffer = "";

void Setup(){
   setupWifi(pin1,pin2);
   setupBluetooth(pin3,pin4);
}

void Loop(){
   messageBuffer = getWifiMessage();
   handleMessage(messageBuffer);
   messageBuffer = getBluetoothMessage();
   handleMessage(messageBuffer);
}

If you set up this correctly, you'll only have to write the buffer handling code once. Which is very useful!
Handling buffers along with all the logic/effects it will cause, should be solid. You (probably) don't want different behaviour when you use bluetooth as when you use WiFi. Imagine your web-browser only working when you use copper, but not when you use glasfiber :)

Protocol

Your message should be exactly the same for WiFi and bluetooth. This way you won't have to deal with two different protocols and it will be easier to implement this at the other (control) side.

A good protocol/message can be this:

"@12#13,255,255,0;"

I use the @ as an start indication. This is very usefull for receiving, since you know where to start (obviously?).
You'll have to make rules for what will follow (maybe a set amount of characters, in my example, between @ and # it will indicate an "address". When you send it to multiple devices, you only want (in my example) device 12 to react. This often is handled by the bluetooth or wifi already, but it can be good to have some sort of unique header. So that random messages (which might look alike) won't be seen as one of your messages.
An message ID is useful, you kinda want to have different types of messages, for either "LED brightness" or "debug request" or "set output".
Each message could have an x amount of parameters, it's often better to separate these. It's important that you specify the maximal amount of parameters and what behavior they will cause.
Some protocols use a set length, but an end delimiter ";" is often the best way to let the other device know your message is completely received.

Some notes

Try to aim for existing protocols, it will be cool if your device is compatible and creating yet another protocol isn't particularly useful.
Mind that possible transmitted text does not include your start/end delimiters. You could use the message length or exclusions/inclusions in this case.
Be wary that the protocol adds overhead. But usually being able to "read" a message will make it much more easier to program a handler or generally work with it.
Check if the message is fully received and does not have errors. If you have an error, be sure your system can handle it and will respond with a message telling so. In no way your system should lock down on error or not provide a reaction (which makes debugging a pain).

The server

From whatever device you're sending your stuff, it should have bluetooth and/or WiFi. Bluetooth is fairly easy and should get you started quite fast.

If you're using WiFi, you should check if your device can make a TCP/IP connection. TCP/IP is basically a "shell" around your message, to shoot it over the internet ;D it comes with some neat addressing and error checking built in (but you can't be 100% sure there will be no error between your receiver and arduino).

But why?

Not only is it useful to learn how to do this, having to write the handler and protocol specification for both the Wifi and bluetooth (and possible usb, rf, ethernet etc).
Apart from that, in embedded systems, you want to be sure that something works, using different handlers for different physical layers will create vague specific errors and might rip up your program logic. Also, if your protocol/application is used/reviewed by more people, you'll be more certain that it works well.


A MAC address must be unique throughout the environment in which it operates, but apart from that is largely arbitrary.  Typically the problem is solved by selling 3-octet prefixes (called OUI's) to manufacturers, who then uniquely assign the remaining 3 octets to individual device units they manufacturer.

However, if you are unable to discovery a globally unique address assigned to your device by its manufacturer, and know that its traffic will be confined to a local network, you can use a privately assigned (ie, "made up") address with the Locally Administered bit set.   An address of the form

02-xx-xx-xx-xx-xx-xx

or any other with the 2's bit of the first octet set will satisfy this criteria as long as you guarantee that it is unique in your system.

Be especially careful not to set the 1's bit of the first octet - if you do so, traffic will be marked as broadcast and so given wider distribution/attention than needed, wasting network capacity and processor time of connected devices.


Because your program uses various String objects in several different sizes, there's a good chance that heap memory (in RAM) is getting fragmented to the point that String allocation begins to fail, or begins to allocate on top of stack variables.  (Typically, heap and stack work toward each other, from opposite ends of memory that is free after static variables are allocated.)

For example, the code for(int y=1; y<=x; y++){ dashes += "-"; } with x=6 creates half a dozen String objects, all of different lengths.

To avoid this problem, you could carefully release each heap allocated object when done with it, or more effectively, could avoid using String objects, which actually aren't needed in this program.

For example, instead of display.println(String(previousMillis/1000)); say display.println(previousMillis/1000); and instead of building dashes a character at a time before using it, just say "------" in place of dashes.


If else statement not mutually exclusive?

if and else if clauses are mutually exclusive. If the if is true then the else if cannot run.

Therefore it must be the case that the code you posted is being executed twice (at least) - once for SLOT_1 and once for SLOT_2.  Just so fast that you think it's happening at the same time.


Mac Big Sur don't recognize generic Wemos D1 MINI PRO based ESP-8266EX


You want a solenoid.

Looks like people sell ones which are specifically made for door locks.


RC522 RFID reader doesn't read NTAG216 chip

I got my RFID kit (RF522) just this week, but I haven't had a chance to play with it yet - nor do I have an NTAG216 implant. But I remember when I was researching them seeing a couple of posts that had to do with "Authentication errors". The problem for you (maybe) is that they were in Python rather than C:

https://github.com/mxgxw/MFRC522-python/issues/24

and Cotix's link

https://github.com/mj3052/MFRC522-Pi

Give them a lookover and see what they can tell you.

The problem with the PICC_IsNewCardPresent() function is that it gives a Yes/No answer, not a "Yes, but there's an error". In that case it would also return false. But the other code may give you a clue - you'll have to delve into the library...


Using Arduino libraries for adding more functionalities to a bootloader

@Majenko: I think, that the task IS possible, but it is really hard (and Leonardo may need more memory for that eventually and some shields too and so ...) but if I understand the problem, than the Leonardo should pretends to be mass storage device for that application, and pretend it have some folders and files on it, depending which RFID is used to activate it.

The application probabelly is NOT going to format the MSD because it would lose all the user data on it.

So Leonardo can do following:

pretend it is already formatted and have some known filesystem on it (vfat is easy enought and probabelly usable as many USB flash sticks came with it)
when the machine detects inserted USB, it ask for type - so it get MSD
then it will read partition table - Leonardo can emulate it easily, having "just one partition of given size and type" the partition can even be stored as a file on that fileserver to save Leonardo's memory.
next goes reading FAT table and root directory

knowing  the user from RFID it is possible to select the right directory on file server,
then enumerate lengths of all files inside (and directories)
make table with the names and "offset"
send back the FAT as if those files were ordered on the "disk" so each entry points to the following sector, until the last marks EOF
root directory begins after FAT and contains names of the files, their lenghts, dates and starting sectors (and some very basic right like read-only, system and such)
then follows files and directories

each time the machine asks for a "sector", it is possible to compute, in which file the sector is placed, read the portion of a file (potentially fill it with zeroes to "sector lenght" and return it as requested "sector"
if the sector is in directory instead, return the part of directory (that means filenames and such)
if the sector is outside it all (should not happen), return just zeroes.

On the other direction:

if you get something outside structure, put it to temp. file along with address of such stray "sector"
if you get something in a file, just replace the file content on given offset
if you get something in directory, you need to compare it with previous version and "rename file", "create file" or "delete file" acordingly.
it would probabely need two directories on the server for each user - one for actual files, other for "lost sectors" and "deleted files" which could be "reconected", "undeleted" or "attached later" to the files/directories. The second directory can be emptied after "removing USB MSD" when user with given RFID logouts.

It is lot of work, but basically it could be done. It also needs a lot of accounting on the Leonardo and lot of communication with the fileserver, but it is possible to do.

It suppose, that the files on fileserver would not be modified by somebody else while "mounted" and that the Windows machine would not "format" the USB to some kind of filesystem, the Leonardo does not understand (how to translate to the real files on server).

But for the supposed use I think those two conditions could be reasonable. The MSD probabelly just holds the "user profile" so the machine can put in records of hir/her activiti, some stats and so on, probabely it would be just a few growing files maybe even just in root directory.

Anyway I would not like to write such system, as it is terrifying lot of work and a lot of things could go wrong, if there is a bug (or bad connection).

Also the size of required memory for Leonardo is large - probabelly larger, than the Leonardo actually have, but it could be offloaded to the filesystem too (in "hidden directory" not shown to the machine) - which would be slow and hard to manage - or expanded by HW RAM, which would be a lot faster, but needs nontrivial settings.

(Remebers me, how I wrote resident program for DOS, which had just 130 bytes, which swaped in two 16KB widows of EMS where the rest of program (actually interpret of some pseudocode) was placed (it was like 4 or 6 such 16KB pages, but was able to swap itself acordingly) while the remaining two EMS pages was reserverd for data (like 300-400KB total of pseudocode and data) which was also swapped as needed to access everything. From DOS point of view it was just the 130B resident API, from the view of program, which was using it, it was 400KB engine running FORTH-like program and containing database. The result was like 3x faster processing of 2.000+ employes wages.)

Here are the memory restrictions even more tight, but I thing, that it is possible to do such thing, only it is extremely hard to make it work reliably.


Can anyone identify why this incrementer is losing count?

Buttons bounce (at least they appear to, electrically), meaning that if you're fast enough, you can detect multiple pulses per button-press. Usually we don't count the button as being pressed until we read the same value {n} times in a row or for {m} mSec, or some similar technique.

Because you call EEPROM.read() immediately after testing the button, perhaps most times the bouncing will have ceased when the call returns, but once in a while one last bounce slips through.

Nick Gammon, a regular contributer here, has a good discussion of de-bouncing on his web site. Have a look at that and pick a technique that's compatible with what you're trying to do.


How to upload program to board using Arduino sketch ver 1.6?

The checkmark button is used to compile your program (which "verifies" your code), but does not upload it to the board. The "arrow" button is used to compile and upload your program.

If you cannot connect to the device, make sure the correct COM port is selected on the Tools->Ports menu, and make sure you have the correct board selected on Tools->Board (usually an Arduino UNO).

If you have not installed the drivers yet, you will not have a port present for your Arduino. If that is the case, here is a great tutorial that will help you get everything installed and set up correctly: https://learn.adafruit.com/lesson-0-getting-started


Fixed by updating firmware on Wifi Shield.


Unsure about how the code works for this Make-It Robotics kit

Indeed, the way the bitwise operations are written is confusing.

  if((sensor_in & 0xf00)==0)
    sensorValue1=sensor_in & 0xff;
  else if((sensor_in & 0xf00)>>8==1)
    sensorValue2=sensor_in & 0xff;
  if (sensorValue1 == 0x00)
    action1 =action1 & 0xfe;
  if (sensorValue1 == 0xFF)
    action1 = action1 | 0x01;
  if (sensorValue2 == 0x00)
    action1 = action1 | 0x02;
  if (sensorValue2 == 0xFF)
    action1 = action1 & 0xfd;

Basically you have two input values that can be in the same variable - differentiated by the 9th bit of the value.  Values between 0 and 255 relate to one sensor, between 256 and 511 to the other.  The bitwise operators split that into sensorValue1 and sensorValue2 accordingly.

Then those sensor values are compared to 0 or 255 and used to define the action to perform - that action being comprised of the lowest two bits of a byte variable, so you have three possible actions:

0 = both sensors off
1 = sensor 1 on, sensor 2 off
2 = sensor 1 off, sensor 2 on
3 = both sensors on

The comments in the program also tell you this information:

action1
         left        right
0x00    black        black
0x01    black        white
0x02    white        black
0x03    white        white

Now you have how to deal with the action value:

if(action1 != action2)
{
  if (action1 == 3 )
    line_following.go_forward(50);
  if (action1 == 1)
    line_following.line_following_turn_left(50);
  if (action1 == 2)
    line_following.line_following_turn_right(50);
  if (action1 == 0)
    line_following.go_forward(50);
}
action2=action1;

So if the action has changed, we can change what we are doing:

If action is 3, so if both sensors read as white, or if action is 0, so both sensors read black (in other words if both sensors read the same) then move forwards.
If action is 1 (so the left sensor reads black) then turn to the left.
If action is 2 (so the right sensor reads black) then turn to the right.

So basically if it doesn't know anything better, it drives forwards, otherwise it turns in the direction that it finds the black line, thus keeping it always on that line.  As it drifts off the line one sensor will sense white, so the robot will turn away from that whiteness and back on to the line.


How to get read user input from DAQ for a given time interval?

It sounds like you are trying to register when a push button has been pressed for 5 seconds. In other words, you want your flag to turn on after the button has been held for at least 5 seconds, and then turn off once the user releases the button.

I would suggest looking at the example programs to do with button debounce. In particular, the debounce example/tutorial from the Arduino website.

My version of the program would look like this:

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int buttonOutput;            // the current reading from the input pin
int lastReading = LOW;       // the previous reading from the input pin

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 5000;  // the debounce time; 5000ms = 5 seconds

void setup() {
    pinMode(buttonPin, INPUT);
    pinMode(ledPin, OUTPUT);

    // set initial LED state
    digitalWrite(ledPin, LOW);
}

void loop() {
    // read the state of the switch into a local variable:
    int reading = digitalRead(buttonPin);

    // check to see if you just pressed the button
    // (i.e. the input went from LOW to HIGH), and you've waited long enough
    // since the last press to ignore any noise:

    // If the switch changed, from off to on (LOW to HIGH)
    // ie, reading == HIGH and lastReading == LOW
    if (reading && !lastReading) {
    // reset the debouncing timer
    lastDebounceTime = millis();
    }

    // If the button is still pressed
    if (reading) {
        // and has been pressed for longer than the debounce delay
        if ((millis() - lastDebounceTime) > debounceDelay) {
            // Then turn on the button output
            buttonOutput = HIGH;
        }
    }
    else {
        // However if the button is not pressed, then turn off the button output
        buttonOutput = HIGH;
    }

    // set the LED:
    digitalWrite(ledPin, buttonOutput);

    // save the reading. Next time through the loop, it'll be the lastReading:
    lastReading = reading;
}

The second part of your question asks how you can register a button press after a complete button press cycle. In other words; the button is pressed, the button is released - only after this cycle has completed recognise it as a button push.

You don't have to detect the whole cycle, all you have to detect is the button being released. After all, the button cannot be released if it hasn't been pressed first.

You could adapt the State Change Detection example/tutorial from the Arduino website so that it is looking for the falling edge of the button input.

You could simplify the edge detection statements to the following:

if (!buttonState  && buttonStateLast) {

Basically it requires the last reading of the button to be HIGH and the current reading of the button state to be a LOW.


Use timer interrupts to read and store the data from serial. Lets assume you are receiving data at baud rate of 115200 in default configuration (8data bits, 1 stop bit), 115200/9=12800 bytes per second, approximately 80 micro seconds for every byte, create a timer interrupt that is called once every 2 millisecond(Choose best time for your application making sure that receiver buffer does not overflow), In 2milli seconds 25bytes of data will be available in the buffer. So you can read data in batches of 25 each. From the interrupt read and store the available data from the buffer.


Receive multiple data from arduino using String builder

You can convert each value to string before sending to bluetooth using string.contain("string"), like this:

if (sbprint.contains("C"){
    temptv.setText(sbprint);}
if (sbprint.contains("H")){
    humidtytv.setText(sbprint);}


Is it possible to upload previously compiled binary?

Yes!
Its possible that you can upload a previously complied binary, using

AVRDUDE - a command line utility which is actually used to upload binaries, behind the arduino IDE.

You can find AVRDUDE in
Arduino folder > hardware  > tools > avr > bin

This some documentation for AVRDUDE
http://www.nongnu.org/avrdude/user-manual/avrdude.html

else simplest thing you can do is turn on verbose output during upload and watch for a command in the end with AVRDUDE in it along with the path of hex file, just copy paste &  run the same command in CommandLine; your task is accomplished.


Is it possible for Arduino to send a message to the internet without using a GSM shield?

Use this example to open a webpage using a push button, you need Python installed on your Windows.

Step 01:

Upload this sketch to your arduino:

const int buttonPin = 2; // the number of the pushbutton pin
int buttonState = 0;

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

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
  Serial.println("OpenWebPage");
  }
}

The Circuit:

pushbutton attached to pin 2 from +5V
10K resistor attached to pin 2 from ground

Step 02:

Open a text editor and paste this code to a new file:

import serial
from subprocess import call

ser = serial.Serial(
    port='COM5', # Change this to your COM port number
    baudrate=9600,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_TWO,
    bytesize=serial.SEVENBITS
)

if (ser.isOpen()):
    print "Serial Port is Open..."
    print "Waiting for a command ..."
    while 1:
        cmd = ser.readline()
        if cmd.strip() == "OpenWebPage":
            print "Received command from Arduino..."
            print "Opening webpage..."
            call(["explorer", "http://www.google.com"]) #change it the address you want

Save the file to your desktop, name it : SerialListener.py

Step 03

Now open a Command Prompt window.
Navigate to your desktop folder and execute this command: python SerialListener.py.
You should see Serial Port is Open... Waiting for a command ...
Press the push button, and a webpage should open in your default browser.


Wire.endTransmission() hangs, but only, if wire.begin(); is called with an address (MKR WiFi 1010)

I want to push data from the slaves to the master immediately when they receive said data.

So that means, that each slaves becomes master directly after it has received data from the MKR. This is still a multi-master setup, even while you are avoiding collisions through a fixed protocol. The Wire library does not support multi-master.

But I also don't understand, why you would need this. Your protocol does this: The MKR sends data to a slave (triggering it and maybe also sending some commands). Then the slave should send data back to the master. Then the transmission ends. This is normally done in I2C with just one master. The master does a master write (via Wire.endTransmission() and sends some command data to the slave. The slave will prepare the data, that the master requested, in it's buffer. Then the master will start a master read (via Wire.requestFrom()) which reads the data from the slave.

So you don't need a multi-master setup for this. It does exactly, what you described, but with only one master.


Basically, your question comes down to this:

"How to generate two PWM signals with only one timer."

(Once you've got that figured out, you could set up 6 PWM channels)

Keep in mind that there also are PWM generator IC's, if you don't want to use up all your timers, which can be usefull for other things.

IF you really want to set all outputs to toggle at the same time (based on your code example) why won't you just use one PWM signal, and drive all the 4 devices with the same signal? (Given you're not going to change it)
IF you're going to drive motors, why would you need 4 different PWM signals? It's often enough to only use one PWM signal for the right tires/tracks and one PWM signal for the left tires/tracks.

Setting the max

Since we want to generate different PWM signals from one timer, we can't just make the timer overrun (and generate a pulse or switch polarity at that point).
We want to let the timer run to completion over and over, and only change the signal when it reaches a set value.

The datasheet tells us this:

  The TOP value can be assigned to be the fixed value 0xFF
  (MAX) or the value stored in the OCR0A Register. (328P datasheet 15.2.1 Definitions)

Setting a limit per pin

We want to set 2 limits on one timer, each timer has an output compare register (OCR), the action will be generated when the timer hits this value.

  The Timer/Counter (TCNT0) and Output Compare Registers (OCR0A and OCR0B) are 8-bit registers. Interrupt
  request (abbreviated to Int.Req. in the figure) signals are all visible in the Timer Interrupt Flag Register (TIFR0).
  All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK0). (328P datasheet 15.2.2 Registers)

Extra info on compare

Below you can read some extra info on the signaling.
What actually will happen, depends on how the WGM

  15.5 Output Compare Unit
  The 8-bit comparator continuously compares TCNT0 with the Output Compare Registers (OCR0A and
  OCR0B). Whenever TCNT0 equals OCR0A or OCR0B, the comparator signals a match. A match will set the
  Output Compare Flag (OCF0A or OCF0B) at the next timer clock cycle. If the corresponding interrupt is
  enabled, the Output Compare Flag generates an Output Compare interrupt. The Output Compare Flag is
  automatically cleared when the interrupt is executed. Alternatively, the flag can be cleared by software by writing
  a logical one to its I/O bit location. The Waveform Generator uses the match signal to generate an output
  according to operating mode set by the WGM02:0 bits and Compare Output mode (COM0x1:0) bits. The max
  and bottom signals are used by the Waveform Generator for handling the special cases of the extreme values in
  some modes of operation (”Modes of Operation” on page 98).

Fast PWM
The actual settings are different per mode/modus, but for fast PWM we have:

Table 15-3. Compare Output Mode, Fast PWM Mode(1)
COM0A1 COM0A0 Description
0      0      Normal port operation, OC0A disconnected.
0      1      WGM02 = 0: Normal Port Operation, OC0A Disconnected.
              WGM02 = 1: Toggle OC0A on Compare Match.
1      0      Clear OC0A on Compare Match, set OC0A at BOTTOM, (non-inverting mode).
1      1      Set OC0A on Compare Match, clear OC0A at BOTTOM, (inverting mode).

The table tells us we need to set COM0A1 and COM0A0 to 1.

COM0B1 COM0B0 Description
0      0      Normal port operation, OC0B disconnected.
0      1      Reserved
1      0      Clear OC0B on Compare Match, set OC0B at BOTTOM, (non-inverting mode)

This table tells us we need to set COM0B1 and COM0B0 to 1.

WGM mode

If it's all set up, we only need to put the PWM in the right mode.

Mode WGM02 WGM01 WGM00 Timer/Counter TOP  Update-OCRx TOV-on
0    0     0     0     Normal        0xFF Immediate   MAX
1    0     0     1     PWM,P-Correct 0xFF TOP         BOTTOM
2    0     1     0     CTC           OCRA Immediate   MAX
3    0     1     1     Fast PWM      0xFF BOTTOM      MAX

So we'll need to set WGM02 to 0 and WGM01 and WGM00 to 1, to use fast PWM.F

Succes?

You should now be able to change the PWM's of these pins by setting the output compare registers of these.
Getting the double PWM of the other timer ready, shouldn't be much more different.
Be sure to set the right prescaler. Though it depends on a lot of external things.


They aren't evil per se, but they do tend to get overused where there is no good reason to use them.

There are plenty of times when global variables are advantageous. Especially since programming an Arduino is, under the hood, vastly different to programming a PC.

The biggest benefit to global variables is static allocation. Especially with large and complex variables such as class instances. Dynamic allocation (the use of new etc) is frowned upon due to lack of resources.

Also you don't get a single call tree like you do in a normal C program (single main() function calling other functions) - instead you effectively get two separate trees (setup() calling functions, then loop() calling functions), which means that sometimes global variables are the only way to achieve your goal (i.e., if you want to use it in both setup() and loop()).

So no, they're not evil, and on an Arduino they have more and better uses than on a PC.


Does Keyboard.begin() and Keyboard.end() make my code slower?

The Keyboard::begin() and Keyboard::end() functions,  if you actually look at the code are empty functions. They do nothing.

In theory the compiler should just optimise them out.


How to sense mobile signal coming to a room using arduino uno

You can't.

Mobile phone signals don't respect artificial boundaries like a room's walls.  You can detect the mobile phone signal from the local cell, but you can't narrow it down to "what is talking to a device in this room".

And if you could just intercept the signals and find out who was calling whom there wouldn't be much security, would there? It's all encrypted and locked down - you can't get at that sort of information "from the air".

What you could do though, is to have your mobile phone send out the phone number of an incoming call via bluetooth (many hands free kits already use this kind of facility) and have your Arduino receive that information to display it.


The Mysterious Case of the Mostly-Vegetable Servo

Is my servo indeed broken?

Yes.

  What's not functioning correctly?

As you said, some of the gears must have shifted in some way hindering the smooth mouvement of the servo or making it simply not working correctly.

  Can it easily be repaired?

Well, it depends on you. Do you like repairing EXTREMELY small things? Are you skilled at that. I would say no, because it requires a lot of knowlage on the servo to be able to remove it, fix it, and not to forget, replace it into its original case. Simply buying a new one is quite cheaper and simpler.