text:
I am trying to control 4 servos with a joystick, but after a few seconds, they start spinning and don't stop until the power source is cut
Here's my code. I don't know if the issue is the power source though. I only have access to my computer for a power source.
#include <Servo.h>

Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;

int joyX = A2;
int joyY = A5;
int Joyx = A2;
int Joyy = A5;

int servoVal;

void setup()
{
  servo1.attach(A0);
  servo2.attach(A1);
  servo3.attach(A3);
  servo4.attach(A4);
}

void loop()
{

  servoVal = analogRead(joyX);
  servoVal = map(servoVal, 0, 1023, 0, 180);
  servo1.write(servoVal);
  delay(15);

  servoVal = analogRead(joyY);
  servoVal = map(servoVal, 0, 1023, 70, 180);
  servo2.write(servoVal);
  delay(15);

  servoVal = analogRead(Joyx);
  servoVal = map(servoVal, 0, 1023, 0, 180);
  servo3.write(servoVal);
  delay(15);

  servoVal = analogRead(Joyy);
  servoVal = map(servoVal, 0, 1023, 70, 180);
  servo4.write(servoVal);
  delay(15);
}

If you think it is a current limitation problem (power) try only controlling 1 servo (disconnect the other servos).  Also check you are using common servos and not continuous servos.

how are the joysticks connected? ... your code indicates that you may be shorting out your power supply

Why are you reading twice from each joystick acis (since joyx and joyX are defined with the same pin)?

... Ah! Nice catch @chrisl.

@jsotla I have the joystick connected to the A2 pin. I am quite a noob to this and would appreciate if you could explain what in my code could be shorting out my power :(

your code shows joyx and  joyX ... that indicates two joysticks ... both are connected to pin A2 ... if you turn one joystick to maximum and the other joystick to minimum, then that provides a low resistance path between Vcc and GND through the common connection at A2


text:
SD Card Initialization Failed, cannot add inactive module
Just to preface I am not that great at coding or anything and I am currently building sensors off of Oregon State University's Smart Rock sensor code, so the code I am being used is not mine. I am currently operating off their 2.5 and 2.5.1 Firmware as the code and every piece of the device works properly except for initializing an SD card, which continuously gives me the error of:
[Factory] Creating: SD
[SD] Initialize failed
[Device] Cannot add inactive module

I have attempted this in many different boards with different SD cards and the issue remains the same, so I am inclined to think the issue is within the firmware. Is there anyone who could potentially guide me in the right direction on this or determine where the issue is coming from. I will respond quickly. I am using a Feather m0 Adafruit board and a Hypnos V3.1 board. Here is the serial monitor report when running this code, just to add, I am only seeking to fix the SD card issues:
Initialized Serial!

= = = = = Parse Config = = = = =

Config Pretty Version:
{
  "general": {
    "name": "Device",
    "instance": 1
  },
  "components": [
    {
      "name": "Analog",
      "params": [
        8,
        12,
        true,
        false,
        true,
        false,
        false,
        false,
        5,
        0,
        4,
        0,
        0,
        0
      ]
    },
    {
      "name": "SD",
      "params": [
        true,
        1000,
        10,
        "data",
        true
      ]
    },
    {
      "name": "DS3231",
      "params": [
        11,
        true,
        true
      ]
    },
    {
      "name": "Interrupt_Manager",
      "params": "default"
    },
    {
      "name": "Sleep_Manager",
      "params": [
        true,
        false,
        1
      ]
    },
    {
      "name": "MS5803",
      "params": [
        119
      ]
    }
  ]
}
SIZE: 949
= = = = = Generate Objects = = = = =

[Factory] Creating: Analog
[Device] Adding Module: Analog
[Factory] Creating: SD
[SD] Initialize failed
[Device] Cannot add inactive module
[Factory] Creating: DS3231
[DS3231] Current Time (before possible reset)
[DS3231] Time: 2021/7/21 23:42:44
[DS3231] Time: 2021/7/21 23:42:44
[DS3231] Clearing DS3231 alarms
[Device] Adding Module: DS3231
[Device] Adding Module: InterruptManager
[Factory] Creating: Sleep_Manager
[Device] Adding Module: SleepManager
[Factory] Creating: MS5803
Oversampling setting: 512
C0 = 0
C1 = 0
C2 = 0
C3 = 0
C4 = 0
C5 = 0
C6 = 0
C7 = 0
p_crc: 0
n_crc: 0
[MS5803_0] Initialize failed
[Device] Adding Module: MS5803_0
= = = = = = = = = = = = = = = = =

[Device] Config:
    Device Name         : Device
    Instance Number     : 1
    Device Type         : Node
    Interval            : 1000
[Device] Modules:
    Others
        [+] InterruptManager
        [+] SleepManager
    Sensors
        [+] Analog
        [+] MS5803_0
    RTCs
        [+] DS3231
[InterruptManager] Registering ISR on pin 12 to be triggered on 0 and is immediate

 ** Setup Complete **
[Device] Json:
{
  "type": "data",
  "id": {
    "name": "Device",
    "instance": 1
  },
  "contents": [
    {
      "module": "Packet",
      "data": {
        "Number": 1
      }
    },
    {
      "module": "Analog",
      "data": {
        "Vbat": 0.012891,
        "EC[0]": 357.7055,
        "turbidity[2]": 2471
      }
    },
    {
      "module": "MS5803_0",
      "data": {
        "pressure": 0,
        "temp": 20
      }
    },
    {
      "module": "LocalTime",
      "data": {
        "Date": "2021/7/21",
        "Time": "15:42:44",
        "TimeZone": "PST"
      }
    }
  ],
  "timestamp": {
    "date": "2021/7/21",
    "time": "23:42:44"
  }
}

Any help would be appreciated! I'm sorry if the formatting is wonky I'm very new to this.

Guessing, by any chance, are you using SDCards formatted by a Microsoft machine?  Try a new from the factory SDCard which is likely formatted traditionally with partition tables.  For what ever reason, Microsoft may have left that off their list of important things to do.

Also you might look here where several people with different problems are discussing SDCard Arduino issues.

This "Cannot add inactive module" has me stumped.  Make sure all you software is up to date including any supporting software like Arduino libraries and board support.

Adding on to the first comment, Make sure that your SD card is not a high capacity version or one that is formatted(use as comes from factory) these factors may be causing you trouble. If you did format it, format it again with a different file allocation table

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
how can I program my sound sensor and pir motion sensor in 1 arduino uno
int pirPin=2;
int buzzerPin=12;
int soundSensor = 19;
int LED = 3;
int statusSensor=0;
int pirVal=0;
void setup()
{
Serial.begin(9600);
pinMode(pirPin, INPUT);
pinMode(soundSensor, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(LED, OUTPUT);
}
void loop()
{
pirVal=digitalRead(pirPin);
if(pirVal==HIGH)
{
Serial.println("Motion Detected");
digitalWrite(buzzerPin,HIGH);
delay(150);
digitalWrite(buzzerPin, LOW);
}
else
{
digitalWrite(buzzerPin, LOW);
 }
statusSensor = analogRead(soundSensor);

  if (statusSensor == 1)
  {
Serial.println("Sound Detected");
digitalWrite(LED, HIGH);
delay(100);
digitalWrite(LED, LOW);
}
  else
  {
    digitalWrite(LED, LOW);
  }
}

Please align your code (select code, press ctrl-k) and align { and } blocks,  what is currently wrong/not according to your expectations? what do you expect?

I expected to run both of them at a time

And what exactly it is not doing now? (we cannot look at the result or expect us to create the circuit you built to check it). How should they interact with each other?

Is your sound sensor analog or digital?

@EmanAli, the body of the question should have more than just the code.  It should also explain your problem.  Remember, the goal is to have a collection of questions and answer that everyone can later use.  If you make an effort to create a good question, then everyone with a similar question will benefit.

First of all there is no pin with pin number 19 (as you defined a soundSensor on it), and there is no problem you can use my sound sensor and pir motion sensor in 1 arduino uno.
But in order to do that please use millis instead of delay so that your arduino doesn't wait to read reading of other sensor during the reading of first sensor.
Here is a link which shows how to use arduino for multitasking..
https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Serial Monitor Not Displaying
I am using BMP 280 for an altimeter to measure the altitude. Once all connected and uploaded the BMP280test code from Adafruit, the serial monitor says busy. But still, when I switch the port in tools, nothing shows on the serial monitor. How do I get the monitor to start displaying data?
Thanks
Code:
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_BMP280.h>

#define BMP_SCK  (13)
#define BMP_MISO (12)
#define BMP_MOSI (11)
#define BMP_CS   (10)

Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

void setup() {
  Serial.begin(9600);
  Serial.println(F("BMP280 test"));

  if (!bmp.begin()) {
    Serial.println(F("Could not find a valid BMP280 sensor, check wiring!"));
    while (1);
  }

  /* Default settings from datasheet. */
  bmp.setSampling(Adafruit_BMP280::MODE_NORMAL,     /* Operating Mode. */
                  Adafruit_BMP280::SAMPLING_X2,     /* Temp. oversampling */
                  Adafruit_BMP280::SAMPLING_X16,    /* Pressure oversampling */
                  Adafruit_BMP280::FILTER_X16,      /* Filtering. */
                  Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */
}

void loop() {
    Serial.print(F("Temperature = "));
    Serial.print(bmp.readTemperature());
    Serial.println(" *C");

    Serial.print(F("Pressure = "));
    Serial.print(bmp.readPressure());
    Serial.println(" Pa");

    Serial.print(F("Approx altitude = "));
    Serial.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */
    Serial.println(" m");

    Serial.println();
    delay(2000);
}

Start simple.  Assuming you are using an Arduino Uno and running on a Win10 machine.  Since you are having problems with talking to the Arduino over the serial port forget about the pressure sensor and this pressure sensor application.  Start with a simpler Arduino program which only talks over the serial port.  Try this or this.

"the serial monitor says busy" - what does that mean? And what do you mean with switching ports?

@chrisl, being sarcastic? It's pretty clear he is talking about com ports. "The serial monitor says" is talking about the serial monitor in Arduino ide (ctrl + shift + m). He obviously has multiple com ports available on his PC and doesn't know what com port represents the usb-serial on his uno. Sounds to me either something else is holding up the com port, or maybe he doesn't have the right drivers loaded: maybe a clone with the ch340 usb-serial chip?

@TimStewart Nope, not being sarcastic. While the topic is clear, I wanted a detailed description of what the OP did exactly. Of course you can write an answer to this question. Me finding the question not clear enough is just a subjective view.


text:
Deepsleep ESP8266 Thing
I have been trying to get my ESP8266 Thing to go to sleep. Power LED has been disconnected. Problem is that the current consumption is initially (briefly) ~78 uA, but nearly always jumps up to ~540 uA for the remainder of the sleep duration. See below. It's as though something is waking up when it shouldn't. Has anyone else experienced this? Any ideas or suggestions?
Thanks in advance :)

#include <Ticker.h> // Ticker can periodically call a function
Ticker blinker; // Ticker object called blinker.

int ledPin = 5; // LED is attached to ESP8266 pin 5.
uint8_t ledStatus = 0; // Flag to keep track of LED on/off status
int counter = 0; // Count how many times we've blinked

void setup()
{
  pinMode(ledPin, OUTPUT); // Set LED pin (5) as an output
  blinker.attach(0.25, blink); // Ticker on blink function, call every 250ms
}

void loop()
{

}

void blink()
{
  if (ledStatus)
    digitalWrite(ledPin, HIGH);
  else
    digitalWrite(ledPin, LOW);
  ledStatus = (ledStatus + 1) % 2; // Flip ledStatus

  if (counter++ > 20) // If we've blinked 20 times
    ESP.deepSleep(60000000, WAKE_RF_DEFAULT); // Sleep for 60 seconds
    //ESP.deepSleep(60000000); // Sleep for 60 seconds
    delay(10);
}

If I'm not mistaken, the longest ESP8266 sleep time is only in the minutes (far less than an hour).  So, is saving about 500 uAmps between wake-ups add up to much when compared to the average current over, say, an hour?


text:
led chaser fill color effect
Please help. I am learning a lot about Arduino. Most all in lightning. I am a newbie. I play with nano and LED ws2812 and use fastled library.
What ask is to make effect like fill effect. For example with larson scanner/chaser.
for (int i = 0; i<NUM_LEDS; i++)
{
  leds[i]=CRGB::Red;
  FastLED.show();
  leds[i]=CRGB::Black;
  delay(50);
}

From that code above how to make LED stop and lit up and loop again and stop and lit up.  I want every LED stop the LED lit up even LED looping start again from first LED. It like this:

10000 01000 00100 00010 00001 10001 01001 00101 00011 10011 01011
  00111 10111 01111 11111

I really don't understand your problem description. It seems, that English is not your native language. Maybe you can write a better description or ask someone to help you with it. We need to understand the problem, to be able to help you.

Agree w/@chrisl, there is no "I have this problem" in the post. Assuming you are not seeing a lit LED traveling down the line of LEDs, try swapping the "delay" line of code w/the line above it.

yes you right, iam not native english,iam indonesia.. sorry for my bad english and wrong title.. :).. but thank you all for advice.. i already have answer from @michel keijzers..

You need two counter for this, one to keep track of how far the LED bar is filled, and one about the current 'running' LED to eventually 'touch' the LEDs which are already moved to the right.
Every led (currentLed) will run from index 0 until the last filled index, while the last filled index is decreased with 1 after every loop.
(note: I haven't checked the code).
// Fill from the right, thus count backwards.
for (int filledLedIndex = NUM_LEDS; filledLed >= 0; filledLed--)
{
   // Now let a LED run from 0 upto filedLedIndex;
   for (int currentLed = 0; currentLed < filledLedIndex)
   {
      // Make previous LED black
      if (currentLed > 0)
      {
         leds[i - 1] = CRGB::Black;
      }

      // Make current LED red
      leds[i] = CRGB::Red;

      // Show.
      FastLED.show();
      delay(50);
   }
}

// Clear all LEDs.
for (int led = 0; led < NUM_LEDS; led++)
{
    leds[i] = CRGB::Black;
}

FastLED.show();
delay(50);

thanks you a lot.. from your advice n little edit for my project and it finally work fine..


text:
Millis...alternate flash
I thought I had the Millis() command sorted but i'm stumped on the one. Aim is to get 2 led's alternately dimming, they work great with delay(); of course....but i can't figure where i'm going wrong with Millis().
Please have a look and point out what i've got wrong.
Thanks
Doug
int LED3 = 5;
int LED4 = 6;

// each "event" (LED) gets their own tracking variable
unsigned long previousMillisLED3=0;
unsigned long previousMillisLED4=0;

int intervalLED3 = 500;
int intervalLED4 = 500;

void setup() {
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);

      digitalWrite(LED3,LOW);
      digitalWrite(LED4,LOW);

}

void loop() {
  //unsigned long currentMillis = millis();
      for(int P=0;P<6;P++){
        //if ((unsigned long)(currentMillis - previousMillisLED3) >= intervalLED3) {
            analogWrite(LED3, 127);
            analogWrite(LED4, 254);
        delay(500);
              //previousMillisLED3 = currentMillis;

      //if ((unsigned long)(currentMillis - previousMillisLED4) >= intervalLED4) {
            analogWrite(LED3, 254);
            analogWrite(LED4, 127);
       delay(500);
             //previousMillisLED4 = currentMillis;
      }
}

Sorry, problems inputting code, but its all there.
I realize that there are some closing brackets missing in the LOOP() section for millis but it is set for delay() to show that it works.

Well, the for loop is useless. Then you need to plan your time cycle. For instance what you want is
time(ms)  LED3  LED4
   0       127   254
 500       254   127
1000 -> back to 0

So implement this. One way can be the one suggested by st2000:
int LED3 = 5;
int LED4 = 6;

// just one tracking, since there is only one sequence
unsigned long previousMillis=0;

int endOfPhase1 = 500;
int endOfPhase2 = 1000;

void setup() {
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);
    digitalWrite(LED3,LOW);
    digitalWrite(LED4,LOW);
}

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

    if ((currentMillis - previousMillis) < endOfPhase1) {
        analogWrite(LED3, 127);
        analogWrite(LED4, 254);
    }
    else if ((currentMillis - previousMillis) < endOfPhase2) {
        analogWrite(LED3, 254);
        analogWrite(LED4, 127);
    }
    else
        previousMillis += endOfPhase2;
}

Just a small note about this: I tend to prefer summing the period instead of setting previousMillis to millis because this way small errors do not accumulate.
This way is the simplest, but the state machine oriented is the one I suggest you, since it is more powerful and you will reuse this a lot of times. Moreover it will detect the "change" of state, thus avoiding the continuous analogWrite (in the previous code the analogWrite instructions are executed a lot of times).
Just define a state machine as two states (state 1, where LED3 is 127 and LED4 is 254, and state 2, where LED3 is 254 and LED5 is 127). The transitions will be after 500ms in each state, but I'll make two separate constants so you can trim them later. Usually each state has a function to be performed when you enter the state, a function to run continuously, a function when you exit and one or more transitions. The way to perform this is

calculate if there is a state change
if there is, perform the exit functions of the previous state and the enter functions of the next state
advance to the new state
perform the actions to be done continuously in the new state

In our case just state transition, enter and advance should be implemented. Usually you use a switch case on a variable holding an index for the state. In this case, for instance,
int LED3 = 5;
int LED4 = 6;

// just one tracking, since there is only one sequence
unsigned long previousMillis=0;

int state1duration = 500;
int state2duration = 500;

uint8_t state;

void setup() {
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);
    digitalWrite(LED3,LOW);
    digitalWrite(LED4,LOW);

    state = -1; // Invalid state, used to force a transition at startup
}

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

    // Check the transition
    uint8_t nextState = state;
    switch (state)
    {
    case 1: // Transition for state 1
        if ((currentMillis - previousMillis) >= state1duration)
        {
            nextState = 2;
            previousMillis += state1duration;
        }
        break;
    case 1: // Transition for state 2
        if ((currentMillis - previousMillis) >= state2duration)
        {
            nextState = 1;
            previousMillis += state2duration;
        }
        break;
    default: // When unknown state, go to state 1
        nextState = 1;
        break;
    }

    // If there is a change, perform the enter functions
    if (nextState != state)
    {
        switch (nextState) // enter functions of the next state
        {
        case 1: // Entering state 1
            analogWrite(LED3, 127);
            analogWrite(LED4, 254);
            break;
        case 2: // Entering state 2
            analogWrite(LED3, 254);
            analogWrite(LED4, 127);
            break;
        }
    }

    // Advance to the new state
    state = nextState;
}

This can be more complicated, but believe me, it is not. Once you get what this means you will be able to solve a lot of problems this way.
According to my experience, never try to simplify this to your particular problem, since it will make things more complicated. Just add, when needed, the exit functions (before switch(nextState) put another switch on state) and the execution (after the advancing, put another switch on state) if needed.

Thanks Guys.
Firstly, the FOR loop was an attempt to execute the cycle a number of times, but even if that worked I had the wrong approach with millis(). I will use the simpler example at this stage but will study the longer version to see if i can get a better grip on it. I have inserted an increment [count = (count+1);]into the phase2 IF statement and added a counter [if (count == 1000) //return to main program] at the end to exit.
This now satisfies my coding question.
Thank you for you input.
Doug

You are trying to use millis() exactly like delay().  The method delay() stops the program from progressing forward.  It blocks the program.  This is frowned upon as the processor could be doing something useful during this time.
The method millis() does not stop the program.  Instead it is like telling you what time it is.  It is your code that then need to know at what time you want to do something.
But in your code, you are doing something odd.  You are switching the brightness of the LEDs then IMMEDIATELY switching them back.  You are using the same time for the two things you want to do.  Instead try to initialize previousMillisLED4 to 500, intervalLED3 to 1000 & intervalLED4 to 1000.

The final sub routine...I did move the counter to get a better result. The variable "ditchFlag" is set in an IF statement further up in the sketch.
The duration of the subroutine is a combination of the timers and the number in "count".
void ditchDim() {
while (ditchFlag == 1) {            //set to 1 when conditions are met

unsigned long currentMillis = millis();

if ((currentMillis - previousMillis) < endOfPhase1) {
    analogWrite(LED3, 127);
    analogWrite(LED4, 254);
}
else if ((currentMillis - previousMillis) < endOfPhase2) {
    analogWrite(LED3, 254);
    analogWrite(LED4, 127);
}else{
  count = (count+1);
    previousMillis += endOfPhase2;
    }
      if (count == 5) {
        count = 0;
        ditchFlag = 0;
        return;
    }
  }
}

thanks
Doug

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

authors: امیرحسین کریمی


text:
Is it possible to move a servo without knowing it's current position?
My Servo has already been built into my project, and I can't remove it without damaging many other things. During the process of inserting it, it was turned by hand. So I don't know at what position it is in. It turns a potentiometer that doesn't rotate fully. So I'm worried that if I just set a degree it could turn too far and damage the potentiometer or the servo.
What should I do to find the current position? Is it even possible?

Your final question is quite different from the title one. Yes, you can command an RC hobby servo without knowing its position, but no, you cannot move it relative to the current position if you do not know the PWM width that put it at that position, or where that position is within its range of movement.

A normal servo is an absolute positioning device. The position of the servo is directly proportional to the length in time of the sync pulse.  This means if you tell the servo to be in a given position, it will seek that position with out regard to the initial position.  It will simply figure out which way to go on it's own and stop when it gets there.
I should add, that in all likely hood, when you manually moved the servo you moved the positioning potentiometer inside the servo.  So it is expected that if the servo is told to go to a particular angle, it will still go to the same angle as it did before you manually moved it.

tahnks, that really helped me :D

Yes. Servo can rotate to a particular angle irrespective of previous position.
But you may face an issue here if you rotated the shaft manually by hand (when servo is not powered), and if you reassembled the shaft to the servo in a different orientation. Actually it is really hard to re assemble a removed shaft to the same angle position.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
qsort is not really sorting
I'm working with Arduino and getting some strange errors. qsorting is not sorting correctly.
//using this libraries
#include <ESP8266WiFi.h>
#include <inttypes.h>

//the red struct is

typedef struct {
    int32_t rssi;
    int id;
} red;

//Here is my compare function
int compare (const void * a, const void * b)
{
  yield();
  red *redA = (red *)a;
  red *redB = (red *)b;
  //Serial.printf("redA->rssi: %d, redB->rssi: %d\n",redA->rssi,redB->rssi);
  //Serial.flush();

  return redA->rssi > redB->rssi ? 1 : (redB->rssi < redA->rssi ? -1 : 0);
  //return ( redB->rssi - redA->rssi );
}

void showNetworks(){
  int n = WiFi.scanNetworks(false,false);
  red listOfRedes[n];

  for (int i = 0; i < n; i++) // ...initialize it
  {
    yield();
    listOfRedes[i].rssi = WiFi.RSSI(i);
    listOfRedes[i].id = i;
    Serial.printf("%d: RSSI%d\n", i, listOfRedes[i].rssi);
    Serial.flush();
  }
  Serial.printf("salio\n");
  Serial.flush();
  qsort (listOfRedes, n, sizeof(red), compare);
  Serial.printf("ordeno\n");
  for (int i = 0; i < n; i++) // ...initialize it
  {
    yield();
    Serial.printf("%d: RSSI:%" PRId32 "\n", listOfRedes[i].id, listOfRedes[i].rssi);
  }
}

and this is the output i get
0: RSSI-69
1: RSSI-65
2: RSSI-72
3: RSSI-50
4: RSSI-60
5: RSSI-87
6: RSSI-87
7: RSSI-79
8: RSSI-80
9: RSSI-88
10: RSSI-74
11: RSSI-77
12: RSSI-78
13: RSSI-83
14: RSSI-79
15: RSSI-60
16: RSSI-85
17: RSSI-86
18: RSSI-66
19: RSSI-88
20: RSSI-80
21: RSSI-74
22: RSSI-81
23: RSSI-87
salio
ordeno
4: RSSI:-60
1: RSSI:-65
0: RSSI:-69
3: RSSI:-50
18: RSSI:-66
15: RSSI:-60
2: RSSI:-72
10: RSSI:-74
11: RSSI:-77
21: RSSI:-74
19: RSSI:-88
20: RSSI:-80
22: RSSI:-81
23: RSSI:-87
12: RSSI:-78
5: RSSI:-87
6: RSSI:-87
7: RSSI:-79
8: RSSI:-80
9: RSSI:-88
13: RSSI:-83
14: RSSI:-79
16: RSSI:-85
17: RSSI:-86

As you can see the sorting is not OK and I don't get why.
Thank you in advance and sorry for my poor English.

Thanks st2000 i did not know how to formatt it

Don't use qsort, use std::sort.

In your program there is this line of code:
  return redA->rssi > redB->rssi ? 1 : (redB->rssi < redA->rssi ? -1 : 0);

Which appears to return a 1 if A is greater then B other wise it will return a 0.  This code can not tell the difference between A < B and A == B.  Consider altering this line of code to allow returning 1 for A > B, 0 for A == B and -1 for A < B:
  return redA->rssi > redB->rssi ? 1 : (redA->rssi < redB->rssi ? -1 : 0);

can't belive i did that.... like.... for hours..... thank you men, i'm an idiot....

I didn't see it for a while either.  Glad I could help.


text:
Controlling a servo motor with a touch sensor
I want to modify my code to move a servo motor only for the duration of time that the sensor is touched and stop moving immediately when the sensor is no longer touched. The code I have moves the sensor from 0 to 90 and back.  That motion is completed even when you remove your finger. I want it to be such that if you remove your finger before the servo reaches 90 degrees the servo stops.  And the servo starts up again toward 90 when touch resumes. This is the code I currently have:
//when signal output is high the sensor is being pressed

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
int pos = 0;    // variable to store the servo position
int sensor=11; //initialises component to arduino digital pins
led=13;

void setup() {
        myservo.attach(9);
        pinMode(led,OUTPUT);
        pinMode(sensor,INPUT);
        Serial.begin(9600);
}

void loop() {

        int value=digitalRead(sensor);
        if(value == HIGH){
                digitalWrite(led, HIGH);
                for (pos = 0; pos <= 90; pos += 1) {
                        myservo.write(pos);              // tell servo to go to position in
                        variable 'pos'
                                delay(15);                       // waits 15ms for the servo to reach the
                        position
                }
                for (pos = 90; pos >= 0; pos -= 1) { // goes from 90 degrees to 0 degrees
                        myservo.write(pos);              // tell servo to go to position in
                        variable 'pos'
                                delay(15);
                }
                Serial.println("TOUCHED ");
        }else{
                digitalWrite(led, LOW);

                Serial.println("NOT TOUCHED ");
                delay(500);
        }
}

You could test the button in the for loop, while the servo is moving. Bail out of the for loop with 'break' if the button is released. When you do that and add more things to the sketch, the code becomes harder to maintain. Another option is rewriting your sketch and use millis, start with the example: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

Leonardo, what I recommend you do is non-blocking "cooperative multitasking". Start with the "Blink Without Delay" tutorial @Jot pointed you to. I've written a few more-advanced examples here: https://stackoverflow.com/questions/50028821/best-way-to-read-from-a-sensor-that-doesnt-have-interrupt-pin-and-requires-some/50032992#50032992 and here: https://arduino.stackexchange.com/questions/75932/calculating-amp-hrs-of-a-solar-panel/75937#75937. You can study my code to see how I do it. Side note: this is the start of building a scheduler, which results eventually in a basic operating system.

To solve your problem, you need to take a tiny step into real time programming.  Most Arduino programs deal with one issue or action at a time.  Your simple twist to interrupt and action "i want it to be such that if you remove your finger before the servo reaches 90 degrees that's where the servo stops" requires you to continuously monitor your input (touch switch) while changing your output (next servo position).
You can go about this 2 ways.  You can use interrupts to inform you when the state of the touch switch changes. This is challenging.  Many find it difficult to conceive of what might happen if their program were to be interrupted at any and all possible points in its execution.  A mistake here can lead to unexpected results.
Or you could take turns polling the state of the touch switch then making a small adjustment in the position of the servo.  When the state of the touch switch changes from active to not-active, exit the loop you are using to change the servo position.


text:
How did I burn out this ESP8266 unit?
ESP8266 -> FTDI -> USB Mac
I followed the wiring on this page: http://williamdurand.fr/2015/03/17/playing-with-a-esp8266-wifi-module/

I was communicating with it via Serial at 115200.  I issued a AT+UART_DEF=9600,8,1,0,0 and a few seconds later I looked over and it was smoking.

I bought 2 of these.  The previous one I had wired to an Arduino Nano running through a logic level converter.  That one only returns Exception (28) over and over again after issuing that same command.
On both units AT+GMR returned:
AT+GMR
AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0

Are these units too hard to use? What did I do to burn it out?
[UPDATE]
Answer given was that I fed it 5v instead of 3.3v. Obvious. I didn't think I did but I checked the output of the FTDI and sure enough it was 5.1v.  So why does the output on it say 3V3 ?  I thought that meant that it was 3.3v...

Should have checked it first.

You supplied 5V to a device that only takes up to 3.6V. Heat generated by the excessive power did the rest.

I'm checkmarking you cause obviously you are correct.  But I hope to also get an answer to why 3V3 doesn't mean 3.3V?  Why not label it as VCC or +5V instead of 3V3 if it's not 3 volts?

The easy answer is that you have a defective FTDI device. It should be 3.3V, but clearly it is not.

Also, the FTDI device likely does not supply enough current on the 3.3V rail to run the ESP8266 module to its full potential regardless; you should get a separate 3.3V regulator and connect it to that.

I bought these but they say 150ma on the back.. http://www.amazon.com/XCSOURCE-Converter-Bi-Directional-Module-TE291/dp/B0148BLZGE?ie=UTF8&psc=1&redirect=true&ref_=oh_aui_detailpage_o02_s00

Those are level shifters, not voltage regulators.

It sort of defeats the purpose of having a small wifi unit if you need a separate power supply or regulator for each of them.  In my project I already ahve 12v going to my nano and rfid reader, a 5v regulator going to a relay and some PIR sensors. And now I need another 3.3v regulator going to this. These power requirements are annoying.

I was only using the FTDI to test and set up the wifi module. In my project it will be wired to the nano. Is there a small regulator that can take 12v and give me 5v and 3.3v out at the same time.

A few, but they won't really save you any money over a separate 3.3V LDO linear regulator. Also, consider running the Nano on 3.3V as well (although there are a few caveats about that, which you can find by searching the site).

What about this: http://www.amazon.com/Qunqi-MP1584EN-Step-Down-Adjustable-Converter/dp/B014Y3OT6Y?ie=UTF8&psc=1&redirect=true&ref_=ox_sc_sfl_title_1&smid=A12MRQC2NA7LMA

Those will work, but keep in mind that a AMS1117-3.3 or equivalent (for dropping the 5V to 3.3V) costs a very small fraction of one of those modules.

Also I found the answer and posted it here as well.  Thanks!

I checkmarked Ignacio's answer because it was correct.  But I wanted to leave an answer also as to HOW I supplied 5v when I thought I was supplying 3.3v.  Maybe it will help someone else.

The backside of this FTDI module has a jumper to select 3.3 or 5v and the default is set to 5v.  I needed to cut the default trace line connecting to 5v and solder my own jumper to switch it to 3.3v.  I should have double checked the voltage before powering it up.  New ESP01's on order.


text:
Implementing an external ADC in Arduino
I'm planning to use a ADS1220 4-channel 24 bit adc but I really have no experience with SPI. I have found this library but I can't really understand the code that much and also this is measuring the differential voltage. I want to use this for my accelerometer (x, y and z data) but I can't seem to find how to do read from 3 channels, and I can't understand the code in the library :( I've also found a video for this adc in youtube but he didn't used it for multiple channels. I'm sorry for asking this, I'm just pressured since the deadline is really soon.
EDITED

sketch
#include "Protocentral_ADS1220.h"
#include <SPI.h>

#define PGA 1                 // Programmable Gain = 1
#define VREF 3.3
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)

volatile byte MSB;
volatile byte data;
volatile byte LSB;
//volatile char SPI_RX_Buff[3];
volatile byte *SPI_RX_Buff_Ptr;

long int bit32, data1, data2, data3;
long int bit24;

Protocentral_ADS1220 ADS1220;

void setup() {
  pinMode(ADS1220_CS_PIN, OUTPUT);
  pinMode(ADS1220_DRDY_PIN, INPUT);

  ADS1220.begin();
  //ADS1220.Single_shot_mode_ON();
}

void loop() {

  byte *config_reg;

  data1 = aRead(0x81);
  data2 = aRead(0x91);
  data3 = aRead(0xA1);

  Serial.print(data1);
  Serial.print("    ");
  Serial.print(data2);
  Serial.print("    ");
  Serial.println(data3);
  delay(500);

}

long int aRead(uint8_t config_byte) {
  ADS1220.writeRegister(CONFIG_REG0_ADDRESS , config_byte);
  uint8_t r = ADS1220.readRegister(CONFIG_REG0_ADDRESS);
  //Serial.println(r,HEX);

  ADS1220.SPI_Start();

  while (ADS1220.NewDataAvailable == false) {
    SPI_RX_Buff_Ptr = ADS1220.Read_Data();
  }

  if(ADS1220.NewDataAvailable = true) {
    ADS1220.NewDataAvailable = false;

    MSB = SPI_RX_Buff_Ptr[0];
    data = SPI_RX_Buff_Ptr[1];
    LSB = SPI_RX_Buff_Ptr[2];

    bit24 = MSB;
    bit24 = (bit24 << 8) | data;
    bit24 = (bit24 << 8) | LSB;

    bit24= ( bit24 << 8 );
    bit32 = ( bit24 >> 8 );
  }

  return bit32;
}

I tried to use the above sketch and I successfully read from 3 different channels but I noticed that the readings vary too much, compared to the example code. In the example code when I turn my potentiometer full CW, it outputs 8388607 which is correct right? since it is signed int.
But when running this sketch, the image below shows the output when the potentiometer is fully CW. Also turning the potentiometer fully CCW leads to negative values (shown in the 2nd picture) but in the example code, it gives 100-300 decimal values.  Also these are the configuration registers I sent in registers 1-3 (I edited it in the part of the library) and for register 0, it is on the sketch.
Config_Reg1 = 0x00;
 Config_Reg2 = 0x40;
 Config_Reg3 = 0x00;

using accelerometer
format is (x,y,z)

What kind of deadline? School project or assignment?

Writing ADC driver code from scratch is NOT easy.  What is wrong with the ADC built into most Arduino's processors?  The ADC driver for most Arduino's is already part of the Arduino SDK.

What's the model number of the accelerometer? Many of them digitize their results already.

@MikaelPatel it's for my thesis in college

@jwpat7 adxl335, this has analog outputs, my adviser wants to have a 24 bit output accelerometer, I know there are lots of accelerometer that has 16 bit output which is already enough for precise measurements but I wanna give a try implementing an external adc before suggesting to my adviser to use accelerometers with digitized outputs

To get an understanding of how to read from the various ADS1220 channels, first review Figure 38, Analog Input Multiplexer, in the Datasheet as obtained from a link on TI.com's ADS1220 technicaldocuments webpage.

As can be seen, you'll need to close a switch from an AINx input line to the AINₚ bus, and also close the switch between AINₙ and AVSS.  The IDACx switches and the BCS switches should remain open.
To operate those switches, first look at §8.6.1, Configuration Registers, in the Register Map section of the Datasheet.  You'll see that MUX bits are in register 0, BCS is in register 1, IDAC is in register 2, and IxMUX are in register 3.  To see what to put into those fields, look at Tables 16, 17, 19, and 20.  For the MUX field, you will want a binary value like 1000, 1001, 1010, or 1011 to select one of AIN0-AIN3 as the AINₚ input and AVSS as the AINₙ input.  BCS, IDAC, I1MUX, and I2MUX all should be zero.
For example, to read channels 0, 1, 2 in sequence, set MUX to 1000, set up other register fields, and trigger a conversion.  After reading the result, change MUX to 1001, trigger a conversion, read result,  change MUX to 1010, trigger a conversion, read result, etc.

Edit 1: In slightly more detail, one could do as follows.

• Use a WREG command [as in §8.5.3.6; or some library equivalent] to send three bytes to set up Configuration Registers 1, 2, 3.
  • For i=0, 1, and 2 in turn, construct a configuration byte, send that byte to Configuration Register 0, start a conversion, await result, read result; as follows:

Set the MUX field of a byte to i
    Set PGA as desired (ie, to 1, 2, or 4, via codes 000, 001, or 010)
    Set the PGA_BYPASS bit (as required when AINₙ = AVSS)
    Use a WREG to send the constructed byte to Configuration Register 0
    Use a START/SYNC command to start a conversion (see §8.5.3.2)
    Wait for DRDY to go low
    Use an RDATA command to read iᵗʰ ADC result (see §8.5.3.4)

Edit 2: In Protocentral's ADS1220.ino sketch, one finds the code sequence
  MSB = SPI_RX_Buff_Ptr[0];
  data = SPI_RX_Buff_Ptr[1];
  LSB = SPI_RX_Buff_Ptr[2];
  bit24 = MSB;
  bit24 = (bit24 << 8) | data;
  bit24 = (bit24 << 8) | LSB; // Converting 3 bytes to a 24 bit int
  bit24= ( bit24 << 8 );
  bit32 = ( bit24 >> 8 );     // Converting 24 bit two's complement to 32 bit two's complement

More competently and concisely, and with SPI_RX_Buff_Ptr renamed to SPI_RX_Buff, this could be written as:
  bit32 = (((long)(SPI_RX_Buff[0]<<8 | SPI_RX_Buff[1])<<8 | SPI_RX_Buff[2])<<8)>>8;

which acts as follows:  Assemble three bytes from SPI_RX_Buff into a 24-bit twos-complement-signed number.  Shift that number left 8 bits so that its sign bit now sits in the sign bit position of a 32-bit signed integer.  Shift that result 8 bits right with sign extension so that the final result is a signed 32-bit integer with possible values from -2²³ up to (2²³-1).
Sign extension occurs – usually – because in many implementations of C, the >> operator does an arithmetic shift instead of a logical shift when its operand is signed.

I just read this and it made me understand the datasheet, thank you so much!! I'll just update you if I was able to make it work

hello I'm wondering what would I send first when I want to read the data. I found this youtube video and he started with setting CS to low (which I think I should also do in my case) then sends a byte which is equal primary byte with a start bit and single/diff mode and to a register mask that isolates 3 LSB. I'm sorry if I'm noob but it would mean a lot to me if you help

I'm guessing I should send all those 4 configuration registers? I just don't know the flow I'm sorry

oh I get it why he and it with a mask, just to be sure that the config register will not be changed during the process, now my main concern is how to send these configuration registers

Edit 1 reflects my understanding (from datasheet) of the process - I haven't tried it out, and haven't looked at what library calls might apply

thank you so much for the fast reply, I'll figure this one tomorrow since its 4 am already but I did a quick scan and now I can at least understand the library already, really appreciate your help! I hope I can do more than saying thanks because your did really help me a lot with the information you gave!

hello I just continued following what you wrote and looking for the commands written in the library, also in your edited line did you mean for the gain in this line Set PGA as desired (ie, to 1, 2, or 4, via codes 000, 001, or 010) ? as I've read in the datasheet the commands corresponds to the gain. I was also a bit confused in the library on the reading of data part.

It is written on line 235, why did he used a loop in reading the data and in the example extracted the data buffer in line 58 do I also need to read the value like this? and also he sent SPI_MASTER_DUMMY which is equal to 0xFF. In the datasheet RDATA command is like this 0001 xxxx, does this mean that the x's are considered 0? so when I read for data I should send a command byte of 0001 0000 and loop it again for the other channels right?

Only gains of 1,2,4 are available for single-ended input, and their codes are 000, 001, 010 in the gain field, which is above the PGA_BYPASS bit in the config byte.  The for loop at line 243 in Protocentral_ADS1220.cpp loops 3 times to read all 3 data bytes of result.  As noted in SPITransfer at arduino.cc,  “SPI transfer is based on a simultaneous send and receive”; if sent data is irrelevant, dummy it.  In 0001 xxxx each x is a don't-care, so can be anything. §8.5.4 says  “An RDATA command does not have to be sent”  after DRDY goes low.

okay thanks again for the help, so I would stick to the library with the for loop in reading right? I'm still a bit confused with the dummy thing, what does it mean if send data is irrelevant? but basically I'll get my reading with the code inside this function right? uint8_t * Protocentral_ADS1220::Read_Data() since it checked for the DRDY to go low so no need for RDATA command

I also have a question in the pin configuration, does AVSS go to ground?

You may need to experiment some with that library.  It uses some 100 μs delays (before dropping CS) that appear unnecessary  and it may improperly depend on delays instead of busy-waiting on flags.  It also uses an if statement instead of a while to check if DRDY is low, rather than busy-waiting for DRDY to go low.  ¶  AVSS is analog low-side voltage (see Pin Functions table, page 4 of specs), typically ground, but some people like to  keep it separate from digital ground DGND.  ¶  Do some web searching for "Analog ground", "busy wait", etc.

hello I tried the library already and it's working, I also added an external reference successfully. I just wanna clarify what you wrote at the top, in my case I should always write a configuration byte to Register 0 right? does this also mean I should change my conversion mode into single-shot? so that every time I write the config byte then I'll start a conversion with the START/SYNC command? the wait for DRDY to go low and read the data, then another configuration byte to the next channel and so on..

Yes, that's my understanding of what you need to do.

hello sorry to bother you again but if you don't mind, please take a look at the edited part. thank you so much!

I'll look at it more later this week - no time ATM - after setting up on a channel try several readings in a row before going to next channel to see if readings settle in

no luck, i tried reading only one channel in single shot mode, still same result. it maxes out at 83875xx and -9xxx as minimum reading

Though I  think depending on my application, i don't really reach the minimum and maximum values since I have -/+3g accelerometer for measuring vibration and it's unlikely for it to reach more than -/+1g. I am having doubt though on the values I'm getting using the accelerometer, I added it at the top. The values should reflect 0g on x and y axis and 1g on z axis. For example I am only getting the +8388608, the value for 0g should be expected to be half of it (between 0-+8388608 = 4194304) but it seems like it's far than that. Also ow can I get the whole 2^24 = 16777216 analog levels?

I asked how to get the whole 2^24 levels since I don't really understand the code above for bit24 and bit32 variables

i actually tried to convert these values to g values and it pretty much does the job!! i got precise measurements now really thanks a lot to your help!!!! and Merry Christmas by the way!

See edit 2 regarding  code with variables bit24 and bit32.   ¶ If the library code turns out to be too slow, there are a dozen or two unnecessary delay(2)'s and delay(5)'s and delayMicroseconds(100)'s egregiously scattered around in Protocentral_ADS1220.cpp.  You probably can remove most of those, or change all the 2's and 5's to 1's, etc

authors: Александр Юферев


text:
Low current in a motor used in a line following robot
I'm trying to make a line following robot for my students, the problem is that I have not done any calculations (I don't know how).
The motor can't move the robot unless I connect it directly to the 9 V power supply, but when i connect the other compenents(arduino) in parralel to the same 9v powersuply the motor doesn't get enough current when put on the floor so it just freeze's.
Where do you think should i start ?
The transistor I used is: NPN C1815
the motor is a brushed dc motor

9V power supply as in PP3 battery?

yes a 6F22 general purpose 9v battery

Does the motor have any form of gearbox?

@Majenko i added a photo of the motor to the post

Make your life easer next time.  Use 2 continuous servo motors instead of 1 regular motor and 1 regular servo.  The continuous servos are as easy to interface (directly to an Arduino) as a servo.  Then drive & steer your robot like a tank (left and right throttles).

You should not use a 9v battery for a motor project - it lacks the power to deliver voltage under load.  Additional, were it actually to deliver 9v it would destroy a typical hobby servo, which is intended for 4.5v - maybe 6v.  You are also missing the base resistor on your drive transistor.

Noticed that there is no base resistor between transistor and Arduino output pin, you may have blown the transistor and/or output pin, if not try a 1K.

@ChrisStratton do you mean that because the battery is 9v thats why it lacks power ? more volts less power !! i don't understand what you meant.
for the transistor base i used a 1k resistor i forgot it just on the schematic, for the servo i'll use a voltage divider

i used a 1k resistance i forget just in the schematic

Most 9V batteries have 6 AAAA batteries inside. Those are relatively small batteries, and can therefor not supply a lot of current. They will also deplete very fast. A 9V battery has 1/5th the capacity of an AA. My suggestion would be to use 4 AA batteries. You have special holders for 4 AA batteries.

@Gerben 4x AA will give 6volts? That's already on the limit for the Arduino Uno input voltage. I've used a 9.6V 2300mAh rechargable pack (https://www.conrad.nl/nl/nimh-accupack-96-v-2300-mah-conrad-energy-stick-tamiya-stekker-206671.html) which is great since it can supply 1C (2300mA) for one hour. Or run 300mA the whole day (8 hour) and it's rechargable. And the voltage is 9.6V so it can power the motors directly and the Arduino through regulated input. So I think such a 9.6V 2300mAh pack is very well suited for use in school. Though you really shouldn't short it out!

@Paul. 9V > 6V! Though 6V is probably on the low side for the regulator to work properly. You could use rechargeable AAs, which would give around 4.8V. PS nowhere in the question it's said that the motor is actually a 9V motor!

No! A 9v pack with meaningful current capacity will destroy that servo unless the circuit is changed to place a moderately high power regulator in front of it.  Hobby servos as made to run on 4 NiCd or Alkaline cells, or in some cases 5 NiCd (even 5 brand new alkalines could be risking damage).  Also the sensor pullups should really go the Arduino's regulated voltage, not the raw batter voltage.

ok i solved this using gears, and two separate power sources (9v transistor radio battery)
i also used a 1.5 amp transistor for driving the motor
thanks everyone

You seem to have ignored most of what was said.  Do not use 9v "transistor" batteries for motors - not one of them, not two of them.  Do not power a hobby servo from 9v.

What is a 1.5 amp transistor?

@ChrisStratton i did use a voltage divider for the servo, and i used one 9v low current battery for the motor and a 9v for the arduino, thats what i have in hand, i also changed the transistor to another one with a max Ic current of 1.5 ampere! i didn't ignore anything of what was said i hope, (i'm in a remote area, if i buy the proposed battery it will take about a month to arrive, by then students will be at holydays..

Voltage dividers are not appropriate for power unless feedback controlled. Feedback controlled voltage dividers are called linear regulators.  You should not use lithium batteries for such a project, nor 9v, just get ordinary AA's.

ok @ChrisStratton thank you very much for the information about voltage divider, i've never heard of Feedback controlled voltage dividers, i'll do a search about it and i will buy AA's because i can find them easily. thanks again

I should have added that, when using the 9V battery, only the motor can be driven directly from it. The servo should have a regulated source (5V is okay). I'm not sure if the Arduino can provide enough current for the servo, but it will do I guess.

Due to only a tiny amount of gearing (what is it - 2:1? 3:1? something like that) your motor is operating near the stall point unless it is able to pick up enough speed (at which point it would smash into the nearest wall and pulverise itself).
Consequently it is drawing far more current from the battery than you'd like.  And that is, without the Arduino connected, about all the puny little PP3 battery can provide.  Add the Arduino etc into the mix and you are over-stepping your current budget by enough to mean the motor cannot start turning (the 1A stall current).
So what to do? Well, two options:

Use a bigger battery.
Increase the gearing of the motor.
(my personal recommendation) Do both.

Increasing the gearing of the motor will decrease maximum output speed, increase the torque, and most importantly, decrease the start-up current. The whole load on the motor will be reduced making it much easier to start.
By increasing the power of the battery (use a 2S or 3S Li-Ion depending on what your motor's voltage limits are) you have a much bigger current budget to play with.

ok, thank you sir, i will give your recommandations a try


text:
What is a flag in programming Arduino?
I have seen many tutorials on programming an Arduino to control a HC-05 bluetooth module. In that I did not understand the term called 'flag'. What does that mean?

And what is the context of this word?

"Flag" is usually a feature that you can turn on or off. The "flag" is the variable that you need to use to do that. But as Majenko stated, with no context, it's just a guess I am taking here.

I've always used flag to indicate a boolean logic value. I would also suggest this is an archaic term.
Was going to come up with my own explanation but found the following at In C language, what does flag mean?:

A 'flag' is a variable that is supposed to signalize something. Think
  about the word itself - flags are used in sending signals. In our
  world of programming a basic boolean flag can either be "up" or
  "down", either true or false.


text:
How do I send a string from an Arduino Slave using SPI?
I have an Arduino Uno acting as a master with 3 Arduino Nano's acting as a slaves.
Looking at this example:
http://www.gammon.com.au/forum/?id=10892, it tells me how to send a string from the master to the slave, but I didn't see any examples sending a string from the slave to the master device. I was able to successfully send and receive digits to/from the master and slave, but I couldn't figure out how to send strings from the slave to the master based on the example.
My understanding is that SPI communications can only send information byte by byte, so am I supposed to convert my string into a byte format before putting that into the SPDR variable so that it can be sent back to the master?
In any case, would I be able to get some pointers on how to send strings from the slave to the master?
Thanks in advance.

Remember the master controls the transmission (provides the clock), however it can be done. For example:

Master
// master

#include <SPI.h>

void setup (void)
{
  Serial.begin (115200);
  Serial.println ("Starting");

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

void loop (void)
{
  char buf [20];

  // enable Slave Select
  digitalWrite(SS, LOW);
  SPI.transfer (1);   // initiate transmission
  for (int pos = 0; pos < sizeof (buf) - 1; pos++)
    {
    delayMicroseconds (15);
    buf [pos] = SPI.transfer (0);
    if (buf [pos] == 0)
      {
      break;
      }
    }

  buf [sizeof (buf) - 1] = 0;  // ensure terminating null

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.print ("We received: ");
  Serial.println (buf);

  delay (1000);  // 1 second delay
}  // end of loop

In this example the master initiates a transmission by sending 0x01 to the slave. Then it gets bytes back until a 0x00 byte (signifying the end of the string). The delayMicroseconds is there to give the slave time to respond.

Slave
// Slave

void setup (void)
{

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= bit(SPE);

  // turn on interrupts
  SPCR |= bit(SPIE);
}  // end of setup

volatile char buf [20] = "Hello, world!";
volatile int pos;
volatile bool active;

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;

  if (c == 1)  // starting new sequence?
    {
    active = true;
    pos = 0;
    SPDR = buf [pos++];   // send first byte
    return;
    }

  if (!active)
    {
    SPDR = 0;
    return;
    }

  SPDR = buf [pos];
  if (buf [pos] == 0 || ++pos >= sizeof (buf))
    active = false;
}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{

}  // end of loop

The slave does everything inside the ISR. The arrival of the 0x01 byte makes it reset its "pointer" to the start of the buffer. After that it responds with another byte from the buffer until it has reached the terminating 0x00 byte.

In part of sender I'm use the convert String to char array method before sending to the receiver.
Master
#include <SPI.h>
const int size_arr = 50;  // define array size (must be less than size of slave)
char buf[size_arr]; // define char array, use for convert from string for send to slave
String main_dat = "jack,12,47,123,8888"; // real String data

void setup() {

pinMode(SS, OUTPUT);
digitalWrite(SS, HIGH);
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV4);

}
void loop() {
main_dat.toCharArray(buf, size_arr); // convert String data to char array
Spi_tranmis(buf); // send char array
delay(500);

}

void send_spi(byte pram) {

  digitalWrite(SS, LOW);
  SPI.transfer(pram);
  digitalWrite(SS, HIGH);
  delayMicroseconds(50);

}

void Spi_tranmis(char buf[]) {
for (int i = 0 ; i < size_arr ; i ++) {
  send_spi(buf[i]);
}

send_spi('\n');
}

And in part of receiver i'm use char array receive from master and convert to String leter.
Slave
#include <SPI.h>

const int size_arr = 51; // define array size (must be more than size of master)
char buf[size_arr]; // char array , use for recive from master

volatile byte pos = 0;
volatile boolean process = false;

String msg; // real data

void setup() {
   Serial.begin(9600);
   Serial.println("test");
   pinMode(MISO, OUTPUT);
   digitalWrite(MISO, LOW);
   SPCR |= _BV(SPE);
   SPCR |= _BV(SPIE);

 }

 ISR(SPI_STC_vect) {
  char c = SPDR;

  if (pos < sizeof buf) {
    if (c == '\n') {
      process = true;
    }
     else {
      buf[pos++] = c;
     }
   }
 }

void loop() {
  recvHandle();

}

void recvHandle() {
  if (process) {  // when SPI available
    msg = String(buf);   // convert char array to String
    Serial.println(msg);
    process = false;
    pos = 0;
  }

}

You must define size of char array in receiver more than sender *

How do I send a string from the an Arduino Slave using SPI?

Depending on your definition of string it would look something like this (for master):
String message = "....";
SPI.transfer(message.c_str(), message.length() + 1);

or
char message[MESSAGE_MAX];
strcpy(message, ....);
SPI.transfer(message, strlen(message) + 1);

For the SPI slave this will need to be transformed to either an SPI ISR or busy-wait for chip-select and then the transfer.
Cheers!

String is only array of char ended by char \0. But you can also access it as array of bytes ended with 0. And send them by one byte until it reaches the 0 (send it too). On master you save it to long enough  array of char (work with it as with bytes) including the final zero and bingo, you have char string transmitted :)


text:
Help! My motors are not working!
I have made a project using Arduino, 3 LDRs and a L293D motor driver shield. My project was that when I block light from the first LDR, the motor will spin. When I block light from the second LDR, the motor will spin in opposite direction, and when I will block light from the third one, it will stop. The code had no errors and I expected it to work... But no luck. When I blocked light from the first or second LDR, the motor only made a faint "zing-zing" type of sound. Why is this happening? Is this a power problem? But I have connected 2 9v batteries to the shield and the Arduino. Please help! Here is the code I used-
#include (AFMotor.h)

const int LDR1 = A0;
const int LDR2 = A1;
const int LDR3 = A2;
const int LightIntensity = 150;
int SensorReading1 = 0;
int SensorReading2 = 0;
int SensorReading3 = 0;
AF_DCMotor motor(1);

void setup(void)
{
  pinMode(LDR1, INPUT);
  pinMode(LDR2, INPUT);
  pinMode(LDR3, INPUT);
  motor.setSpeed(255);
}

void loop()
{
  SensorReading1 = analogRead(LDR1);
  SensorReading2 = analogRead(LDR2);
  SensorReading3 = analogRead(LDR3);

  if (SensorReading1 < LightIntensity)
  {
    motor.run(FORWARD);
  }

  if (SensorReading2 < LightIntensity)
  {
    motor.run(BACKWARD);
  }

   if (SensorReading3 < LightIntensity)
  {
    motor.run(RELEASE);
  }
}

Please Specify What Motors You Are Using. I Would Recommend Using A 12v Battery Or A Wall Adapter That Gives More Current. Also I Would Recommend Using Servos As They Are Much Less Trouble and Work Off Relatively Low Current. You Can Make Them Run When Something Is Sensed. This Will Make Your Circuit Use Less Power. You Can Get Small Servos For Like 5 Bucks That Will Do The Job. There Would Be No Need For A Shield. But if You Insist On Using Your Current Motors, Use Something Like A 12 Volt 7.5 Ah Battery (Thats What I Use). It Will Last Longer and Provide More Current. Also I Would Recommend

You have not said what you motor is and that normally has a big bearing on the answer, but I think your problem is you need more power.
A 9V battery doesn't actually give you much current, you would be better off with a 'wall wart' aka a mobile phone charger.  The higher the amps the better normally, particularly with motors.  Try and find one that can put out 5Volts at 1Amp (assuming you have a 5V motor).
Also make more use of Serial.println() to show you what your program is doing.  If you had debug statements in the LDR if statements then you would know the switches are working.


text:
Troubleshooting an Arduino Computer Program
I am trying to make a serial monitor print something based on when a button is pushed.
When the button is not pushed, the variable storing it equals 1.
When the button is pushed, the variable equals 0.
When I have an if statement like this, why does it print what I want when I have one where the zero is, but not when it is like that and the button IS pressed.
Thanks
int led = 2;
const int buzzer = 3;

int upButton = 5;
int downButton = 7;
int enterButton = 6;

int up = 1;
int down = 1;
int enter = 1;

bool homeActivated = true;
bool appsActivated = false;

int homeLocation = 1;
int appsLocation = 1;

bool homePrinted = false;
bool appsPrinted = false;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode (upButton, INPUT);
  pinMode (enterButton, INPUT);
  pinMode (downButton, INPUT);
  Serial.println("Initializing");
  delay(2000);
}

void loop() {
  up = digitalRead (upButton);
  enter = digitalRead (enterButton);
  down = digitalRead (downButton);

  //move up and down
  if (up = 0)
  {
    if (homeActivated = true)
    {
      homeLocation + 1;
      Serial.println("Scrolled Down 1");
      delay(1500);
      homePrinted = false;
    }
    else if (appsActivated = true)
    {
      appsLocation + 1;
      Serial.println("Scrolled Down 1");
      delay(1500);
      appsPrinted = false;
    }
  }

You need to learn basic C syntax.
= is assignment, not comparison.
For comparison you use ==

https://www.tutorialspoint.com/cprogramming/c_operators.htm

That explains a lot. Thank you so much. Thank you again, I wouldn't have figured that out. I am new to Arduino programming.


text:
ADC pin shutting off on its own under certain condition
A0 pin not working when full PV system in use
I am using the DFRobot Leonardo with Xbee R3. I am using the A0 pin to read a 0-5V voltage from my voltage sensor, which samples and steps down 130VDC from a solar panel, in parallel to 0-5V for my Arduino to read.
Album with all relevant images
PV Array is 7 Panels in Series, Vpeak 18.7V Apeak: 11.23A

When the PV system is in open circuit mode (not connected to the grid), A0 can read the voltage without any issues and output's it into my serial monitor.
When the PV system is connected to the grid, A0 seemly shut's itself off and i no longer get any serial output. Testing with multimeter shows that the A0 pin is still getting a voltage in the range of 0-5V.
My assumption is that when a load is applied to the system, either A0 shuts itself down to protect the board for some reason, or the current is not flowing through the voltage sensing circuit due to it's higher resistance.
Current sensor is a 0-20A ACS712 board.

The analog pin can not “shut down”. It makes no sense. What can happen is that your Arduino shuts down (e.g. for lack of power) or your program locks itself inside an infinite loop (a bug). You may want to blink the onboard LED in your main loop() just to confirm your program is still running. Also, the information you provide in the question is not enough to help you: everything looks correct. You should provide a complete schematic and post a Minimal, Complete, and Verifiable example for the software side.

Definitely not a lack of power as i am connected to my laptop's USB port for data and power.
Program is still running, data is being recorded, shown on serial monitor and sent to a datalogging server (ThingSpeak) https://gyazo.com/a17799f90fa1f17ad59848350a9c9183

Does the laptop and the circuit share a common ground?

You wrote in the question: “i no longer get any serial output” and then in your comment: “data is being [...] shown on serial monitor”. This seems like a contradiction. Please clarify.

Sorry for the confusion. My serial monitor prints both Voltage and Current readings from my sensors every 0.5secs. When the system is not connected to the grid (i assume no load) the serial monitor shows my voltage value e.g 130V, which is verified by multimeter testing. However, when i do connect the system to the grid, serial monitor will show the voltage value as 0V. When i disconnect the grid again (i assume removing load) serial monitor starts showing the correct voltage value again.

@Code Gorilla I'm not too sure, but the ground of my sensors is connected to the GND pins on the Arduino board, USB that connects Arduino to Laptop has GND as well

Please add more information to your question to clearly define the question you are asking.

If you remove the current circuit that goes into A0 and replace it with a potentiometer, does that then read the analog voltage correctly?

@sa_leinad A0 can successfully read analog voltage using a 1k pot. The issue i am facing is that A0 will stop reading analog voltage when the PV system that i am monitoring is connected to the grid.
When it is not connected to the grid, i have no issues with A0 reading analog voltage

Your wording is causing confusion. Your analog pin never shut off. Your Arduino never stopped reading the analog voltage. It is reading zero, which is very different from not taking any reading. 2) Yours looks like a ground problem. Your connection to the grid is linked to earth's ground. If your laptop is being powered from its PSU, it is linking the Arduino GND with earth's ground. Your circuit may end up having too many grounded nodes. You should post a complete and accurate schematic.

@EdgarBonet Your mention of grounding might be the issue at hand now that i think of it. Completely amateur when it comes to EEE so i may have got it wrong. I have updated the imgur ablum in the original post with a better schematic as you requested.
The voltage sensor design has the negative input connected to GND as denoted by the wire below the sensor in the diagram

Went through my designs again, noticed that i have my PV negative connected to common ground for all my sensor modules and arduino. Could this be the issue? Will test and report back as soon as i get back in the lab.


text:
Serial Port Issues Elegoo Mac OX High Sierra
Edit:
Unfortunately the question that has been linked to my question does not answer my question. I have followed its instructions but it is a slightly different issue. Any help on my question would be hugely appreciated:

Apologies but I am very new and trying to learn how to use the Arduino. I bought a starter kit from Elegoo the included an Arduino Uno (I think it is a knock off and no the real thing?). I Have been trying to get the code to upload on to it and keep getting the following errors:

Sketch uses 2282 bytes (7%) of program storage space. Maximum is 32256 bytes. Global variables use 212 bytes (10%) of dynamic memory,
  leaving 1836 bytes for local variables. Maximum is 2048 bytes.
  avrdude: stk500_recv(): programmer is not responding avrdude:
  stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

So I know that that my iMac is recognising the Arduino but I am still not able to upload any code to it. I have spent hours trying work around solutions I have found on the internet or Elegoo have sent me.
I have three questions. Firstly if I just buy a real Arduino from Arduino (I had not realised I was being sent an imitation) will this solve my problems?
Secondly, if not can anyone recommend a work around that I would be able to implement? I am reasonably computer literate but not to the level of diving into the Terminal and inputting lots of code!
Thirdly, I am really struggling being a beginner with the instructions given by Elegoo, they are very badly translated and confusing. Can anyone recommend a way to learn the basics and complete some basic projects for a beginner. I am happy to pay for the tutorials if needed.

Possible duplicate of My Arduino isn't showing up on my computer. What should I do?

"So i know that that my iMac is recognising the Arduino " => How?

Ah hi! I followed the instructions in the question that got linked to my question. By going to About this Mac and then looking at the Hardware and the USB port and i can see under Communication device it says all the device information and then: Manufacturer: Arduino (www.arduino.cc)

And in the Arduino IDE, you have selected a programming port that looks like /dev/tty[something] ?

The Port i have selected is: /dev/cu.usbmodemFA131 (Arduino/Genuino Mega or Mega 2560)

The Programmer i have selected is: AVRISP mkII. Is that what you meant?

I don't know if i should have also said when i plug it in there is a constant green LED and a flashing yellow LED

I have also tried to fix the problem with this video that says it is for High Sierra. I get the same errors, although the yellow light does become constant while my Mac is trying to upload the code.


text:
Creating a Web Interface for ESP32
I am working on a project that involves moving various servos and lights and I need a good UI to work with the device. I've previously used Blynk, which worked very well but I didn't like some of the limits it has. My current code works with Blynk and I'd like to change it to a web server so it can work on any device without an app or internet connection.
Right now my esp configures itself as an access point and I can navigate to its IP address to get to my "hello world file" but after that I'm stuck. What really stumps me is getting the input from the interface that I make in HTML, I could fairly easily make an arrangement of buttons, sliders, and fields, that fits my need but how do I get the value of these as a variable in my arduino code?
I've seen some examples of code that are very simple essentially a couple buttons redirect to different web pages on the server and it takes these commands to assign a variable, but that seems kind of poor form, is there a better way, or how do I make that work with a complex interface with many buttons and switches.
I've heard of Jquery and Ajax but not familiar on how to make this work with Arduino code.

have you tried googling "ESP32 web server library"? What you need to do is implement a web server that gives you access to those controls.

I would highly recommend splitting it into two parts: back end (C++) and front end (JS). You'll probably want to connect to a router, so your clients, like a phone and laptop need not be on that AP hotspot w/o internet.
You first build an API with arduino using GET params to control, example pin values int level = server.arg("level").toInt(); analogWrite(2, level);, or whatever you need to do. Put that in a function called handlePin, and subscribe it in setup(): server.on("/pin", handlePin);. Then just add CORS to the server response: server.sendHeader("Access-Control-Allow-Origin","*"); and you can now hit it from any computer on the network. To test, just enter it's URL and some params into a browser URL bar; http://192.168.2.123/pin?level=512 to dim halfway.
Once you have the URLs working, the interface part is built completely separately using whatever tools you want. All you need to do is have your UI hit the API using simple ajax calls. As a quick and dirty example: Level:<input type=range id=val max=1024> <br> <button onclick="fetch('http://192.168.2.123/pin?level='+val.value)">update</button>
That's hows the pros do it, you just swap C++ for PHP or C# or whatever, and use any UI framework you want. Once you have the source of your client app ready, you can upload it to the SPIFFS of the ESP, but I find it easier to host and update system-wide on a "real" server.
If you don't want to write the UI code yourself, you can use node-red to make a quick and dirty "control panel", just like HTML but with drag and drop functionality (more or less). You still use the same API on the ESP, and you can use more than one system at a time; all the ESPs care about is hitting the right URL.

I could fairly easily make an arrangement of buttons, sliders, and fields, that fits my need but how do I get the value of these as a variable in my arduino code?

The same way a web server does! What you need to do is implement a web server on the ESP32. You will serve a page with the controls, and then that page must make a request back to the server which will then processes it and do whatever you program it to do.
There are two ways to do this:

Use a get/post form; send all the data at once
Something like ajax; each control sends data asynchronously


text:
Connect optocoupler 4N35 to Arduino Uno to control LED light strips
I want to use an Arduino Uno to control the LED light strips, based on the input signal from a robot controller. The robot controller sends a digital signal with "HIGH" of 24 V and "LOW" of 0 V.  I have thought of using an optocoupler between the robot controller and the Arduino to reduce the voltage from 24 V to 5 V, suitable for the Arduino pin.
Can I connect the optocoupler's emitter to the Arduino ground?
The LED strips work on 12V DC and at 2000mA. If I power the Arduino with 12V DC power source connected to the DC jack, can I give the power to the LED's also using the V-in pin of the Arduino?
Please look at my circuit and tell me where I went wrong and why?

I have attached an image of my circuit? ... Why are you asking us? Don't you know if you did or not?

why do you think that you went wrong?

Can i connect the optocoupler's emmitter to the arduino ground?

Yes. Don't forget to either enable the internal pullup on the GPIO pin or use an external pullup on the collector.

If i power the arduino with 12 V D.C power source connected to the D.C jack, can i give the power to the LEDs also using the V-in pin of the arduino?

Not at the current rating you are talking about, no. The header is only rated for 1A, and the diode on the barrel jack input is also rated for only 1A.  You would need to split the LED power off from the incoming power before it goes into the Arduino.
The way you have your MOSFETs wired at the moment is wrong. The moment you turn one on it will let the Magic Smoke escape. You are using them to short circuit the LEDs, which is very very bad.
Each one should be wired in series with the LED between the cathode and ground:

simulate this circuit – Schematic created using CircuitLab


text:
Serial Monitor appears unreadable characters

Hello
My serial monitor keep showing these unreadable characters. Anyone know what is going on? Many thanks!

maybe the data is binary, not ascii

Can you try a minimal example of Serial.begin(9600); Serial.println("Hello world!");?

@MaximilianGerhardt Hi yes one line of hello world appeared

Then start adding connections, components and code until the error shows up. Does connecting RX to the Arduino change anything?

@MaximilianGerhardt Yes connecting to RX looks normal but after connected ground to ground unreadable codes appear

Since the Serial connection to PC works correctly: Maybe you have changed the communication mode of the headset to 57600 baud like described on this site (though this is a wild guess)

It can have many reasons, but the most likely are:

You set the baudrate wrong
You set the stop/start bits wrong
You send wrong data
The cable is bad

It helps if you show your sketch(es), for sender/receiver and possibly your circuit.

Hi Michel thanks for your suggestions, these are my sketches and circuit: https://imgur.com/a/Ksg4w

It seems the baudrate is correct, start/stop bits is hard to see. Probably the date you send is wrong, you should check what happens in the Brains functions you call and what is returned (which is what you send).


text:
Problem in reading data from encoder with arduino
Hello guys I am trying to count the number of the steps of a stepper motor with an encoder (Avago heds).
I found an Arduino sketch to count that steps and display them on the console and I found online the scheme to connect that encoder to Arduino.
The problem is that the encoder returns as output only 0, even if I rotate manually the motor. I also tried to measure the voltage of the encoder with a voltmeter but the voltage does not change even if I rotate the motor.
That is the Arduino Sketch
Here some picture's of Arduino-encoder connections

P.S. The motor works because I tried it before
Thank you for help

What is the point of a stepper motor with an encoder? When you make 100 steps with the stepper motor, it has done 100 steps.

@Jot it can skip or something can exceed the holding torque, it also allows calibration on startup without a detectable home position or limit switches .

@ratchet freak you are right

I think the encoder @zzan has pick only outputs relative position information. So the argument of using this encoder to find home position may not work out.  2. Most design steppers to have more than adequate torque for an application so detecting slipping is not necessary. 3. There are much simpler ways to find home position such as end-stop switches found on 3d printers and CNC machines.

Additional thought, are you sure the shaft is rotating the encoder wheel?

Yes the encoder wheel is rotating. I am building a robot arm and I need the encoder to determine the steps to go in a position with the motors turned off

Is the encoder this one? https://www.robotdigg.com/product/893/1000-line-rotary-incremental-encoder-kit

yes, do you have any idea? @sa_leinad

try to use the oscilloscope to visualize the outputs of channel A &B

In my experience (industrial encoders and PLCs) when the output don't change when the motor shaft is rotated its usually one of the following:

The set screw connecting the motor shaft to the encoder that isn't tight,
broken wire (bad connection to the encoder) or
a bad encoder.

Your picture shows what looks like a cover over the encoder coupling to the motor.  Look and make sure that the encoder is actually rotating with the motor.
Then double check your connections.  If a DMM still shows no voltage changes (use AC range if turning the motor to show that the encoder output is pulsing).
If there is still no joy, its likely that the encoder is bad.


text:
ESP8266 - does it really have terrible wifi range by default?
ESP8266  - does it really have terrible WiFi range by default??
First time to try this module out and we're disappointed with the range.. as per our testing we can only get max 5m WiFi range line of sight (LOS) to our regular WiFi router (TPlink and other routers we tried)
LOS Distance (Test results based on RSSI):

at 6 meters NO CONNECTION
at 5 meters  -77
at 4 meters -70
at 1 meter -56
at 3 meters -59

We also tried using different WiFi Channel from 1-11
We also tried removing wifi password (no password) and WEP password
We tried also using different modes B G N
NO change ..
Are we doing something wrong here?  Or is this module just that bad?
Any solution not requiring hardware change? (because we already bought a lot)
here's our little module

Interestingly, I saw these guys test the module and it seemed to work well .. Could we have a fake chip?
https://www.youtube.com/watch?v=7BYdZ_24yg0
We have really hit a stumbling block. hope you guys can help

try to erase the flash with esptool to get rid of old WiFi setting, not compatible with SDK you currently use

Do you have a ground plane passing under the antenna? Ideally the antenna should hang over the edge of the board.

My ESPs can talk to my inside router from halfway down the block; something is wrong...

The very first thing I notice is that your WiFi antenna is shielded by the PCB. That is the antenna is placed right over the top of the ground plane of the PCB and your range is going to be severely limited.
You will notice on the NodeMCU design below that they have placed a PCB cutout where the antenna is located. In other pictures you can also see that the ground plane does not go past where the antenna starts.

On other boards the antenna sits proud of the main PCB such as this one from Tronixlabs:

If money is tight and new hardware is out, you could try cutting a cutout where the antenna sits using your Dremel (or other rotary tool). If there are any traces underneath the antenna you will need to fix them up with wire worms. Of course it is best to remove the ESP module first.
Alternatively, you could redesign the PCB and send it out for another manufacturing run. I use PCBShopper.com to find the best price for the bare PCBs.
Edit:
Something else you could do is to unsolder the ESP and mount it 90 degrees to the PCB. You would need to solder wires from the base PCB to the terminals of the ESP. This should work and you won't need to cut the base PCB.

tnx, ur reply is so insightful. didnt realize the both sides of the antenna needed to be exposed. What if I just solder some wires to the antenna to kind of "extend" it out of the pcb? so i wont need to make pcb adjustments anymore , do you think that's ok?

@BrownChiLD the length of an antenna is tuned so as to transmit/receive at certain frequencies. Adjusting the length will move the frequency away from the WiFi band and result in signal loss. I don't advise doing this at all.

crap... ok. but what if, we cut the built in antenna, and solder our little piece of wire antenna to it to preserve length.. at least this way the antenna is more exposed.

That may work but it probably won't be as good as the design of the onboard antenna.

right.. well we'll keep it as last option.. thanks much for your insights.
btw, how long a range should we be expecting from this ESP module in the first place? definitely at least 20m LoS right?

20m sounds reasonable.

It's not just that both sides of the antenna need to be "exposed", but proximity to other conductors, metal objects, or a ground plane matters. The further you can get the PCB antenna away from any other conductors the better, and your PCB design ideally would have your components on one side of the module and the module's antenna on the other side, much like most of the ESP* dev boards you see.

The size and shape of the antenna has been optimised by testing for a certain frequency; soldering more wires to it will change its characteristics and possibly make it worse. It's best to stick with what the engineers have given if possible, and consider an alternative module with an external antenna connector if it's not possible to redesign the PCB or device so the module's antenna sits further away.

Datasheet specifies 15mm free on each side of the antenna.


text:
Esp8266 and HttpClient not working properly
I am working on a project to send data to an API. Here is my code
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ESP8266HTTPClient.h>

#define USE_SERIAL Serial

ESP8266WiFiMulti WiFiMulti;

const char* key="***********";

void setup() {

    USE_SERIAL.begin(115200);
    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }

    WiFi.mode(WIFI_STA);
    WiFiMulti.addAP("******", "*********");

}
String data=" ";
void loop() {
    data+="{";
    data+="\"";
    data+="light";
    data+="\"";
    data+=":";
    data+=830;
    data+=",";
    data+="\"";
    data+="temperature";
    data+="\"";
    data+=":";
    data+=23;
    data+=",";
    data+="\"";
    data+="humidity";
    data+="\"";
    data+=":";
    data+=202;
    data+="} ";

    // wait for WiFi connection
    if((WiFiMulti.run() == WL_CONNECTED)) {

        HTTPClient http;

        USE_SERIAL.print("[HTTP] begin...\n");
        // configure traged server and url
        http.begin("https://us-central1-sensorapp-d2a64.cloudfunctions.net/getData",key);      //Specify request destination
        http.addHeader("Content-Type", "application/json");  //Specify content-type header
        int httpCode = http.POST(data);   //Send the request
        String payload = http.getString();                  //Get the response payload
        USE_SERIAL.println(httpCode);   //Print HTTP return code
        USE_SERIAL.println(payload);    //Print request response payload

        USE_SERIAL.print("[HTTP] GET...\n");
        if(httpCode > 0) {
            // HTTP header has been send and Server response header has been handled
            USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

            // file found at server
            if(httpCode == HTTP_CODE_OK) {
                //   String payload = http.getString();
                USE_SERIAL.println(payload);
            }
        } else {
            USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
        }

        http.end();
    }

    delay(30000);
}

After one successful request, it gives error 400 (Bad Request) until I reset the nodemcu. But then again it sends the data once successfully and continues with 400 (Bad Request).
Why are all the following requests bad? Is there something I haven't done?

You declare and initialize data as a String in the global space. Then, in loop, you use a bunch of concatenations to build your request string.
You never clear the contents of data, but back at the top of loop() on the next round, you concatenate all the string data again, which duplicates it.
Side note, the String type is terrible for low-memory devices, and especially bad when you use a lot of concatenations. Because of the way the String type works internally, when you concatenate strings, you end up leaving "holes" in the RAM that aren't likely to be able to be re-used.
Even if you do fix the code by clearing data after you submit your HTTP request, your program will still run out of RAM pretty quickly.
Better would be to build the constant parts of the string as constant globals and just concatenate the variable parts when needed and clear it after use.
Best would be to stop using String and use instead a char data[DATA_SIZE] type of string buffer and use the standard C string utilities like strncpy(), strnlen(), strncat(), etc.

Thank You For the reply. I will do it and will update things.

Just using the statement data=" "; in the loop solved my problem.


text:
Running two NEMA 17 motors, one by one, using the Arduino Uno
I am new to Arduino. I am trying to run two stepper motors NEMA 17 through respective A4988 driver and controlling via Arduino Uno.
The thought is that first stepper motor will carry out a first horizontal scan and then as it reaches to its initial position, second stepper motor will move a single step in vertical direction. This is a kind of raster scan that I want to perform with both motors.
When I am running the code, only horizontal scan motor is running and vertical scan motor is not moving. I have checked my circuit, motors and drivers and everything is working fine. I think there is some mistake in my code. It is a basic level code and I would really appreciate the help for helping me out.
int x, y; //stepper motor 'x' and stepper motor 'y'
#define BAUD (9600)

void setup()
{
  Serial.begin(BAUD);
  pinMode(6,OUTPUT); // Enable for x
  pinMode(5,OUTPUT); // Step for x
  pinMode(4,OUTPUT); // Dir for x
  digitalWrite(6,LOW); // Set Enable low for x

  pinMode(9,OUTPUT); // Enable for y
  pinMode(8,OUTPUT); // Step for y
  pinMode(7,OUTPUT); // Dir for y
  digitalWrite(9,LOW); // Set Enable low for y
}

void loop()
{

  digitalWrite(9,LOW); // Set Enable low for y

  for(y = 0; y < 20; y++)
  {
     digitalWrite(6,LOW); // Set Enable low for x
     digitalWrite(4,HIGH); // Set Dir high for x - Clockwise

     Serial.println("CLOCKWISE HORIZONTAL SCANNING IN PROGRESS");

     for(x = 0; x < 50; x++) // Loop 50 times
     {
      digitalWrite(5,HIGH); // Output high for x
      delay(10); // Wait
      digitalWrite(5,LOW); // Output low for x
      delay(100); // Wait
     }

    digitalWrite(6,LOW); // Set Enable low for x
    digitalWrite(4,LOW); // Set Dir low for x - Anticlockwise

    Serial.println("ANTICLOCKWISE HORIZONTAL SCANNING IN PROGRESS");

    for(x = 0; x < 50; x++) // Loop 50 times
    {
      digitalWrite(5,HIGH); // Output high
      delay(10); // Wait
      digitalWrite(5,LOW); // Output low
      delay(100); // Wait
    }

    Serial.println("ONE STEP CLIMB ON VERTCAL AXIS");

    digitalWrite(7,HIGH); // Set Dir high for y

    digitalWrite(8,HIGH); // Output high for y
    delay(100); // Wait
    digitalWrite(8,LOW); // Output low for y
    delay(100); // Wait
  }

  digitalWrite(9,LOW); // Set Enable low for y
  digitalWrite(7,LOW); // Set Dir low for y

  Serial.println("RESETTING ON VERTCAL AXIS");

  for(y = 0; y < 20; y++) // Loop 20 times
    {
      digitalWrite(8,HIGH); // Output high for y
      delay(10); // Wait
      digitalWrite(8,LOW); // Output low for y
      delay(100); // Wait
    }

}

Do i need to look after the delay being provided??

Stupid question, but are you expecting the motors to move at the same time?

First of all I find it strnage that you put the baud rate as a macro and the pins as constants. I strongly suggest to declare the pin names as constants (e.g. const byte X_EN = 6;), so that you can easily redefine them and avoid forgetting one. Then are you sure the second motor is not moving? Maybe the stepper is a 200 step/turn, and in one turn you move 1mm, so the full 20 steps are 0.1mm and you can't see it... Can you try swapping X and Y motors?

@ code gorilla - No both motors will not run at the same time. X motor  - 50 steps to right, then 50 steps to left. Then Y motor will movie one step up. Again X motor moves 50 steps to right and then 50 steps to left. Then again Y motor will move one step up. This loop continues for 20 steps of Y motor. At the end of 20th, Y motor moves 20 steps down. the loop continues.

@ frarugi - Yes, second motor is not at all working. I have also tried to swap both motors. But no result. One thing i want to share that i am using A4988 and HR4988 drivers. Is that any problem?? Because when they are used together, A4988 connected motor is not working and HR4988 connected motor is working. When i swapped the drivers, neither of the two motors is woking.

A minor issue that probably won't affect your result is that
Serial.println("ONE STEP CLIMB ON VERTCAL AXIS");
--> digitalWrite(9,LOW);  // This line 'needs' adding
digitalWrite(7,HIGH); // Set Dir high for y

I can't see anything in the code that will prevent the motors running, OK it will take ~13 seconds to start moving, but it should move.
So - without any hardware attached to the motor spindles - is it possible to switch the motors over to check for a wiring breakage issue?  With one motor working and one not it implies to me that either the motor is broken, the wiring is broken or the driver circuit is broken.  If the fault moves then its a motor/wiring fault if it stays the same then its a driver fault.

it's at the beginning, and it never gets modified...

@frarugi87 - Yes and so is the one for the X axis, but that's also set in the loop.  Its just my natural software engineer's distrust of hardware that says it could be that, because you never truly know what the pixies are doing on that blue board.:)