Project 2: Arduino controlled spaceship interface

So everyone else knows where this is from enter image description here.

EDIT

I have edited the image you gave to attempt to answer your question on 'wiring' :

The first image shows simply and crudely how the parts are basically connected or there relationship.

The second one shows how the current flows on the circuit, there is a key.

What you need to do is take the information from the link you give in the comment and apply logic to it, like if you used a logic probe and stuck it one end of the switch, the right side in that image, it would be high, if though you do so on the left it would be low. Hence no current flows in that circuit but there is current flow in the circuit looking at it.

What you have not examined is the code related to your project or the description of the project.

Looking at the code:

// Create a global variable to hold the
// state of the switch. This variable is persistent
// throughout the program. Whenever you refer to
// switchState, you’re talking about the number it holds
int switchstate = 0;

void setup() {
  // declare the LED pins as outputs
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);

  // declare the switch pin as an input
  pinMode(2, INPUT);
}

void loop() {

  // read the value of the switch
  // digitalRead() checks to see if there is voltage
  // on the pin or not
  switchstate = digitalRead(2);

  // if the button is not pressed
  // turn on the green LED and off the red LEDs
  if (switchstate == LOW) {
    digitalWrite(3, HIGH); // turn the green LED on pin 3 on
    digitalWrite(4, LOW);  // turn the red LED on pin 4 off
    digitalWrite(5, LOW);  // turn the red LED on pin 5 off
  }
  // this else is part of the above if() statement.
  // if the switch is not LOW (the button is pressed)
  // turn off the green LED and blink alternatively the red LEDs
  else {
    digitalWrite(3, LOW);  // turn the green LED on pin 3 off
    digitalWrite(4, LOW);  // turn the red LED on pin 4 off
    digitalWrite(5, HIGH); // turn the red LED on pin 5 on
    // wait for a quarter second before changing the light
    delay(250);
    digitalWrite(4, HIGH); // turn the red LED on pin 4 on
    digitalWrite(5, LOW);  // turn the red LED on pin 5 off
    // wait for a quarter second before changing the light
    delay(250);
  }
}

From this we see that the default state of this code in the first if() statement is to turn on PIN3 and leave the rest off when the button is not pressed.

From Arduino:

   A green LED will be ON, until you press a button. When the Arduino
 gets a signal from the button, the green light will turn off and 2
 other lights will start blinking.


Arduino zero Error: unable to find CMSIS-DAP device

I had exactly the same error with the same board. Running the IDE as root solved the problem. So, Chris was right pointing out a permission issue.
I found more information here : http://bitofahack.com/post/1437909576
Then I added the file /etc/udev/rules.d/98-openocd.rules :
ACTION!="add|change", GOTO="openocd_rules_end"
SUBSYSTEM!="usb|tty|hidraw", GOTO="openocd_rules_end"
ATTRS{product}=="*CMSIS-DAP*", MODE="664", GROUP="plugdev"
LABEL="openocd_rules_end"

I then ensured that I was member of group plugdev.
udev looks for changes in his rules directory so you don't have
to restart it.
I plugged the board again and it worked.
Note that you can force udev to read the rule files again by entering :
sudo udevadm control --reload

I had to do this because I first made a mistake in the rule file.
Hope this helps.


Controlling two AC devices, device turning on incorrectly

Imraan, you have most definitely NOT build your circuit safely as to do so is impossible on a 'breadboard' when using 220 VAC.  The contacts on these boards are extremely poor not to mention that the separation between the metal contacts is inadequate.  Please read up on track separation for mains voltages on PCB's to get an idea of what is required.
The commonly used 0.1" pitch strip board is also unsuitable for mains voltages.


Have Arduino write data to a MySQL database?

It's possible if you forget about the Arduino directly writing to the database.

Simply put, the Arduino is restricted to a serial connection.  To directly communicate with MySQL you would need a network connection, and then implement the MySQL protocol - a huuuge amount of work.

The normal way is to have an adapter program running on the PC which receives data from the Arduino over the serial connection, then performs any insert, select, etc instructions on the MySQL for you.

There is a "MySQL Connector" available* (https://launchpad.net/mysql-arduino) but of course that requires you to have an active network connection of some form to your Arduino.  Remember that the Arduino (certainly the Uno) is very limited on memory and program space, so having the Arduino connect direct, and doing anything else, might be mutually exclusive.

*Nice find, @SomeHardwareGuy...


Serial.parseInt() takes longer time than desired

this is what you want:

void read() {
  for (i = 0; i < 7; i++) {
    while (!Serial.available()); // wait forever for some input
    data[i] = Serial.parseInt();
  }
  flag = 1;
}


From what I understand, you want to read two ADC channels
simultaneously. First, you have to understand that you cannot read them
exactly at the same time, as you have a single ADC. What you can do,
however, is read them one after the other: you read the V channel, then
the I channel, then the V channel again, etc. This means you will have
to change the multiplexer setting (the ADMUX register) in between the
readings. The most convenient place to do this is within the ADC ISR,
the logic of which becomes:

Save the value that has just been read
switch the multiplexer to the other channel
turn off the ADC if you are done.

Example code (not tested):

const byte PIN_V = 0;  // A0
const byte PIN_I = 1;  // A1

// ADC complete ISR.
ISR(ADC_vect)
{
    if (ADMUX & 7 == PIN_V) {
        // We have just read the V channel.
        // Save the value and switch to the I channel.
        resultsV[resultNumber] = ADC;
        ADMUX = bit(REFS0) | PIN_I;
    } else {
        // Otherwise we completed a (V, I) pair, we can increment
        // resultNumber.
        resultsI[resultNumber++] = ADC;
        ADMUX = bit(REFS0) | PIN_V;
    }

    // Turn off the ADC when done.
    if (resultNumber == MAX_RESULTS)
        ADCSRA = 0;
}

Note that this example assumes you do the readings in the (V, I) order.
Thus, within setup(), you have to initialize the multiplexer for the V
channel, as in

ADMUX = bit(REFS0) | PIN_V;


just for a closure:

added an array (thank to Juraj):const char* topicsArry[]={deviceTopic, msgTopic, groupTopic, "HomePi/Dvir/Clock", "HomePi/Dvir/Alerts"};

a for loop to over this that loop, and using sizeof ( which was not trivial for me ), led to :

void reconnect() {
        // Loop until we're reconnected
        while (!client.connected()) {
                Serial.print("Attempting MQTT connection...");
                // Attempt to connect
                if (client.connect(deviceName,user, passw)) {
                        Serial.println("connected");
                        pub_msg("Power On");
                        for (int i=0; i<=sizeof(topicsArry)/sizeof(char *); i++){
                          client.subscribe(topicsArry[i]);
                          char msg[50];
                          sprintf(msg, "Subscribed to %s",topicsArry[i]);
                          pub_msg(msg);
                        }
                } else {
                        Serial.print("failed, rc=");
                        Serial.print(client.state());
                        Serial.println(" try again in 5 seconds");
                        // Wait 5 seconds before retrying
                        delay(5000);
                }
        }
}


This is a bug in UECIDE. It doesn't like lambda functions in constructors.

A complete rewrite of the sketch parser to use Exuberant Ctags is under way.


To answer this question

The arduino in question was broken. Shortly after asking I was not even able to connect it to my PC successfully. I replaced it with a new one and everything runs smoothly now for months.

Since this unit survived a whole product development-process I am not surprised at all. In fact I had three and expected one to get killed in action.


Global Variable not able to be accessed in function?

The problem is that this is not an Arduino Sketch, but a processing file which is noted by the initial import statement that is Java based. Because the Arduino IDE is not very sophisticated, it didn't shout out obvious errors such as import type not defined or even ThresholdGraph not defined.

To use this file it is necessary to use the following IDE: https://processing.org/reference/environment/


You have to use a constant expression, one that produce always the same value.

const int specLength = 17;
int spec[specLength - 1];

Otherwise, the compiler won't know how much space reserve for the array.

The problem with C/C++ is that the compiler doesn't really know if a variable is modified somewhere or not (thru pointers, for example). You have to tell the compiler that something is static, not changing.

You can also use a #define for the same porpuse:

#define SPEC_LENGTH 17
int spec[SPEC_LENGTH]

Why both? const int val=17 means that val has a type (int). Using #define is just a text search-and-replace before compiling. So, SPEC_LENGTH has no type at all. If needed, you have to use a cast, like (int) SPEC_LENGTH.


The specifications for each stepper motor varies, with the larger models having the greater torque. With great torque comes the requirement of great power. A quick search for nema 17 stepper motors finds the torque figures on the low side of your request, while the nema 23 motors display a greater range, including your figures.

The additional power requirements may exceed the capabilities of the Arduino Motor Shield (2a per channel, 4a max), while the A4988 board specifies up to 2a per coil. Also note that to achieve the use of the higher power levels, these boards will require heat sinks.

If you expect to require the higher figure for torque, consider to research for a driver board that has a greater power limit, "just in case".


Altering code to run a timer while checking for a data input

What's with the double-spacing? It makes it hard to read.

if(ssec==10);

That is wrong.

Arduino programming traps, tips and style guide

  I understand that it is very hard to run these together at the same time due to the fact that I am using a delay function to run the timer.

I know StackExchange doesn't like link-only answers, but it is this or copy-and-paste:

How to do multiple things at once ... like cook bacon and eggs


The led strips will have their own current limiting / drivers. A couple of quick calculations:

24V at 12W is (I=P/V) 12/24 = 0.5A per meter
5 meters = 0.5*5 = 2.5A

So each strip takes 2.5A. The CAT4101 is a 1A max driver, but since it is a constant current driver it's not suitable for a strip that has its own current control built in.

I suspect each meter consists of 10 chains of 6 LEDs with a current limiting resistor or two. Out of interest, calculations:

6 LEDs at (say) 3V forward voltage would be 18V.
24 - 18 = 6 volts to drop
500mA divided by 10 chains = 50mA
R=V/I = 6 / 0.05 = 120Ω current limiting resistors.
P=I²R = 0.05²×6 = 300mW dissipated from the resistors.

Instead all you need is an N-channel MOSFET as a low-side switch that can operate with that much current and not dissipate too much heat while switching. The more you derate the MOSFET the less heatsinking it would need.

A quick look on Digikey gave a possible match of PSMN022-30PL - 30V, 30A, 27mΩ (typ) at 4.5V gate voltage.

simulate this circuit – Schematic created using CircuitLab


Expected unqualified ID before numeric constant

Bad luck. There is a file within Arduino called "binary.h", and it contains a define called "B1". Which means you may not use "B1" as a variable. In my opinion, that file "binary.h" is totally unnecessary.

In the preferences you can turn on extra output for the compiler and turn on line numbers. The compiler will tell what is wrong, but you have to know how the compiler does that. The first compiler error is the most important.

".../hardware/arduino/avr/cores/arduino/binary.h:31:12: error: expected unqualified-id before numeric constant #define B1 1" means that the compiler was reading the file "binary.h" and at line 31 it noticed something it did not understand and it has to do with "B1".


Attiny85 PB4 works for analog output but not PB3?

The hardware PWM is only suported on pins with output compare altenate function on it. The pinout in your question shows Attiny13 but the rest of your question is about Attiny85, which has different capabilities from Attiny13

As you can see, only pins with PWM capability are PB0, PB1 and PB4


You haven't shown us all the code – in particular, the call to Draw() from loop() is missing – so this answer is speculative, based on the assumption your loop() is as follows.

void loop(void) {
    Draw();
}

If so, your first bit of code will constantly redraw because loop() runs repeatedly without delay.  Try adding a delay(1000); after Draw() in that case.

Your second bit of code will begin by drawing your image once, and in that Draw() call it will set needsUpdate to false.  Then loop() runs again, and the firstPage() call erases the screen.  Since needsUpdate now is false and remains false, subsequent calls don't draw an image.

Rather than putting your picture loop into Draw(), perhaps use Draw() just to draw primitives, and keep your controls in loop():

void loop(void) {
  Display.firstPage();
  do {     // picture loop
    Draw();
  } while( Display.nextPage() );
  delay(1000); // delay before next picture
}

If you still get repeated fast redraws, for troubleshooting comment out the do and } while lines.


Arduino "Maximum Power point tracker" (MPPT) Problem

Your current signal will also show PWM, so you will need to filter that before measuring.  It would be much simpler if you could rearrange your circuit to put the sense resistor on the ground side of the MOSFET, since then you can use a simple RC filter and a single A0 measurement.   Also, you wouldn't have to worry about the no-load voltage from the solar panel (when the MOSFET is off) going above the 5V limit of the A0 pin.


How are libraries added to the Arduino library manager?

You have to submit a ticket to the Arduino GitHub page. If you want to do this in an automated fashion, you can use this python program. Make sure beforehand that your library fits the Arduino library specification.


Plug a USB Host Shield into the Leonardo.

USB mouse --- USB Host Shield --- Leonardo --- PC

USB Host Shield Library

Circuits@Home Project

/*
 * USB Mouse pass through. Works at HID report level. HID report is not decoded.
 * Tested on Leonardo with Arduino USB host shield, IDE 1.8.5, and Logitech Marble
 * trackball/mouse. This is a proof of concept so is not guaranteed to work with
 * all USB mice/trackballs.
 */
// USB host mouse from USB Host Shield Library. Install using Library Manager
#include <hidboot.h>

// USB device mouse library included with Arduino IDE 1.8.5
#include <Mouse.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

class MouseRptParser : public MouseReportParser
{
protected:
    void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};

void MouseRptParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
{
  Serial.print("MouseRptParser::Parse");
  // Show USB HID mouse report
  for (uint8_t i = 0; i < len ; i++) {
    Serial.print(' '); Serial.print(buf[i], HEX);
  }
  Serial.println();

  // On error - return
  if (buf[2] == 1)
    return;

  if (len > 2) {
    uint8_t mouseRpt[4];
    mouseRpt[0] = buf[0];
    mouseRpt[1] = buf[1];
    mouseRpt[2] = buf[2];
    mouseRpt[3] = 0;
    HID().SendReport(1,mouseRpt,sizeof(mouseRpt));
  }
}

USB     Usb;
HIDBoot<USB_HID_PROTOCOL_MOUSE>    HidMouse(&Usb);

MouseRptParser Prs;

void setup()
{
  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial) delay(1); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  Serial.println("Start");

  if (Usb.Init() == -1) {
    Serial.println("USB host shield did not start.");
  }
  delay( 200 );

  HidMouse.SetReportParser(0, &Prs);

  Mouse.begin();
}

void loop()
{
  Usb.Task();
}


Is it possible to upload an arduino sketch through the serial port (RX) instead of USB

No need to have a specific bootloader. The basic bootloader can do that (in Arduino that's the case so I hope this answer will apply in your case. But if not, the principle is certainly the same).

Once you perform a reset on the board, the bootloader look at the serial port during a short time. If something come, it checks if it's an hex file and if yes it send it to flash. The USB just use the RX input.

So you can send data using a direct connection or using for example a Bluetooh like HC-05. I do that for some project in order to update via Android: the Android app send an order to the Arduino, through Bluetooth.
Receiving this, the Arduino RESET itself, and then the Android App send immediatly data.

On Arduino side: connect for example A0 to RESET PIN and perform a digitalWrite(PIN_RESET,HIGH);
Have also a look at Reset an Arduino Uno in code

After the RESET, the board will reply with 0x14 0x10 (so it send this to TX and so if you have a bluetooh module, you'll received than on your Android App (eg))

You must then send  0x50 0x20 to the board to tell it you enter programming mode.
Then send 0x75 0x20 to get the id of the board in order to be sure you will send the HEX file for the right hardware.
You will receive 0x14 XXX 0x10 where XXX = id of the board

Then you can send the HEX file.

For that, you will send it by blocks of 128 bytes

So start by dividing the HEX to know the number of blocks then loop against this  number:
Start at ADR=0 (adresse dest in flash) and send:

For each block:

1) Send 0x55, low byte of ADR, high byte of ADR, 0x20

2) check reply (must be 0x14 0x10)

3) Send the 128 bytes: 0x64, 0x00, 0x80, 0x46 then the 128 bytes and finish by 0x20 (0x80 is the size)

4) check reply (must be 0x14 0x10)

5) update ADR. Take care: ADR is a word pointer (2 bytes). So ADR = ADR+0X40

Loop on num of blocks

Finish the job by sending 0x51 0x20 (exit programing mode)

Some details:

0x46 before the 128 bytes tells you want to write in flash. Other codes are available eg for checking, getting data etc..

It seems mandatory to send each time 128 bytes. So if your last block is smaller, you need to add some '\0' to get a total of 128. I've been unable to get good results trying to change the 0x80 value and send less bytes. :(

It's not very easy and need tests to get a good code but that really fine to be able to have an Arduino the user can update.

Hope this will help.


Understanding the contents of a library in C

What I have always wanted to know is: where can you find the "instruction set", inc C, for these libraries?

The libraries are usually found in the libraries sub-folder under your sketchbook folder (wherever that is). There is also another libraries folder inside the IDE install folder for the "official libraries".

  How can I find out what commands are available for me to use with this library?

Usually the library documents them in one way or another. Try looking inside the .h file used by the library to see what functions are exposed.


String::Substring does take a start and an end value. So you can do something like this:

String s1 = longtext.substring(0,15);
String s2 = longtext.substring(16,31);


Take a look at the SimpleTimer [http://playground.arduino.cc/Code/SimpleTimer] library in the Arduino IDE environment.

You can have timers to:

call a function at a consistent interval,
call a function once after a set delay,
call a function a set number of times with a consistent interval
between.


How to get readings on serial monitor in every 10s?

There is one fundamental error with your code that I feel I should point out - one that I see time and time again.

The basic structure of your code is:

Forever:

Send a ping
Wait for the pong
Print the result
Delay for 100ms (or whatever time you choose)

And you expect to get a result every (delay) milliseconds.

However, you won't.  What you will actually get is a result every so often, where that time is defined as 100ms + the time to send and receive a ping.

So if it takes 11.6ms (200cm, the limit of most pin sensors) to receive the pong, then you also delay for 100ms, you're going to end up with 111.6ms between each print. It's even worse if the pong never arrives back - then pulseIn() will wait for up to a second before returning. You can, of course, reduce that to say 15ms by adding the timeout parameter as per the manual

When you reduce your printing delay to just 10ms you actually run the risk of delaying for more than double the time you expect to (21.6ms instead of 10ms).

Instead you need to use millis() to check to see if it is time to print something so that it doesn't matter how long the pong took to arrive, as long as that never exceeds the amount of time you want between prints, otherwise it's going to get delayed regardless.


No, you will not be able to use this dongle. This device needs to be plugged into a USB Host device, which an Uno is not capable of doing for several reasons, one of which is that this dongle would require some driver on the host device, and the only drivers made for it are likely made only for Windows/Mac/Linux type operating systems.

Most of the WiFi shields communicate with Arduino over a non-USB protocol like SPI or I2C, while it looks like this dongle is a purpose-built chip that communicates with a host over USB only, not I2C or SPI.

It's likely you can find an ESP8266 device for a lower cost than this dongle would cost, however. The ESP8266 device would communicate with an Arduino via UART (serial port).


Send HTTP request from Arduino Ethernet to server on PC

The answer was simple. Instead of trying to connect to the IP address of the local server (192.168.56.1) I had to use the IP address of the ethernet connection between the Arduino and the PC (found using the ipconfig command on the command prompt).


Linking Arduino Nano with ESP8266 Wifi module

The easiest way to work with these devuces is to connect them to a spare pair of Arduino pins and use SoftwareSerial for communicating (unless you're using one of the Arduinos with more than one UART). SoftwareSerial work up to 9600 baud on 16MHz devices, 4800 on 8MHz devices, so you'll need to set the ESP8266 to accommodate that. They currently ship at 115200 baud. You can use the hardware UART on pins (0, 1) but then re-programming the Arduino means disconnecting & reconnecting the ESP temporarily each time, and gets old pretty quickly.

Here's what I do with new ESPs (If you've re-flashed your ESP, you'll need to download the AT instruction-set emulator and re-flash it with that, first):

# To configure a new ESP module:
# Connect the ESP and the FTDI as in your top diagram, set your
# terminal-emulator to 115200 baud, and enter the following:

AT                             # ESP should respond "OK"
AT+RST                         # Resets the ESP
AT+UART_DEF=9600,8,1,0,0       # Sets ESP UART: 9600,N,8,1,no flow ctl

# Now change the terminal emulator baud rate to 9600

AT+CWMODE=1                    # Set ESP to station mode (client)
ATE0                           # Set ESP's echo off
AT+CWLAP                       # List access points - after a short pause
                               # the ESP returns a list of WiFi access points

For future reference, here is a link to the ESP8266 AT Instruction Set.

Update June 2020: The above link was broken, now fixed. You can also find documentation at Espressif's github account (online readable, but not pdf, as of this date).


If they are an intentional part of the design they are jumper wires. If they are to correct a mistake in the design they are bodge wires.

They aren't anything special, just wire. They look to be in the range of 24 to 30 AWG and PVC jacketed.

You can buy it in any electronic store.

You can also salvage it from things like old SCART cables and similar things.


There is a way of doing it that's ESP32 specific. However it means changing how you define your I2C object.
The ESP32 system is set up so that if the TwoWire instance is destructed the I2C bus is released. But you can't do that with the way you normally define the object. So instead you have to use dynamic allocation to control it:
TwoWire *I2Clightmeter;

void setup() {
    I2Clightmeter = new TwoWire(1);
    I2Clightmeter->begin(I2C_SDA, I2C_SCL);
    lightMeter.begin(BH1750::ONE_TIME_HIGH_RES_MODE,0x23,I2Clightmeter);
    delay(1000);
    uint16_t lux = lightMeter.readLightLevel();
    delete I2Clightmeter;
    // rest of code
}

Another alternative is to keep the TwoWire object in a local scope so that it gets destroyed when you leave that scope - maybe with a special function for it:

uint16_t getLux() {
    TwoWire I2Clightmeter(1);
    I2Clightmeter.begin(I2C_SDA, I2C_SCL);
    lightMeter.begin(BH1750::ONE_TIME_HIGH_RES_MODE,0x23,&I2Clightmeter);
    delay(1000);
    return lightMeter.readLightLevel();
}

void setup() {
    uint16_t lux = getLux();
    // rest of code
}


What is the best Arduino board for a Quadcopter with camera and Wifi?

Given the current (lack of) detail of the question, the best advice I can give you is to have a look at instructables.

You will find many options with varying cost, complexity and range of applications.

It should help you form a better vision, in case you still do not have one good enough to make the choice of components obvious.


Arduino + motor driver (L293D) power consumption

To calculate L293D power usage, you need to lookup the datasheet and check the Voh and Vol. These are the High level voltage and Low level voltage.

On Texas Instruments datasheet, we have:

So you will lose about 1.4V when your output is -0.6A, and 1.2V when your output is 0.6A. If your motor uses 2 outputs (bi-directional) then you have to add the losses.

Then, to get the power dissipated on the power side of the L293D, you take this voltage drop and multiply by the motor´s current.

Example:
Lets say your motor is using 0.6Amps and your power source is 5V + 24V @ 25°C (just like in the datasheet).

The power loss in the L293D is aprox.: (1.4V + 1.2V) x 0.6A = 1,56W.
Since you´ve lost 2.6V in the L293D, your motor will use: (24V - 2.6V) x 0.6A = 12,84W.

To measure this directly on your real circuit, use a multimeter in Ampere mode to measure current, and Volt mode to measure the voltage on the motor terminals when it is on.

As for the arduino, your battery has 2000mAh and I assume it is a 7,4V battery. So it has 2000mAh x 7,4V = 14800mWh of energy stored in it.

If you are running your arduino at 5V, then: 14800mWh / 5V = 2960mAh at 5V.
Now let´s say your arduino and it´s modules, the L293D´s and the motors are using 500mA average, then your battery will last: 2960mAh / 500mA = 5.92 hours in theory.
Why "in theory"? because in real life it is impossible to extract all the energy from inside a battery. A minimum ammount of energy has to remain inside it and some power is lost when you extract it´s energy.

Of course, this is a very raw calculation. In reality, you have to calculate power used in every component. But by calculating the "big guns" first you can get an idea of where you stand.

Basic power loss calculation is done by multiplying voltage drop by the current in each circuit. Voltage drop is the difference between your volts before and after the component.


Yes, the analog pins must be addressed using A0, A1,... when using them for digital I/O.

Depending on the board you are using A0,A1,etc. are mapped to different values (for instance it looks like A0 is 18 on some boards but 14 on others.

One solution for looping over the analog pins would be this:

static const uint8_t analog_pins[] = {A0,A1,A2,A3,A4};
// Setup pins for input
for (int i = 0; i < 5; i++) { //or i <= 4
  digitalRead(analog_pins[i]);
}

If you are using the analog pins only with the analogRead() call you can use 0,1,... instead of A0,A1,...


Can you use an Arduino to control the output current and voltage of a DC/DC converter?

Yes, and it's actually far simpler than most realize. I've tried digitpots, but they are quite un-linear and only handle 5v, unless you spend $$$. Early on, i had soldered an LDR in parallel to a buck converter's adjustment pot, and fed that PWM. It worked to somewhat adjust the vout, but had a lot of ripple and was not linear. I had gotten an MCU-controlled linear PSU going, that wasn't too hard, but i always wanted a buck. Just recently, i've found an awesome method and built several MCU-controlled SMPSs.  You don't have to have any special parts or de-solder anything!

Basically, you:

use a buck/boost (or dual) with a built-in V-adj potentiometer.
use a lowpass to convert the MCU's PWM output into a 0-vcc signal.
feed smoothed PWM voltage to a unity gain opamp to buffer available current.
create a common ground between MCU and SMPS.
feed the buffered 0-vcc control through a resistor into the pot's wiper, ~200-1k.
the amount of "injected" voltage will be inversely proportional to the SMPS's output voltage.

Since most SMPS's feedback is in the area of 1-2.5v, the 0-3.3/5v output of the MCU works well to provide or take away feedback from the regulator. The best part about this scheme is that output voltage regulation is maintained by the SMPS's hardware, the MCU just sets an offest. In short, you can set it to 10v via the MCU, attach a big load, and the voltage stays at 10v!

I've used this technique on the xl4005 and the xl4015, but i would imagine it would work for just about any common driver package.


There are a few problems with your code sample:

You check for Serial.available()>0, but then assume/grab only one character:

if (Serial.available() > 0) {
  s = Serial.read();
}

It is possible that the serial receive buffer has more than one byte waiting, but you only capture one.

k[10] = s;

You assign the captured character to the last element of the byte array, regardless of all else. This presents two main problems

A C-style string must be terminated with a null character ('\0'), and you have immediately put real data in the position that should contain the terminating byte.
There is no possible way that bytes 0-9 can ever have any data written to them by this code.

Your code assumes that the entire string exists in k[] every time through loop(). Instead, you should assume that it might take hundreds or thousands of times through loop() just to finish receiving your string. The input string should have some kind of end-of-string marker like a newline ('\n') or carriage-return ('\r') (or both) so that your program can look for that and know when the input is fully received.

Below is a simple program that receives a string. Note that it has a portion labeled for when to process the recieved data. That block of code is only entered once a newline and/or carriage return are received.

#DEFINE MAX_INPUT 90

char inputBuffer[MAX_INPUT+1]; // Handles up to 90 bytes in a c-style string, with a null character termination.

void setup()
{
  Serial.begin(115200); // initialization
  inputBuffer[0] = '\0'; //Initialize string to emtpy.
  Serial.println("Begin:");
}

void loop() {

  if (Serial.available()>0)
  {
    char input = Serial.read();
    static int s_len; // static variables default to 0
    if (s_len>=MAX_INPUT) {
      // Have received already the maximum number of characters
      // Ignore all new input until line termination occurs
    } else if (input != '\n' && input != '\r') {
      inputBuffer[s_len++] = input;
    } else {
      // Have received a LF or CR character

      // INSERT YOUR CODE HERE TO PROCESS THE RECEIVED DATA //
      // YOU COULD COPY TO A NEW VARIABLE WITH strncpy() OR //
      // SET A FLAG TO SAY TO START SOME OTHER TASK         //
      Serial.print("RECEIVED MSG: ");
      Serial.println(inputBuffer);

      memset(inputBuffer, 0, sizeof(inputBuffer));
      s_len = 0;             // Reset input buffer here if you
                             // have already copied the data.
                             // If you don't reset here, then
                             // you can't start receiving more
                             // serial port data. This is your
                             // 'software' serial buffer, contrast
                             // with the hardware serial buffer.
    }
  }
}


Porting SH1106 Oled Driver - 128 x 64 / 128 x 32 Screen is garbled but partially responsive

While your initialization routine looks fine to me (comparing to the datasheet and as evidenced by the fact the display turns on), what doesn't look right is your drawing routine:

//set column address
dcPin.Write(DisplayCommand);
SendCommandB(0x21);
SendCommandB(0);
SendCommandB((byte)(Width - 1));

//set page address
SendCommandB(0x22);
SendCommandB(0);
SendCommandB((byte)(_pages - 1));

The commands 0x21 and 0x22 don't correspond to any commands I can see in the datasheet.  They look more like commands more commonly seen with ILIxxxx or SSDxxxx screens to create an "addressable window" from 0,0 to Width-1, _pages-1.

Instead you should be using the same commands you used in the setup routine to set the current col / page coordinate in RAM to write to.

Commands (0x00 | (col & 0x0F)) and (0x10 | (col >> 4)) set the column position, and (0xB0 | (page & 0x0F)) set the page number.

You then write all 128 bytes for the current page before moving on to the next page.  This means you will have to do it a page at a time, something like:

for (ushort page = 0; page < 4; page++) {

    // Set the current RAM pointer to the start of the currently
    // selected page.
    dcPin.Write(DisplayCommand);
    sendCommandB(0x00); // Set column number 0 (low nibble)
    sendCommandB(0x10); // Set column number 0 (high nibble)
    sendCommandB(0xB0 | (page & 0x0F)); // Set page number

    // Send a single page (128 bytes) of data.
    // Without knowing the rest of your program I don't know the right
    // data sending routines to use, so I made them up. Change it to
    // do it how your program expects.  Maybe with your SendArray
    // function.

    dcPin.Write(DisplayData);
    for (ushort col = 0; col < 128; col++) {
        sendDataB(displayBuffer[page * 128 + col]);
    }
}

Note that this method is very similar to how the KS0108 GLCD drivers work.  Each byte of the page represents 8 pixels on the screen so the screen, at 32 pixels high, is split into 4 pages, where each page is 8 pixels, or one byte, high.

The effect you are currently seeing is because you are never changing the current page number (0) so you are always writing your data to the first page.  This loops around multiple times, so you end up writing all 4 pages to the same strip of the display ending up with the last page being displayed, which is the last 8 lines of your display data.  The rest of the display is never being touched and just contains whatever random data was in the RAM at power-on.


I2C LCD Serial Interface Board not displaying text (wrong pins?)

First of all, it looks like these wires aren't properly connected:

I haven't disassembled a female jumper before, so that might not be the issue. However, it seems likely that this could be a cause.

Also, you need to adjust the contrast by turning that trimmer (the blue thing that looks kinda like it has a screw in it). LCDs will either display nothing, a washed out version of the text, or blue boxes if the contrast is not set correctly. This is probably the cause.


You have at least three problems here:

1) First and most critically, a nominal 6v pack does not meet the input voltage requirements of the regulator used an Arduino even before it gets loaded down by a motor, and it only gets worse under load

2) L293/L297 and similar bipolar bridges have absurdly high internal losses, so are unsuited to low voltage systems - effectively one of your cells goes just to feeding the wasteful driver chip.  Use a modern and efficient FET driver like a TB6612FNG, or else add another cell to the pack.

3) The 433 MHz RF modules are notoriously low fidelity, and in many places not permitted for the control of RC models anyway.  You'll have much better results with the sophisticated digital radio modules sold at comparable prices for 2.4 GHz, which are incidentally the functional equivelent of what most RC toys now use (and actually in many cases can be made interoperable with them).

Granted, you may well have other issues as well, such as errors in your software.


Your first problem is that there is no way for schar to contain two characters in the first place; Since schar is declared as a char, it can only contain one character.

You need to make a String out of the serial input. Serial.read() only returns one character at a time, so you will need to make sure you iterate over all the input. Then you can compare the whole String with another, and see if both characters match at once. Just look at this code to see different ways of manipulating Strings: http://arduino.cc/en/Tutorial/StringComparisonOperators

Notice that string literals use double quotes, not single quotes like characters.

Also, be aware of the fact that string and String are different things. lowercase 's' is an array of characters, capitol 'S' is the class that has those useful string comparison member functions. The class is more resource intensive, but I think in your case the readability and convenience are worth it.


Your calculation is not correct. The encoder has its 0 to 10V output voltage distributed over the whole distance, that the cable can reach, so 1.25m. And that gives you the resolution: 1.25m/1024 = 1.22mm. The resolution doesn't change, if you use less than the maximum length. It's still the same resolution of about 1.22mm. The encoder doesn't care, if you are only using 1m of its range.


Is this a good function for I2C receive?

No problem with multiple returns but it could be reduced to:

uint8_t I2C_rx(bool ack_rx)
{
  uint8_t cr = (1<<TWINT) | (1<<TWEN);
  if (ack_rx) cr |= (1<<TWEA);
  TWCR = cr;
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

or

uint8_t I2C_rx(bool ack_rx)
{
  TWCR = (1<<TWINT) | (1<<TWEN) | (ack_rx<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

Cheers!


What is the use of reserved pins and SDD2, SDD3 pins of the NodeMCU?

The ESP8266 uses an external flash memory chip to store your program. It communicates with this flash chip over a 4 bit SDIO interface, on GPIO6-11. These pins are labeled SDDn, SDCLK and SDCMD.
Usually, the interface uses all 4 data lines (QIO), but you can also configure it to use only 2 of the 4 lines (DIO), giving you access to two more GPIO pins (9 & 10).
The reserved pins are not mentioned in the schematic. They cannot be IO pins, because there simply are no other pins on the ESP8266/ESP-12. It could be pins connected to the USB chip, connected to power lines, or not connected at all. The designers probably wanted to allow for extra pins on next iterations of the board, without changing the form factor. A quick search online didn't yield any results, so your best bet is to trace the connection on the PCB, or measure it with a multimeter. You probably shouldn't be using them anyway, because they are "reserved".


Connect 2 Arduino UNOs via Bluetooth? (HC-05 and HC-06)?

Have a look at this for how to pair them http://www.martyncurrey.com/connecting-2-arduinos-by-bluetooth-using-a-hc-05-and-a-hc-06-pair-bind-and-link basically you need to use the AT mode.
As far as I know you will be using the serial connection to communicate, but if you are using UNOs debugging becomes a bit more difficult, because you can't use serial for debugging.


SPST switch - powered from pin output, or voltage regulator

You could configure one of the digital pins as INPUT_PULLUP and connect one end of the switch to it. The other end of the switch goes to ground. LOW = switch ON, HIGH = switch OFF.

const byte pinNumber = 3;

void setup(){
  pinMode(pinNumber, INPUT_PULLUP);
}

void loop(){
}


ESP8266(01) doesn't work when servo connected to GPIO-2

It's what Juraj said.

  add external pull-up to io 2 -Juraj

sovled it


What pins to use to externally power an Arduino Fio (without battery)

I used the external switch input JP7-1 for 12v, any GND hole, and make sure the switch is off.  This bypasses the charge circuit which doesn't like 12v.


Unable to issue any AT commands to BT BLE Breakout Board

I found out that there is no need for a voltage divider to reduce the voltage being given to RX pin of BLE from FTDI's TX since both FTDI232RL and HM-10 are 3.3V devices (from here)

I connected the TX from FTDI directly to the RX of BLE using female to female jumpers.

Used No Line Ending and 9600 as the baud rate.

Then it worked fine, I got an OK acknowledge for my AT command.


Dimming 6W (24V DC 0.25A) LEDs using Arduino

I would suggest using the CAT4101 constant current sink PWM LED driver.  It can handle up to 1A at up to 25V and deals with the constant current regulation for you - just provide at least the 24V you need and enough current capacity and connect the correctly calculated current setting resistor and the CAT4101 will do the rest for you.  You can then control it through the PWM input pin direct from the Arduino.


Connecting a switch and a MOSFET to an Arduino?

I think you should keep the R2 resistor, but make it 1k and put before it a pull-down resistor of 10k so that any charges stored in the NMOS Cgate capacitance are discharged, whenever there is High-Z at the port D9. Also never forget the resistor limiting the diode forward current, which is typically 20 mA, but you should check that every time in datasheet. In case of LED strip there are usually internal resistors, but if you are using higher voltage still you need to restrict the current. Could you tell us more about why you are using PWM not a simple output port with an integrator for example and what you exactly observe and measure when you turn-on-off (fade-on-off) the LED?

simulate this circuit – Schematic created using CircuitLab

How to make the diagram a bit smaller?


Used this code -

/*
Coded by Marjan Olesch
Sketch from Insctructables.com
Open source - do what you want with this code!
*/
#include <Servo.h>

int value = 0; // set values you need to zero

Servo firstESC, secondESC; //Create as much as Servoobject you want. You can controll 2 or more Servos at the same time

void setup() {

  firstESC.attach(9);    // attached to pin 9 I just do this with 1 Servo
  Serial.begin(9600);    // start serial at 9600 baud

}

void loop() {

//First connect your ESC WITHOUT Arming. Then Open Serial and follo Instructions

  firstESC.writeMicroseconds(value);

  if(Serial.available())
    value = Serial.parseInt();    // Parse an Integer from Serial

}

the problem was when i was connecting the battery , it was not making any sounds...it was already calibrated by open pilot GCS so it was not calibrating again... i needed to reset the ESC and then run this program from arduino


How to write Arduino API code in VL53L1X?

He's not asking about a VL53L1X Arduino. He's asking for code to support the VL53L1X (which is an ST distance sensor) that runs on an arduino.

ST have provided a library, but it's huge with many large buffers and doesn't run on an arduino as distributed. They've also forbidden anonymous distribution of a corrected version, presumably because they don't want to make it easy to run on 16-bit processors. It might run easily on a Teensy 3.

Sparkfun have just released a library. It's much smaller but, like the Polulu library for the  VL53L0X, it's full of magic numbers where they've stripped the structure out and just write the end result into the registers - so it will be difficult to get the best from the sensors.

https://github.com/sparkfun/SparkFun_VL53L1X_Arduino_Library/blob/master/src/SparkFun_VL53L1X_Arduino_Library.cpp

There is a good case for writing something halfway : without the overcomplicated code typical of ST's Cube environment but with a bit more content than Sparkfun's version.

It's a boring job unless you have something you need from it. Worthwhile only if you have a good case to support it on AVR. If you try to build the ST sources, look carefully at the maximum write size on I2C (135 bytes) and compile with maximum warnings enable (it will pick up several 16/32 bit wordsize errors, mostly critical).


Powering an Arduino Uno using 2 (or as few as possible) AAA batteries

I've got a page about power saving.

My first suggestion would be to not use a Uno, which is quite heavy (because of its size) but a smaller Arduino like a Mini. Second, I think you'll find that LiPo batteries are quite light, and come in various sizes (and thus, weights). A single cell will output around 3.7V which is fine for driving an Atmega328P. Possibly you could drop the clock to 8 MHz because of the voltage.

If you don't need it to be "awake" all the time consider using the techniques described in my link above to make it sleep for (say) 4 seconds at a time and then take a measurement.


I'm trying to control a servo with a push of a button but its not working HELP

This condition below is never met because a boolean comparison is implied :

if( buttonPushed ){

and buttonPushed is declared as :

int buttonPushed =0;

A proper comparison should be OK :

if( buttonPushed == 1)
{
   // Do something
}

Also the buttons need proper debouncing or the push event will have undetectable results :

https://dduino.blogspot.com/2012/03/arduino-button-debouncing.html


How to display float variables on oled display (0.96'')

The printf group of functions in the Arduino library don't implement float and double conversions. For those, you need the function

char *dtostrf(double dval, int8_t width, uint8_t prec, char *buf);
  Convert the double value passed in dval into an ASCII string stored in
  buf. Conversion is done as "[-]d.ddd". The minimum field width of the output
  string (including the '.' and the possible sign for negative values) is given
  in width, and prec determines the number of digits after the decimal. width
  is signed, negative for left adjustment.
  Returns buf.

, which you'll need to call for each float you want to convert.

Note that you could convert several floats into strings, upfront, each into its own character buffer, then use sprintf to format the final buffer - remembering that in sprintf's format string, those buffers contain character strings, which you'll need to specify with '%s' format-specs.


How to stabilize magnetic levitation system?

The answer to the solution was quite simple. I just had to comment out all serial port reading and Arduino processing became 60 times faster which helped to levitate the magnet. Thanks to everyone who helped me here :)


How to Store the Value of A Sr04 Ultrasonic distance sensor (ping)?

First you must verify that storing the value as int is even possible: long int can represent much larger values than int. Are you 100% sure that the maximum reading you will ever get can be represented as int?
In case the answer to the previous question is "yes", then you can just cast it on the fly:
int int_val = (int)function_returning_longint();
In case the answer is "no", you can either give up the idea of using int and stick with long, which is not necessarily bad, or you can scale down the value, at the price of loosing some resolution:
int int_val = function_returning_longint() >> 8; This assumes that long is 16 bit and int is 8 bit, but it would be preferable to use explicit types, like int8_t and int16_t. And in your case you might have to shift by a different value than 8.

Either way, do not make casts of from big type to small type without being 100% sure that the max value you will ever deal with can fit in the small type.


How exactly is voltage measured on an Arduino?

Known voltage is usually provided by a diode or similar reference. The atmega328p chip has a separate aref pin so you can choose your own reference.

An ADC or analog to digital converter http://en.m.wikipedia.org/wiki/Analog-to-digital_converter is a collection of comparators. A comparator is a logic gate that simply tells which of two inputs has more voltage. This aref voltage is divided evenly into 2^10 values (it's a 10 bit ADC). Then the incoming signal is compared against all of these and the largest comparator which triggers is the reading you get in your arduino code.


nodemcu esp8266 does not boot up when 5V pin is connected as a VIN source

IO pins 0, 2 and 15 are boot configuration pins. 15 must be LOW at boot, 2 must not be LOW at boot and 0 determines the flashing mode. For normal run pin 0 must be HIGH. The NodeMcu board has necessary pull-up and pull-down circuits.

You can connect to pins 0, 2 and 15 only devices which don't change the boot state.


Servo only going one direction till it reach limit

!flip doesn't really do anything and will probably be optimized out by the compiler. You need to save the result: flip = !flip;

You can simplify the code a bit:

void loop() {
    if(flip) {
        servo.write(60);
    }
    else {
        servo.write(100);
    }
    flip = !flip;
    delay(650);
}

Or, get rid of the delay altogether:

uint32_t last_millis = 0;
void loop() {
    if (millis() - last_millis >= 650) {
        servo.write(flip ? 60 : 100);
        flip = !flip;
        last_millis = millis();
    }
}


detachInterrupt(0) in arduino not working ? after giving continuous ground to INT0 wakeupnow function should execute once not again and again

You're detaching in completely the wrong place. After sleep_mode() returns from sleep and before the interrupt is detached you have an entire second of time where your interrupt can still fire. And it will fire, since a LOW interrupt will keep firing while the input is LOW.

sleep_mode();     // here the device is actually put to sleep...!!
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
                  delay(500);
                  Serial.println("Rajat2");
                  delay(500);
detachInterrupt(0);

Instead you should detach the interrupt within the interrupt routine itself:

void wakeUpNow()
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up

    detachInterrupt(0);

  int count=10;
  while(count!=0)
  {
    delay(1000);
    count--;
    Serial.println(count);
    delay(1000);
  }
}

Also, all those delays and Serial prints in an interrupt are seriously problematic. An interrupt should never delay() and should never Serial.println().


Error is SPF_MicrOLED.h no such file or directory.

That is to be expected because the library doesn't contain a file named SPF_MicrOLED.h.

It does contain a file named SFE_MicroOLED.h. Use the correct filename in your #include and the problem will be solved.


Stacking Arduino Shield (Motor Shield, LCD Keypad, LED Sensor)

The Motor Shield 2A plugs in on top of the Arduino Uno, and the LCD Keypad plugs in on top of the motor shield. [But see Edit 1 below]

There is better information about the  4 Channel Line Tracking Sensor at uctronics.com where you can see that its main board (with the LM339 chip) connects to the Arduino via six lines: Vcc, Gnd, Out1, Out2, Out3, Out4.  That main sensor board does not mount on the stack, but instead can be located whereever is convenient and leaves its four comparator-level pots accessible for adjustment.
Mount the four small boards for the tracking module as convenient and necessary for line following.

For connecting the six lines from the sensor main board to the Uno, you probably will need to solder two headers (rows of pins) to a board in the stack.  Using right-angle headers (see below) will allow the pins to come out of the side of the stack without interfering with other layers of the stack.  One of the headers should let you connect sensor Out1...Out4 digital outputs to four otherwise unused analog or digital pins, and the other header should let you connect Vcc and Gnd.

Edit 1: In the LCD shield page, section 2 (Diagram) shows Vcc, Gnd, and D0-D3 available at the top right corner (the angled corner).  Those six pins probably are a reasonable place to add a six-pin angled header for the sensor board.

Given that the LCD KeyPad Shield is a DFRobot.com model, the summary pinout at shieldlist.org shows that its use of D4,5,6,7 will conflict with use of those same lines by the DFRobot 2A Motor Shield.  There are several ways to handle a conflict like this:  1, use two Uno's, one per shield; 2, make one shield or the other use different lines; 3, share the lines.

Method 2 could work as follows:  Stack the LCD shield directly on the Uno (or any other compatible Arduino).  Besides a header for the sensor board, add a header for a cable to the motor board, and drive the motor board's D4-7 inputs with some other lines from the Uno, eg A4-7.  [Alternately  one could remove the D4-7 pins on the LCD shield and jumper from A4-7 to the D4-7 lines on the LCD shield.  This would leave the boards in a single stack but would make some serious changes to the LCD board.]

Method 3 would work as follows:  The LCD shield only pays attention to D4-7 (which from the DFRobot schematic drive DB4-DB7 on an LCD TC1602 chip) when the TC1602's E line is strobed.  See pages 7 and 8 of Adafruit.com's copy of TC1602 specs, where timing diagrams show about half-microsecond times for writing to or reading from the TC1602.

You would need to run tests with your motors and see if they work ok in spite of the four inputs to the motor shield being random during the occasional half-microseconds that data is being written to the LCD.  You might have to add more diodes or capacitors to  suppress electrical noise due to rapid switching.

DFRobot's motor shield page has links to that board's schematic and to its L298 chip data sheet.  Page 7 of the datasheet says

  An external bridge of diodes are required when inductive loads are driven and when the inputs of the IC are chopped; Shottky diodes would be preferred.

The motor shield schematic shows diodes; although not drawn using Schottky diode symbols they might be Schottky anyway (which would give better noise suppression, less heating, etc).  The schematic also shows that JP1, a 16-pin dual row header, has jumpers that control ENA and ENB on the L298.  In a "proper solution" for sharing D4-7 between the LCD and motor shields, you'd drive ENA and ENB low when using D4-7 for LCD i/o, which would allow the attached motors to briefly free run, as opposed to being suddenly commanded to stop or reverse.


How to increment and decrement an output voltage by using two buttons?

If all you have to do is to read those 2 buttons, you could just forgo the interrupts and simply poll in the main loop.
The Bounce2 library does basically the same.

Also, about the PWM, why not an R-2R?

10V/0.5V + 1 => 21 steps < 32 => 5 bits => 6 resistors.

But it could be more precise, as you would not depend on the oscillator, rather on the precision of the resistors.


When and where do I have to worry about accounting for sensor "noise"?

Switch bounce is a physical issue that can be cleaned up with filtering. Since the sense states are very simple, only very crude (time-based) filtering is required to clean up its signal.

Other mechanical sensors that can exhibit similar characteristics are bump sensors, tilt sensors, and accelerometers. Bump and tilt sensors are also very simple, and similar filtering will clean up their signals.

Accelerometers on the other hand react to very minute perturbations, so they may require more advanced filtering based on the application they will be used in; orientation sensing can use time-based filtering, whereas things such as motion tracking including dead reckoning will require one or more layers of calculus in order to clean up the signal.


Your problem is probably from the level converter. Which one did you use?
Most level converters are uni-directional, and don't work for I2C.
See the App note and device from NXP:
http://www.adafruit.com/datasheets/an97055.pdf


Why does my code treat my sound sensor as if it's always HIGH

The robojax microphone switch I was using outputs LOW when it senses a sound rather than outputting HIGH as I assumed. The solution was just to replace all the if statements testing for a HIGH input with LOW.

note: sorry about not looking into the microphone earlier.


Arrays, and for loops... faster to use together, or not to use?

Have a look at the compiler output.

The Loop option

The first alternative produce a preface (setting things) and the loop itself.

Preface

40201803:   21c9        s32i.n  a12, a1, 8
40201805:   3109        s32i.n  a0, a1, 12
40201807:   00a0c2          movi    a12, 0

loop

4020180a:   202cc0          or  a2, a12, a12
4020180d:   01ccc2          addi    a12, a12, 1
40201810:   ff8585          call0   4020106c <delay>
40201813:   f38c66          bnei    a12, 8, 4020180a <_Z6XYtestv+0xa>

The unfolded option

While the unfolded version is:

40201823:   020c        movi.n  a2, 0
40201825:   3109        s32i.n  a0, a1, 12
40201827:   ff8445          call0   4020106c <delay>
4020182a:   120c        movi.n  a2, 1
4020182c:   ff83c5          call0   4020106c <delay>
4020182f:   220c        movi.n  a2, 2
40201831:   ff8385          call0   4020106c <delay>
40201834:   320c        movi.n  a2, 3
40201836:   ff8345          call0   4020106c <delay>
40201839:   420c        movi.n  a2, 4
4020183b:   ff8305          call0   4020106c <delay>
4020183e:   520c        movi.n  a2, 5
40201840:   ff8285          call0   4020106c <delay>
40201843:   620c        movi.n  a2, 6
40201845:   ff8245          call0   4020106c <delay>
40201848:   720c        movi.n  a2, 7
4020184a:   ff8205          call0   4020106c <delay>

So, the loop execute 4 instructions per each array element, while the unfolded version had only 2 instructions per array element.

But you are trading speed for space and and risking an error while coding the same repetitive thing.

However, GCC (the 'Arduino' compiler) can unfold the loop by itself, so you still can write a loop but execute a sequence. Look at Tell gcc to specifically unroll a loop

Real numbers

I run a sketch (Arduino UNO) to time loop vs unfolded. The times for 1,000 execution of each method are:

loop:     6524us
unfolded: 3808us

Quit a difference!

Sketch

int pause[8] = {1, 2, 3, 4, 5, 6, 7, 8};
typedef int (*fn)(void);

void setup() {
  Serial.begin(9600);
  while(!Serial);
  Serial.println();

  Serial.print("Timing loop: ");
  Serial.print(time(met1));
  Serial.println(" us");

  Serial.print("Timing unfolded: ");
  Serial.print(time(met2));
  Serial.println(" us");
}

void loop() {

}

int time(fn f) {
  unsigned long start = micros();
  int x = 0;
  for (int i = 0; i < 1000; i++) {
    x = f();
  }
  unsigned long dif = micros() - start;
  return dif;
}

int met1() {
  int sum = 0;
  for (int i=0; i < 8; i++) {
    sum += pause[i];
  }
  return sum;
}

int met2() {
  int sum = 0;
  sum += pause[0];
  sum += pause[1];
  sum += pause[2];
  sum += pause[3];
  sum += pause[4];
  sum += pause[5];
  sum += pause[6];
  sum += pause[7];
  return sum;
}


http://playground.arduino.cc/Code/Keypad#Example here is the setup for you, you should see, what you are pressing.

then try something like this:

int temp=0;
bool in_press=false;
void loop() {
  char key = keypad.getKey();
  if (in_press &&  key == NO_KEY){ in_press=false; return;} // key released
  if ( ! in_press ){
    if (key != NO_KEY){ // if key is just pressed - proceed it
      in_press=true;
      if (key == '*') {temp=0; return;} //cancel input
      if (key == "#') { do_something_with(temp); temp=0;return;} //accept input
      // key is '0'..'9' - add it to result
      temp= temp*10 + (key-'0'); // maybe check it temp is not too high ...
      return;
    }
  }
  // this pass of loop no new key was pressed, do anything else to do
  // if we want, we can test in_press to see, if key is holded or not
  // or ignore it at all
  do_other_stuff_like_blinking_leds_or_what();
} // end of loop()


Your question is not clear to me. First of all does your parser get the whole response? And second by first action do you mean "action_id":35"?
If both are true then your solution is simple.

First you separate every comma ", " and put in a string array then you further split each index by ":" so the first part is the name "action_id" and the second is the value "35". I hope that helps . You can look up the split function, it's easy.

But if the above is not what you needed then I am afraid you cannot get only the first response, because that has to do with the server itself.

Here is a solution, do try it.

I found an easier solution. Follow the example and replace the content and fields with your response content and you will be done in minutes.


With checking the temperature in the room. When the contact is closed store the current temperature. Check after a minute the temperature again. If it is higher, the heater is on.


In a circuit with a switch and a pull-down resistor, why does the high impedance of the input not discourage current from flowing into pin?

Yes, all of the current that flows goes through that resistor to ground.  That way almost all the voltage drops across that one resistor and you are able to read the voltage with the pin on the high side of it.  Only a very very small amount of current flows into the pin when you read a voltage.  It just needs to charge up a very small capacitor.


How can I connect an 8-relay board without using 8 digital pins?

A likely solution is to use the Arduino SPI interface and the Arduino SPI library to control a SPI relay board.  Here is a 6 year old thread talking about such a board. And another more recent relay thread where SPI is brought up.


here one says that he literally just connected the antenna to ground and LNA_IN would that work?

Yes. LNA_IN is the input to the Low Noise Amplifier - the input stage of the receiver / output stage of the transmitter.

  and which antennas would you recommend? (as small as possible is only gonna be used for BLE and)

You want one tuned for 2.4GHz. The simplest is a quarter wave dipole at 3.125cm in length. Better would be a proper 2.4GHz antenna of the kind you get on a WiFi router or some USB WiFi dongles.


I am going to make this answer as simple as I can, the body is not THAT conductive, you gotta use something like a touch sensor.


Trouble connecting Arduino Pro Mini (Atmega328, 3.3V) to nRF24L01 over SPI, receiving all 0 values when I use radio.printDetails();

Whenever you get an all zeros output from the printDetails() function you can bet you are having a communication issue between the Arduino and the nRF24 module.

Start by checking your connections.

Check your connections again, using a multimeter to ensure continuity.

Check your connections again (no, I'm not joking).

Finally add a capacitor (anything between 1uF and 100uF will do) between the VCC and GND pins of your nRF24 module: those modules are pretty sensitive to voltage fluctuations and they are subject to current consumption spikes at startup.

Pair that with a possibly not state of the art voltage regulator (especially on cheap Arduino clones) and you end up with a non responding nRF24 module: the capacitor will provide the extra juice whenever it's required by the radio module.

This is such a common problem that I started soldering the capacitors directly onto the modules to save breadboard space!


How to wait outside the loop without delay()?

You could split Request() into two separate functions: You call sendRequest(), then go do other stuff, then, some time later, you call getResponse(). If you get RESPONSE_NOT_READY, then you know you have to call it later:

#define REQ_WAIT_DELAY     250  // Wait for 250 ms
#define RESPONSE_NOT_READY ((uint16_t) -1)

uint32_t time_request_sent;

void COZIR::sendRequest(char* s)
{
  Command(s);
  time_request_sent = millis();
}

uint16_t COZIR::getResponse()
{
  if (millis() - time_request_sent < REQ_WAIT_DELAY)
      return RESPONSE_NOT_READY;
  buffer[0] = '\0';  // empty buffer
  int idx = 0;
  // From here, same as original COZIR::Request()
}

This assumes that RESPONSE_NOT_READY (0xffff) is not an otherwise valid response. If all 2^16 values of an uint16_t may be valid, then you need another way for the library to signal that the response is not ready. Also, make sure you never compare timestamps, because of the millis() rollover problem. Taking the difference between two timestamps and comparing this with a specified delay (as in the example above) is rollover-safe.

Update: Here is an example of how this could be used:

COZIR cozir(some_serial_connection);

void loop()
{
    static bool waiting_for_a_cozir_response = false;

    if (time_to_get_another_cozir_reading()) {
        if (waiting_for_a_cozir_response) {
            report_something_is_wrong("This COZIR is too slow!");
        }
        else {
            cozir.sendRequest("Hi Cozir! Pliz send me another reading.");
            waiting_for_a_cozir_response = true;
            /* We won't get the response on this iteration. *
             * We will ask next time.                       */
        }
    }
    else if (waiting_for_a_cozir_response) {
        uint16_t response = cozir.getResponse();
        if (response == RESPONSE_NOT_READY) {
            /* Nothing to do now, really. We will just try again *
             * at the next loop() iteration.                     */
        }
        else {
            waiting_for_a_cozir_response = false;
            do_something_with_the_cozir_response(response);
        }
    }
    do_whatever_else_has_to_be_done_in_the_loop();
}


2 Channel Relay normal open is not working with NodeMCU but led on board light up

Your second configuration is right because from picture of relay module it clear that it requires 5V supply.

 relay working principal is:

when the signal port(in1/in2) is at low level, the signal light will light up and the optocoupler (it transforms electrical signals by light and can isolate input and output electrical signals) will conduct, and then the transistor will conduct, the relay coil will be electrified, and the normally open contact of the relay will be closed.
When the signal port(in1/in2) is at high level, the normally closed contact of the relay will be closed. So you can connect and disconnect the load by controlling the level of the control signal port.

As you mentioned that in second configuration there is no LED glow. For find out solution of your problem, you have do one test. Test voltage level of D1/D2. Just make connection on breadboard as mentioned in image.

If voltage level is correct that it might be problem with your relay module.

Also I have attached here relay connection reference for your directness.


MATLAB - Read from 2 SPI inputs synchronously

Yes and No.
 Synchronously in development slang means step-by-step execution. Asyncronously mean by some event.

Arduino has only one core. Even if you use interrupt, Arduino can only execute one command at once.

Best way for you I guess would be read both on Arduino and combine into single value to read at once. Just reading both with readDigitalPin  would give huge latency.


cannot show free space of SD card with arduino nano

You have two instances of SdFat class. In setup() you begin the SD and for free space you try to use sd. Delete SdFat sd; line and in ShowFreeSpace use SD.vol().


Code uploads successfully on esp8266-01 but doesn't run

if you are using a nodemcu, the pin numbers do not correspond to the digital pins, they correspond to the gpio pins. The digital pin 2 is the gpio 4 and the digital pin 4 is the gpio 2.
Here you have a list of digital and gpio pins:

D0 = GPIO16;
D1 = GPIO5;
D2 = GPIO4;
D3 = GPIO0;
D4 = GPIO2;
D5 = GPIO14;
D6 = GPIO12;
D7 = GPIO13;
D8 = GPIO15;
D9 = GPIO3;
D10 = GPIO1;


Programming 328PB from Arduino IDE using Atmel-ICE to ICSP port

Hello The 328 "PB" has major issues with running external clocks...(yes I have first hand experience with this PB model)... Try switching to the internal oscillator as I can testify first hand the the external clocks on the PB don't work correctly. They tend to sell the PB a few bucks cheaper because you will only buy them once and only once when you find out how bad the external crystal clock driver is. If you look at the latest datasheet for the PB they try and talk their way out of the bad driver by explaining how you need to match capacitors with the following snippet. I call BS as the 328p never needed such precision on it Xtal1 & 2 pins to run but to be fair they PB is meant to be low power.
This Crystal Oscillator is a low power oscillator, with reduced voltage swing on the XTAL2 output. It gives
the lowest power consumption, but is not capable of driving other clock inputs, and may be more
susceptible to noise in noisy environments.
The crystal should be connected as described in Clock Source Connections. When selecting crystals,
load capacitance must be taken into consideration. The capacitance (Ce+Ci) needed at each TOSC pin
can be calculated by using:
�� + �� = 2�� − ��
where:
• Ce - is optional external capacitors. (= C1, C2 as shown in Figure 11-2)
• Ci - is the pin capacitance in Table 11-3.
• CL - is the load capacitance specified by the crystal vendor.
• CS - is the total stray capacitance for one XTAL pin.
Table 11-


If (serial.available()) conditional statement

In C, 0 is false and anything else is true. So if Serial.available() returns 0 it is considered false. If it returns 7, 23, 44, etc it is considered true.


If condition for switch not working as expected

It's hard to tell which pins of the switch do what. Since you have your inputs set up as INPUT (instead of INPUT_PULLUP) you should have a resistor (10k Ω, say) tying those pins to ground. Then the other end of switch should connect to +5V. Don't connect the switches to both +5V and ground.
Use a multimeter on continuity to make sure that the pins of the switch that you are using are open normally, and close when you press the switch. With 4 pins it's easy to get confused as to which switch pin does what.


A simple bluetooth module like a HC-05 wired to your Arduino will give you a  serial stream that can be read and/or written.

With the RX/TX connected to say pins 10 & 11, a SoftwareSerial() object will provide access:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

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

void loop()
{
    int value;

    if (mySerial.available(sizeof(int)))
    {
        value = mySerial.parseInt();
    }
}

If you connect the module to pins 0 & 1 - you can just use the Arduino standard Serial functions, but it will cause problems uploading to the board.  In which case you would disconnect the bluetooth module for uploading.


Unable to interface AD7705 (SPI) with Arduino

I think the main problem is the values you are passing to spiTransfer().  By the way they are written I think you think you are passing binary values, you aren't you are passing decimal values.  So

data = spiTransfer(00111000);  // select ch1 and setup read 16bit data

should be

data = spiTransfer(B00111000);  // select ch1 and setup read 16bit data

The number needs prefixing with a B

Also passing a volatile parameter to this function looks wrong to me, especially when you only pass in constants.


Please add the RTC library in the Arduino as below.

Open the Library Manager and search for "Rtc by Makuna" and install.

You can also checkout the Github page for that particular library at

https://github.com/Makuna/Rtc


Maintaining pull down on a relay with a shift register

You have misunderstood how shift registers work - and one of the main reasons they exist in the first place.

Shift register ICs have a common 'latch' pin which latches the data present at the input of the cell into the cell, thus updating the output. Some ICs also offer an "output enable", which switches the outputs to a high-impedance state irrespective of the values in the cells - this might not be useful in your case, but the feature exists.

With a serial-to-parallel shift register you can shift in as many bits as you want, at whatever rate you choose, and the outputs will never change until you trigger a rising edge on the LATCH pin.

How a (latching) Shift Register works:

You have eight spaces within the register:

             ___    ___    ___    ___    ___    ___    ___    ___
[DATA_IN]-->|___|--|___|--|___|--|___|--|___|--|___|--|___|--|___|-->[DATA_OUT]
            BIT0                                              BIT7

The 'spaces' are chained together; at one end of the chain is the DATA_IN pin and at the other end is the DATA_OUT pin.

Every time there is a rising edge on the CLOCK pin, data is shifted down the chain from DATA_IN to DATA_OUT, one space at a time. For example, if the state of the 'spaces' is as the left hand column, then upon the rising edge of the CLOCK pin the spaces will change to the values in the right hand column:

 DATA_IN PIN = 1  ->  C  -> ?
BIT0 'SPACE' = 0  ->  L  -> 1
BIT1 'SPACE' = 1  ->  O  -> 0
BIT2 'SPACE' = 1  ->  C  -> 1
BIT3 'SPACE' = 0  ->  K  -> 1
BIT4 'SPACE' = 0  ->  E  -> 0
BIT5 'SPACE' = 1  ->  D  -> 0
BIT6 'SPACE' = 1  ->  G  -> 1
BIT7 'SPACE' = 0  ->  E  -> 1

You will see that BIT(n) changes to the value of BIT(n-1), with BIT0 changing to the value of DATA_IN. The DATA_OUT pin is used to daisy-chain multiple shift registers together. The important thing to note here is that the outputs do not change without a rising edge on the LATCH pin. You can pulse CLOCK as many times as you want, with whatever values on DATA_IN, and the outputs will not change. Ever.

When you finally trigger the LATCH pin, the value in each 'space' is latched into a second row of 'spaces' - these represent the outputs. On a latch trigger, the outputs therefore change to the values of the last eight bits that were shifted into the DATA_IN pin. For example:

OUTPUT = 11001010
                   SHIFT IN "01101111" (starting with RHS first)
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 01101111
                   SHIFT IN "11110000110011001100"
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 11110000   i.e. the LAST EIGHT BITS that were shifted in
                   SHIFT IN "10"
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 10111100   again the LAST EIGHT BITS that were shifted in

It is generally never the case with a serial-in-parallel-out register that you would ever shift in less that eight bits at a time, so the last example is only there to illustrate the functioning of the IC.


Which IDE should I use to write Pythonic-programs for Arduino

The recommended IDE for writing C/C++ for Arduino for beginners is the formal Arduino IDE, of which you can read more on the arduino.cc website.

Python is an interpreter language, and as such, require an interpreter running on the target machine. Unfortunately, the Arduino does not natively support running an Python interpreter, although some efforts has been made in that direction, for example the Python on a chip project, or the Python Arduino Proto API v2.
See this SO question for more details. If you go with any of these options, the IDE you would use would be your favorite Python IDE.

Note that both projects have their downsides, and actually there is no real alternative equivalent to running compiled C/C++ code on the Arduino. If you have strong Python programming abilities, this shouldn't be too hard for you as well :)


How to store gps values in EEPROM arduino?

Consider TinyGPS++ over TinyGPS only if you are running on Due or processor which can take advantage of the higher precision of 64-bit “double” floating-point.

char data; should be double data;. You're wasting resources otherwise.

data=(gps.location.lat(), 6); isn't how you do it. You only need to specify precision when writing to Serial, like Serial.print(gps.location.lat(), 6);. Make it data = gps.location.lat();.

address ++; should be address = address <=512-sizeof(address) ? (address + sizeof(data)): 0 ;

address <=512-sizeof(address) ensures that the last value written to the EEPROM is written in it's entirety.

Alternatively, I would recommend this to save you data structure directly to EEPROM, and what @jfpoilpret mentions.


You have your whole 100ms wait time while the pin is low.
You need half of it while low, half while high.

while(1){

    PORTB &= ~(1<<PORTB1);
    _delay_ms(50);
    PORTB |= (1<<PORTB1);
    _delay_ms(50); // You need a delay here too.
}


Converting a message received in char buffer to integer

atoi() is the simplest way:

int val = atoi(buf);

If that doesn't work then your buffer doesn't start with the number you are after. If that is the case you will have to work out where in the buffer the number is and convert just that portion. How you do that depends on what the format of the data is in your buffer.


How to send chars and values at the same time from processing to Arduino

The Arduino code sample you've provided is incomplete, and does not compile. On the Processing side, I would combine the LED On time with the Off time, using a separator, then ending with a \n. Something like this: myPort.write("1000:2000\n");.

There are many ways to parse the serial data into unsigned long to be used in the delay() function. Here is a sketch illustrating one way to parse it. I am using the serial monitor to send the following test data 1000:2000 (LED on for 1 second, off for 2 seconds). The serial monitor is sending the \n character.

char buffer[16];
unsigned long onTime;
unsigned long offTime;

void setup(){
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop(){

  if(Serial.available() > 0){

    Serial.readBytesUntil('\n', buffer, 13);

    char * pch;
    pch = strtok(buffer, ":");
    onTime = strtol(pch, &pch, 10);
    pch = strtok(NULL, ":");
    offTime = strtol(pch, NULL, 10);

    digitalWrite(13, HIGH);
    delay(onTime);
    digitalWrite(13, LOW);
    delay(offTime);
    memset(buffer, 0, sizeof(buffer));
  }
}


Receiving garbage value when sending a Json object from Arduino Uno to NodeMCU using SoftwareSerial

The problem with ArduinoJson.h is that it doesn't ensure robust and reliable transfer over UART serial.

Instead, you should use SerialTransfer.h to automatically packetize and parse your data for inter-Arduino communication without the headace.The library is installable through the Arduino IDE and includes many examples.

Here are the library's features:

  This library:

  can be downloaded via the Arduino IDE's Libraries Manager (search "SerialTransfer.h")
  works with "software-serial" libraries
  is non blocking
  uses packet delimiters
  uses consistent overhead byte stuffing
  uses CRC-8 (Polynomial 0x9B with lookup table)
  allows the use of dynamically sized packets (packets can have payload lengths anywhere from 1 to 254 bytes)
  can transfer bytes, ints, floats, and even structs!!

Example TX Arduino Sketch:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  char buff[] = "hi";

  myTransfer.txObj(buff, sizeof(buff));
  myTransfer.sendData(sizeof(buff));
  delay(100);
}

Example RX Arduino Sketch:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  if(myTransfer.available())
  {
    char buff[40];

    myTransfer.rxObj(buff, sizeof(buff));

    Serial.println("New Data: ");
    Serial.write(buff, sizeof(buff));
    Serial.println();
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }
}


Even though this is not elegant by any means, for now this is what I've came out with:

typedef struct
{
  char naming[20];
} student;

student record[] {
  {""},
  {""},
};

int a = 0;

char buf[20];

// the setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);    // initialize serial communication at 9600 bits per second
  while (!Serial);              // wait for Serial Monitor to open
  Serial.println("Program Starts \n Insert 2 students name:");  // Title of sketch
}

void loop() {
  if (readline(Serial.read(), buf, 20) > 0) {
    if (a == 0) {
      Serial.print("First student: ");
      strncpy(record[a].naming, buf, 20);
      Serial.println(record[a].naming);
      a = 1;
    }
    else if ( a == 1) {
      Serial.print("Second student: ");
      strncpy(record[a].naming, buf, 20);
      Serial.println(record[a].naming);
    }

  }
}

int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\r': // Ignore CR
        break;
      case '\n': // Return on new-line
        rpos = pos;
        pos = 0;  // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len - 1) {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
    }
  }
  return 0;
}

Basically by using int a, the program decides the sequences of the name. Although it will not repeat the sequence after the 2nd input (ie 1st>2nd>1st>2nd), at least the sequence is not randomize anymore.

Btw thanks for the tips @chrisl!


Leds become dimmer after they reach a certain brightness, why?

The described behavior stems from 2 important facts:

The loop() function will run very fast (microsecond range), while the button presses of a normal human will be rather slow (in the tens or even hundreds of milliseconds). That means, that with only one button press you will enter the corresponding if statement many times, everytime adding 10 to the value. You don't have control how many times exactly the if statement will be entered, so the value, that comes out after your button press is somewhat randomly growing.

While the analogWrite() function takes an int as the value parameter (16 bits on AVR), internally it assigns that value to the corresponding Timer register, which is only 8 bits big. So it can only hold values between 0 and 255 anyway. If you provide a bigger number as a parameter, the higher part will just be cut off. For example: Providing 257 will result in a value of 1 (= 257 % 256 = 257 % 2^8 --> 257 modulo 256). The higher values get wrapped around back into the range of 0 to 255.

So together you have a value, that is growing very fast and somewhat randomly, while the analogWrite() function will only take the lower 8 bit of that value. The outcome is a rather erratic, somewhat random LED brightness, which is difficult to control.
What to do now? That depends on what behavior you want to have exactly:

One button click (press + release) should increase the value of the corresponding LED by 10:

Currently you are checking, if the button is being pressed. Instead you have to look for the transition between not-pressed and pressed, so a HIGH to LOW transition. You can do that by saving the last read value in a variable at the end of the button reading part and comparing this previous value to the newly read value at the start of it. Though that still leaves you with the bounce problem. There are many measurements, that you can do, to debounce the button (you can google that easily), though here I just will suggest using the Bounce2 library. You can find it here on github or in the library manager (I think). It makes it much easier to read buttons reliably. It has good examples to learn how to use it.

The value should rise, while the button is pressed, and stopping to rise, when it is released again:

Here you should limit the rate in which the if statement is entered. You can do this by limiting the execution rate of the loop() function with a simple call to delay(), though that isn't a good coding practice and can limit you, when adding more functions to your code (because it's blocking the execution of other code). Instead you can use the non-blocking coding style involving the millis() function, that you can see in the BlinkWithoutDelay example. You use a timestamp variable to save the last time, when the if statement was executed. The if statement should then check (additionally to the button state), if enough time has passed, meaning if the difference between millis() and the timestamp is high enough. You can change the interval for this comparison to change the rate, in which the value is increased.


Send ECG signal with NRF24L01 from Arduino to Raspberry Pi 3

I see multiple flaws in your code:

radio.write(&s, sizeof(s)); does not what you think it would. The correct statement would be radio.write(s, sizeof(s)); without the ampersand.
You are using double. Not using floating point numbers at all would be preferable.
Your s is of type byte. Thus it only holds 8 bytes. So your floating point calculations are being truncated to the range [0, 255]. From your problem description this is not what you are trying to achieve, I think.


I would guess the problem is the IDE not properly handling device names containing spaces. Consider your symlink a workaround rather than a hack - unless you want to repair the IDE itself.


A question about Continuous Rotation Servo and Arduino

You can track the servo rotation with an encoder and after reaching a specific position, you can send different instructions to execute other actions.

Other alternative is maybe you can place a limit switch at the position where you want it to stop.


The hardware you have chosen is perfect for the job at hand.
But what @Hapi also mentioned was that you could probably do away by not using the Arduino !
The ESP8266 is in itself programmable. There are many Firmwares available to help you do so. (You can even program your own)

This can help you getting started : http://randomnerdtutorials.com/esp8266-web-server/

This is something like what you need at the end : https://hackaday.io/project/4562-esp8266-wifi-smart-garage-door

One thing to note : ESP8266 works with 3V, while your Relay would require 5V.
Happy hacking my friend.


AVR-GCC can't call function located on fixed address

I've tried this code with arduino and it worked (i taught, of course, i can't add the "-Wl,--section-start=.app_start=0xFA0" flag to the compilation process so the function not gonna be moved to other section)
So i set the arudino IDE to show every command from the compilation to the end of the upload process.

The problem lies in the usage of avr-objdump, whose i found somewhere and used witouth overview the CLI switches.

I've also made a mistake when i wrote the question. To disassemble the object file, the right command is:

avr-objdump -S --disassemble  ubb.o > ubb.asm

THe command i've used to create hex file:

avr-objcopy -j .text -j .data -O ihex ubb.o ubb.hex

The working one (extracted from arduino):

avr-objcopy -O ihex -R .eeprom ubb.o ubb.hex

-j means keep only the given section(s)

while

-R means, remove only the given section(s)


Is it permissible to connect 3.3V powered devices to the 5V I2C bus?

There are 3.3V devices that have 5V-tolerant inputs; that may be the case for your devices, but I would not risk it. Use a level converter designed for I2C, such as https://www.adafruit.com/product/757. Or you can make your own; https://cdn-shop.adafruit.com/datasheets/an97055.pdf explains how such a level converter works. Use a BSS138 if you are comfortable with soldering SMT components; otherwise use a 2N7000.


Hardware interrupts for buttons not directly assigned to pins

The MCP23017 has two interrupt outputs. The Adafruit shield however doesn't bring out either of those two pins. You could solder a wire between one of these pins and one of the unused arduino-header pins.


How to set float to variable with 7 digits after the decimal point in arduino?

float x = 3154681.124 / 100000; //x = 31.54;

x is now 31.5468112 (or close to).
Serial.println(x);

Output: 31.54
Why? Because Serial.println defaults to 2 decimal places for floats.

Syntax
Serial.println(val)
Serial.println(val, format)
Parameters
val: the value to print - any data type
format: specifies the number base (for integral data types) or number of decimal places (for floating point types)

So the solution: specift 7 decimal places when you print:
Serial.println(x, 7);


Ok, so you have some misconceptions here:

strtok() will not create a new c-string/character array. It returns a pointer, which points to the place in data, where your current token begins. So dong delete[] on split does not make much sense. Also note, that strtok() will alter the c-string, that you give to it. So data will be altered, after the function executed. strtok() inserts a null character \0 at the place of the delimiter (: in this case. That way c-string functions can be provided with the pointer, that strtok()` returns, and will only read until the end of the token (since they look of the null character as end of string).

The String class is bad on Arduino (also on the ESP, but not in the same urgency), because they have very few memory for variables. The String class allocates its memory dynamically, everytime, that you do concat, assign or change the size of the string. That means, it creates and destroys arrays with different sizes rather often, which will lead to memory fragmentation. You will get small holes in your memory, which are too small for new allocations. With the time you will get more and more holes, until your memory is full. Then the Arduino crashes. Since Arduinos often have very few memory (and don't have an OS, that manages the RAM), that happens rather fast. The ESP has more memory, so it doesn't happen that fast, but the problem is still the same.
It is the same situation with every dynamic memory allocation. In the rare cases, where you don't get memory fragmentation, you can as easy use a local variable (managed automatically on the stack for you).

In this instance, if I have an array d, I can use that for something, free it, create a new one and fill it with different data. This saves having another unnecessary array.

Actually: No, not really. The array d is created somewhere at the start of the process() function and deleted at the end of it. Just like a local variable (statically allocated). The only benefit here is, that d can have a variable size (not know at compile time). Though that can also create problems with the dynamic allocation, as described above (depends on if you are doing dynamic allocation in between of the allocation and deletion).

The _realloc_and_null_array() function makes only sense, when the size is different from the size of the provided array. But then again you can run into the issue described above.

I don't like to just create variables all willy-nilly.

What do you mean with "willy-nilly"? You are only creating variables, that you really need. But that doesn't mean, that these variables cannot be statically allocated. A common misconception, that programmers coming from bigger platforms (like PCs) often have, is that you should keep the memory footprint as low as possible, thus using dynamic allocation to free resources, that aren't currently needed. On a PC the freed memory can be used by other programs running on it. But on an Arduino there is only one program running. Memory, that you don't use, will just be doing nothing. So keeping the memory footprint is important, when you are actually running out of memory for your program, but not important, when you still have enough memory. As dynamic memory allocation comes with big caveats on these platforms, it is mostly not really worth it.

All in all: Dynamic memory allocation comes with huge caveats. You cannot just use it like on a PC. If you still can use it depends on your code and your requirements (like on code runtime, before it gets unstable). There are situations, where you can get away with it, and others, where you don't.


All mains electrical work should be performed by a fully qualified electrician.

Yes, this relay board will easily switch a light bulb.

A note on current: A single 100 Watt incandescent globe will only draw 0.83 Amps at 120V AC (0.416 Amps at 240V AC). The equation I used: I=P/V. You would start coming close to the maximum rating after 10 globes (although I advise staying well below the maximum).

You mention that your bedroom runs on 15 Amps, which I assume means that the mains runs through a 15 Amp circuit breaker (or fuse). This circuit breaker will trip if the total current to all devices after it exceeds 15 Amps.

A similar question was asked by Matthieu Napoli over on the Electrical Engineering Stack Exchange site. There are a number of high quality answers there that would be helpful for you. Worthiest to mention is Cybergibbons answer where he recommends using the PowerSwitch Tail as a very safe way of switching mains voltage. You don't need an electrician when using the PowerSwitch Tail providing the light you are controlling has the matching plugs.


How to print stack trace and register dumps on arduino serial monitor?

Got the required trace logs at the output. All I had to do was enable PSRAM in tools.


Serial Getting Garbage Data with real data

The Arduino should read only whole lines (non-newlines until a newline). Discard the line if it doesn't start with "stat>".

This will make your program more robust and less likely to fail with bad input. Fixing the transmitting app instead still leaves your Arduino vulnerable.

Consider the rule of thumb for serial communication: "Be restrictive in what you'll transmit; be lax in what you'll receive." Specify your communication protocol (e.g. "Packets will begin with 'stat>' and end with <newline>", maximum length of a packet, formats of variables and numbers, etc.). Then write your sender to hold as tightly to the spec as possible and write your receiver to accept whatever minor variations in otherwise good packets, that won't cause you to mistakenly accept bad ones. This principle will make your communications systems more robust and easier to get working in the first place.