Arduino Serial library (Synchronous or Asynchronous?) On an Arduino 101, I have this code running:

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

int counter = 0;

void loop()
{
 Serial.print(millis()/1000);
 Serial.print("\t");
 Serial.print(counter);
 Serial.print("\t");
 Serial.println(digitalRead(2));
 counter++;
}

A wire can be used to jump Pin2 between 3.3V and GND.

When running with the Serial Monitor on, I see the values increment at a rate where counter increases by the hundreds very quickly and steadily ticks through the thousands over time.

If I close Serial Monitor momentarily and re-open it, I notice that this counter value has increased dramatically (by the tens-of-thousands).  Another sign of this is when starting the program and waiting a moment to start the Serial Monitor.  As the Arduino 101 does not restart when the Serial Monitor is opened, I see a large initial value in the tens of thousands despite having just started the program.

My question is this: is the Serial library operating synchronously or asynchronously? I was led to believe that it was asynchronous; however, if that was the case, why should the Arduino execute any slower when the serial monitor is on?

While I understand that increasing baud rate will increase the speed at which counter increases, I still see the same dramatic increase in this code when the monitor is closed and then re-opened.

Another possibility I thought of was that maybe counter was being stored in a buffer and what I was seeing was not an up-to-date time or count.  To check this, the program prints the digitalRead value of pin2 as I swap the jumper between 3.3v and GND. This change in value was reflected instantaneously on the Serial Monitor, and I believe this means I am not seeing past data slowly being printed out to the monitor.

One last attempt at understanding what was going on was executing this code:

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

int counter = 0;

void loop()
{
counter++;
if (counter%1000==0)
 {
  Serial.println(counter);
 }

In this example, counter can be seen ticking through quite fast, by the hundreds of thousands, which indicates that the program is capable of running very quickly until a print statement is made. The effect is notably less when baud rate is increased to something like 115200 but is that saying that baud rate is literally slowing the processing speed of the controller?

Any kind of explanation as to what exactly is going on would be very appreciated.

Thank You for your Time.

Source of Arduino being supposedly Asynchronous:
https://itp.nyu.edu/physcomp/lessons/serial-communication/serial-communication-the-basics/

The Arduno 101 doesn't communicate to the PC using a UART. It uses CDC/ACM over USB, which looks like a UART to the PC.  But it isn't.

USB sends packets of data, not individual characters
It only sends if there is something to receive it at the other end
There is no such thing as baud rate with USB.

Basically, when the CDC/ACM port has been opened by an application (e.g., the serial monitor) the Arduino 101 starts to send the data down the line. When the port is closed all data to be sent gets silently dropped by the Arduino since there is nowhere to send it to.

Hence when the port is closed it runs much faster since the data that would normally have to be packed into packets and sent down USB isn't. It's just thrown away.

To address your confusion:

You are misunderstanding the concept of synchronous and asynchronous with regards to serial. There are basically two types of serial communication: Asynchronous, where both ends have to (pretty precisely) agree on the speed of communication (baud rate), and synchronous, where one end tells the other end what the speed is by providing a discrete clock signal. UART (RS-232, RS-485, etc) is asynchronous. It sends at a specific rate and has to rigidly stick to that rate for the other end to be able to receive it properly.  SPI and I2C are synchronous - they both (as master) provide a clock signal to the receiving end (slave) and the receiver synchronises its reading and writing of data with that clock signal (hence synchronous).

You are confusing those concepts with another meaning of synchronous and asynchronous - terms that could better be used would be parallel and sequential processing. If something happens in parallel then two (or more) things happen at once. This is the case of the hardware UART where you submit characters to be sent to the buffer and they get transmitted out by the hardware separately to the sketch - in parallel. Sequential would mean that one thing has to happen after the other. If the UART behaved like that your program would stall every time you wanted to send a single character.

So UART processing happens in the background, in parallel to your sketch. So does USB data processing for CDC/ACM. These things are generally coupled with interrupts to allow the CPU to handle tasks such as placing more data in the buffer or storing data that has arrived somewhere that you can get to it.  Interrupts aren't strictly parallel, in that they do stall your program while they run, but they are kind of in a different thread, or context. So they appear to be parallel.


How to add toggle button for LCD display text and backlight? I have set up a BMP180 and a DHT11 to display data on an HD44780 20x4 LCD.

I want to be able to toggle the altitude from meters to feet, the temperature from Celsius to Fahrenheit, and the pressure from absolute to sea level pressure using a tactile push button.

Here is the software code I have:

// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

#include <SFE_BMP180.h>
#include<dht.h>
dht DHT;

#define DHT11_PIN 8 // Second pin, leave 3rd pin unconnected 4th is ground
#include <SFE_BMP180.h>
#include <Wire.h>

// You will need to create an SFE_BMP180 object, here called "pressure":

SFE_BMP180 pressure;

#define ALTITUDE 237.0 // Altitude of Phillaur in Punjab, India. in meters

void setup() {
  lcd.begin(20, 4);
  lcd.setCursor(0, 0); // Zeroth Row
  lcd.print("hello, world!");
  lcd.clear();
  int chk = DHT.read11(DHT11_PIN);
  // Initialize the sensor (it is important to get calibration values stored on the device).
  if (pressure.begin()) {
    lcd.print("BMP180 init Success");
    delay(300);
  } else {
    lcd.print("BMP180 init fail");
    while (1); // Pause forever.
  }
}

void loop() {
  char status;
  double T, P, p0, a;
  lcd.clear();
  lcd.setCursor(0,0);
  //TODO Display in Feet as well using toggle
  lcd.print("Altitude: ");
  lcd.print(ALTITUDE, 0);
  lcd.print(" mtrs ");
  status = pressure.startTemperature();
  if (status != 0) {
    // Wait for the measurement to complete:
    delay(status);
    status = pressure.getTemperature(T);
    if (status != 0) {
      // Print out the measurement:
      Serial.print("temperature in deg C, From BMP180: ");
      lcd.setCursor(0, 1);
      lcd.print("Tmpratre: ");
      lcd.print(T, 2);
      lcd.print("'C");
      lcd.setCursor(0, 2);
      lcd.print("Humidity: ");
      lcd.print(DHT.humidity, 1);
      lcd.print("%");
      status = pressure.startPressure(3);
      if (status != 0) {
        // Wait for the measurement to complete:
        delay(status);
        status = pressure.getPressure(P, T);
        if (status != 0) {
          lcd.setCursor(0,3);
          // Print out the measurement:
          lcd.print("Pressure: ");
          lcd.print(P * 0.0295333727, 2);
          lcd.print(" mb");
          p0 = pressure.sealevel(P, ALTITUDE);
          // we're at 234 meters (Phillaur, Pb)
          // TODO: toggle to sea level to absolute pressure
          Serial.print("relative (sea-level) pressure: ");
          Serial.print(p0, 2);
          Serial.print(" mb, ");
          Serial.print(p0 * 0.0295333727, 2);
          Serial.println(" inHg");
          a = pressure.altitude(P, p0);
          Serial.print("computed altitude: ");
          Serial.print(a, 0);
          Serial.print(" meters, ");
          Serial.print(a * 3.28084, 0);
          Serial.println(" feet");
        } else Serial.println("error retrieving pressure measurement\n");
      } else Serial.println("error starting pressure measurement\n");
    } else Serial.println("error retrieving temperature measurement\n");
  } else Serial.println("error starting temperature measurement\n");
  delay(5000);  // Pause for 5 seconds.
}

You need to connect the button(s) to available digital inputs of the Arduino. I suggest that you use more than one button based on your description in the question.

The following tutorial describes the circuit needed and the associated code to read that input. All you have to do is duplicate it with a few more buttons on separate (available) digital inputs.

Arduino button tutorial


L9110H-bridge motor driver So I have this old RC car which doesn't seem to connect to the joystick very well so im going to modify it with an Uno with 433 MHz receiver/transmitter.

Both the steer and drive motors work as intended so long as you can reverse their current. I've seen people use the dual channel drivers which is what I know I probably what I should use to drive the motors. I bought a starter kit a while back which came with a single L9110H Chip. I thought maybe I could order another one and just solder them to a PCB and mount the PCB along with the Uno inside the car that way I don't have an extra chip just collecting dust. I've looked at the data sheet for the L9110H and came up with a diagram on Fritzing.

I was hoping someone could tell me if I'm on the right track with this?

Yes, looks good to me. That looks to be identical to the "Application Circuit" on page 2 of the datasheet you link to.


Pro Mini 5v with Adafruit motor shield v1 power sharing problems I am trying to convert a RC car into autonomous car using Arduino Pro Mini 5v 16 Mhz. I have done this with UNO and Adafruit motor shield 1.0 with 4 gear motors and one micro servo for mounting range finder sensor. That worked fine.

Need to mention here that originally the RC car was using 5 AA cells for 2 motors and its RC reciever which looks like a customized motor shield as well.

I tried to move everything to Arduino Pro Mini 5v, and motor shield v1 to reduce space. Now how I wired everything.

Uses 8 AA cells to power the motor shield on EXT-PWR input.
From EXT-PWR in motor shield one wire goes to RAW in Pro mini.
From Pro Mini, VCC connected to +5v on motor shield.
One micro servo having range sensor getting its current from motor shield.
Motor shield has to run two motors, 1 for rear wheels and 1 for turning front wheels. (they are small motors look like 3v)

Now when I turn on the power the motor sometimes run and sometimes sound like bee and no movement. That also cause the L293d chip on motor shield becomes very hot and I think I have burnt one yesterday and replaced it from another motor shield. Same for servo it sometimes move or not move but sounds like hmmmmmmmm. The Arduino power light on and red. But sometimes it flickers and other light is also on and off.

At this point I have no idea whats wrong here. I changed the input voltage to lower but no progress. Tried to disconnect the 5v input from Pro Mini to motor shield and give 9v input to motor shield but nothing works. Please suggest best or correct power distribution in this case.

Thanks

Qazi

I would check each motor without the motor shield to see if the motors are ok. Check the motor shield motor supply, should be around 12 volts with 8 AA cells. You might run a simple test program to see if the motors run full power forward and full power backward with the motor shield. Check the servo with a simple program like the Arduino Knob program. I suspect the Pro Mini 5 volt regulator is overloaded, causing the buzzing sound, but you have to find out why. One possible reason is that you are dropping from 12 volts to 5 volts via the pro mini linear regulator, creating all kinds of heat. The additional load of even a small servo might push the power dissipation spec over the edge.


How do I use Microduino (mCookie) on Linux? I'm interested in getting the mCookie working in Linux — specifically, in Fedora 23. The Arduino IDE (version 1.6.4) is already available. I'm very familiar with Linux, fine with C, and completely new to Arduino.

The tutorials for Windows or Mac describe installing a customized version of the IDE along with drivers. Do I need special drivers on Linux? On the projects' GitHub site, I found the examples and a directory called 'avr' which has promising subdirectories like "bootloaders" and "libraries", along with files boards.txt and platform.txt.

Can I download this stuff and add it to the existing "system" arduino package somehow? How, and what will I need?

First you will need the arduino 1.6.x package from updates, not the 1.0.x package from fedora. Then:

  You will be adding a URL to the new Additional Boards Manager URLs option: https://github.com/wasdpkj/Microduino-IDE-Support/raw/master/package_Microduino_index.json

source

This tutorial tells you where and how to add that URL to the preferences, as well as how to actually install the required support files.

As of this writing, the platform configuration supplied as part of the above won't work out of the box in Linux; you will also have to edit ~/.arduino15/packages/Microduino/hardware/avr/1.6.7/platform.txt to:

replace compiler.path={runtime.tools.avr-gcc.path}/bin/ with just compiler.path=/usr/bin/
on the line starting recipe.ar.pattern=, change {archive_file_path} to {build.path}/{archive_file}

Hopefully this will be fixed in future versions.

You probably also want to prevent ModemManager from probing the serial device with this udev rule, just replace the vendor and product IDs as appropriate:

SUBSYSTEM=="usb-serial", ATTRS{idVendor}=="xxxx", ATTRS{idProduct}=="xxxx", ENV{ID_MM_DEVICE_IGNORE}="1"


How to generate true random numbers over Arduino Uno without any external hardware? Using a 'random' function in sketch gives same pattern of numbers every-time. But, I need to generate different numbers such that any number to repeat itself should have a very less probability.

The standard (but not very good) solution is to seed the random number generator from an analogRead() on an unconnected pin. For better options, see this answer to a related question.


Softserial - max speed - loosing characters I have a Ublox-NEO6M gps module that I am trying to read using SoftwareSerial. The GPS sends a few NMEA sentences at 9600 baud each 5th second - totally a couple of hundred characters. My 3.3V atmega 328 on an arduino pro board seems not to be able to cope and is loosing characters. One set of NMEA sentences ends up looking like

$GPRMC,131953.00,A,5939.89405,N,01038.33769,E,0.399,,060316,,,A*79
$GPVTG,,T,,0,.K2$G335.50.6,745,0*
GA1,2,0,.1,2
G,5,12702,21214G,,1,,,84,81037$S,,26,55,09,17*
G41,12388,2*$L39,1.615,6

The first one is good, all the following are mangeled (they should always start with $G and never contain a $ within the string.

If I set the transmission speed to 4800 baud, the arduino reads it without problems. Connecting the GPS to the same Serial USB interface that I use for the pro, so it talks directly to the PC, everything works at 9600, so the problem must be at the arduino. Is is as expected that soft serial is not working at higher baudrates than 9600? are there any settings I could change?(I was looking for possible buffer values without finding anything) Or are there other soft-serial libraries that is faster than SoftwareSerial?

I may end up using the hardware serial interface if I need the speed, but as that makes development and debugging a bit harder, I would prefer to use some other serial interface.. (and now, it is not possible to use a mega, this is prototyping for a gpssystem that cannot be too large)

This is a classic example of where you choose the wrong chip just because it's the most popular chip around here.

What you want is a dedicated hardware UART just for the GPS that isn't used for your debugging connection.

But, you say, you can't use a Mega because it's too big. And that's true as far as it goes. However, you have blinkered yourself into considering either a Nissan Micra or an 18-wheel juggernaut. You forgot the Ford Focus or the Renault Meganne.

There are other chips besides the (what is too under-specced for you) ATMega328 and the (what is too over-specced for you) ATMega2560. Chips that have other facilities.

Chips like the ATMega32U4 for example.

One hardware UART like the 328, which you can use for the GPS. One USB interface, which you can use for debugging.

And there are boards already with that chip on it - boards like the Arduino Leonardo, or the Arduino Micro.


Feeding microcontroller and linear actuators (motors) with the same power supply I have already made a diagram using a motor controller. I want to use only one power supply to feed arduino and motors. I want to use MDD10 dual motor driver.

The details of the actuators each one is:

Input voltage: 12VDC,
Max Load: 750N(168.607lbs),
Stroke Length: 16 inch,
Travel Speed: 12mm/s,
Duty Cyle: 25%,
Current: 5A.

The power supply is 12V, 10A.

Could you please check if it is ok, or which would be the best solution?

Some of my concerns are:

Be sure if the feed of 12 volts for the motors, and 5 volts for Arduino are correct and can live together as shown.

Be sure if the wiring for the Arduino, driver and motors is correct since it looks kind of simple.

I want to know if this is the natural approach by doing it with a voltage regulator to feed the Arduino and with 12V 10A power supply to feed the motors, or if there are other, better options to make the circuit feed only using one power supply (12V, 10A).

MDD10 Datasheet Link: https://www.robotshop.com/media/files/content/c/cyt/pdf/cytron-10a-7-30v-dual-channel-dc-motor-driver-shield-datasheet.pdf

Thanks in advance

UPDATE

I have increased power supply to 13A, also changed the linear voltage regulator (7805) to a switching voltage regulator (OKI-78SR-5), what do you think about this approach?

Or I should try with the 12V DC Vin of Arduino(I understand that it works with a linear voltage regulator)? Being this option, it could be maybe with a voltage pre-regulation stage(for example from 12V to 9V) or maybe connecting directly to the jack.

Thanks, Best Regards.

First of all I would look to see if the two motors will actually run at the same time.
If not then the 10A power supply, is fine.
If they do run together, for how long? (you mention 25% duty cycle), power supplies usually have a over capability for a short period of time, and batteries will supply more current but at a slightly reduced voltage, so if going slightly slower isn't an issue then this would be fine.
Then there is the question of do they really use all 5Amps, I very much suspect not, unless you are fully loading the actuator(750N), they prob run at 2-3 amps at most.
Secondly
Circuit protection, fuses or thermal shutdown links for the motors is required, better still instant overcurrent protection for them set at 1.2x nominal current.
Do some worst case tests and measure the current, set the protection to 1.2 x this.
Remember if there is an issue the supply voltage will start to drop, its now that the micro will suffer if the voltage dips too much and you have no protection/sensing.

So suspect the power supply is more than ok.


Is it safe to power Arduino project using a power bank and wall charger? I got an Arduino project that need a constant source of power. Rather than dealing with batteries, I want to use a power bank like this:

Better yet, I want to keep the power bank plugged in to the wall outlet using a wall charger like this:

The USB wire coming out of the power bank, I can modify it and connect it to the 5V on the Arduino (Pro Mini 5V version). Is it safe to do so? The application uses a stepper motor that draws around 200mA and only runs intermittently.

Thanks

Yes you can.  A promini will run very well on 5V from a wallwart.  Connect 5V to VCC (not RAW or VIN).  You can also find wallwarts with 2.1mm/5.5mm plugs, and a mating barrel jack adapter that ends in screw terminals so you don't have to try hacking up a USB cable.

Power bank, you will have to play games to convince it that something is connected and drawing sufficient current to keep it turned on.

Wallwart example  https://www.mpja.com/5-Volt-DC-Plug-Power-Supply-4A-Regulated/productinfo/18520+PS/

Barrel jack to screw terminal adapter example  https://www.mpja.com/55_21mm-Power-Jack-Screw-Terminals/productinfo/19454+PL/


Send serial command and wait for reply I am new to Arduino and have tried all kinds of code for attempting to achieve this. None with any luck, however. I feel that it should be a relatively easy task and therefore, figured that someone out there with more proficiency with an Arduino than me, would be able to help.

Essentially, I have two commands sent to a device via the Leonardo serial port. One is the single character "R", and the other is the single character "O". The device then sends back 8 binary bytes (non ASCII) in floating point format per command. So if I send O, it will return 8 binary bytes, and then the same goes for if I sent R.

The commands O and R need to be simultaneously sent via the serial every 250ms and wait for their respective responses before sending the next command.

I also need to store the device's response to O and the device's response to R in respective variables that will have a new value every 250ms. I am not familiar with single point format and therefore am unaware of what variable system to use.

Here is my best, yet unsuccessful attempt:

unsigned long previousMillis = 0;
const long interval = 250;
int responseO;
int responseR;

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

    while(!Serial);
}

void loop()
{
    unsigned long currentMillis = millis();

    if(currentMillis - previousMillis >= interval) { //timer for every 250ms
        previousMillis = currentMillis;
        Serial.println("R");               //Figured that "println" with a string for the character R should be ok

        if(Serial.available() > 0) {          //Don't know if I am correct here, I was hoping that the serial would only be read if the device responded to the command R
            responseR = Serial.read();       //Read serial for device's response to command R and save it in a variable
        }

        Serial.println("O");               //Do the same thing for the command O

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

However, whenever I test this, it appears that the program is unable to differentiate between which responses are due to one command, and treats one response as if both commands requested it when only one did. Also is a floating point format variable just a float?

Thank you so so much, I really need some help this has been burning away at me for days........

Cheers, Harry

The code shown in two previous answers is problematic.

For example, in Look Alterno's code, Serial.println("R") will trigger an R response.  The while(!Serial.available()); construct will wait for the first byte of the response.  Then responseR = Serial.read(); will read one byte.  Next, Serial.println("O") will attempt to trigger an O response.  The second while(!Serial.available()); will wait for a byte to be available, which should happen when the second byte of the R response arrives.  Then responseO = Serial.read() will read that byte.

In ratchet freak's code, each quarter second bytesToReadFromR and bytesToReadFromO are set to 8.  In the next several passes through loop(), if(bytesToReadFromR) and if(bytesToReadFromO) are satisfied, so while(bytesToReadFromR && Serial.available()) and while(bytesToReadFromO && Serial.available()) will be controlled by whether a character is available.  At 9600 bps, about one character per millisecond will become available, so most of the time we are just spinning through loop() dozens of times per millisecond, waiting for characters.  The if statement for bytesToReadFromR has a slightly higher chance of catching fresh characters, but which buffer (responseR or responseO) gets any given character still is left to chance.

Instead of the code previously shown, consider something like the following:

enum { dataBytes = 8, interval=250 };

float getResult (char trigger) {
  union { byte d[dataBytes], float f[2] } u;
  byte rin=0;
  Serial.print(trigger);
  while (rin < dataBytes) {
    if(Serial.available())
      u.d[rin++] = Serial.read();
  }
  return u.f[0];        // Assumes bytes in forward order
}

unsigned long prevMillis = millis();
float RValue, OValue;

void loop() {
  if(millis() - prevMillis >= interval) {
    prevMillis = millis();
    RValue = getResult ('R');
    OValue = getResult ('O');
    // put code here to consume the results
    // ...
  }
}

Note, this code will get stuck if too-few characters arrive from the R&O device, or if some characters get lost for any reason.  One could add a timeout to the loop in getResult(); it could check for millis() - prevMillis >= interval and if so, break the loop and return a NAN.

Note, this code assumes the byte-order of floats from the R&O device matches that of the Arduino.  That will be so if both are big-endian, or if both are little-endian.  If they differ, store bytes in reverse order into the u.d array, and return u.f[1] instead of u.f[0].

Note, union is a C / C++ technique for accessing data multiple ways.  The declaration union { byte d[dataBytes], float f[2] } u says that u is a structure where the array d starts at the same address as the array f.  Thus, the float u.f[0] corresponds to the first four bytes of u.d, and u.f[1] to the next four.

Note, if the R&O device requires an end-of-line character, change  Serial.print(trigger) to Serial.println(trigger).


Doubt with the library esp8266wifi and Station Mode I have been working for a while with the ESP8266 I have a question:

According to the online documentation of GitHub from the esp8266wifi library I can initialize the WiFi in Station mode to (obviously) connect to a nearby AP, I can initialize the station mode in 3 "different ways":

WiFi.begin (): The module initializes the Station mode and connects to the last network that is connected, because the credentials (SSID and Password) are stored in its internal memory (flash?).
WiFi.begin (ssid, password): The module initializes the Station mode and connects to the network with "ssid" and "password".
WiFi.begin (ssid, password, channel, bssid, connect): The same as the previous one, only that you pass more parameters: the one that interests me is the bssid, which is the MAC address of the AP to which I am going to connect.

Now comes the question: if I wanted to use the last mode, because I want to make sure that the ESP connects ONLY to an AP (a kind of MAC filtering), I also have to specify the channel and set the connect parameter? Or I can simply use something like this:

WiFi.begin ("MyOwnNetwork", "123456789", "00: 1B: 44: 11: 3A: B7")

I can not prove it right now, I do not have the module in my hands.

This is the function prototype:

Per C++ rules, in order to supply an argument for bssid, you have to pass an argument for channel as well, but connect is optional since it's positioned after your target argument. This should not be a problem though since you can just pass the default value of channel (i.e. 0) into the function; the channel argument is only relevant if you enter a value between 1 and 13 inclusive.

So your call should basically look like:

char ssid[] = "ssid";
char pwd[] = "pwd";
uint8_t bssid[] = {0x00, 0x1b, 0x44, 0x11, 0x3a, 0xb7};
WiFi.begin(ssid, pwd, 0, bssid);


How do I use PlatformIO to flash ESP-12F (ESP8266MOD) In PlatformIO while creating a project , in the board selection there is no ESP-12F in the boards. While there is ESP-12E. I can flash ESP-12F while choosing ESP-12E from the boards without any flashing issue. But there are some runtime issues, the one that I noticed is the LED doesn't blink when flashed from PlatformIO , but works fine, when flashed using Arduino IDE using the same code.
So there may be some difference in the configurations.

  C:\Users\USER\.platformio\platforms\espressif8266\boards

In this directory I found the esp-12e board which is a JSON format.

{
  "build": {
    "core": "esp8266",
    "extra_flags": "-DESP8266 -DARDUINO_ARCH_ESP8266 -DARDUINO_ESP8266_ESP12",
    "f_cpu": "80000000L",
    "f_flash": "40000000L",
    "flash_mode": "dio",
    "ldscript": "eagle.flash.4m1m.ld",
    "mcu": "esp8266",
    "variant": "nodemcu"
  },
  "connectivity": [
    "wifi"
  ],
  "frameworks": [
    "arduino",
    "simba",
    "esp8266-rtos-sdk",
    "esp8266-nonos-sdk"
  ],
  "name": "Espressif ESP8266 ESP-12E",
  "upload": {
    "maximum_ram_size": 81920,
    "maximum_size": 4194304,
    "require_upload_port": true,
    "resetmethod": "nodemcu",
    "speed": 115200
  },
  "url": "http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family",
  "vendor": "Espressif"
}

How do I add ESP-12F to the PlatformIO boards and flashing without any issue.

At the PlatformIO community I asked the same question, and pfeerick  suggested to add a build flag.

  It’s most likely the onboard LED is on GPIO2, not GPIO1 so try adding

  build_flags = -D LED_BUILTIN=2 to your platformio.ini … hopefully that
  kicks in before the pins_arduino.h defintion.

But It didn't did the trick.
And the compiler throws a bunch of warnings.
What I did to make it work is to ignore LED_BUILTIN constant and use 2 instead.

#include <Arduino.h>
void setup() {
 pinMode(2, OUTPUT);
}

void loop()
{
  digitalWrite(2,LOW);
  delay(200);
  digitalWrite(2,HIGH);
  delay(200);
}


Phasing a Stepper Motor Control Project Problem I have a project involving stepper motors, in which I want to manage electronic equipment. What I'd like is a system allowing me to run the stepper motor continuously forward as long as I step on a floor pedal. I'd like to control the rotation speed with a variable pot if possible.

Next, I'd like the motor to automatically reverse once I release the foot pedal.  I'd like to control the reverse rotation speed with a variable pot if possible, and to control how long the motor runs in reverse before stopping.  That time may range from 1 ms to 10 sec. If possible, I would love to use pushwheel switches to control the reversing time.

I might suggest looking at 3D printing firmware such as Repetier and Marlin, and the Arduino Playground for smaller projects such as simple stepper control, reading and debouncing switches, and digital rotary and Analog pots. I bought a cheap (wired USB) PS3 controller to get some ideas. It has a wide variety of input options. And the local hardware store comes in handy along the way.

I'd also recommend moving up from the Arduino native IDE to something like the free version of Microsoft Visual Studio with the Visual Micro add-in for Arduino. This will give you breakpoints, variable access, and handy formatting enhancements.

Getting to where you want will take a while, but the end result will be lots of learning, and an end project that does exactly what you want, which no one else sells or even has.


Understanding NRF24L01 specifications I was reading this tutorial about the NRF24L01 and came across a few terms which I did not clearly understand.

It uses the 2.4 GHz band

Does this refer to the frequency of the EM waves that the device uses to communicate?

If used in open space and with lower baud rate its range can reach up to 100 meters.

I know baud rate refers to how many "groups of bits" are transmitted per second. I don't quite understand why the range increases for a lower baud rate.

The module can use 125 different channels which gives a possibility to have a network of 125 independently working modems in one place. Each channel can have up to 6 addresses, or each unit can communicate with up to 6 other units at the same time.

Here, does a channel mean a single frequency? How is the range of possible channels decided (why 125) and how is the smallest detectable resolution decided (smallest change in frequency which would cause a change in channel)? So does a single unit work on only one frequency or could the same unit communicate at different frequencies at the same time and so be a part of different networks simultaneously? In effect, I am not able to make sense of this paragraph!

It uses the 2.4 GHz band

Does this refer to the frequency of the EM waves that the device uses to communicate?

Yes. It generates (and receives) radio waves in the region of 2.5GHz.

If used in open space and with lower baud rate its range can reach up to 100 meters.

I know baud rate refers to how many "groups of bits" are transmitted per second. I don't quite understand why the range increases for a lower baud rate.

Think of it like talking to someone. If you're stood right next to them you can speak nice and fast and they can understand you. Your speech comes across nice and clear.
However if you're the other side of a quarry you have to shout really loud, and if you talk too fast they can't understand you. You. Have. To. Shout. Slowly. so that they can understand you.
The environment makes a lot of difference to how your speech propagates. In large areas there's lots of echo and other things.  It's similar with RF communications. There's more noise and things that can interrupt communication. By having lower baud rates you're giving the receiver more time to understand what it's receiving and make sense of the data.

The module can use 125 different channels which gives a possibility to have a network of 125 independently working modems in one place. Each channel can have up to 6 addresses, or each unit can communicate with up to 6 other units at the same time.

Here, does a channel mean a single frequency? How is the range of possible channels decided (why 125) and how is the smallest detectable resolution decided (smallest change in frequency which would cause a change in channel)? So does a single unit work on only one frequency or could the same unit communicate at different frequencies at the same time and so be a part of different networks simultaneously? In effect, I am not able to make sense of this paragraph!

There's a number of different factors at play here. First there is the "Bandwidth" of the channel. This is the maximum amount of data that can be squeezed into a particular carrier frequency with a particular amount of "space" around the signal. You can think of the channel width as the diameter of a pipe. The wider the pipe the more water can be pushed through the pipe per second.
You want to slice the RF allocation up into enough channels to give enough concurrent access to lots of devices, but at the same time you want to have enough bandwidth per channel that you can transfer reasonable amounts of data.
It's all a balancing act.
Nordic decided 125 channels was the optimal balance for their application.
One nRF24L01+ can work at one frequency at a time. That's not to say you can't instruct it to change frequencies at any time, but it can only be listening on the one frequency at once. Just like a normal FM radio - you can only listen to one radio station at a time.
But the nRF24L01+ protocol uses addresses within that one chosen channel, so lots of devices can all be on the same channel to talk together, and each is distinct by its address.
The protocol also includes the concept of "pipes" which are virtual wireless circuits between two physical devices. Once you have configured a pipe with an address any other device can communicate with that pipe. You can configure up to 6 pipes, so up to 6 devices can send to the same target at the same time and each devices data is kept separate and distinct from the others. It's kind of like having 6 serial ports all connected to different devices at once.


Exit from for function after detecting obstacles #include <HCSR04.h>

int red = 13;
int green = 12;
int blue = 11;
int trigger = 9;
int echo = 8;
int halt;

void setup(){
  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(trigger, OUTPUT);
  pinMode(echo, INPUT);
  Serial.begin(9600);
}

void redLed(){
  rgb(255,0,0);
  delay(200);
}

void rgb(int r, int g, int b){
  analogWrite(red, r);
  analogWrite(green, g);
  analogWrite(blue, b);
}

void fadeBlu(){

    for (int i=0; i<=255; i+=5){
    rgb(0,0,i);
    delay(40);

    Serial.print("halt in IF is ");
    Serial.println(halt);
    }

    for(int i=255; i>=0; i-=5) {
      rgb(0,0,i);
      delay(40);

      Serial.print("halt ELSE is ");
      Serial.println(halt);
    }
}

void human() {

  UltraSonicDistanceSensor distanceSensor(trigger, echo);
  double distance = distanceSensor.measureDistanceCm();
  halt = 0;

  // cover sensor
  if (distance<=30) {
    halt=0;
    redLed();
  }
  // no cover
    halt=-1;
    fadeBlu();
}

void loop(){
  human();
}

I'm looking for a way to exit from "for" loop of fadeBlue() function if the hand is detected in front of sensor. I would like that in any case of fading and if there is hand in front of sensor the led became red. In my code the led doesn't stay red if I had hand in front of the sensor and also the value of "halt" doesn't change. I put some serial.println to make debugging.

First, try to avoid duplication of code, so make a sub function (I slightly changed the print statement, but I assume it's only for debugging):
void fadeBlu()
{
    fadeBlueCycle(0, 255, 5);
    fadeBlueCycle(255, 0, -5);
}

void fadeBlueCycle(uint8_t start, uint8_t end, int8_t step)
{
    for (int i = start; i != end; i += step)
    {
        rgb(0, 0, i);
        delay(40);

        Serial.print("halt in step ");
        Serial.print(step);
        Serial.println(halt);
    }
}

Now to break from the for, you can use break, or simply return. It's not a good practice to have multiple return statements in one function, thus put it at the end, and use a break. Also, some people don't like a break and prefer using a `while. This would look like:
void fadeBlueCycle(uint8_t start, uint8_t end, int8_t step)
{
    uint8_t i = start;
    bool condition = true;

    while ((i != end) && condition) // or !condition, depending on what you prefer
    {
        rgb(0, 0, i);
        delay(40);

        Serial.print("halt in step ");
        Serial.print(step);
        Serial.println(halt);

        condition = `some condition`;
        i += step;
    }
}


Arduino digital I/O pins I heard that using digital io pins in INPUT_PULLUP mode is much reliable and stable than in the case of using them in INPUT MODE.Then why is INPUT MODE still used...I mean Why isn't INPUT_PULLUP mode put as default ??

When the internal pullups are activated, a small amount of current is sourced by the pin's circuitry whenever the input is low.

That means that to drive the signal low, an external driver must not only sink current to discharge the capacitance of the internal and external circuitry, but it must continue doing so to dominate the attempt of the internal pullup to make the line high so that the voltage of the resistive voltage divider formed by the internal and external resistors is low enough to be an unambiguous low.

This means that the external circuit must be stronger - not normally a problem for an active device, but potentially an issue for monitoring some very high impedance external circuit.  So for example, if you wanted an external pull-down resistor, it would have to be substantially lower in value than the internal pull-up.

It also makes low power design (long life on batteries) difficult, as a system cannot take advantage of the best micropower suspend modes when any signal is being asserted against the direction of a pulling resistor.  With just one or two such cases you might still get reasonable life when using flashlight batteries, but not with a coin cell, something a well designed ATmega circuit can presently do.

After seeing Igor's comment, and re-reading your post, it seems maybe you are asking why the default is to have them disabled, rather than why you have the ability enable/disable them at all.  Most likely, the reason the Arduino core software has them disabled by default is because the ATmega resets that way.  As to why the ATmega resets that way, you might have to ask the design engineers, but generally it has been the norm to have an MCU reset to a state where it has the least influence on the external circuitry.  However, that is not necessarily the best - floating (undriven) inputs can potentially cause a typical CMOS input structure to consume more power than ones weakly driven to a known value.


How to know positive and negative in breadboard I have this breadboard, and there is no indication on it about what is positive/negative on it.

In comparison, this other breadboard (pic from the internet) DOES have indications:

Can anyone give me a hint ?

You decide which rails are positive and which are negative when you connect them to the + an - from your power supply or battery.

A breadboard isn't polarised per se. It's just a bunch of cross-connections inside a perforated plastic case. No active or passive components inside.

Some manufacturers may choose to paint indications regarding where to connect the positive and negative rails, but those are just a guideline. Ultimately it's your choice, you're free to connect + and - wherever you want in the breadboard rails.


How to connect Sparkfun M6E Nano UHF Rfid reader and ESP8266 NodeMCU 0.1 I am using an ESP8266 NodeMCU v0.1 and Sparkfun M6E Nano UHF Rfid reader. How to connect NodeMCU to M6E Nano UHF Rfid reader?

The interface of Sparkfun M6E Nano UHF Rfid reader is Serial TTL. So you should connect it to Serial pins of the NodeMcu. Don't use USB then, because it is connect to Serial too.


What options do I have to wirelessly connect my computer to an arduino? For my project I have an arduino Uno connected to my robot. I need to control it wirelessly. I have thought of using a bluetooth module , but I need a larger range. Then I thought of using an RF-module like the Xbees and the 2.4 Ghz nRF24L01. However I can't use the Xbees due to budget issues. As for the nRF24L01- I understand that using the trasmitter and receiver modules I can transmit information between 2 arduinos- however I need to transmit from my computer to my remote arduino. I want to achieve this without using a second arduino at the transmitting (computer) end. Is there a way to achieve this?

How about using wifi?
The esp8266 costs as low as 3$ and has good range.
here's a quick tutorial
What you'll need to do is send a command to the esp8266 and in turn it'll communicate with the arduino via Serial (or Software Serial) and tell it what to do.


Arduino Mega vs servo shield I am currently designing a hexapod with a total of 18 servos. I come from a computer science background and know little about electronics, so there is one thing which puzzles me.
Adafruit is selling this servo shield. It can power up to 16 servos while only using two pins. But it's quite expensive as it would cost me ~30€. Add the cost of an Arduino Uno and you are at >50€. At the same time I could just buy an Arduino Mega and power all Servos for a lower price.

I like to think that Adafruit wouldn't sell a uselessly overpriced product, so would there be any advantage to using this shield?

Bonus question: If I'd end up buying the shield, could I just power 16 Servos with the shield and 2 via the Arduino? Would there be any problems with that? Like a delay in the 16 motors or similar issues which could through my kinematics over bord? Would I have to buy two shields (which is not really an option at that price)? Any other suggestions I have not heard of are also very welcome!

If it is of any relevance, I am planning to buy these servos as they are pretty strong and come super cheap in bulk.

The idea of that particular servo shield is that it provides 16 PWM (pulse width modulation) channels. These are all operated simultaneously with no additional processing overhead on the Arduino.

The Arduino Uno itself does not offer 16 (or 18) hardware PWM channels but only 6 (see here). So driving 18 servos without an additional shield would require software PWM which requires some of the Arduino's ressources to be devoted doing the calculations. This may or may not interfere with the rest of your program.

Furthermore the Uno does only provide 14 dedicated digital GPIO pins in total (+6 multiplexed digital/analog pins, as ZS6JMB's answer points out), so additional hardware would* be required either way - or using an Arduino with more pins (such as the suggested Mega). The Mega however offers only 15 hardware PWM channels, leaving you with soft PWM again. (* assuming some pins will be needed for sensors or user interfacing).

An alternative is this board or, uhm, well, cheaper clones if you like. It features the same chip as the shield but with a PCB half the size and thus skipping the "free use area". I expect it to behave the same way like the shield and operate with the same libraries as the both the shield and this board communicate only via I2C. Both can be chained (or stacked for the shield if you will) for up to 992 PWM outputs (62 boards).


Wifi.status() always returns WL_NO_SHIELD I've an Arduino Mega 2560 R3 and recently bought a Wifi Shield CC3000 from ebay http://www.ebay.de/itm/201405512301
They write that the firmware has the version ServicePack 1.11.1.
The WiFi shield is connected to the Arduino and green status light is on.

I try to run this example code:

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
}

// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
  Serial.println("WiFi shield not present");
    // don't continue:
  while(true);
}
...

It seems that Wifi.status() always returns WL_NO_SHIELD.
What can I do?

Thanks for help.

The problem is solved now.

I imported the Adafruit_CC3000 library which can be downloaded here: https://github.com/adafruit/Adafruit_CC3000_Library
I run the example but the output was chinese nonsense
Instead of

Serial.begin(115200);

I used

Serial.begin(9600);

then the examples run without any problem

Thanks @Majenko. His question was very helpful.


Remote temperature sensor system without slave board I want to build a temperature control network over my house reading data from each room and sending it to the main board for further processing. I need about 6 sensor nodes sending the data over the air to the main node.
There are tons of tutorials of making master-slave temperature/pressure etc control systems of 2 Arduino boards communicating via wireless channel.
I find it a bit expensive to have a board per sensor node. Is that possible to build a sensor device without a controller using just a sensor, a battery and a wireless transmitter plus required radio components? It's ok to send raw data to the main node. Assuming it knows the protocol it will be able to decode the data there from all the incoming channels.

As @Majenko said on comment, its possible. One of the choice is ESP8266. Your project has been successfully accomplished, you can check here, here, or here. NSP8266 only needs 3-3.6V (low current) supply voltage.


Stepper motor is only moving one step at a time with an IR sensor I am trying to get both the motors to run simultaneously once the motion detector senses an obstacle. Both motors run fine by themselves but when I implement the sensor the motors only move one step per motion detected.

Arduino Mega (ATMega 2560)
(2) NEMA 17 stepper motor/ A4988
Digital IR Sensor Module

#include <Arduino.h>
#include <avr/io.h>
#include <AccelStepper.h>

AccelStepper stepper(1,5,4); // w/Driver (1,Step, Direction)
AccelStepper stepper2(1,9,8);

const int pin_ir_in = 3;
int prev_state = 1;
int curr_state = 1;
int counter =0;

void setup() {
  Serial.begin(9600);
  pinMode(6,OUTPUT); // Enable
  pinMode(10,OUTPUT);

  digitalWrite(6,LOW); // Set Enable low
  digitalWrite(10,LOW);
}

void loop() {
  digitalWrite(6,LOW); // Set Enable low
  if (stepper.distanceToGo() == 0)
  {
    delay(1000);
    stepper.moveTo(100);
    stepper.setMaxSpeed(200);
    stepper.setAcceleration(100);

  }

   digitalWrite(10,LOW); // Set Enable low
     if (stepper2.distanceToGo() == 0)
  {
    delay(1000);
    stepper2.moveTo(100);
    stepper2.setMaxSpeed(200);
    stepper2.setAcceleration(100);

  }

int curr_state = digitalRead(pin_ir_in);
if (curr_state != prev_state)
{
  if (curr_state == 0)
  {
    stepper.run();  // Actually makes stepper move
    stepper2.run();
    delay(500);
  }
  prev_state = curr_state;

}

}

As chrisl said, you need to call run repeatedly.

I tried to rewrite the code you've given, though I'm not entirely sure what it is you try to achieve.

void loop()
{
  stepper.run();  // Actually makes stepper move
  stepper2.run();

  int curr_state = digitalRead(pin_ir_in);
  if (curr_state != prev_state)
  {
    if (curr_state == 0) // Motion sensor activated
    {
      stepper.moveTo(100);
      stepper.setMaxSpeed(200);
      stepper.setAcceleration(100);
      stepper2.moveTo(100);
      stepper2.setMaxSpeed(200);
      stepper2.setAcceleration(100);
    }
    prev_state = curr_state;
  }
}


DFRobot GSM / GPS shield with UNO init error Apologies, but I have little experience of Arduino etc. Has the "Sim808 init error" been resolved anywhere please? I have tried every example I can find including the ones on these StackExchange pages without success. I started with the GPS test code from:
https://wiki.dfrobot.com/SIM808_GPS_GPRS_GSM_Shield_SKU__TEL0097
Parancey, Marcello, Pooya and Arslan and others have suggested mods to this code so I have tried all of them I think - none working.
Then I watched this video:
https://www.youtube.com/watch?v=fN8fwX3KmsM
which appears to show the code below or similar:
/*
### Get GPS data
1. This example is used to test SIM808 GPS/GPRS/GSM Shield's reading GPS data.
2. Open the SIM808_GetGPS example or copy these code to your project
3. Download and dial the function switch to Arduino
4. open serial helper
4. Place it outside, waiting for a few minutes and then it will send GPS data to serial

create on 2016/09/23, version: 1.0
by jason

*/
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

//#define PIN_TX    10
//#define PIN_RX    11
//SoftwareSerial mySerial(PIN_TX,PIN_RX);
//DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

DFRobot_SIM808 sim808(&Serial);

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

  //******** Initialize sim808 module *************
  //while(!sim808.init()) {
  while(!sim808.checkPowerUp()) {
      delay(1000);
      Serial.print("Sim808 init error\r\n");
  }

  //************* Turn on the GPS power************
  if( sim808.attachGPS())
      Serial.println("Open the GPS power success");
  else
      Serial.println("Open the GPS power failure");

}

void loop() {
   //************** Get GPS data *******************
   if (sim808.getGPS()) {
    Serial.print(sim808.GPSdata.year);
    Serial.print("/");
    Serial.print(sim808.GPSdata.month);
    Serial.print("/");
    Serial.print(sim808.GPSdata.day);
    Serial.print(" ");
    Serial.print(sim808.GPSdata.hour);
    Serial.print(":");
    Serial.print(sim808.GPSdata.minute);
    Serial.print(":");
    Serial.print(sim808.GPSdata.second);
    Serial.print(":");
    Serial.println(sim808.GPSdata.centisecond);

    Serial.print("latitude :");
    Serial.println(sim808.GPSdata.lat,6);

    sim808.latitudeConverToDMS();
    Serial.print("latitude :");
    Serial.print(sim808.latDMS.degrees);
    Serial.print("\^");
    Serial.print(sim808.latDMS.minutes);
    Serial.print("\'");
    Serial.print(sim808.latDMS.seconeds,6);
    Serial.println("\"");
    Serial.print("longitude :");
    Serial.println(sim808.GPSdata.lon,6);
    sim808.LongitudeConverToDMS();
    Serial.print("longitude :");
    Serial.print(sim808.longDMS.degrees);
    Serial.print("\^");
    Serial.print(sim808.longDMS.minutes);
    Serial.print("\'");
    Serial.print(sim808.longDMS.seconeds,6);
    Serial.println("\"");

    Serial.print("speed_kph :");
    Serial.println(sim808.GPSdata.speed_kph);
    Serial.print("heading :");
    Serial.println(sim808.GPSdata.heading);

    //************* Turn off the GPS power ************
    sim808.detachGPS();
  }

}

I have mounted the DFRobot shield on a UNO and powered through the barrel connector with a 2_amp 5V stabilised power supply. The DFRobot shield shows a red LED power light and pressing reset flashes the blue LED next to it, but nothing else does anything - the serial monitor just repeats "Sim808 init error". In the video the blue "net" LED flashes even before the SIM card is inserted, but my card does not flash. Do I return the board to Farnell and ask for my money back?
Any help greatly appreciated!

The dfrobot board has a weird boot button system that you need to follow to boot up the board. I spent ages attempting to get it to work before I finally achieved anything.
There is a blue led on the board that will flash continuously at different rates if the chip has been correctly powered and is searching for a mobile network.
I noticed that you commented it the while(!sim808.init()) line. This attempts to power the board on automatically, but I do remember something being funny about the implementation.
From doing a while load of research the dfrobot breakout board is not the best hardware implementation of this chip. Actually from memory there aren't any modules I have been able to find which satisfy all my requirements for a project. I'd recommend looking at all the documentation dfrobot provide on their website. Hopefully that should get you working.
Summary: it's an insanely fiddly process to get it working, but the boards are functional


Mic input and Speaker output using arduino I am trying to make a small project. Firstly, I want to record voice using a small microphone(electret) for the time button is pressed and on releasing the button, the speaker of my laptop should output the recorded voice or a speaker attached to the arduino should output.

Note: I don't want to use any shield to do so. Simply Arduino

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

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


how to make this work auto on off led with fading I'm working on a project with Arduino to make LED timer with fading feature. After doing some research finally I wrote some code but it's not working until now
P.S i don't have any knowledge in coding at all T_T

Edit: Adding more details about the issue;
when trying to check upload this error is always shown.

Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

\SunRisetimer.ino: In function 'void loop()':

SunRisetimer:55: error: 'startOff' was not declared in this scope

     startOff();
\SunRisetimer.ino: In function 'void startOn()':

SunRisetimer:89: error: variable or field 'startOff' declared void

 void startOff

SunRisetimer:91: error: expected '}' before ';' token

analogWrite(uled, 1);

SunRisetimer:116: error: expected '}' at end of input

 }
exit status 1
'startOff' was not declared in this scope

Code:

#include <DS3231.h> //Include the clock library

// Changable Vars
int fadeTimeOn = 30; // How long the light will fade to max
int fadeTimeOff = 30; // How long the light will fade to min
int setHourOn = 9; // Set hours to wake (military time)
int setMinOn = 15; // Set minute to wake
int setHourOff = 9; //set off h
int setMinOff = 30; //
int uled = 9; // Set pinout with with PWM

// Set up Vars
DS3231  rtc(SDA, SCL);
Time t;
void start();

void setup()
{
  pinMode(uled, OUTPUT);
  Serial.begin(9600); // Match to serial monitor
  rtc.begin();
}

void loop()
{
  t = rtc.getTime(); // Make a time class called 't'

  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  if (t.hour == setHourOn && t.min == setMinOn) // Check if it's time to wake up!
  {
    startOn();
  }

  // Wait one second before repeating
  delay (1000);

 if (t.hour == setHourOff && t.min == setMinOff) // Check if it's time to off!
  {
    startOff();
  }

  // Wait one second before repeating
  delay (1000);
}

void startOn()
{
  // Fix for SB LED
  analogWrite(uled, 1);
  delay((fadeTimeOn * 60000)/50);
  analogWrite(uled, 2);
  delay((fadeTimeOn * 60000)/50);
  analogWrite(uled, 3);
  delay((fadeTimeOn * 60000)/50);
  analogWrite(uled, 4);
  delay((fadeTimeOn * 60000)/50);
  analogWrite(uled, 4);
  delay((fadeTimeOn * 60000)/50);
  analogWrite(uled, 5);
  delay((fadeTimeOn * 60000)/50);

for (int i = 6 ; i <= 255; i++)
    {
    analogWrite(uled, i);
    delay(((fadeTimeOn * 60000)/306));
    Serial.print(" mil sec ");
    Serial.print(((fadeTimeOn * 60000)/306));
    Serial.print(" PWM " );
    Serial.print(i);
    {
}

void startOff
{
  analogWrite(uled, 1);
  delay((fadeTimeOff * 60000)/50);
  analogWrite(uled, 5);
  delay((fadeTimeOff * 60000)/50);
  analogWrite(uled, 4);
  delay((fadeTimeOff * 60000)/50);
  analogWrite(uled, 3);
  delay((fadeTimeOff * 60000)/50);
  analogWrite(uled, 2);
  delay((fadeTimeOff * 60000)/50);
  analogWrite(uled, 1);
  delay((fadeTimeOff * 60000)/50);

  // Fade script
  for (int i = 6 ; i <= 255; i++)
  {
    analogWrite(uled, i);
    delay(((fadeTimeOff * 60000)/306));
    Serial.print(" mil sec ");
    Serial.print(((fadeTimeOff * 60000)/306));
    Serial.print(" PWM " );
    Serial.print(i);

  }

}

Look at your function definitions:

void startOn() // works
void startOff    // doesn't work

You are missing the () after startOff.


Arduino - Button to start / stop loop So basically I'm trying to create a device where when I push a button it starts a loop. When I push this button again, it stops the loop. Right now I have it logged to serial. It starts up correctly with no output. When I press the button the loop begins and it spits out "toggled on" continuously. When I press the button again... nothing happens. What should happen ideally is that it should stop spitting out "toggled on" and just go back to doing nothing.

#include <Bounce2.h>

Bounce bouncer = Bounce();
const int W = 10;
bool wOn = false;

void setup() {
  Serial.begin(9600);
  pinMode(W, INPUT_PULLUP);
  bouncer.attach(W);
  bouncer.interval(5);
}

void loop() {
  bouncer.update();
  if (bouncer.read() == LOW) {
    wOn = !wOn;
  }

  if (wOn > 0) {
    Serial.println("toggled on");
  }
}

If you change your sketch to this one, you'll see the issue:

const int W = 10;
bool wOn = false;

void setup() {
  Serial.begin(9600);
  pinMode(W, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(W) == LOW) {
    wOn = !wOn;
  }

  if (wOn) {
    //Serial.println("toggled on");
  }
  Serial.println(wOn);
}

The button's contacts "bounce" (Google "contact bounce"), sending multiple low to high signals. There are several software solutions that will eliminate this issue. Have a look at: arduino.cc/en/Tutorial/Debounce. There are a couple of libraries that simplify de-bouncing buttons: playground.arduino.cc/Code/Debounce and playground.arduino.cc/Code/Bounce


7segment blink when the button is pressed I have programmed an IR remote control along with an LED and an 8bit 7segment on an Arduino Uno.
the segment displays the number I press via the remote, and the LED turns on and off
here's my code:

case 16738455:
  Serial.println(0);
  if (oldvalue == results.value){
    on(num0);
    delay(1000);
    on(num00);
    delay(1000);
    oldvalue = results.value;
  }

oldvalue stores the last value pressed, which is the DEC value of the buttons, num0 displays the number zero, and num00 turns all the segments off.
I want the 7segment to blink again when I press the same button again.
Can anyone help me with this?
Thanks

A simple solution would be to not worry about blinking as a piece of code, ie. remove those delays (I hate blocking code) and instead, if you are currently receiving a signal from the remote, do not display any number (or display your num00). Once the value is received and processed, then display that number.

This way, whilst ever the remote button is down, the display will blank out, and the number will appear as soon as the number is released. If it's the same number, then you will see the number, see a blank display, and then see the same number again. Obviously, if it's a different number, the new number would be displayed.

Since most people would only press the remote button for 100-1500ms, it should give you a nice delay anyway.

Finally, you may encounter some flashing if you process the data so quickly and the remote auto repeats. This could be handy if that number is processed multiple times by the receiving unit. The flashing would indicate that that is the case. If that is undesired, implement a simple state machine.

edit: your pastebin code came up whilst I was writing this answer. Having a quick look at your code, I would suggest that in the section:

if (irrecv.decode(&results)) {
  //receiving data? display nothing
  on(num00);
  digitalWrite(ledPin, HIGH);
  Serial.println(results.value, DEC);
  irrecv.resume();
  delay(100);
  int oldvalue = results.value;
  switch(results.value){
    case 16738455:
      Serial.println(0);
      num2display=0;      // make sure to declare this var somewhere
      //if (oldvalue == results.value){
      //  on(num0);
      //  delay(1000);
      //  on(num00);
      //  delay(1000);
      //} else {   // I think you missed an else here
      //  oldvalue = results.value;
      //}
      //on(num0);
      //delay(1000); // you don't want such large blocking delays
      irrecv.resume();
      break;
    case 16724175:
      Serial.println(1);
      num2display=1;       // add this for each section
      irrecv.resume();
      break;
      . . .
  }
}
else{
  digitalWrite(ledPin, LOW);
  on(num2display);
}

you only set the variable to be displayed, but display num00. Then in the else, you can display that number


Store data in flash/EEPROM and process it in parallel I want to store incoming data in flash or EEPROM and then apply FFT or some other method to detect frequency and intensity.

I am taking sound through microphone amplifying it with an LM741 and giving this amplified signal as input to an Arduino and then processing it at the same time.

But the problem is that the time taken in running the code is interfering with the sampling rate. I want to store say 50 inputs in flash and then process these 50 numbers, while at the same time the next set of 50 numbers is being stored, so that I can have data stored at a constant sampling rate.

Also how can I store data continuously? Because if I do this in loop() won't it again have time lag due to rest of the code?

I am new to Arduino, so please give details or some link to help me understand.

Thanks.

A common method of overlapping data input with data processing uses double (or multiple) buffering.  For example, one of two buffers is processed in the foreground (that is, in the loop() routine) while another buffer is filled in background (via interrupt handlers).  Each time a buffer fills, the usage of the two buffers swaps: that which was being processed now refills, while the recently-filled buffer gets processed.  To make this work, buffer processing must take less time than buffer filling.

For recording conversion times, because free-running ADC conversions each take the same amount of time, you can just save fill-start and fill-end times with each buffer, and interpolate to find out reading times.

If you plan to process audio data at near-normal speeds, it's likely most Arduinos won't be fast enough to keep up.  However, using an Arduino Due probably is feasible.  The Due is based on an ARM Cortex M3 processor with 72 MHz operating frequency, 32-bit arithmetic, large RAM (for an Arduino), etc.

An alternative method of processing audio data is to use a frequency analysis chip.   Here is a low-end example:  The MSGEQ7 Graphic Equalizer Display Filter is about $5 in an 8-pin DIP package from sparkfun.com.  Apparently, it continuously measures peak spectral intensity in each of seven frequency bands, and can read the peaks out perhaps a thousand times per second.  Audio goes in on the "Audio in" pin.  A Reset pin resets an output-multiplexor counter to zero.  Each time after you clock a strobe line, a band's reading is presented as an analog voltage on a "DC out" output line; the band's peak reading is decayed about 10%; and the multiplexor advances one band upward in frequency, rolling over from highest to lowest every seven strobes.


Do we need another controller when using ArduPilot? I'm a newbie on the all Arduino platform and I'm currently building a drone with Autopilot functionality. I've heard about ArduPilot and I'm wondering if that is all I need, in terms of controllers (I'm excluding the ESC, engines, and the rest). Can I simply program the ArduPilot, connect a Wireless interface to it and merrily be able to control it ?

Cheers,
r

There are a few key points worth making before answering your question:

Ardupilot has undergone a re-branding and is now known as APM; this change was made to reflect that the technology has grown beyond strictly using an Arduino environment. You can see this for yourself at their website.
The term(s) Ardupilot/APM have been used somewhat interchangeably for both the hardware and software. This can be confusing so I'll refer to the hardware as an "APM Kit"

Can I simply program the ArduPilot, connect a Wireless interface to it and merrily be able to control it ?

Yes, 3DRobotics offers APM Kits that are plug-and-play hardware packages with preloaded firmware. They (optionally) supply all of the components needed to operate a small unmanned hobby aircraft including:

Power module
Transmitter and receiver for the APM-to-Ground-Station link
GPS module w/ compass

The user is generally expected to provide:

Airframe
Batteries
Servos
RC transmitter and receiver
An additional voltage-regulator/BEC if using high-torque servos
A computer (groundstation)

However, the unspoken question is:

How easy is it to setup Ardupilot/APM to work safely and correctly?

In truth, it takes considerable effort to put together a properly working system. The plug-and-play hardware saves you a great deal of trouble but tuning and operating an RC aircraft requires a different skillset. If you're experienced in RC, this may not be a problem.

From experience, you can expect to spend a number of weekends configuring and tuning APM (the software) even if you have a perfectly tuned RC aircraft.


Serial Communication Between Two arduinos (Asking and Receiving) Can anyone help? I'm trying to develop two sketches, where data can only be sent when a request is made for it between two arduinos. A simple hello world message can suffice. I tried out the Serial Ascii Call and Response on the arduino IDE but it didn't work for me???. Do find below the code sketches

//Arduino Sketch 1
uint16_t alpha;
uint16_t lambo;
Banana nanas;    //to hold the Banana object
uint16_t dataArray[2];
void Setup(){
    Serial.begin(9600);
    establishContact();
}

void loop(){
    alpha=nanas.getRad;
    lambo = nanas.getBars;
    dataArray[0] = alpha;
    dataArray[1] = lambo;
    Serial.write((uint8_t*)dataArray, sizeof(dataArray));
    Serial.flush();   //clear the serial port
}

void establishContact()
{
    if (Serial.available())
    {
        while (Serial.available()  > 0)
        {
            int newByte = Serial.read();
            if (newByte == 'Q')
            {
                Serial.write(newByte);
                Serial.flush();
            }
        }
    }
}

The sketch for the other arduino is shown below

//Arduino sketch 2
static char buffer[2];
void setup(){
    Serial.begin(9600);
    Serial1.begin(9600);
    establishContact();
}
void loop(){
    if(Serial1.available())
    {
        while(Serial1.available() > 0){
            uint16_t gondola1 = Serial1.read();
            uint16_t gondola2 = Serial1.read();
            uint16_t crixus = gondola2 >> 8;
            crixus = (crixus | gondola1);

            gondola1 = Serial1.read();
            gondola2 = Serial1.read();
            uint16_t mario = gondola2 >> 8;
            mario = (mario | gondola1);
            buffer[0] = crixus;
            buffer[1] = mario;
            Serial.write(buffer, sizeof(buffer);
            Serial1.flush();
        }
    }
}
void establishContact(){
    if (Serial.available()){
        uint16_t newByte = Serial.read();
        if(newByte == 'Q')
        {
            Serial.flush();
            Serial.write(newByte);
        }
    }
}

it is not really easy to follow your code but here is a "hello world" procedure to do an on demand data send between two arduinos:

upload this code to arduino uno before you make any connection on pins 0 and 1 of the board:

/**
 * Code for server side (arduino uno)
 */

uint8_t data2send = 'A'; //data to send on a received request
uint8_t incomingByte;

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

void loop() {
        // send data only when you receive data:
        if (Serial.available() > 0) {

                // read the incoming byte:
                incomingByte = Serial.read();

                if(incomingByte=='Q'){  //if incoming data is the expected request (request code = 'Q' in this example)
                        Serial.write(data2send);
                }
        }
}

connect:

UNO  | MEGA
------------
pin0 | pin18
pin1 | pin19
GND  | GND

upload to arduino mega this code:

 /**
 *  code for arduino mega.
 *
 *  proxy between Serial0 and Serial1
 *
 *  send data to Serial0 to forward it to Serial1.
 *  when data is received from Serial1 it will be forwarded to Serial0.
 */

void setup() {
        // initialize both serial ports:
        Serial.begin(9600);
        Serial1.begin(9600);
}

void loop() {
        // read from port 1, send to port 0:
        if (Serial1.available()) {
                int inByte = Serial1.read();
                Serial.write(inByte);
        }

        // read from port 0, send to port 1:
        if (Serial.available()) {
                int inByte = Serial.read();
                Serial1.write(inByte);
        }
}

open the mega's serial monitor and send some characters. Check that you receive back data only when you send a 'Q' character.


Change character sequence I turn on the transmission of one key that works to open the door, but after a certain time I need to close the door, and for this I need to use the second key. I want to do without additional buttons, so it is required to emit key 1 when power is applied, and after 20 seconds, for example, switch and emit key 2. What is the most simple and correct way to do this?
Apply a timer or emit key 1, for example 1000 times, and after overflow 1000, start emitting key 2.
This sketch only constantly sends the first key to the digital pin, without switching to the second.
You need to figure out how you can switch to the second key.
const int KEY_LEN = 54; //Number of characters in the key
const char key1[KEY_LEN] = {"SSSSSS001101001001110001000000000000000000000011001010"}; // Open
const char key2[KEY_LEN] = {"SSSSSS001010111010000000000001000000000000010000000000"}; // Close

int Preamble = 1000; // Preamble duration in microseconds
int zero= 200; // Duration of zero in microseconds
int One= 440; // Duration of a unit in microseconds

const int LED_PIN = 13; // Used digital pin 13 of the arduino to connect the transmitter
void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{

    for (int n = 0; n < KEY_LEN; n++)
    {
      if (key1[n] == '1') //execute if bit value == 1
      {
        sendSignal(One);
      }

      else if (key1[n] == '0')//execute if bit value == 0
      {
        sendSignal(zero);
      }
      else
      {
        sendSignal(Preamble); // Стартовый импульс
      }

    }
  }

void sendSignal(int duration)
{
  digitalWrite(LED_PIN, HIGH);
  delayMicroseconds(duration);
  digitalWrite(LED_PIN, LOW);
  delayMicroseconds(duration);
}

I usually recommend against using delay()s, but if this system will only ever have to do what you've described, using delay()s is the simplest way to implement it.
I would suggest sending key-1, possibly several times, maybe a half second apart, delay for the 20 seconds you suggested, then send key-2, definitely several times for security.


Weight Measurement System using arduino and load cell I want to use a load cell (Capable of measuring up to 1 ton) connected to a arduino board.
I am a beginner, my questions are as follows :
1. How to calculate the current generated by the load cell ?
2. If current is too high, how will We make the arduino use the current to display weight ?

p.s If you know some helpful articles that might help me learn, please suggest.

You need to use a load cell amplifier between the Arduino and the load cell. Load cells are around 350 Ohms. Four wire. And the signal that needs to be measured are very small.

The current will not be too high. The question indicates that you don't understand the application. (and therefore you are looking for help)

Here are some useful links.

https://www.hackster.io/MOHAN_CHANDALURU/hx711-load-cell-amplifier-interface-with-arduino-fa47f3

https://circuits4you.com/2016/11/25/hx711-arduino-load-cell/

A typical load cell has an output of 2 millivolts per volt of excitation voltage at the full rated weight. For example, if 5 volts were used for the excitation voltage, and the output is 2 mV/volt, then the voltage out would be 10mV at full scale. The voltage difference (compared to the unloaded load cell) is what is measure.

If the excitation voltage (just a technical name for applied voltage) were 5 volts, the voltage at the output terminals, measured from the negative terminal, would be 2.5 volts, half of the applied voltage. But this 2.5 volts is not the measured output. What is measured is the difference between the +signal and the -signal wires.


RF receiver for integer only, how to cast uint8_t to int? I'm using the RadioHead library with ASK Driver to transmit/receive data with generic RF modules. It works fine, but I'm lacking some knowledge in programming the code to use the data received. Most examples I could find show how to send a string, but I only need to send and receive an integer.

I'm sending the decimal value '1' through the transmitter:

    uint8_t *data;
    uint8_t value;

    void loop() {
    value = 1;
    data = &value;
    driver.send(data, sizeof(value));
    driver.waitPacketSent();
    delay(200);
    }

And I have in the receiver:

void loop() {
  uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
  uint8_t buflen = sizeof(buf);
  int value;

  if (driver.recv(buf, &buflen)) {
    driver.printBuffer("Received:", buf, buflen); //prints 1.
    value = (int) buf; //my attempt to cast
    Serial.println(value); // the output is 2233, so this is wrong.
  }
  if (value == 1){ //example
  Serial.println("good");
  }
}

So what I think it is, I'm receiving bytes from the transmitter, which the library function 'driver.printBuffer' reinterprets as decimals and prints the value '1'. But how do I interpret (or cast) this as an integer so I can use it for other things like in the example (If condition) at the end? Any help is very much appreciated. Thanks.

buf is a pointer to the received bytes. Try value = buf[0]; instead.


ping pong with two Arduinos over serial I have two Arduino boards and want to make them communicate with each other over serial. The code I have used for the two boards is almost identical.

Every one second the "A" board sends a "ping" message over serial.
The "B" board receives the "ping" message and responds with a "pong" one.
The "A" board receives the "pong" message and prints it on screen.

Board A - ping code
String inputString = "";
boolean stringComplete = false;

void setup() {
  Serial.begin(9600);
  inputString.reserve(200);
}

void loop() {

  Serial.print("ping");

  if (stringComplete) {
    Serial.println(inputString);
    inputString = "";
    stringComplete = false;
  }
  delay(1000);
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == 'g') {
      stringComplete = true;
    }
  }
}

Board B - pong code
String inputString = "";
boolean stringComplete = false;

void setup() {
  Serial.begin(9600);
  inputString.reserve(200);
}

void loop() {

  if (stringComplete) {
    Serial.println("pong");
    inputString = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == 'g') {
      stringComplete = true;
  }
 }
}

The code seems to work, but not exactly as expected. I initiate the serial monitor of the board "A" and expect to see every one second:

pingpong

Instead I see this:

pingpong
pong
pong
....

which means that the pong message is repeated more than one time per second. But I want the "B" board to transmit the "pong" message only when it receives the "ping" one.
Why is this happening? Is there an error in the code? Is there a detail about the serial protocol which escapes me?
Any thoughts would be appreciated.

The problem is with your protocol and also with how you are using the serial.

You are using the same serial channel both for your communication protocol and for the reporting of the results.  What you see the B end sees.

So A sends ping, and when it sees the letter g it responds with pong.  You then print that pong to the serial, so end B sees pong. It gets the character g and thinks "That was a ping, I'll respond with a pong", so it does - it sends pong, which you then receive and duly print - starting the sequence over yet again.

You either need to separate out the communication and the reporting, or make your protocol look for the whole string "ping" so it never inadvertently responds to a "pong" when it shouldn't.

Here's a good resource about reading serial strings on the Arduino: http://hacking.majenko.co.uk/reading-serial-on-the-arduino


Modbus TCP together with MQTT over same ethernet I'm currently in a planning phase for a project.
I want to read some sensor data over Modbus TCP, do some simple calculations on the Arduino and publish the results over MQTT. Which means I have 2 RJ-45s and two different protocols.
Given a Arduino Mega with an Ethernet shield.
Does it work if I simply add a network switch and connect the sensor and an internet router to it, and use both protocols in parallel?
Or are there any problems running such a thing on only one Arduino?

Does it work if I simply add a network switch and connect the sensor and an internet router to it, and use both protocols in parallel?

Kind of, yes. You just connect both the MODBUS device and the Arduino to the network provided by the router. The Arduino is just a normal network device - the IP address for it allocated by the router, as is the MODBUS device.
Any device can communicate with any other device in a network.


How to / is it possible to change Vendor Name in ESP8266-12E? I am aware of that it is possible to change hostname for ESP8266 but I want to change vendor name also so that it lists my company/product name in routers/firewalls.

Is it possible?

No. The Vendor Name is associated with the OUI.  The OUI is the first three parts of the MAC address.

The OUI's are all registered with IEEE here and Espressif's entries are:

18-FE-34   (hex)        Espressif Inc.
24-0A-C4   (hex)        Espressif Inc.
24-B2-DE   (hex)        Espressif Inc.
2C-3A-E8   (hex)        Espressif Inc.
30-AE-A4   (hex)        Espressif Inc.
3C-71-BF   (hex)        Espressif Inc.
54-5A-A6   (hex)        Espressif Inc.
5C-CF-7F   (hex)        Espressif Inc.
60-01-94   (hex)        Espressif Inc.
68-C6-3A   (hex)        Espressif Inc.
80-7D-3A   (hex)        Espressif Inc.
84-0D-8E   (hex)        Espressif Inc.
84-F3-EB   (hex)        Espressif Inc.
90-97-D5   (hex)        Espressif Inc.
A0-20-A6   (hex)        Espressif Inc.
A4-7B-9D   (hex)        Espressif Inc.
AC-D0-74   (hex)        Espressif Inc.
B4-E6-2D   (hex)        Espressif Inc.
BC-DD-C2   (hex)        Espressif Inc.
C4-4F-33   (hex)        Espressif Inc.
CC-50-E3   (hex)        Espressif Inc.
D8-A0-1D   (hex)        Espressif Inc.
DC-4F-22   (hex)        Espressif Inc.
EC-FA-BC   (hex)        Espressif Inc.

The ESP8266 does not advertise the vendor. The router / other device maintains a list of OUI to Name mappings (on Linux it's stored in /usr/share/ieee-data) and uses them to create a pretty display.

You would need to

Change the ESP8266's MAC address somehow
Subscribe to IEEE and pay the relevant fees
Be allocated an OUI
Hope that every device in the world that would ever talk to your hardware updates its OUI mappings (which they seldom do).


HC-12 modules stopped receiving, cannot understand why I've created a simple transmitter with an HC-12 and an Arduino Nano (clone), where I send the values of DHT11 and LM35 sensors to a receiver unit made only of a Wemos D1 and another HC-12.

Setup is really simple and worked fine for a couple of days (transmitter in the cellar 2 floors down, receiver in my living room, it was POSTing data to my own server correctly), then I unplugged the receiver and modified the transmitter to add a JSON library; when I plugged them back again the receiver is not getting anything anymore.
Transmitter seems to be working fine, at least it prints the number of bytes written in the Serial Monitor.

I tried:

reverting back to the working version (no JSON), but still the same
tested each of the HC12 modules with a simple test code and AT commands, they all responds and are all set to factory configuration, like it was before actually (AT+DEFAULT)
made another receiver with an Arduino Uno and a lcd screen - a setup that I was successfully using before changing to the Wemos. Strangely, now this setup doesn't work too...
Switched the modules and what I got? The transmitter still transmits, the receiver doesn't receive, nothing changed.

Tried sending a simple string "Test", still no results.

Relevant code:

Transmitter:

#include <ArduinoJson.h>
#include <DHT_U.h>            // just Adafruit Library
#include <DHT.h>
#include <SoftwareSerial.h>
#define DHTTYPE DHT11   // DHT 11
SoftwareSerial HC12(10, 11); // HC-12 TX Pin, HC-12 RX Pin
int DHTPIN = 4;
int LMPIN = 5;
DHT dht(DHTPIN, DHTTYPE);
StaticJsonDocument<80> doc;

void setup() {
  analogReference(INTERNAL);
  Serial.begin(9600);             // Serial port to computer
  HC12.begin(9600);               // Serial port to HC12
  dht.begin();
}

void loop() {
  delay(5000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  int reading = analogRead(LMPIN);
  float lmt = reading/9.31;
  doc["dht_h"] = h;
  doc["dht_t"] = t;
  doc["ds_t"] = lmt;
  char result[50];
  serializeJson(doc, result);
  Serial.println(result);
  int written = HC12.print(result);
  Serial.println(written);    // it's 39 chars
}

Receiver (all wifi sections are removed):

#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#define STASSID "....."
#define STAPSK  "....."
SoftwareSerial HC12(D13, D15); // HC-12 TX Pin, HC-12 RX Pin

const char* ssid     = STASSID;
const char* password = STAPSK;
const char* host = "...........";
const uint16_t port = 3000;

void setup() {
  Serial.begin(9600);
  HC12.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500); Serial.print(".");
  }
}

void loop() {

  String content = HC12.readString();
  Serial.println(content);
  if(content.length()) {
    // This will send a string to the server
    Serial.println("sending data to server");
    if (client.connected()) {
      //....
    }
  }
  delay(1000);
}

I'm pretty stumped by the fact that it stopped working, and that both the HC-12 modules seem to be working fine (at least they respond to all the AT commands).
I even tried purging arduino from the system and reinstalling (I now have the very latest IDE release) but nothing....

Am I missing something obvious? (I've a weak electronic background, I'm a web developer by trade).
Is there a way to check if data is actually sent?
How can I debug these modules?

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

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

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

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


Level tracking using optical or capacitance sensors I am looking to devise a level tracking system using arduino and some sensors. My particular situation is I have solute that is coming out of solution and I want to track the formation rate of the solid phase as the salts settle at the bottom and build a bed of particulates.

I am looking for precision at about 0.5mm and over a range of like 6 inches. My initial idea was to get a sensor bar that could detect when and where light is hitting the sensor and post processes that signal. I have to design this device to sit outside the cylindrical vessel. The solvent is transparent so any form of light would work. I am stuck on finding the parts that could pull this off and I was hoping the more experienced community could point in the right direction.

* UPDATE *

a little cartoon for a clearer picture of the idea
I am leaning towards capacitance since using light seems like a rabbit hole. I was playing with some foil and it may work but I need a much more sensitive tool on the order of pico-Farads to work.

What about measuring this with two resistive probes - the electricity will go through down one probe to the top of the water, across the water, and up the other probe. You can measure how much of the probe it went down, by measuring the resistance. You would need the probes to be a specific, very consistent distance apart, and be made of resistance wire.

Another option is to use a float of some kind, and measure it this way. This is a lot easier if all you need to know is full/not full.


Arduino raise the error "variable-sized object 'my2dArray' may not be initialized" while trying to change the elements of 2d array I' m trying to change 1 to 0 in two-dimensional (5x5 matrix) for specific servo positions.First, i tried to program forward movement of my robot.  My code is like this:

#include <Servo.h>
#define x 5
#define y 5

Servo myServo;
Servo myServo2;

int pos = 0;

int counter1;
int counter2;
int integer;

void setup() {
  Serial.begin(9600);
  myServo.attach(9);
  myServo2.attach(10);
}

void loop() {

  int my2dArray[x][y]= {
  {1,1,1,1,1},
  {1,1,1,1,1},
  {1,1,0,1,1},
  {1,1,1,1,1},
  {1,1,1,1,1},
  };

  int robot = my2dArray[2][2];

   if (counter1 > 0){
     for (integer = 0;  integer <2; integer +=1){
      int my2dArray[2 + integer][2] = robot * my2dArray[2 + integer][2];

     }
 }
}

  int moveForward(){
  for (pos = 0; pos <= 360; pos += 1) {
    myServo.write(pos);
    myServo2.write(pos);
    delay(15);
    if (pos == 360){
    counter1 += 1;
    }
    return counter1;
}
}

int moveBackward(){
  for (pos = 360; pos <=0; pos -= 1) {
    myServo.write(pos);
    myServo2.write(pos);
    delay(15);
    if (pos == 360){
    counter2 += 1;
    }
    return counter2;
}
}

But i can' t change the [3][2] and [4][2] elements from 1 to 0. I get an error:

 error: variable-sized object 'my2dArray' may not be initialized

Can you help me?
Thanks.

The error is in this line:

  int my2dArray[2 + integer][2] = robot * my2dArray[2 + integer][2];

The presence of the word int there tells it to try and make a new variable. You don't want to do that, since it's an error.  Lose the int and it might work.


MAX6675 gives a climbing reading I am using a MAX6675 board and a k-type thermal couple to measure temp. The problem is even when running the example the temp value keeps climbing.

MAX6675 test
27.25
C = 27.25
F = 130.10
109.00
C = 218.00
F = 816.80
872.00
C = 1744.00
F = 2624.00
832.00
C = nan
F = nan
512.75
C = nan
F = nan

I am using the max6675.h library. Is there a way to fix this?

#include "max6675.h"

int thermoDO = 4;
int thermoCS = 5;
int thermoCLK = 6;

MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);
int vccPin = 3;
int gndPin = 2;

void setup() {
  Serial.begin(9600);
  // use Arduino pins
  pinMode(vccPin, OUTPUT); digitalWrite(vccPin, HIGH);
  pinMode(gndPin, OUTPUT); digitalWrite(gndPin, LOW);

  Serial.println("MAX6675 test");
  // wait for MAX chip to stabilize
  delay(500);
}

void loop() {
  // basic readout test, just print the current temp

   Serial.print("C = ");
   Serial.println(thermocouple.readCelsius());
   Serial.print("F = ");
   Serial.println(thermocouple.readFahrenheit());

   delay(1000);
}

edit: Added code (https://github.com/adafruit/MAX6675-library/blob/master/examples/serialthermocouple/serialthermocouple.pde)

After test some other K-type thermal couples on this I am now thinking I just got a bad board. I was able to order a new one and it worked without issue


What Version of the Sketch did I leave on there? Is there a way to "ask" the Arduino what sketch was compiled on it?

There are several versions of the sketch and I need to see which version the Arduino has been running.

First, you have to store the desired information in your sketch.

#define VERSION F("0.01 4-Apr-2019")

void setup() {
   Serial.begin(9600);
   Serial.print(F("Test Sketch V"));
   Serial.println(VERSION);
}

void loop() {
}

Of course any other way might work as well:

Only print it, if at reset a test button is pressed
Check for a Serial command and respond the version info.
Don't print it, but use avrdude and a programmer to read the FLASH memory and search it for the version string. (Similar to jot's comment above)


Due : DMAC BTSIZE trimmed modulo 8192? On Arduino Due, I set-up DMA transfers using direct control of memory mapped hardware registers.

There is a 16-bit BTSIZE field in CTRLA which indicates the number of (width sized) transfers.  If I specify larger than 8191, the value of btcount is trimmed to 13 bits after the DMA channel is enabled.  I set chunk size src/dest to 1.

The ATMEL data sheet for the sam3x (linked from the due page) does not mention this 'limitation' (section 22.7.16), or possibly I'm using it wrong.

What reference is canonical and correct for the DMAC (dma controller)?

As noted in the links in the comments, multi-buffer transfer can work around this, but since I don't know why it works or fails, it's hard to decide if that solution will work in all cases.

I'll quote the answer given in this link to help make this question more useful for future people who search this problem.

The dmac.h file in asf library has a macro named DMA_MAX_LENGTH set to 0xFFF = 4095. We tried changing it to higher values but still Buffer Transfer size (BTSIZE) register was showing only values till 4095. This seemed to us to a hardware limitation of the DMAC in Atmel SAM3x8E (which we did'nt see mentioned in the datasheet). So this closed the option of single buffer transfer for us and we moved to multi-buffer transfer
It was a simple way out (even though I took some time to figure it out :P ) - Use multi-buffer transfer with contiguous source address! (see table 22.4 Row 3)


How can I test/demonstrate what the serial input and output buffers are? Serial is causing me a lot of pain, and I think there are certain basic principles that I simple have not understood. I hope that by understanding how to test/demonstrate the buffer size, I will come one big step closer to understanding how serial works.

I suspect it is only possible to demonstrate this by writing a piece of software for "the other end"; the pc. I do understand Python, and to some extent how to work with serial on Python, so if possible, please write the pc code in Python.

If you supply an example (piece of code), please explain how the example works.

You can think of the incoming serial buffer as a bucket of water under a dripping tap. Next to the bucket is a cup.

Water arrives through the tap and drips into the bucket. When you want to get some water, if there is enough water in the bucket, you dip the cup in and remove a cupful of water. If there isn't enough water you don't get anything in your cup.

If you don't dip the cup in for a while too much water will dribble into the bucket and it will overflow all over the floor.

It's exactly the same with serial data. It arrives through the UART hardware and is placed into the "bucket" by the UART receive interrupt. If you don't dip your cup in fast enough (Serial.read()) the bucket will overflow and any new data that arrives will spill onto the metaphorical floor.

To test this out you can just send more data to the Arduino than will fit into the serial buffer (typically 64 bytes) without reading any. Then after you have finished flooding the buffer you can read what is actually in the buffer and send it back again (maybe formatted nicely) so you can see what has actually ended up in the buffer and what hasn't.

One quick and dirty test would be to send the raw bytes 0 to 255 to the Arduino, then after a delay read them back and display the DEC values for them (Serial.print(Serial.read(), DEC))) to see exactly which bytes arrived and which didn't (hint: you should see the numbers 0 to 63 if the buffer is 64 bytes big).

For the transmit buffer it's slightly different.  You can think of it more as a bucket with a small hole in the bottom.

You pour data (water) in the top at whatever speed you want, and it trickles out of the bottom at a pre-set rate (the baud rate - the size of the hole). You don't like wet messes though, so if the bucket is full you wait a while before putting more water into it. Just like with serial - if the transmit buffer is full any attempts to add to it will block until data has been sent out by the UART transmit interrupt.


Read information from Twitch's API and execute actions depending on the output i'm trying to create a display that notifies me when someone goes live on twitch. I need to acess the API and check if the 'stream' object is null or not. Then, perform an action depending on this.

The address to the API is http://api.twitch.tv/kraken/streams/pedrinholuizf

What can I do? I'm using an Arduino Leonardo with the Ethernet Shield.

Break your problem into small steps and try to identify the success criteria for each step. So you might:

Try to set up the Ethernet shield and get it to respond to a ping on your local network.
Try to connect to a site outside of your network.
See if you can find some examples of using the Twitch API.
Try to replicate one of the simple examples.
See if you can get the Stream object that you want.
See if you can read the value of the object.

If you have a plan and try to follow it you'll be able to tell us what you've been doing and where you got stuck / confused. That is likely to get you better answers – both because we can be more specific and also because we can see that you're "carrying your weight" as we work on the problem.


Sending binary data to HTTP server I am new to low level programming.I am trying to send binary data to the http server.At the moment i just fill up the byte array with numbers and send them to the server(eventually i want to send image file). I can see the request in the server log as
2016-05-18T23:30:26.688040+00:00 heroku[router]: at=info method=POST path="/api/users" host=myapp.herokuapp.com request_id=ed2b7852-7021-4642-a663-f9709e1aea70 fwd="99.89.114.63" dyno=web.1 connect=0ms service=2ms status=404 bytes=221

Questions

1.My question is as you can see in the log, what is bytes=221 i thought if i sent byte array of length 32 i should see 32 bytes(or around 40s).And i made the buffer of length 1024 byte array, still in the server log is bytes=221.Are my bytes are even being sent?

2.How would i handle the bytes received on the server side just to be sure client.write actually succeeded?(Just in high level...doesn't matter you can guide me in any language,Java,ruby,C,NodeJS)

Here is my code.Thank you in advance.

#include <ESP8266WiFi.h>
#define SSID "ssid"
#define PASS_SSID "password"
#define HOST "myapp.herokuapp.com"
WiFiClient client;

byte buffer[32];
int bufOffset = 0;
byte startByte = 0;
byte nextByte = 0;

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

void loop() {

  if (client.connect(HOST,80)) {
           Serial.begin(115200);
           Serial.println("conected to the server");
           String start_request = "";
           String end_request = "";
           start_request = start_request  + "--AaB03x" + "\n"
                                   + "Content-Disposition: form-data; name=\"picture\"; filename=\"cam.jpg\"" + "\n"
                                   + "Content-Type: image/jpeg" + "\n" + "Content-Transfer-Encoding: binary";
          end_request = end_request + "\n" + "--AaB03x--" + "\n";
          client.println("POST /api/users HTTP/1.1");
          client.println("Accept: */*");
          client.print("Content-Type: multipart/form-data; boundary=AaB03x");
          client.println(start_request);

         //Fill the buffer with values
            nextByte = startByte++;
            for(int ii = 0; ii < sizeof(buffer); ii++) {
            buffer[ii] = nextByte++;
        }

          //write it to the server
        int count = client.write(&buffer[bufOffset], sizeof(buffer));

       //end the request
       client.println(end_request);
        client.stop();
       }
      }

You should forget about MIME, that is only needed if you are sending multiple files to the server. Your best bet is to just send these headers, then a blank line, then your data:

POST /api/users HTTP/1.1
Accept: */*
Content-Type: application/octet-stream
Content-Length: 123

On the other end, you just look at "request.body" and it should have your binary data. (Replace 123 with sizeof(buffer))