How to send multiple data from PC to arduino I have a project in arduino that i interface with java. The arduino is connected to the computer via usb cable , I use the serial communication.
 I have two variables:

//Code in arduino
int ADelay = 1000;
int BDelay = 1000;

I want to change the value of each variable based on the input of the user using the java interface.
Is there a code that let the arduino identify that this data:

2000

Is intended to or for:

int ADelay

and this

300

is for

int BDelay

My only idea on how to achieve this is to add A or B before the number before i send to arduino

A2000
B300

And use Delimeter in arduino to split the data and use if else condition to decide where the data belong , Is there any other way ? Thanks

The approach noted in the question – having an identifying character at the front of each number – is a workable approach.  Other approaches include:
•  always sending numbers in pairs, eg 2000,300 would denote A2000 B300.
•  encoding the A or B as part of the number; eg, the range 0-4999 could denote A delays of 0 to 4999, while the range 5000-9999 could denote B delays of 0 to 4999.
•  sending A delays via decimal digits, and B delays via letter-substitutes for digits; eg DAA could encode a B delay of 300.

One of the easiest-to-parse approaches is to have an identifying character at the end of each number, rather than at the front.  This allows your code to pick up digits until a letter appears, and then dispatch based on the letter.  Here's some example code:

// Sketch that accepts numbers and action code via serial input.
// Silently ignores any numbers not followed by a valid action letter.
// Does not test for number overflow.      - jiw 3 Nov 2016

void setup() {
  Serial.begin(115200);         // init serial port
}

unsigned int val=0;
void loop() {
  char inc;
  while (Serial.available()) { // Get characters
    inc = Serial.read();
    if (inc >= '0' && inc <= '9') {
      val = 10*val + (inc-'0');
    } else {
      switch (toupper(inc)) {
      case 'A':
        Serial.print("Case A got ");
        Serial.println(val);
        break;
      case 'B':
        Serial.print("Case B got ");
        Serial.println(val);
        break;
      default :
        ; // handle blanks, returns, etc
      }
      val = 0;  // Set val to zero after any non-digit
    }
  }
}

Edit 2: This edit incorporates some code suggestions from comments into the answer.

If you need to know whether a number for val1 has been specified -- that is, if you handle items like 500B as well as 300,500B -- you can set/test/clear a flag:

...
case ',':
  val1=val; v1flag=1;
  break;
...
case 'B':
  if (!v1flag) val1=val1default;
  Serial.print("B stuff with val and val1");
  v1flag=0;
  break;
...

To retain when the power is off, you can write a recordData() function, that when called will write selected data to EEPROM if the value has changed.  In setup(), load data from where you stored it. For data validation, you can store in the cell after a value v its complement, ~v.  If when you reload data it fails the validation test, use a default value instead, and write it to EEPROM for future use.

The code snippet shown next, from kaisarGreat's 8 May comment, has several problems to be corrected:

case a :
  WATEREQFORN1 = val;
  EEPROM.put(0, WATEREQFORN1);
case b :
  WATEREQFORN2 = val;
  EEPROM.put(1, WATEREQFORN2);
case d :
  DELAY = val;
  EEPROM.put(3, DELAY);

Logic or syntax problem: Missing break statements at  ends of cases.  This error will allow execution to flow from one case into the next.  While there are situations where that's useful, this is not one.

Logic or syntax problem: Unless a, b, ... are declared constants they won't work as case designators.  Perhaps use 'A', 'B', ... instead.

Style problem:  Variable names in all upper case.  Conventionally, C and C++ programmers use all-upper-case names to designate defined constants or macros.  Contravening that convention can lead to confusion if other people use or maintain the code.  Instead of WATEREQFORN1 consider waterEq1.

Allocation problem:  Presumably the WATEREQ... variables are multiple bytes in length.  EEPROM.get() and put() read and write data types with multiple bytes using several consecutive bytes of EEPROM.  For example, if WATEREQFORN1 is a real and takes 4 bytes, it will occupy cells 0, 1, 2, 3 in EEPROM.

The following code snippet fixes some of those problems.

enum { WaterAddr1=0, WaterAddr2=WaterAddr1+sizeof waterEq1, DelayAddr=WaterAddr2+sizeof waterEq2 };
...
case 'A':
  waterEq1 = val;
  EEPROM.put(WaterAddr1, waterEq1);
  break;
case 'B':
  waterEq2 = val;
  EEPROM.put(WaterAddr2, waterEq2);
  break;
case 'D':
  Delay = val;
  EEPROM.put(DelayAddr, Delay);
  break;
  ...


Compiling source with Arduino.h with avr-g++ How should I include the Arduino libraries when I'm compiling from the the command line? I tried to do it like this:

avr-g++ -g -Os -Wall -mcall-prologues -mmcu=atmega328p -fno-exceptions -o blink.obj blink.cpp -L. -lutil -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" -I"D:\Projects\Arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores"

but it returns undefined reference to the function that I am trying to use.

Arduino version: 1.8.2

You need to do a whole lot more than just run the one command.

You need to compile each individual source file for the libraries you want (using -c to just compile and not link), then (ideally) archive them into a library file. Do the same for the core. Then you need to add paths to your sketch compilation command pointing to where the header files are for those libraries, and compile the sketch to an object file (again with -c). Finally you need to link everything together into an ELF file, and convert that to a HEX file.

TBH you're best off using an already-existing Makefile project, or arduino-builder.


Ultrasonic sensors with 12v motors will not work! (ADRUINO) ok... so I am using four 12V motors and one ultrasonic sensor with a motor shield... and I am getting some odd results...
in my code I have it so when the distance to a object is less than 4 cm it will go backwards and when something is not 4 cm in front of the robot it will go forwards... simple!
but the wheels on the left side of my robot will stop! and just do nothing!

The weirdest part about it is when I make some code JUST moving the wheels back and forth the wheels will work PERFECTLY fine. and when I use some code JUST for the sensors... it works fine! but together... it does all that weird stuff.

this is the shield I am using: https://www.pololu.com/product/2507

if there is any information I missed that you need let me know and I will get back with you. I am new to Arduino so I am extremely confused...

the code.

#include "DualVNH5019MotorShield.h"
DualVNH5019MotorShield md;

#define trigPin 7
#define echoPin 8

void setup() {
    md.init();  //setting up wheel code
    Serial.begin (9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
}

void loop() {
    long duration, distance;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;

//This is the sensor testing if somthing is in range!
if (distance < 4){
        Serial.println("in range");
        md.setM1Speed(100);
        md.setM2Speed(-100);
}
else {
        Serial.println("not in range");
        md.setM1Speed(-100);
        md.setM2Speed(100);
}

if (distance >= 200){
        Serial.println("!");
}
else {
        Serial.print(distance);
        Serial.println(" cm");
}
    Serial.println(distance);
    delay(500);
}

TLDR: change your project (both program and connection) to use ultrasound sensor on any two of pins 3,5,11 and it should work.

You are using pins 7 and 8 for ultrasound.

At the same time you are using the shield  https://www.pololu.com/product/2507 for motors, but if you look at the shield description on picture Dual VNH5019 motor driver shield with an Arduino (shield and Arduino powered separately).https://a.pololu-files.com/picture/0J3753.1200.png?5877a2053bf73d6dbb43d10e7d268ce5
You will see, that the shield is using pin 7 as M2INA and pin 8 as M2PINB

So each loop you push M2INA (trigPin) LOW, then HIGH then LOW, then wait until the sensor write HIGH to M2INB (echoPin) just to immediately send PWM pulses to both trigPin (M2INA) and echoPin (M2INB) via commands

    md.setM1Speed(100);
    md.setM2Speed(-100);

No way it can work as you expect.

You must use other pins (unused by the shield) for your ultrasound sensor. I suggest to declare

#define trigPin 3
#define echoPin 5

and connect your ultrasound sensor there acordingly.

(You can use also pin 11 if you want. I would not recomend pin 13, as there is connected the Arduino LED, which is used by bootloader too so you could confuse the sensor, nor the pins 1 and 2, as they are used by Serial (and USB). Also you can use the "analog pins" A2..A5 as digital pins, but it may confuse you a little (AVR can use "analog" pins as "digital" but many beginers does not like constructs as "digitalWrite(A2)", "digitalRead(A3)").

Also keep in mind, that A4 and A5 are used for I2C communication, if you would use I2C later in project.


Do Arduino Megas Burn Out? Im building a bedside alarm clock/home assistant. I have a few buttons that input, an LCD display and some RGB LEDs. The LCD and RGBs are only on when commanded to be on. I was wondering if I could leave the mega plugged in and constantly running or if that would burn it out. Im a bit new to this so sorry if this is dumb. If it would burn out, how long is its lifetime?

As long as you operate the electronics within specification they will run for years and years. The first thing to probably fail will be the electrolytic capacitors that will dry out after maybe 10 years.

When reading datasheets and specifications the metric you are interested in is the MTBF - the Mean Time Between Failures.


cheap long lasting options for battery? I recently made a differential drive using Arduino UNO, two BO dual shaft 9v Motor and ld293d.To power Arduino, I am using a Hi-Watt 9 volt battery, to power the ld293d 5v pin (VCC1) I am using Arduino 5v Vout pin and to power its motor driver pins (VCC2) I am using Hi-Watt 9 volt battery.

The problem is its not long lasting and after moving just a bit like 30 seconds it slows down and stops ,or one of the motor stops working.I have tried this with multiple new 9v batteries, I don't understand why is this happening because the batteries still seems to be work on other projects.Should I use some other kind of battery if yes then what would be the cheapest option?

9V batteries are not meant for high-current discharge, as you would find when powering a motor. Not only that, they are low capacity. If you need to power motors, you should use batteries such as C or D cells in series to build the voltage required, or try Lithium-Polymer (LiPo) for a rechargeable option.

On a side note, the L293 H-Bridge is a poor choice of H-Bridge these days, especially for a battery-powered project, as there are more efficient motor driver ICs these days.


'crash' when using pin change interrupts I'm noticing a crash when testing out some interrupt code for a project I'm working on.

I've returned to the example provided with the library PciManager and I'm still experiencing the same issue. There doesn't appear to be any patten to when the crash appears, and on occasion I've been playing for several minutes and not seen a crash. NOTE I had to add a file (Task.h) from the developers other project (SoftTimer) to get it to compile.

here is the code:

#include <PciManager.h>
#include <PciListenerImp.h>

#define INPUT_PIN 3

PciListenerImp listener(INPUT_PIN, onPinChange);

int i = 0;

void setup() {
  Serial.begin(9600);
  PciManager.registerListener(INPUT_PIN, &listener);
  Serial.println("Ready.");

}

void onPinChange(byte changeKind) {
  i++;
  Serial.print("pci : ");
  Serial.print(i);
  Serial.print(" : ");
  Serial.println(changeKind);
}

void loop() { }

I have a wire connected to pin 3 and 3.3v which I'm pulling out and then connecting again. Some times when disconnected it continually interrupts, I was expecting this. Sometimes it doesn't which I found strange, the crash appears to happen more in the latter case.

Here is a trace from the serial monitor

Ready.
pci : 1 : 0
pci : 2 : 1
pci : 3 : 0
pci : 4 : 1
pci : 5 : 0
pci : 6 : 1
pci : 7 : 0
pci : 8 : 1
pci : 9 : 0
pci : 10 : 1
pci : 11 : 0
pci : 12 : 1
pci : 13 : 0
pci : 14 : 1
pci : 15 : 0
pci : 16 : 1
pci : 17 : 0
pci : 18 : 1
pci : 19 : 0
pci : 20 : 1
pci :

I've run this on a shrimp and on a freeduino diecimila compatible board both resulting in the same effect.

Anyway down to question; is the issue the way I'm interrupting? i.e. not stopping the floating pin? or is it a problem with the library, or is it a fundamental problem with pin change interrupts.

Your onPinChange() function is called with interrupts disabled.

For you what it means is this function should:

last as short as possible (because NO interrupts are handled during its execution, that includes timers that are used by several Arduino core libraries)
not use Serial functions as these functions are slow and sometimes wait on interrupts (that could thus mean wait forever)

You can read further advice about these so-called Interrupt Service Routines (ISR) here and there.

If you want to trace all calls to onPinChange() then you will have to use some kind of circular buffer as a global volatile variable, which will be written into by onPinChange() and read from by loop().

Accessing that buffer from loop() should be protected against concurrent write by ISR.

Here is sample code I have just written (disclaimer, I have not checked that it compiles but I think it should work correctly) that uses such a circular buffer as described above, and ensures all shared variables accesses are protected against concurrent write by ISR:

#include <PciManager.h>
#include <PciListenerImp.h>

// Structures and function to manage circular buffer of changes
struct Change {
    int i;
    byte kind;
};

// We allow max SIZE changes in the buffer; if onPinChange() is called more often
// than loop(), then at one time the buffer will be overwritten.
const int SIZE = 100;
volatile Change changes[SIZE];
volatile int start = 0;
volatile int end = 0;

// Get the next change recorded by onPinChange()
Change* nextChange() {
    static Change change;
    Change* result = 0;
    // Disable interrupts as we are accessing variables modified by onPinChange
    cli();
    if (start != end) {
        change = changes[start];
        start = (start + 1) % SIZE;
        result = &change;
    }
    // Re-enable interrupts before leaving the function
    sei();
    return result;
}

#define INPUT_PIN 3

PciListenerImp listener(INPUT_PIN, onPinChange);

// No change necessary in setup()
void setup() {
    Serial.begin(9600);
    PciManager.registerListener(INPUT_PIN, &listener);
    Serial.println(Ready.);
}

void loop() {
    // Get the next change recorded by onPinChange (if any)
    Change* change = nextChange();
    if (change != 0) {
        // One change occurred since last time, trace it to Serial
        Serial.print("pci : ");
        Serial.print(change->i);
        Serial.print(" : ");
        Serial.println(change->kind);
    }
}

void onPinChange(byte changeKind) {
    // i does not have to be visible outside this function
    static int i = 0;
    i++;
    // Write information to the end of the circular buffer
    Change& change = changes[end];
    change.i = i;
    change.kind = changeKind;
    // Prepare for the next call (write to the next item of the buffer)
    end = (end + 1) % SIZE;
}


Mechanical requirements for Arduino compatibility If I want to design an Arduino-compatible board I guess I'll have to use the same outline, and connector positions to fit existing enclosures. (Beats me why they didn't choose a simple rectangular board, which would have been cheaper.) But I wonder if the ICSP header's position is standardized. Some enclosures have a hole above it, but many don't. Can I move the ICSP header to another position?

(Can somebody add a "compatibility" tag? Thanks. Also, neither "mechanical" nor "board" nor "layout" seem to exist as tags. Feel free to improve my generic tagging.)
The "shield" tag was suggested, but this isn't about shields, it's about the ICSP header.

Depends on what you define as "Arduino compatible".

My "Arduino Nano" is 'Compatible' but a whole other design.

Or well, it already separates here.
"Software compatible" working with the Arduino IDE and/or Libraries. In general, any board with ATMega 328P / USB or ICSP / Bootloader could be considered compatible.

But, however, for an "Arduino clone" being "Hardware compatible" you could also look at:

Pin placement (Thus being compatible with shields).
Using the same FTDI chip, thus being directly compatible with arduino
drivers (not sure)
Using "exactly" same electronic specifications.
Size and/or shape or even weight of the board.

Strictly, moving the ICSP header will make it 'incompatible' for some shields.
But, well, for most shields it won't be a problem. For casings that have an opening for the ICSP header it'll mostly just look funny.
By replacing the ICSP header it might touch components of other shields/casings and thus be not compatible with it.

(update)
The website and file below are from the arduino site and could thus be considered to be the 'standard' as it's set by arduino. You can however make your board how you want it and compatible with what you want. But changes will often make it incompatible with (some) shields/adapters.

The arduino website with specifications on the board:
http://www.arduino.cc/en/Main/ArduinoBoardUno

EAGLE files:
http://arduino.cc/en/uploads/Main/arduino_Uno_Rev3-02-TH.zip


How to compare two string? I meet a terrible problem. I can't compare two string!

My job is simple, every 1ms use SoftwareSerial read_card(2, 3);to check if i read a id card.And don't read a card twice.Here are my code:

bool CardReader::check()
{
    String str= read_card.readString();
    if (str.length() == 0 ) return false;
    //Log("card:%s", str);
    Serial.println("card_id");
    Serial.println(str);
    Serial.println(card);
    Serial.print("cmp:"); Serial.println(str == card);
    if (str.length() == card.length())
    {
        uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)str.c_str();
        for (int i = 0; i < card.length(); i++)
            if (p1[i] != p2[i])
                break;
        return false;
    }
    card = str;
    return true;
}

Let's see output:

card_id
 Rq
 僐R
cmp:1

The hex are:

00 01 52 71 02
00 83 52 52 00

Why the two string is equal?

Bugs are fixed.If string begin with '\0',== can't work and = can't work either.

bool CardReader::check()
{
    String str = read_card.readString();
    if (str.length() == 0) return false;
    if (str.length() == card.length())
    {
        uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)card.c_str();
        for (int i=0; i < card.length(); i++)
        {
            Log("%d:%d", p1[i],p2[i]);
            if (p1[i] != p2[i])
                goto find_card;
        }
        return false;
    }
find_card:
    for(int i=0;i<5;i++)
        card[i]=str[i];
    return true;
}

Why the two string is equal?

        uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)str.c_str();

Both p1 and p2 point to the same string so of course they will always compare equal.

Do you mean:

if (str == card)
   // do something


read first line from sd card and save the position for again reading from sd card I am reading sd card .txt file, I want to read the first line then how to save the position of the pointer for the next line read?

You should not need to save the position, the file knows where you last read from. You'd only need to manually save such information if you close the file and re-open it again, which unless you have a good reason is actually a very wasteful operation.
If you really do need to you can use the .position() and .seek() functions:
Save the location:
uint32_t pos = myFile.position();

Recall the location:
myFile.seek(pos);

Documentation:

https://www.arduino.cc/en/Reference/FilePosition
https://www.arduino.cc/en/Reference/FileSeek


Cheat Sheet for interruption Just read a post about timers and there was a timers cheat sheet posted there. It has been very helpful and I wonder if there is one for interrupts as well?

The post with the nice timer cheatsheet was this one Arduino constant clock output

Perhaps something like this (for the Arduino Uno based MPU):


Debouncing results in no reaction at all Update:

I changed the code to this, but it does not work either.

`if ((millis() - lastDebounceTime) > debounceDelay) {

   if (button) {
 //DEBOUNCING

     if (!button_prev && button) {

      int e = input[j];`

I am trying to debounce a button and integrated this code http://arduino.cc/en/Tutorial/Debounce into my sketch.
The result is, that there is no reaction to the button at all.
I can't figure out the mistake, but maybe someone else sees what I overlook.

Circuit

Parts marked with //DEBOUNCING are only for the purpose of it, parts marked //DEBOUNCE relevant are necessary for the code to run as well when there is no debouncing.

void setup() {

  Serial.begin(9600);

  //setting button pin as input and LOW

  pinMode(8, INPUT);
  digitalWrite(8, LOW); //DEBOUNCE relevant

  //setting input pins as output

  int act_pin[6] = {A0, A1, A2, A3, A4};

  int k = 0;

  for (k = 0; k < 5; k++) {

      pinMode(act_pin[k], OUTPUT);

    }

  //setting state pins as output

  int z_pin[5] = {2, 3, 4, 5};

  int a = 0;

  for (a = 0; a < 4; a++) {

      pinMode(z_pin[a], OUTPUT);

   }

  //setting output pins as output

  int out_pin[6] = {9, 10, 11};

  int b = 0;

  for (b = 0; b < 3; b++) {

      pinMode(out_pin[b], OUTPUT);

   }

  //setting input

  for(k = 0; k < 5; k++) {

      randomSeed(analogRead(5));

      int i = random(2);

      if(i == 1){

         digitalWrite(act_pin[k], HIGH);

         input[k] = 1;

         Serial.print(input[k]);

      }

       else{

         digitalWrite(act_pin[k], LOW);

         input[k] = 0;

         Serial.print(input[k]);

      }

    }

   //setting initial situation

   digitalWrite(2, LOW);
   digitalWrite(3, HIGH);
   digitalWrite(4, LOW);
   digitalWrite(5, LOW);

   }

//DEBOUNCING

long lastDebounceTime = 0;  // the last time the button pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers
int buttonState;

//DEBOUNCING

boolean button_prev = 0;

boolean button = 0;

int j = 0; //value shows current lamp being processed

//setting initial state

char z[4] = "z_0";

void loop() {

    button_prev = button;

    button = digitalRead(8); //DEBOUNCE relevant

    // DEBOUNCING
    if (button != button_prev) {

    lastDebounceTime = millis();

    }

    if ((millis() - lastDebounceTime) > debounceDelay) {

       if (button != button_prev) {
     //DEBOUNCING

         if (!button_prev && button) {

          int e = input[j];

           //provides a nice output
            Serial.println(" ");
            Serial.print("Current lamp being processed:");
            Serial.println(j);
            Serial.println(" ");
            Serial.print("Current input:");
            Serial.println(e);

             delta(e, z);

            Serial.print("State outside function:");
            Serial.println(z);

            lamda(e, z);

             j = (j+1) % 5;

      }

    }

   }
}

It's difficult to tell without seeing your circuit, but it looks like there could be a mix up between pin 12 and pin 8.  Can see that you initialize the pinMode for pin 12 in setup, but it isn't used in the loop.  You didn't initialize pin 8 (not completely necessary) in setup, but it is used in the loop.  If you don't feel this is relevant, please provide some more detail.


nRF24L01 using sender as receiver and vice versa with RF24 library I have two nRF24L01 modules (I tried 2 with antenna and 2 without antenna) paired with their power base module and connected to two different Arduino Mega 2560 boards.
I'm able to send from one module to another up to 32 byte of data and get the acknowledge without any problems. But when I switch them, when I try to send data from receiver and receive it on the sender I have nothing. No data received, no acknowledge sent as response.

As I said before, first part of this code works well, but when it comes to the second part, which is after delay(1000); there's silence...

my code is:

Receiver

#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include "printf.h"

// Set pipes
const uint64_t pipe01_ = 0xE8E8F0F0A1LL;
const uint64_t pipe02_ = 0xE8E8F0F0A2LL;
const uint64_t pipe03_ = 0xA3LL;
const uint64_t pipe04_ = 0xA4LL;
const uint64_t pipe05_ = 0xA5LL;
const uint64_t pipe06_ = 0xA6LL;

RF24 radio(9, 53);

void setup()
{
    Serial.begin(115200);
    delay(250);
    radio.begin();
    radio.setChannel(0x57);
    radio.setPALevel(RF24_PA_LOW);
    radio.enableAckPayload();
    radio.openReadingPipe(1, pipe01_);
    radio.openWritingPipe(pipe02_);
    radio.enableDynamicPayloads();
    radio.startListening();
}

void loop()
{
    if (radio.available())
    {
        char newMessage[33];
        memset(newMessage, 0, sizeof(byte) * 33);
        while (radio.available())
        {radio.read(newMessage, 32);}

        Serial.println("newMessage: " + String((const char*)newMessage));
        delay(1000);
        radio.stopListening();

        char response[32] = "1234567890qwertyuiopasdfghjklzxc";
        radio.write(response, 32);
        unsigned long ack = 0;
        if (radio.isAckPayloadAvailable())
        {
            radio.read(&ack, sizeof(ack));
            Serial.println("ack: " + String(ack));
        }
        radio.startListening();
    }
}

Sender

#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include "printf.h"
// Set pipes
const uint64_t pipe01_ = 0xE8E8F0F0A1LL;
const uint64_t pipe02_ = 0xA2LL;
const uint64_t pipe03_ = 0xA3LL;
const uint64_t pipe04_ = 0xA4LL;
const uint64_t pipe05_ = 0xA5LL;
const uint64_t pipe06_ = 0xA6LL;

RF24 radio(9, 53);

void setup()
{
    Serial.begin(115200);
    delay(250);
    radio.begin();
    radio.setChannel(0x57);
    radio.setPALevel(RF24_PA_LOW);
    radio.enableAckPayload();
    radio.openReadingPipe(2, pipe02_);
    radio.openWritingPipe(pipe01_);
    radio.enableDynamicPayloads();
    radio.stopListening();

    char message[32] = "qwertyuiopasdfghjklzxc1234567890";
    radio.write(message, 32);

    radio.startListening();
}

void loop()
{
    if (radio.available())
    {
        char respMessage[33];
        memset(respMessage, 0, sizeof(byte) * 33);
        while (radio.available())
        {radio.read(respMessage, 32);}

        Serial.println("respMessage: " + String((const char*)respMessage));
    }
}

Please help me.

Update: It was working yesterday, but today... same thing as with "delay()". What's wrong with these radio-modules??

I have discovered that the delay() function was causing this abnormal behavior.

So I have implemented periods instead of delay() and now I'm able to switch operating mode between "receiver" and "transmitter". Moreover, I have discovered few additional conditions that must be met (read the comments for the code).

Below is working sample code where transmitter sends some large message. Receiver gets it, waits 2 secs, then responds with another large message and gets the acknowledge for this message:

Sender

#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include "printf.h"
const uint64_t pipe01_ = 0xE8E8F0F0A1LL; //Writing pipe must be full address if acknowledges will be used
const uint64_t pipe02_ = 0xE8E8F0F0A2LL; //At least one of reading pipes must be full adress
const uint64_t pipe03_ = 0xA3LL;
const uint64_t pipe04_ = 0xA4LL;
const uint64_t pipe05_ = 0xA5LL;
const uint64_t pipe06_ = 0xA6LL;
RF24 radio(9, 53);

void setup()
{
    Serial.begin(115200);
    delay(250);
    radio.begin();
    radio.setChannel(0x57); //not necessary. But must be equal at both sides
    radio.setPALevel(RF24_PA_LOW); //not necessary. But must be equal at both sides
    radio.enableAckPayload(); //For ability to change the Ack Payload with writeAckPayload()
    radio.openReadingPipe(2, pipe02_); //At least one of reading pipes must be full adress
    radio.openWritingPipe(pipe01_); //Writing pipe must be full address if acknowledges will be used
    radio.enableDynamicPayloads(); //If not set, size will be of fixed length. Default fixed length is 32 bytes

    /*Must run this if "startListening()" will be used anywhere in the code below.
    nRF24L01 remembers it's state even if Arduino was restarted*/
    radio.stopListening();
    Serial.println("Sending the message...");
    char message[32] = "qwertyuiopasdfghjklzxc1234567890"; //some test message
    radio.write(message, 32); //Send message over the predefined "writing pipe"

    Serial.println("Waiting for response...");
    radio.startListening(); //Resets TX buffer and switches radio module's mode to "receiver"

    uint16_t ack = 123;
    radio.writeAckPayload(2, &ack, sizeof(ack)); //Custom ACK payload must be set after "startListening()". Because "startListening()" resets TX buffer
}

void loop()
{
    if (radio.available())
    {
        char respMessage[33];
        memset(respMessage, 0, sizeof(byte) * 33);
        while (radio.available())
        {radio.read(respMessage, 32);}

        Serial.println("respMessage: " + String((const char*)respMessage));
    }
}

Receiver

#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include "printf.h"

#define period_  2000

// Set pipes
const uint64_t pipe01_ = 0xE8E8F0F0A1LL; //At least one of reading pipes must be full adress
const uint64_t pipe02_ = 0xE8E8F0F0A2LL; //Writing pipe must be full address if acknowledges will be used
const uint64_t pipe03_ = 0xA3LL;
const uint64_t pipe04_ = 0xA4LL;
const uint64_t pipe05_ = 0xA5LL;
const uint64_t pipe06_ = 0xA6LL;

unsigned long checkPoint = 0;
bool messageReceived = false;
RF24 radio(9, 53);

void setup()
{
    Serial.begin(115200);
    delay(250);
    radio.begin();
    radio.setChannel(0x57); //not necessary. But must be equal at both sides
    radio.setPALevel(RF24_PA_LOW); //not necessary. But must be equal at both sides
    radio.enableAckPayload(); //For ability to change the Ack Payload with writeAckPayload()
    radio.openReadingPipe(1, pipe01_); //At least one of reading pipes must be full adress
    radio.openWritingPipe(pipe02_); //Writing pipe must be full address if acknowledges will be used
    radio.enableDynamicPayloads(); //Writing pipe must be full address if acknowledges will be used
    radio.startListening(); //If not set, size will be of fixed length. Default fixed length is 32 bytes
}

void loop()
{
    if (radio.available())
    {
        char newMessage[33];
        memset(newMessage, 0, sizeof(byte) * 33);
        while (radio.available())
        {radio.read(newMessage, 32);}

        Serial.println("newMessage: " + String((const char*)newMessage));
        checkPoint = millis();
        messageReceived = true;
    }

    unsigned long timePassed = millis() - checkPoint;

    //When it receives, controller waits for 2 seconds then sends the response just one time
    if (messageReceived && timePassed > period_)
    {
        messageReceived = false;
        checkPoint = millis();
        Serial.println("sending response...");

        //This must be called before sending anything (except acknowledges)
        radio.stopListening(); //Resets TX buffer and switches radio module's mode to transmitter

        char response[32] = "1234567890qwertyuiopasdfghjklzxc";
        radio.write(response, 32);

        unsigned long ack = 0;
        if (radio.isAckPayloadAvailable())
        {
            radio.read(&ack, sizeof(ack));
            Serial.println("ack received: " + String(ack));
        }

        radio.startListening(); //Resets TX buffer and switches radio module's mode to "receiver"
    }
}


Identifying Arduino-compatible board signatures in code I am developing libraries for compatibility across a number of Arduino/compatible boards. I know that Arduino boards can be identified by the test "#if defined (AVR_ATmega328P)" and compatibles as well: #if defined(TM4C123GH6PM).   There are a few lists of these IDs on the web but are all outdated. I have searched various cores and library code and do not see where these defines are actually defined.

Nick Gammon's Sketch to detect Atmega chip types identifies the chip type. What I'm looking for the board type to define pin configurations, etc.

Where and in what format are board signatures stored? Is there c++ code that can find the board signature? Does anyone know of a site where these signatures are stored and updated by the Arduino community?

In the boards.txt file each board has a board type definition, such as:

uno.build.board=AVR_UNO

When you compile your sketch that is adapted into a "board" define by prepending -DARDUINO_ to it and adding it to the compilation command line - so that one becomes the same as #define ARDUINO_AVR_UNO.  You can, of course, test for it with:

#ifdef ARDUINO_AVR_UNO
....
#endif

The location of the boards.txt file varies with different versions of the IDE, but every installed core will have one.  Look around in your Arduino program folder in the hardware subdirectory.


How to read pinMode for digital pin? Is there a way for me to read the pin mode for one of the digital pins on Arduino?   In other words, can I determine whether a pin's been set to an input or output?

There are functions which can get you the registers and bit numbers from a pin number built into the Arduino API.

uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);
volatile uint8_t *reg = portModeRegister(port);

if (*reg & bit) {
    // It's an output
} else {
    // It's an input
}


Coding force sensitive resistor to give output based on time used? I have a basic set up of having a force sensitive resistor being used to power an LED as can be seen below. I am wondering how I can code it so that the LED is lit after a pressure has been applied to the FSR for a specified amount of time. Leading on from that I would like to use an RBG LED and have it so that after specified intervals on continuous pressure the LED changes colour.
Any advice would be greatly appreciated.

//Constants:
const int ledPin = 3;     //pin 3 has PWM funtion
const int sensorPin = A0; //pin A0 to read analog input

//Variables:
int value; //save analog value

void setup(){

  pinMode(ledPin, OUTPUT);  //Set pin 3 as 'output'
  Serial.begin(9600);       //Begin serial communication

}

void loop(){

  value = analogRead(sensorPin);       //Read and save analog value from potentiometer
  Serial.println(value);               //Print value
  value = map(value, 0, 1023, 0, 255); //Map value 0-1023 to 0-255 (PWM)
  analogWrite(ledPin, value);          //Send PWM value to led
  delay(100);                          //Small delay

}

You'll need to declare a variable to hold the start time (millis()) of when the force has exceeded the threshold.

You'll need to declare a constant to hold the threshold value (with analog data, you likely don't want to have your pressure threshold be "anything greater than 0", because noise and other things like small vibrations will trigger.

Also declare a constant to hold your "hold-off time" in milliseconds.

In your loop(), when you have an analog value that exceeds the pressure threshold, store the value of millis(). Also in your loop(), when the current millis() minus the start value  is greater than the "hold-off time", activate your LED.

For RGB, same setup, but you can set your color based on how much greater the time difference is than the hold-off time.


What's the difference between all the Software Serial Libraries? Which one is Arduino Nano compatible? There are so many Software Serial Libraries, what are the differences between them? And which one I can use with my Arduino Nano? For my Arduino Nano I need one Hardware Serial Port and one Software Serial port at a baud rate of 115200.

On which pins of the Arduino Nano can I use the software serial library?

This answer lists the 4 basic choices:

HardwareSerial, always the best.  Simply use the pre-defined Serial variable.  On some Arduinos, there are extra HardwareSerial ports, called Serial1, Serial2, etc.  The Nano only has Serial.
AltSoftSerial, the best of the software serial libraries.  Only one instance is allowed, and it is must be used on one of the Input Capture pins (pins 8 & 9 for a Nano).
My NeoSWSerial is next best.  It works on any two pins, but only at baud rates 9600, 19200 and 38400.
SoftwareSerial is the worst choice.  It works on any two pins, but it is very inefficient.  It disables interrupts for the entire time that a character is being sent OR received, and it cannot do both at the same time (unlike all the other serial choices).  This can interfere with other parts of your sketch, other device communications, or with libraries.

If you could use a slower baud rate, you could keep your debug prints on Serial, and use either AltSoftSerial or NeoSWSerial for your device.

But if you have to use 115200, the only reliable choice is Serial.  Although AltSoftSerial and SoftwareSerial allow that baud rate, they may not send/receive data correctly.

In that case, I would suggest using Serial for the 115200 device.  Unless you are using an ISP, you will have to disconnect the device to upload a new sketch over USB.

Then use AltSoftSerial or NeoSWSerial for your debug statements.  You will need a TTL Serial-to-USB adapter (aka FTDI) on the selected pins to connect to the PC.  The Serial Monitor or other Terminal emulator program will read from that USB COM port.


How to add data without pre-defining variables? I am currently working on a RFID card reader. I need the reader to send the ID to a storage space.

What I am trying to achieve is a person swipes their card, enters their name on the serial monitor, and then have that data stored in a pair. The thing is that I do not know how many people will have cards. After that, I could call a person's name and it would show "Hello w, your ID number is xxx xxx xxx xxx xxx.

So I know there are no such things as "dynamic" variables. And I think I would need to pre-define a TON of arrays if I wanted to use them. So I am kinda at a stopping point. Is there no way to generate a new variable name and store data to that variable?

Also, I work with PLCs so I thought that indirect addressing might work, but I am unfamiliar on how to even do that in C++, only in ladder logic or if it would even work. Or how I would be able to call out an ID by name with that approach.

Use the EEPROM. This allows data to remain intact and unchanged even when power is disconnected.

As you say you're new to programming, and because I wrote a similar program just last week as an experiment for something bigger, I'll talk you through some of it. However, I'm not going to give you the whole code to copy-and-paste, I'm only going to give you information on dealing with EEPROM and structures. C-aficionados may grumble at some bits, and Arduinites at others - sic vita est. This is something of a crash-course so it's not gospel, but it should be more than enough to guide you. You may already know some or most of it; it's included nonetheless for completeness, for those who don't.

For those who don't know

In C, data relevant to an object can be stored in a structure, or struct. You can put all sorts of different types of data in a struct, like so:

struct personalProfile {
    char    firstName[8];
    char    lastName[8];
    uint    cardID;           // 'uint' is an unsigned int...
    bool    accessAllowed;
};

You can then use that structure to create a 'personal profile' for however many people you want:

// within your main program:

struct personalProfile Person1;
struct personalProfile Person2;

// Now you can directly access individual aspects as so:

Person1.firstName = "John";
Person1.lastName = "Brown";
Person1.accessAllowed = TRUE;

Person2.firstName = "Dodgy";
Person2.lastName = "Dave";
Person2.accessAllowed = NOT_A_HOPE_IN_HELL;

You can use the members of a structure in exactly the same way you'd use that member type if it wasn't part of a structure. Nice and easy.

The best way to store multiple instances of a particular variable type is in an array:

struct personalProfile listOfPeople[5];

You now have an array of five (blank) structs, which can be accessed by listOfPeople[n].firstName = Potato;, where 'n' is between 0 and the number-of-entries-minus-one. So far so potato.

An array is pretty basic. It's present in all sorts of programming languages because it's inherently essential to almost any program, but the trouble is that it's static. Using the code above, once the array has been created with five structs in it you can't add or remove any. One solution is to create a massive array, and set all the values in each struct to zero, or some other 'empty' identifier, so you're always going to have enough entries (up to a point). However, that's lazy, time inefficient (you've got to set aaaaalll the individual elements to your 'empty' signifier), resource inefficient (look at all that unused space!), and the data only lasts while the program is running. As soon as you cut the power to the Arduino, the information is lost.

Next comes containers. These are part of the Standard Template Library (STL) in C++. They're great for creating and managing dynamic-length arrays. There are different types for different purposes (see the link), but they don't exist in C (at least as far as this post is concerned) and they're not available as part of the Arduino IDE without installing a bunch of libraries or some other intervention. Therefore you've got to make your own version. It's actually pretty easy...

EEPROM basics

The EEPROM library that comes with Arduino is of course essential for this. It doesn't have many functions, and the ones that exist are fantastically easy to understand. EEPROM, for those who don't know, is non-volatile memory. That means that when you store data it stays there forever, even if you remove the power. The only way to get rid of the data is to write over it. The downside of EEPROM is that it has limited amount of times it can be written to - 100,000 times per bit typically so you don't need to start keeping count, it just means you shouldn't be using it as regular program memory. Reading data from EEPROM isn't limited in the same manner.

Using the function EEPROM.put(address, data) you can put ANY data type - an int, char or - you guessed it - a struct into the EEPROM, starting at the byte specified by address. Of course there has to be enough space so you can't put an int, which takes up more than 1-byte of space, into the last address without the function failing. (Or can you? I haven't tried it yet because I'd never do it in practice.)

So you've created your structure, and made sure that all it's members are a fixed size. That means the structure has a fixed size. If you know that size, you can start putting them into the EEPROM.

// within main program

struct personalProfile Person1;
struct personalProfile Person2;

// fill in the details for Person 1...
// fill in the details for Person 2...

// ...then put Person1 in the EEPROM at address 0.
EEPROM.put(0, Person1);

// Done. Now put in Person2. But where?
// You need to make sure you put them AFTER Person1.

int AddressJump = sizeof(personalProfile);

// AddressJump now equals how many bytes are need to store one person.

EEPROM.put(AddressJump, Person2);

Simple as that.

If you create a Person3, you're going to need to put them sizeof(personalProfile) bytes AFTER Person2, i.e. EEPROM.put(AddressJump*2, Person3);. So, you add PersonN to address AddressJump * (N-1).

Retrieving data is the same principle, except you use EEPROM.get():

// provided you've used the above snippet somewhere to actually
// populate the EEPROM with something!

struct personalProfile personA;

EEPROM.get(0, personA);

Serial.print("Person A is called:");
Serial.println(personA.firstName);

Again, you're going to need sizeof(personalProfile) to read the second, third, or Nth person. If you 'send EEPROM.get() to the wrong address it will still populate the personalProfile instance with data, it will just be gobbledygook. Once you start putting people in the EEPROM you're going to need to keep track of things otherwise you'll end up lost. You need to manage the list to make sure you don't put one person on top of another (you could get in trouble for that) and you don't want to get someone that isn't there.

List management

This is where I leave you, for now. When you have digested the information above, and you want to continue, I'll carry on.

Your first task is to determine what sort of array you want. Inevitably it's going to be a Linked List. This is an array of structs, where each struct element in the list contains the memory address of the following element, thus the list is linked. You need to consider:

How the array will be linked (if at all);
Whether or not the array is space-critical (does it have to be as small as possible);
Where the array is going to start;
How you're going to keep track of how many people are in the array.

@TL140 I await your response, good luck!


How to install a library for a single project How do you install an Arduino library so it's only available for a specific project?

Say I have a codebase located at /myproject, and I want to install libraries at /myproject/lib/somelib. I can't find how to make arduino myproject.ino find the libraries under ./lib.

Googling "installing Arduino libraries" only finds me examples of installing libraries globally (and through the GUI no less), which is horrible practice and guarantees version conflicts.

When I used ino, it supported a local ./lib directory, but I can't find any equivalent feature in arduino.

I ended up switching to ano, which supports a local lib directory.


Is there a way to shift through sensors We are doing a project and have to use around 25 temperature sensors. Is there a way to shift through them on one Arduino similar to using a shift-register?

It is a set of analog sensors in a fridge.

As I mentioned in the comments, one way to do this is to use a multiplexer.

You haven't said which temperature sensors you are planning to use, so I'll illustrate this example using the TMP36 Analogue temperature sensor.

Now, if you were using just one of these, the connection would be trivial:

But you want more sensors than available pins. That's where the multiplexer comes in.

I'm going to illustrate this using 16 sensors and the Sparkfun 16-channel multiplexer breakout board which is based on the 74HC4067 multiplexer. For 25 sensors, you could use a 32-channel multiplexer (like the Analogue Devices ADG732, for example), or just combine two 16-channel multiplexers (which is probably cheaper, but requires a little more care in the wiring).

[If your soldering skills are OK, I wouldn't even bother with the Sparkfun breakout board myself. It's pretty simple to connect something like this on protoboard, or make your own PCB.]

The 16 sensors are connected to pins Y0 - Y15 on the 74HC4067 (pins C0 - C15 on the Sparkfun board). Take care to note which sensor is connected to which pin!

With 16 inputs, we need 4 bits to address them. The address pins are labelled S0 - S3. The Sparkfun datasheet for their breakout board includes a Truth Table mapping the addresses to the inputs:

The input from the selected device becomes the output from the multiplexer (pin Z on the 74HC4067; the SIG pin on the Sparkfun breakout board).

The diagram below shows one way of connecting 16 TMP36 analogue temperature sensors to an Arduino Nano using the Sparkfun breakout board:

Note the mapping chosen for the address pins:

D5 -> S0
D4 -> S1
D3 -> S2
D2 -> S3

This makes the drawing layout simpler, but may not be the most intuitive mapping when you come to write your code. My advice is to assign meaningful labels to the pin-mappings in your code, and document that decision with comments! (I'm sure that I'm probably preaching to the choir here, but this may help someone reading this in the future to avoid some of the pitfalls.)

Now, you cycle through a loop:

while true {
    increment the address to be written to pins D5-D2 (note the order)
    read the input on A0
    <do whatever you need to do with the temperature reading>
}

And Robert is the male relative of your choice.


Arduino Upgrading from 1.0.6 to 1.6, code doesn't work anymore I'm using Arduino UNO, and today I upgraded my IDE from 1.0.6 to 1.6, just to upgrade, nothing special.

I got my libraries again but I got an error with a code that was working OK.

The error was:

In file included from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:223:0,
                 from C:\Program Files (x86)\Arduino\libraries\ModbusMaster-master\ModbusMaster.h:53,
                 from C:\Program Files (x86)\Arduino\libraries\ModbusMaster-master\ModbusMaster.cpp:32:
C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h: In member function 'HardwareSerial& HardwareSerial::operator=(const HardwareSerial&)':
C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h:83:7: error: non-static const member 'volatile uint8_t* const HardwareSerial::_ubrrh', can't use default assignment operator
 class HardwareSerial : public Stream
       ^
C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h:83:7: error: non-static const member 'volatile uint8_t* const HardwareSerial::_ubrrl', can't use default assignment operator
C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h:83:7: error: non-static const member 'volatile uint8_t* const HardwareSerial::_ucsra', can't use default assignment operator
C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h:83:7: error: non-static const member 'volatile uint8_t* const HardwareSerial::_ucsrb', can't use default assignment operator
C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h:83:7: error: non-static const member 'volatile uint8_t* const HardwareSerial::_ucsrc', can't use default assignment operator
C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial.h:83:7: error: non-static const member 'volatile uint8_t* const HardwareSerial::_udr', can't use default assignment operator
C:\Program Files (x86)\Arduino\libraries\ModbusMaster-master\ModbusMaster.cpp: In member function 'void ModbusMaster::begin(uint16_t)':
C:\Program Files (x86)\Arduino\libraries\ModbusMaster-master\ModbusMaster.cpp:139:16: note: synthesized method 'HardwareSerial& HardwareSerial::operator=(const HardwareSerial&)' first required here
       MBSerial = Serial;
                ^

I couldn't find the real error, can someone help me?

You should not have added libraries to the Arduino files in the "C:\Program Files (x86)\Arduino" folder in the first place.
That is only for the Arduino program files and standard libraries that are included with the Arduino IDE.

Could you uninstall the Arduino and serial drivers. Remove also the "C:\Program Files (x86)\Arduino" folder, to be sure that absolutely nothing is left behind, because that will interfere with a new version that will be installed. Remove also the hidden "arduino15" folder(s).
Do you know the location of your sketches, it is in the preferences and is often "Documents\Arduino". Go to that folder and go into the "libraries" folder. Remove unused libraries or libraries that have been included in the Arduino files.
Do you have Java installed ? Some Java versions are not compatible with the Java files of the Arduino. If you don't need Java, then uninstall it.

Install the newest Arduino 1.8.3 from Arduino.cc Software.
Use the Library Manager in the Arduino IDE, and search for modbus. Install the "ModbusMaster by Doc Walker" with the Library Manager. The modbus library that will be installed is this one: Github 4-20mA ModbusMaster.

There has been a few changes, for example with PROGMEM. All PROGMEM data must now be 'const'. You might have to make a few adjustments.


SoftwareSerial data being corrupted - looking for suggestions I'm having problems running a serial communication between a NodeMCU ESP8266 and an Arduino Uno. I'm using the "standard" SUART setup, i.e. pins D1&D2 on the ESP are hooked up with GPIOs 2&3 on the UNO; the tx from UNO to ESP is fed through a voltage divider to step it down to 3.3V.

The setup used to work fine; suddently - yeah I've read it before, my setup suddently doesn't work, but honestly that's what happened - data is being corrupted.
The devices exchange a json formatted string:

{"action":"position","lat":123,"lon":123}

and it just worked. Now what I receive is something like:

{"⸮⸮⸮⸮⸮⸮":"pos⸮⸮⸮onb,"l⸮tF:0,"lo⸮":0,"⸮⸮s⸮⸮":0⸮

Both SUART are on 115200 baudrate, physical connections have been checked and are fine, both devices are grounded on the same reference level.

I've tried swapping the ESP with another one and changing TX/RX pins on the UNO - no results.

So I'm looking for suggestions what to do next to debug the issue, what to check and what could be wrong. Thank you in advance.

Below are UNO and ESP code snippets.

ESP8266

SoftwareSerial SUART(4, 5);

int16_t last_fetch = 0;
int16_t last_serial = 0;

double azimut, elevation;

#define DATA_FETCH_TIME_INT 3
#define SERIAL_TRASMISSION_TIME_INT 5

void setup() {
  Serial.begin(115200);  //enable Serial Monitor
  SUART.begin(115200);   //enable SUART Port

  WiFi.begin(ssid, password);

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

  Serial.println();
  Serial.println(WiFi.localIP());
}

void loop() {
  if (secs() - last_fetch >= DATA_FETCH_TIME_INT) {
    last_fetch = secs();
    fetchData();
  }

  if (secs() - last_serial >= SERIAL_TRASMISSION_TIME_INT) {
    last_serial = secs();
    sendDataViaSerial();
    }
}

void fetchData() {
  //connects to server and fetches data
}

void sendDataViaSerial() {
  int lat_i = (int) elevation;
  int lon_i = (int) azimut;
  int checksum = lat_i + lon_i;

  const int capacity = 200;
  StaticJsonDocument<capacity> doc;

  doc["action"] = "position";
  doc["lat"] = lat_i;
  doc["lon"] = lon_i;
  doc["cksum"] = checksum;

  Serial.println("Sending data via serial: ");
  serializeJson(doc, Serial);

  //SUART.flush();
  //serializeJson(doc, SUART);
  // works the same

  String outstring;
  serializeJson(doc, outstring);
  SUART.println(outstring);
}

ARDUINO UNO

SoftwareSerial SUART(2, 3);
#define arraySize 150
char inData[arraySize];

void setup() {
  pinMode(STATUS_LED, OUTPUT);
  digitalWrite(STATUS_LED, HIGH);

  Serial.begin(115200);
  SUART.begin(115200);

  Serial.println("Ready to go.\n");
}

void loop() {
  readSerial();
}

void readSerial() {
  short index = 0;
  char inChar;

  if (SUART.available() > 0) {
    while (SUART.available() > 0 && index < arraySize - 1) {
      inChar = SUART.read();
      inData[index] = inChar;

      index++;
      inData[index] = '\0';  // Add a null at the end
    }

    SUART.flush();
    String myData = (String)inData;
    Serial.println(myData);

    // consume data
    //parseIncomingData(inData);
  }
}

As @Juraj mentions in the comments, don't use 115200 baud with SoftwareSerial.

The problem is that the AVR isn't fast enough to handle incoming data at that speed reliably.  Yes, it can receive a byte fine at that speed, but what it can't necessarily do is store that byte away in the receive buffer in time to be ready to receive the next byte - so it misses the first few bits and corruption ensues.

Running at a lower baud rate (such as 9600 baud) simply gives it more time to process the data as it arrives.


Arduino ADC converter calculation I am trying to choose a wire encoder for my project. So far, I found this wire encoder (see link). Assuming the measurement range of my cylinder is 1 m. Then, with a 10 bit ADC converter of my Arduino Mega2560, I would have a resolution of 0.09cm (= 100cm/1024). But, lets say some cylinder only have a measurement range of 0.5m. Then the resolution would be 0.048 (=50cm/1024).
I can see that I am missing something here, because the resolution of the later case should be worse than the case with the full measurement range 1m. I would be appreciate for any tipps.

Edit:

Cylinder's movement range 0~1m

Wire encoder's measurement range 0~1.25m

Wire encoder's analog output 0~10v
ADC resolution 10 bit

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


Raspberry pi -Arduino bridge I am building a small wireless controlled robot using the Arduino and the raspberry pi. It works by the user wirelessly connecting through to the raspberry Pi (using vnc or some other form wirelessly) and using the user inputs to send a command to the Arduino which controls the motorised wheels. SO for example if the user presses the up button, a 'W" command is sent from the Raspberry Pi to the Arduino which then reads it and pushes the wheels forward.

I was looking to use one of the new Arduino-Raspberry Pi bridges to connect the two to make it easier to use, but I am not too familiar on how they work. Had a few question such as:

1) How exactly do they work (connection wise)?

2) is it possible to write one python code in the raspberry pi that when run can load the specific ino code into arduino?

3) which bridge would be the most suited for my project? (eg: Arduberry, alamode, gertduino, etc?)

Sorry really new to the raspberry pi and need to find a solution soon so any help would be awesome.

Cheers

1) How exactly do they work (connection wise)?

Physically they all sit on the GPIO sockets of the Pi, sitting on top of the pi. The Gertduino and AlaMode seem to have the same form factor as the Pi which makes them a little more appealing to me but I guess then is personal choice.

Communication appears to differ but it will use Serial, SPI or I2C. I would imagine that you'd be able to choose an alternate one but not read enough about them to know for sure. Serial appears to be fairly simple, and it would be easy to debug, however you might struggle if you wanted to receive data on the Pi without the communication being initiated by the Pi.  I2C would overcome this as you can run it in multi-master mode.

  2) is it possible to write one python code in the raspberry pi that
  when run can load the specific ino code into arduino?

As you can call external programs with python I would say that even if you have to resort to this mechanism then it would be possible. You can turn on the debugging in the Arduino IDE to see what it actually does, then either script it or make the calls from your python program.

  3) which bridge would be the most suited for my project? (eg:
  Arduberry, alamode, gertduino, etc?)

I'd go for either the gertduino or alamode purely on looks particularly the matched form factor.


Connecting an AB phase encoder motor to arduino i'm trying to understand how to connect this motor:

"Mitsumi 334P/R AB"

Link to the motor i bought

connections are:

GND - Obvious.

5v - Obvious.

rest of the connections are a bit confusing to me and i do not want to fry my arduino trying.

do i need a driver or this looks like a built in one?
do i need to add any electrical components like resistors and capacitors ect?

It's just a regular motor, with a (optical) rotary encoder inside. So the first two motor pins are to run the motor. So connect to VCC and GND, or GND and VCC, if you want to run it in reverse. (VCC doesn't have to be 5v; it can be 3v to 30v).

Connect A and B to a digital input pin. You can see what kind of signal you can expect in the screenshot of the oscilloscope, attached to the ebay-listing. So you can measure the speed, and relative position of the motor-shaft.


Local variable usage in SRAM not counted I use the following code to print the currently used SRAM space:

// this function will return the number of bytes currently free in RAM
// written by David A. Mellis
// based on code by Rob Faludi http://www.faludi.com

#include "TypeDefs.h"

int availableMemory()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

int printAvailableMemory(uint32 location)
{
  Serial.print(F("Available Memory at "));
  Serial.print(location);
  Serial.print(F(": "));
  Serial.println(availableMemory());
}

My main application (stripped) looks like:

...
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  printAvailableMemory(1);

  printAvailableMemory(2);

  test();
  printAvailableMemory(3);
}

void test()
{
  Preferences _prefs2;
  _prefs2.Set();
  printAvailableMemory(4);
}

While preference (.h) looks like:

#include "TypeDefs.h"

class Preferences
{
   private:
      uint8 _startChannel;
      uint8 _endChannel;
      uint8 _startNote;
      uint8 _endNote;
      uint8 _startCc;
      uint8 _endCc;
   ...
};

The output is:

Available memory at 1: 1065
Available memory at 2: 1065
Available memory at 4: 1065
Available memory at 3: 1065

I would expect the numbers (1065) would change, since a local variable (_prefs2) is made so at location 4 I would expect more space to be used.

Also, if I remove the _prefs2 code like below, the numbers stay the same.

void test()
{
    printAvailableMemory(4);
}

Why is the local variable not counted?

Why is the local variable not counted?

Let us start with the function availableMemory(), what does it do?

int availableMemory()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

It returns the amount of memory between the top of stack (address of local variable v) and the heap end.

The answer lays in how the compiler works. One strategy that is used is function in-lining. This forces the functions test(), printAvailableMemory(), availableMemory(), etc. to be unfolded into loop() (which actually also gets unfolded into main()).

A common frame with the local variables is created and the variable for the top of the stack becomes one of them. You need a tougher test case to see how the stack top changes, e.g. tell the compiler not to in-line a function.

int availableMemory() __attribute__ ((noinline));

To check this generate the assembly listing for your sketch.

Cheers!


Problem with LED (Builtin) connected to pin 13 This is Aakash. Student of Electrical Engineering in a University.
I want to ask some information. Today I Purchased Arduino UNO R3 board. and facing some problem which are :

          "**Builtin LED at pin#13 is always ON on my board**".

Is there any problem with the board ?

I tried to upload these sketches and got these results::
1)...with empty setup(){} and empty loop(){}, Still LED is ON.
2)...When I uploaded these command "pinMode(LED_BUILTIN,OUTPUT);" in setup() and "digitalWrite(LED_BUILTIN,LOW);" in loop(), LED turned OFF
3)...If i touch pin13 and Ground both by a wet finger at back of board, LED turns OFF.
4)...but on uploading empty or any other code, BUILTIN_LED turns ON again and do not turns OFF.

Kindly reply me ASAP! So that if i have got faulty Board then i might go for claim.

This is a normal thing. All my arduino boards do the same. The reason for this is that the micro controller don't care about the pins that aren't defined in the code. When they aren't defined they all have a HIGH on them. Here is my board with this code:

void setup() {
}
void loop() {
}


How much ohm resistance I should put between tp120 base and uno? I have set up solenoid on of based on soil moisture,
The solenoid is powered by 24 volts, so I power solenoid by 24 volt and Arduino uno by stepping down to 6 volt powering through Vin and gnd.

I have used resistance of 10k ohm but I have twice burnt em.
Not sure how should calculate resistance required of signal coming out from D6 pin to TP120 base !

To calculate you need to know the maximum current the solenoid uses. The TP120 has a gain of around 500-1000. So the current going into the base needs to be 1/500th of the current going through the solenoid.

So now you know the current needed. Then you can calculate the resistance value you need with R = V/I. So R = 5 / ( <solenoidcurrent> / 500 ).

So with e.g. a 2A solenoid, you get a value of 1.2kOhm.


Interpreting pull-up values Rp and Rpu in AM3202 (DHT22) datasheet In the AM2302 datasheet at page 3, table 4, it gives min, typ and max values for Rpu (that the pull-up resistor as it says verbatim) being 30K, 45K and 60K ohm respectively.

Elsewhere in the same table it gives figures for Rp (no u) < 25K ohm.

What is the difference between Rpu and Rp here, and how should the two rows be interpreted?

The datasheet is as inaccurate as the sensor itself and it is even worse than you think!

In that datasheet is also written: "usually require an external about 5.1kΩ pull-up resistor".

In the datasheet is also mentioned that the output signal can go up to 8 mA for a high output and minimal 10 µA low output. The 10 µA means that the pullup resistor should be 500k or more. That is not correct.

In this datasheet is a picture with 1k.
In this Chinese datasheet is a picture with 5k.
I ran that Chinese datasheet through Google Translate, but that did not help.

Conclusion: The datasheet is not reliable.

You can do as everyone else: use a 10k resistor for short wires, and try 4k7 for longer wires.

That is not the only problem. Some DHT libraries create a shortcut on the data signal.

The AM3202 is not accurate for measuring the humidity. If you want to avoid trouble, then use a better sensor.
A sensor from Bosch is a good choice (for example the BME280 or BME680). Bosch makes datasheets that are reliable. Those sensors from Bosch operate at 3.3V, if you are going to connect that to a 5V Arduino board, then you need level shifters for the signals.


Can you connect more sensors of the same type to a single board while not using up more pins than if you were to use a single sensor? I'm as new as you can be at Arduino programming and specific electronics, so I don't even know if I'm asking the correct question.

I've ordered an Arduino a breadboard and some PCBs and now I'm looking for a few parts that I should buy in order to get some basic projects done.

I'd like to start with a garden automation project, a fairly simple one.
Humidity sensors, temperature sensors and a water pump.

Can I connect all (4) of the humidity sensors to a single local circuit and then connect that to the board so I can limit the number of input pins used? I'd still need to get independent readings from the sensors. Or would I need to use another board incorporating RF/Wireless/Bluetooth modules to receive the information and then send it to the board for further processing?

I'm sorry if what I just said makes no sense and I thank you for your time.
All I have is low-mid level electronic related experience. Battery checkers, Power supplies, basic light sensors, PCB making ETC.

If the connection is a digital sense pin then you can use a parallel-in serial-out IC to read them all simultaneously and then shift it in. Takes up 3 pins on the arduino a latch a clock and a data pin.

If the connection is SPI then you can connect the clocks and MISO pins together and then need a slave select for each. you can control many of them with a serial in parallel out IC or a decoder.

If the connection is with the I2C protocol and each device has a different address then you can simply connect them all in parallel.

If the sensor has an analog output then you can use an analog to digital converter (ADC) which can have multiple inputs and often have a serial interface.


Memory Problems on Arduino Uno I am doing a project using Arduino UNO, cc3000 WIFI chip, micro SD card shield, and a TTL serial camera in order to make a security system that will post a picture online (not enough processing power for video) when motion is detected on the camera.

Thankfully, the hardware works after a few shortcomings, but my program seems to be taking up 97% of the Flash storage.

Also, I am looking for a better way to transfer the image than saving it 32 bits at a time and then waiting about 10 sec so the HTTP request will send it to the server.

One thing I do know is that I have tested all the hardware and those functions are working. My problem is in the logic.

Any help appreciated! (Image is around 13KB and UNO only has 2kb of dynamic memory).

My full code is here: https://www.dropbox.com/s/arxa253mxwvqtg1/HomeProj.rtf?dl=0

void loop(void)
{
    cam.setMotionDetect(true);

    while (1) {
        if (cam.motionDetected()) {
            Serial.println("Motion!");

            cam.setMotionDetect(false);
            if (! cam.takePicture())
                Serial.println("Failed to snap!");
            else
                Serial.println("Picture taken!");

            uint16_t jpglen = cam.frameLength();
            Serial.print(jpglen, DEC);
            Serial.println(" byte image");

            char filename[13];
            strcpy(filename, "IMAGE00.JPG");
            for (int i = 0; i < 100; i++) {
                filename[5] = '0' + i/10;
                filename[6] = '0' + i%10;
                // create if does not exist, do not open existing, write, sync after write
                if (! SD.exists(filename)) {
                    break;
                }
            }

            File imgFile = SD.open(filename, FILE_WRITE);
            while(jpglen > 0) {
                uint8_t *buffer;
                uint8_t bytesToRead = min(32, jpglen);
                buffer = cam.readPicture(bytesToRead);
                imgFile.write(buffer, bytesToRead);

                //Send Request
                Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);
                if (client.connected()) {
                    Serial.println("Connected!");
                    client.println("POST /upload HTTP/1.0");
                    client.println("From: Arduino");
                    client.println("Host: fierce-chamber-5675.herokuapp.com");
                    client.println("Content-Type: image/jpeg");
                    client.println("Content-Length: " + 32);
                    client.print("Connection: close");
                    client.println();
                    for(int i = 0; i < 32; i++) {
                        client.print(buffer[i], HEX);
                    }
                    client.println();
                } else {
                    Serial.println(F("Connection failed"));
                    return;
                }
                client.close();

                Serial.println(F("-------------------------------------"));
                jpglen -= bytesToRead;
            }
            imgFile.close();
            cam.resumeVideo();
            cam.setMotionDetect(true);
        }
    }
}

You are running a wireless TCP stack, an SD card interface, and a web camera with some sort of motion detection, on a less than $20 computer?  I think you should congratulate yourself and move on to the next project.

I believe you are asking too much to add more to it. At $20 a pop, I would think about adding another UNO if you really do want to add more functionality. Let the 2 talk via serial, with one processing the video, the other processing the wireless.  The TCP part uses a considerable amount of resources, both memory and processing power.


Arduino powered from motor shield and USB issue I am using an Arduino (Elegoo) Mega with Motor shield to drive a digital train set. The Motor shield is powered from a 12v 1.1 amp dc power supply and I have the Arduino plugged into my laptop via USB. I have an app which sends commands via serial to the mega which are then turned into commands for the train set and sent down the line.

When using this all of a sudden the main chip on my Arduino blew up and my Laptop seemed to blow a re-settable fuse shutting off instantly (It was dead for about 10-20 minutes then worked again).

Would this be because something caused power to get back through the Arduino to my laptop?

The railway will short from time to time if a locomotive derails for example.

I know there is a trace on the Motor Shield which prevents the shield powering the Arduino. I have now cut this although it says you only need to cut it if using over 12v.

Looking at pictures of the Elegoo Mega 2560 they use a "hash fill" for the pour on the tab of the regulator, not a solid fill, and zero vias to another dissipation layer on the reverse. While this may look more funky it provides only a fraction of the heat dissipation of a solid double-layer fill, meaning the regulator is more likely to overheat. Also because this is a Chinese clone the component quality will be lower (cheaper) meaning the regulator probably doesn't have proper thermal overload protection.

So it gets too hot too easily, and pop your Arduino is dead as the regulator fails "short" and 12V gets pumped directly into the rest of your Arduino.

Byebye Arduino, and byebye computer (fortunately temporarily in the case of your computer).


How to expand program memory on an arduino? Sometimes I run out of space of the program size for the embedded C program that I want to put on an arduino. So what chip do I need to expand the program memory of the arduino so that I can use bigger C programs with my arduino?

An ATmega2560 is the chip to add for more memory when you run out of program memory on an Uno.  Referring to the Memory webpage at arduino.cc, you'll see that it has Flash=256KB, SRAM=8KB, EEPROM=4KB, where the ATmega328 chip on the Uno has Flash=32KB, SRAM=2KB, EEPROM=1KB.

When you run out of program memory on an Uno, you have about three choices that are practical:  make the program smaller; remove the bootloader (to free up one or two KB); use a different board with a more-capable processor.  The CPU on an Uno board doesn't have a way to access program bytes from places other than the on-chip 32KB flash.  The CPU on a Mega2560 board starts out with 8 times as much flash, so it can hold bigger programs than an Uno can.

If you remove the bootloader, you could instead program using a USBASP board, as described in a
“Program AVR chip using a USBASP with 10 pin cable” article at learningaboutelectronics.com.


Allocate object memory statically; intialize it dynamically? I have an object whose constructor gets passed a parameter. If I know the parameter value at compile time, I can construct the object statically:

static FOOOBJ foo(3);

(I understand that it isn't really done statically, i.e. by the compiler, but is actually done during setup).

But if I don't know the parameter value at compile time, I'd still like to pre-allocate space for the object but construct the object in that space at run time. Can it be done without a separate .initialize() method?

You can use placement syntax to specify an existing allocation in which to instantiate the class.

FOOOBJ foo(0);

 ...

  FOOOBJ *f = new (foo) FOOOBJ(3);


Pro Mini not communicating with computer when I try to upload blink program to my Pro Mini, I get this error:

avrdude stk500_getsync() not in sync resp=0x00

I've tried everything, changing the COM port, different USB cable and even another computer. Here is what I'm dealing with:

Arduino Pro Mini 328 5v 16M (Fake)

FT232RL USB to serial adapter

Nothing is connected to any pins on the Arduino, just trying to get LED to blink. I'm pretty sure the bootloader is installed, because when I hit the reset button, the LED blinks. I've tested the FTDI chip by connecting the TX and RX pins together, and it does echo in the serial monitor.
Help appreciated!

You did set the Serial Port and then tell the Arduino IDE that it's talking to a Pro Mini right?

This gets me every time I switch between my Nano & Uno.

On the main menu
[Tools]->[Board]=>"Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega 328"

I've also had this problem trying to use a longer USB cable, it just wouldn't work.  The stock cable (shorter) worked fine.


Nrf24l01 sending multiple signals I have 2 arduino nano and have setup them as a transmitter and reciever. I press a button on the transmitter and the reciever lights up the individual addressable LED sequence as programmed.

The issue is that when I release the button, the signal is sent 3 to 4 times even when the switch is open, this causes the LED sequence to run thrice before returning to the original state. I also tried to ads a delay to remove the bouncing but still no luck.

You are witnessing button bouncing. You need to incorporate a "button debounce" in your code. What is happening is when you press the button your code continues to loop (e.g. cycle). The Arduino detects the button is pressed every cycle. If your arduino has a 16 mhz crystal oscillator its means 16 Million cycles per second. Thats fast, much faster than you press and release the button.

There are number of why to solve this. One is using an interrupt instead of polling, but you will still need to incorporate a debounce.

Google Arduino Button Debounce.


Controlling an analog potentiometer using an Arduino I want to be able to control an analog potentiometer. I'd like to be able to go from the minimum range to the maximum range possibly using an Arduino and a motor/servo. I want to be able to control vintage equipment, so the knobs on the pot must still work. I want to be able to rotate both by hand and by sending  a (MIDI) signal.How would I go about doing this?

The first problem we have is that replacing the original potentiometer might be wrong thing to do. Analog audio hardware is usually nonlinear, because the volume of the sound is actually a logarithmic function. So the potentiometers might be fine tuned specifically for particular device, and impossible to acquire today since it's vintage.

I suggest a different approach. Connect the knobs to rotary encoders, or cheap linear potentiometers. That way you will receive data about what the user is doing, and what setting does he want to change. They usually are small and you might even fit an extra el-cheapo 28BYJ485V stepper motor to move the knobs to provide feedback. (It can be modified doubling it's torque)

Move all the audio potentiometers inside the case of the device and connect them directly to a stepper motor or a servo to move them only with Arduino.


How to communicate the Arduino board with SIM900? I have a problem. I bought a SIM900 board, but I can not connect there with the Arduino. To send AT commands on the serial the SIM900 doesn't respond, but the LED indicating that the network is on. I've tried to change the baud rate of 9600 to 19200 in the firmware of the Arduino, but it still fails. I think I'm having a problem with the connections of the SIM900, since this board strikes me as obscure (could not find the schematic on the Internet)

The board I have is identical to this:

I'm 90% sure that I am connecting to the wrong pins. But I tried to reverse the jumpers and even some soldered pins on UART.

I'll tell you what worked for me, because I didn't find the schematics of this board. But your board may work differently, so it is always good to check the datasheet and the schematic (if you have one).

Power

Be sure to use an external 5V source that can supply up to 2A without dipping significantly.

Code

#include <SoftwareSerial.h>

SoftwareSerial GPRS(7, 8);         //7 = TX, 8 = RX
unsigned char buffer[64]; port
int count=0;
int i = 1;                         //if i = 0, send SMS.
void setup(){
  //delay(10000);
  GPRS.begin(19200);               // the GPRS baud rate
  Serial.begin(19200);             // the Serial port of Arduino baud rate.
  Serial.print("I'm ready");
  Serial.print("Hello?");
}

void loop(){
  if (GPRS.available()){         // if date is comming from softwareserial port ==> data is comming from gprs shield

    while(GPRS.available()){          // reading data into char array
      buffer[count++]=GPRS.read();     // writing data into array
      if(count == 64)break;
    }
  Serial.write(buffer,count);            // if no data transmission ends, write buffer to hardware serial port
  clearBufferArray();              // call clearBufferArray function to clear the storaged data from the array
  count = 0;                       // set counter of while loop to zero
}

if (Serial.available())            // if data is available on hardwareserial port ==> data is comming from PC or notebook
  GPRS.write(Serial.read());       // write it to the GPRS shield
  if(i == 0){
    GPRS.print("AT+CMGF=1\r"); //sending SMS in text mode
    Serial.println("AT+CMGF=1\r");
    delay(1000);
    GPRS.print("AT+CMGS=\"+554988063979\"\r"); // phone number
    Serial.println("AT+CMGS=\"+554988063979\"\r");
    delay(1000);
    GPRS.print("Test\r"); // message
    Serial.println("Test\r");
    delay(1000);
    GPRS.write(0x1A); //send a Ctrl+Z(end of the message)
    delay(1000);
    Serial.println("SMS sent successfully");
    i++;
  }
}

void clearBufferArray(){              // function to clear buffer array
  for (int i=0; i<count;i++){
    buffer[i]=NULL;                  // clear all index of array with command NULL
  }
}

Connection

Testing...

Open the serial monitor Arduino, set the baud rate in 19200 in "Both NL & CR". If not work, set to "Carriage Return". Type "AT" and wait for an OK.

Help

If you need help, these links were useful to me:

http://www.seeedstudio.com/wiki/GPRS_Shield_V1.0
http://www.seeedstudio.com/wiki/GPRS_Shield_V2.0
http://www.elecfreaks.com/wiki/index.php?title=EFCom_GPRS/GSM_Shield


ESP8266 Web Server Crash + Arduino IDE I am working on HTTP GET Request. I have created ESP wifi as web server. It creates a access point with IP address : 192.168.4.1
When my android app is connected to web server, it sends values every 50ms on 192.168.4.1/R"VALUE". Value is integer type (0~1023). Example :- 192.168.4.1/R546

However, it is working fine when I send values every 1s, but esp crashes, when IP is hit every 5ms second. I have captured the crash detail on serial monitor. Attaching the file and code as well. Kindly help.

#include <ESP8266WiFi.h>
#include <EEPROM.h>
#include <ESP8266WebServer.h>

#define RED_LED     12

WiFiServer server(80); //Initialize the server on Port 80

char myTestUrl[100];

void setup()
{

  EEPROM.begin(512);
  Serial.begin(9600); //Start communication between the ESP8266-12E and the monitor window

  WiFi.mode(WIFI_AP); //Our ESP8266-12E is an AccessPoint
  WiFi.softAP("LED_Downlight1", "12345678"); // Provide the (SSID, password); .
  server.begin(); // Start the HTTP Server

  IPAddress HTTPS_ServerIP = WiFi.softAPIP(); // Obtain the IP of the Server
  Serial.print("Server IP is: "); // Print the IP to the monitor window
  Serial.println(HTTPS_ServerIP);
}

void loop()
{
  WiFiClient client = server.available();
  if (!client)
  {
    return;
  }

  String request = client.readStringUntil('\r');
  //Serial.print(request);

  request.toCharArray(myTestUrl, 100);

  char *Red = strstr(myTestUrl, "/R");
  if (Red)
  {
    int RedValue  = atoi(Red + 2);
    analogWrite(RED_LED, RedValue);
    Serial.print("Red: ");
    Serial.print(" ");
    Serial.print(RedValue);
    Serial.print("\n");

    int SetRedValue = (RedValue / 4);
    EEPROM.write(0, SetRedValue);

    EEPROM.commit();

    Serial.print("Red Memory Write :");
    Serial.print(" ");
    Serial.print(SetRedValue);
    Serial.print("\n \n");

  }
}

I've worked with ESP8266 to create a centralized network over which different devices could communicate. In my first iteration I used an ESP8266 as an AP and let other ESP8266s connect to it. This didn't work for longer than 5 minutes. I suspected the ESP8266 couldn't handle many connections for a long period of time and bought an USB WiFi router. Now, I connected all ESP8266 to the WiFi router, including the ESP8266 that I set up as server. And it worked.

In other words: the ESP8266 isn't strong enough to be an AP and communicate a lot of data at the same time. Instead, you'd rather like your ESP connect to an existing wireless network with other devices and let those devices connect to the IP of the ESP.


simultaneously read 16 hall sensor and maximum current allowed by Arduino My question is about maximum current allowed by Arduino.

I know it's 200mA in Arduino and 40mA in every pin (lower in arduino mini). Just wondering if simultaneously read 16 hall sensor (than can be all activated at the same time) is too much.
My calculation is 200 / 16 = 12.5 mA máximum current I can drive to a pin from a sensor, but it's enough to read the sensor? Specs from 3144 hall sensor says it outputs 25mA when activated. Can I put a resistante between output's sensor and Arduino pin?

I'm planning to use Arduino mini and sensor hall 3144.

Sorry for my english, and thanks in advance!

p.s: The original idea was read all 64 sensors with one Arduino, but breaking it into several arduinos is easiest as my electronics knowledge is seriously limited :)

Since this sensor doesn't need to be driven directly from a pin, the maximum current for one pin is not important here. The hall sensor uses two of it's pins as supply voltage. The output pin is an Open-Collector pin. So it will be connected to GND trough a transistor depending on the magnetic field. If you use an external pullup resistor (as connection between OUTPUT and positive supply voltage), you get somewhat like a voltage divider. Since the hall sensor seems to behave as a switch, there will only be two possible states. When the magnetic field is low, the transistor doesn't let the current flow. The pullup resistor can pull the pin to the positive supply voltage (5V -> 1 as digital value). If the magnetic field is high enough, the transistor will open the connection to GND. Now a maximum of 25mA of current can flow throw it to GND. The voltage of the pin is now determined by the voltage divider the transistor and the pullup resistor build. You can calculate the virtual "resistance" of the transistor in this state with Ohm's law

  R = U/I

(R is resistance, U is voltage and I is current) With 5V supply voltage and 25mA current you get a resistance of 200 Ohm. Since you just want to use the sensor as a switch, you only have to ensure, that the pin cannot be pulled to a significantly greater value than 0V. So grab a resistor, that is significantly higher than 200 Ohm and use it as pullup resistor. Keep in mind, that you always must use the pullup resistor with the supply voltage, that runs the Arduino. A higher voltage can fry the Arduinos components.

Then you connect this pin to a digital pin of the Arduino, which you configure as INPUT. In this state the pin has a high impedance, so that the current, that flows into it, is really small (it CAN source 25mA, but it does not have to. The current depends on your external circuit). So this isn't something you have to bother about.

This leaves us with the supply current, that the sensor needs to work. In the datasheet it says, that at a supply voltage of 8V the supply current is at maximum 9mA. For 16 sensors this gives us a total of 144mA, which is still comfortable inside the 200mA the Arduino can provide. So you should be able to drive all of them safely.

That said, if you want to add more components, that draw current, it might be better so source the current you need not over the Arduino but directly from your power source (if this is possible for you). Depending on the current you may need, it can also be good, to get an external voltage regulator (if your supply doesn't directly give you 5V), that can provide enough current.


Unexpected result with the GSM module A6 I have a GSM A6 module, like this one.

I'm going to use an Arduino Nano as a bridge to communicate with it, I have an external power source (since I read that this module can consume up to 2A at its maximum consumption) (this power supply shares the GND with the module and the Arduino) and I upload the following code in the Nano:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11);

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and A6
  mySerial.begin(115200);

  Serial.println("Initializing...");
  delay(1000);

}

void loop()
{
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

I set the baud rate at 115200 of my SoftwareSerial port (connected to 10 and 11 pins on the ArduinoNano) because (even if the module says that it has auto-detect speed hability) doesn't work if I set the speed at 9600 (or any other), and I modified the SoftwareSerial library for expand the buffer from 64k to 512k (trying to solve this problem) following this page instructions (also: NICE WORK in this page!!!).

And it works ... it works relatively well, I mean:
The AT commands to test (according to the datasheet itself) are AT and ATI (in one I recieve "AT /r OK" and the last one give some usefull information like the OS and other things), and they work, only they do not show me the same answer always, I leave screenshots:

As you can see, the answers are not always exact, there is some garbage characters, and I need them to be exact, because my idea is to create a kind of alarm, in which the Arduino (One, Nano or Mega) sends and receives AT commands. I worked with the SIM900 module before and always received the same answer when I sent an AT command.

So... any help?!

Apparently the SoftwareSerial library have some limitations, so I change the baudrate communication in the moduel ussing this sentence:

  AT+IPR=9600

And change the code that I upload to the Nano, changing the baudrate speed in the declaration, from:

mySerial.begin(115200);

to

mySerial.begin(9600);

And now all is well :D


Newbie question: Set servo at certain degrees when something happens I am trying to set my servo at f.e. 90 degrees when the friendlyValue of the soil sensor is < 50%. The servo isn't moving at all, is it because the code is running too fast and the servo doesn't have time to reposition in between? I tried putting in delays but that didn't work, how do I fix this?
I am new to Arduino and would appreciate any help.

#include <Servo.h>
Servo myservo;

int dryValue = 1024; // max
int wetValue = 0; // min

int friendlyDryValue = 0; // %
int friendlyWetValue = 100;

int sensor = A0;
int sensorValue;

void setup() {

  Serial.begin(115200);

  pinMode(A0, INPUT);
  pinMode(D6, OUTPUT);
}

void loop() {

  int rawValue = analogRead(A0); // soil sensor

 Serial.print("Raw: ");
  Serial.print(rawValue);
  Serial.print (" | ");

   int friendlyValue = map(rawValue, dryValue, wetValue,     friendlyDryValue, friendlyWetValue);

  Serial.print("Friendly: ");
  Serial.print(friendlyValue);
  Serial.println("%");

if (friendlyValue <50)
{
  myservo.write(9);
  }
  else
  {
    myservo.write(90);
    }
  }

From your statement pinMode(D6, OUTPUT);, It looks you're using pin6 for the servo - ? If so, you need instead: myservo.attach(6); to prepare a servo object to use that pin to drive a servo. Not having done this is the reason why your servo wasn't moving. There is an example program to drive a servo using the servo library on the Arduino site.

Your code will run very fast, but since soil moisture can't change rapidly, the value being read from the soil sensor shouldn't either - unless there is electrical noise (and there will always be some; it's a question of how much). Your print statements should show you how consistent the readings are.

There are a couple of things you can do about it:

Delay for a second or so at the bottom of the loop() function so the servo updates will come less frequently and the servo will have time to track them. This really doesn't help with a noisy signal though, and you probably don't want it to track noise. Also, I don't usually suggest using delays but in so uncomplicated a program as this one, it is really the most straightforward approach.
Calculate the servo position from an average of a few sensor readings rather than using just one. This will help with noise so the servo should only have to track real data rather than data+noise.
Do both. Update less frequently and average a few readings taken a few 10s of milliseconds apart. This will both reduce noise and keep the servo updates to within its tracking ability.


Is it possible for Arduino as ISP board to flash an ISP master board? I have a setup of 2 Arduino Leonardo boards. Let's refer to them as Board A and Board B.
Board A is a master SPI board that is constantly communicating via SPI to an array of sensors. At some point, board A will need to be flashed with a new sketch.  That's where Board B comes in.
I want to use Board B go use an Arduino as ISP sketch to go and flash a new sketch onto board A. Problem is that Arduino as ISP uses SPI, which conflicts with the code on board B since board B is a master device communicating to other sensors via SPI.
Is it possible for board B to flash board A via ISP?

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

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