text:
HLW8032 UART sends random data ( Registers Overflow often)
I designed  my own version of smart socket just like the Sonoff with power metering chip HLW8032. And when I read the data in ESP-12F the data doesn't have a fixed format.
To troubleshoot the issue, I bought HLW8032 Breakout Board and analyzed the data sent by HLW8032, and I found the results are the same as the board I designed.
And that made me think that I may be reading the data from the Serial port the wrong way.
HLW8032 sends 24 Bytes on the serial and the format should be like this:
F2 5A 02 DA 78 07 1A E0 00 3D 3B 03 EC F5 4C C4 58 9C 2A 39 61 00 00 79
F2 5A 02 DA 78 07 1A E0 00 3D 3B 03 EC F5 4C C4 58 9D C2 9F 61 00 00 78

The data that I receive is in this format,
F2 5A 2 D3 70 6 BC D4 0 3D 4F 4 98 B4 4D F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FB EC 17 61 0 1 38 0 3D 4F 4 98 B4 4D E1 80
FD 84 7D 61 0 1 38 F2 5A 2 D3 70 6 AA 59 F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 2 D3 70 6 AA 59 0 3D 4F
4 98 B4 4D E1 80 FE FF 1 61 0 1 38 F2 5A 1 61 0 1 38 F2 5A 2 D3
70 6 AA 59 0 3D 4F 4 98 B4 4D E1 80 FE FF F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 0 3D 4F 4 98 B4 4D E1 80
FE FF 1 61 0 1 38 F2 5A 2 D3 70 6 AA 59 38 F2 5A 2 D3 70 6 AA 59
0 3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 4F 4 98 B4 4D E1 80 10 1B
D4 61 0 1 39 F2 5A 2 D3 70 6 AA 59 0 3D F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 13 4E 9E 61 0 1 39 F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 14 E8 3 61 0 1 39 E1 80 16 82 67 61 0 1 39
F2 5A 2 D3 70 6 AA 59 0 3D 4F 4 98 B4 4D F2 5A 2 D3 70 6 AA 59 0

We can see that the registers overflows again and again.
The code that I use to read the data is:
#include <SoftwareSerial.h>
#define BAUD_RATE 4800

SoftwareSerial swSer(13, 12);

void setup()
{
  Serial.begin(BAUD_RATE);
  swSer.begin(BAUD_RATE);
}

byte data[24];
void loop()
{
  if (swSer.available() > 0) {
    int a = swSer.readBytes(data, 24);
    yield();
  }

  // Display
  for (int i=0;i<24;i++)
  {
    Serial.print(data[i],HEX);
    Serial.print(" ");
  }
  Serial.println();
}

Schematic:

I feel that there is no issue in my hardware design, and the issue seems to be in the sketch.

What can be the possible problem with my setup?

How do I make the output of HLW8032 Stable with no overflow of registers?

Is there any library someone can recommend me to read the data from HLW8032 on SoftwareSerial?
Note: After some troubleshooting I found that delay() cause the problem to be more worse. And won't receive a stream of Bytes whose first byte , second nibble is F like F2, F4, as from the datasheet , first four bits are 1s by default.

It could be that the data is being sent too rapidly (each byte too close together) for SoftwareSerial to be able to cope with it. The only cure would be to not use software serial, but to use an Arduino with the resources you need to connect the device properly

@Majenko Yes, But as the required Baud rate for HLW8032 is 4800bps, and that is quite low. I searched about better alternatives to SoftwareSerial, and found there is AltSoftSerial and I read someone said as to be better than SoftwareSerial for lower baud rates. I gave it a try and the result is the same. Since the chip I'm using is ESP8266 and it only have one HardwareSerial, and I'm using that for Debug logs.

The ESP8266 has two hardware UARTs, not one. Although, you may find that the RX pin isn't exposed on whatever board you have - or if it is, it's not labelled as it.

I would never recommend using any form of SoftwareSerial ever. If you can't do it in hardware on your chosen board / platform, then you are using the wrong board / platform.

Use the Serial1 object in the same way that you would use the Serial object.

error: 'Serial1' was not declared in this scope. (PlatformIO)

@Majenko and due to limitations of the ESP8266, only UART 0 is capable of receiving data.

Well that's [expletive deleted] then isn't it? Upgrade to an ESP32 then.  The ESP8266's peripheral offerings have always been sadly lacking.

which version of the esp8266 boards package do you use? what pins do you use for SoftwareSerial? what esp8266 module do you have? Serial1 must be available. you don't need receive data for debug prints

@Juraj     I'm not using any board(like NodeMCU , Wesmos D1 etc). I'm using my own board which has an ESP-12F module. I use GPIO13 and GPIO12 for the SoftwareSerial.     Serial1 isn't available. I need debug prints , since it's  the first Rev  of the board that I designed, and I must debug and see everything.

@Juraj   But for understanding and troubleshooting the Issue , I got an Arduino UNO board and HLW8032 Breakout board ,  and it has the same result as my board. I've been using SoftwareSerial for quite many applications even receiving data from RS232 port, I never been in any trouble,

@Majenko   An esp8266 SoC has two hardware UARTs , UART 0, and UART 1.                           UART 1 is not capable of receiving data. That's why Serial1 is not defined for esp8266 based boards. That's where I'll follow your advice and Upgrade to and ESP32

https://arduino-esp8266.readthedocs.io/en/latest/reference.html?highlight=serial1#serial

@Juraj Thanks you so much!! That's too comprehensive information. I gave it a try and see  the results.

@Majenko   It is not an issue of SoftwareSerial. I tested the HLW8032 on the Hardware Serial of Arduino Mega using that code and the results are the same that is the registers overflows. Then I used an HLW8032 Library which only works on HardwareSerial, and the values are perfect. The way the library reads Serial is quite different. It's annoying me why it's making issues using readBytes() with me.

First of all I swaped UART0 to GPIO15 (TX) and GPIO13 (RX), (Luckily the Tx of HLW8032 is connected to GPIO13 in my hardware design and This is the UART0 RX pin after swap). Then I analyzed the data coming and the results were the same as of that SoftwareSerial i.e the registers overflows.
Then I used an HLW8032 Library (Which I've forked and will make changes for improvements) which only works on HardwareSerial, and the values are perfect. The way the library reads Serial is quite different.
So in short my issue resolved using two things:

I swaped UART0 to GPIO15 and GPIO13 using Serial.swap()
Used a library for the HLW8032

Thanks to @Juraj who provided the useful link about Serial Swap in ESP8266.

Serial uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX). Serial may be remapped to GPIO15 (TX) and GPIO13 (RX) by calling Serial.swap() after Serial.begin. Calling swap again maps UART0 back to GPIO1 and GPIO3.

#include "HLW8032.h"

HLW8032 HL;

void setup()
{
    HL.begin(Serial,4);
    Serial.begin(4800);
    Serial.swap();
}

unsigned int V;
void loop()
{
    HL.SerialReadLoop();

    if(HL.SerialRead == 1)
    {
    V = HL.GetVol();
    }
}

With this I can't print and see my debug prints on  GPIO1 (TX) and GPIO3 (RX), but at least without changing a bit in the hardware, my design works fine.


text:
What are the negative PINs for on the IndustrialShield M-Duino 58 Analog
I am working as an internship on an Arduino based PLC. It is the M-Duino 58 Analog from IndustrialShields. I try to figure out how it works; Reverse Engineering. But i dont know why it has negative Digital Inputs like normal Digital Input I1.0 also has a connection -I1.0.
It is probably a simple question but i cant figure it out. Hope you guys can help me.

I guess i figured it out. Seems to be the GND connections. Should read the Manual better next time.

Looks like the cathode of an opto isolator maybe? Would need a full schematic not a pinout diagram. The manual should tell you.

Thx, i guess these are the GND connections. Did not see it when i read the manual the first time.

Yeah, I think the inputs are all opto-isolated - so the input is actually a resistor and LED, with the "input" being the anode and the "-" being the cathode. It's hard to find any real information though, documentation seems to be a little poor.

The Manufacturer's documentation is at https://www.industrialshields.com/technical-features-industrial-m-duino-plc-arduino-ethernet-58-ios-analog-digital-plus

It looks like those inputs are opto-isolated. That means that the "input" goes through a resistor and the internal LED of an opto-isolator, which then comes back out of the "-" pin:

simulate this circuit – Schematic created using CircuitLab
So "-" connects to the ground of the remote device, and the "input" connects to the signal.

source: Stack Exchange

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

sort: votes


text:
Dynamically create functions for AccelStepper that use Adafrut_StepperMotor.oneStep methods?
In the Adafruit_MotorShieldV2Library>Accel_MultiStepper example, AccelSteppers are initialized using the following static forwardstep1 and backwardstep1:
#include <Wire.h>
#include <AccelStepper.h>
#include <Adafruit_MotorShield.h>

//First, get an Adafruit_MotorShield
Adafruit_MotorShield AFMStop(0x60); // Default address, no jumpers

//Then, get a stepper motor from it
Adafruit_StepperMotor *myStepper1 = AFMStop.getStepper(200, 1);

//Then, create callbacks for the AccelStepper's constructor
void forwardstep1() {
    myStepper1->onestep(FORWARD, SINGLE);
}
void backwardstep1() {
    myStepper1->onestep(BACKWARD, SINGLE);
}

//Finally, create the stepper motor
AccelStepper stepper1(forwardstep1, backwardstep1);

I intend to then use these AccelSteppers as members in a MultiStepper, which I'm skipping here because it shouldn't be relevant.
I want to make a function that automates this process. Ideally it would work something like this:
typedef void(*mover)();
AccelStepper makeStepper(Adafruit_StepperMotor myStepper){
    // create functions of type mover
    mover forward = []{myStepper->onestep(FORWARD, DOUBLE);};
    mover back = []{myStep->onestep(BACKWARD, DOUBLE);};
    return AccelStepper step(forward, back);
}

What I've tried:

Obviously the above solution. This doesn't work because myStepper isn't captured, but if you capture it it's not a mover object and can't be passed to AccelStepper.
Using an object's function. This doesn't work because object functions have the implicit first parameter this. See this for more info
Making the parameter myStepper static after it's passed in. This doesn't work because it gets over-written on every call to the function.
Using std::forward. This would probably work, but I don't think std::forward is defined in ArduinoSTL because I keep getting the error 'forward' is not a member of 'std'. See the code below:

Note, In an attempt to make this work, I upgraded the following folders to -std=gnu++17 on my ubuntu machine, resulting in __cplusplus == 201500:

~/.local/share/umake/ide/arduino/hardware/arduino/avr/platform.txt
~/.local/share/umake/ide/arduino/hardware/hardware/platform.txt

std::forward attempt
#include <ArduinoSTL.h>
using namespace std;
#include <iostream>
#include <functional>
#include <utility>

typedef void(*mover)();

template <classF>
mover lambda_to_ptr(F&& f){
    static F fn = std::forward<F>(f);
    return []{ return fn();};
}
AccelStepper makeStepper(Adafruit_StepperMotor myStepper){
    // create functions of type mover
    mover forward = []{myStepper->onestep(FORWARD, DOUBLE);};
    mover back = []{myStep->onestep(BACKWARD, DOUBLE);};
    return AccelStepper step(lambda_to_prt(forward), lambda_to_ptr(back));
}

p.s. Of course, I could always change the functions in the library, but this is (almost) always a bad idea.

I ended up just inheriting AccelStepper, and extending the
AccelStepper::AccelStepper  (   uint8_t interface = AccelStepper::FULL4WIRE,uint8_t pin1 = 2,uint8_t pin2 = 3, uint8_t pin3 = 4, uint8_t pin4 = 5, bool enable = true ) constructor to add my own Adafruit_StepperMotor instance variable and using it in an overridden step0 (which is the only function those callbacks were used in).
class MyAccelStepper: public AccelStepper
{
   public:
       MyAccelStepper(Adafruit_StepperMotor *myStepper):AccelStepper(0,0,0,0,0,false)
       {
         //MyStepper(0, 0, 0, 0, 0, false);
         _myStepper = myStepper;
       }
   protected:
       void step0(long step){
          (void)(step);
          if(speed() > 0){
            _myStepper->onestep(FORWARD, DOUBLE);
          }else{
            _myStepper->onestep(BACKWARD, DOUBLE);
          }
       }
    private:
       Adafruit_StepperMotor *_myStepper;
};

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


text:
Anomalous behaviour of ADC, digitalWrite and floating point operations
I'm trying to analyse mic (A0) input, calculate certain spectral lines with Goertzel algorithm to detect a number encoded by DTFM and display it with 8x8 matrix display (max7219 driver).
The code works perfectly fine without a display sending the result to serial, however when I added a display, strange things started to happen.

if goertzel(..) is called before displayDigit the display doesn't show anything
if displayDigit is called first the output of goertzel(..) is a complete mess
if I comment out 1 line in goertzel(..) which is amp = sqrt(re * re + im * im); // [1] the display works (but it doesn't make sense)

I'm using Arduino UNO, ADC in free-run mode.
The code below:
/**
 * 8x8 LED matrix display with MAX7219 driver
 * +5V, GND, CLK (8 pin), CS (9 pin), DIN (10 pin)
 */
#include <binary.h>
#include <LedControl.h>

#include "font8x8.h"

#define N           256
#define IX_LEN      8
#define THRESHOLD   20

/* Display PINs */
#define CLK     13//8
#define CS      12 //9
#define DIN     8 //10

LedControl matrix = LedControl(DIN, CLK, CS, 1);
int8_t lastDetectedDigit = -1;
int8_t currentDigit = -1;
uint32_t lastDetectedMillis = 0;

const int adc_channel = 0;

volatile uint16_t samples[N];
volatile uint16_t samplePos = 0;

float spectrum[IX_LEN] = {0,0,0,0,0,0,0,0};

// Frequences [697.0, 770.0, 852.0, 941.0, 1209.0, 1336.0, 1477.0, 1633.0]
// Corresponding spectrum indexes [18, 20, 22, 25, 32, 35, 39, 43]

// Calculated for 9615Hz 256 samples
const float cos_t[IX_LEN] = {
  0.9039892931234433, 0.881921264348355, 0.8577286100002721, 0.8175848131515837,
  0.7071067811865476, 0.6531728429537769, 0.5758081914178454, 0.49289819222978415
  };

const float sin_t[IX_LEN] = {
  0.4275550934302821, 0.47139673682599764, 0.5141027441932217, 0.5758081914178453,
  0.7071067811865475, 0.7572088465064845, 0.8175848131515837, 0.8700869911087113
  };

const char table[4][4] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

const uint8_t char_indexes[4][4] = {
  {0, 1, 2, 12},
  {3, 4, 5, 13},
  {6, 7, 8, 14},
  {10, 9, 11, 15}
};

void initADC() {
  // Init ADC; f = ( 16MHz/prescaler ) / 13 cycles/conversion
  ADMUX  = adc_channel; // Channel sel, right-adj, use AREF pin
  ADCSRA = _BV(ADEN)  | // ADC enable
           _BV(ADSC)  | // ADC start
           _BV(ADATE) | // Auto trigger
           _BV(ADIE)  | // Interrupt enable
           _BV(ADPS2) | _BV(ADPS1) | _BV(ADPS0); // 128:1 / 13 = 9615 Hz
//  ADCSRB = _BV(ADTS2) | _BV(ADTS0);              // Timer/Counter1 Compare Match B
  ADCSRB = 0; // Free-run mode
  DIDR0  = _BV(adc_channel); // Turn off digital input for ADC pin
}

void goertzel(volatile uint16_t *samples, float *spectrum) {
  float v[N + 2];
  float re, im, amp;

  for (uint8_t k = 0; k < IX_LEN; k++) {
    float a = 2. * cos_t[k];
    v[0] = v[1] = .0;
    for (uint16_t i = 2; i < N + 2; i++) {
      v[i] = float(samples[i - 2]) + a * v[i - 1] - v[i - 2];
    }
    re = cos_t[k] * v[N + 1] - v[N];
    im = sin_t[k] * v[N + 1];
    amp = sqrt(re * re + im * im); // [1]
    spectrum[k] = amp;
  }
}

float avg(float *a, uint16_t len) {
  float result = .0;
  for (uint16_t i = 0; i < len; i++) {
    result += a[i];
  }
  return result / len;
}

int8_t get_single_index_above_threshold(float *a, uint16_t len, float threshold) {

  if (threshold < THRESHOLD) {
    return -1;
  }

  int8_t ix = -1;
  for (uint16_t i = 0; i < len; i++) {
    if (a[i] > threshold) {
      if (ix == -1) {
        ix = i;
      } else {
        return -1;
      }
    }
  }
  return ix;
}

char detect_digit(float *spectrum) {
  float avg_row = avg(spectrum, 4);
  float avg_col = avg(&spectrum[4], 4);
  int8_t row = get_single_index_above_threshold(spectrum, 4, avg_row);
  int8_t col = get_single_index_above_threshold(&spectrum[4], 4, avg_col);

  if (row != -1 && col != -1) {
    return table[row][col];
  } else {
    return 0;
  }
}

void displayDigit(uint8_t c) {
  if (currentDigit == c) {
    return;
  }

  for (uint8_t i = 0; i < 8; i++) {
    matrix.setColumn(0, 7 - i, IMAGES[c][i]);
  }
  currentDigit = c;
}

void setup() {
  cli();
  initADC();
  sei();

  matrix.shutdown(0, false);
  matrix.setIntensity(0, 2);

  Serial.begin(115200);

}

unsigned long z = 0;

void loop() {
  while(ADCSRA & _BV(ADIE)); // Wait for audio sampling to finish

  goertzel(samples, spectrum);
  samplePos = 0;

//  if (z % 25 == 0) {
    displayDigit(2);

    for (int i = 0; i < IX_LEN; i++) {
      Serial.print(spectrum[i]);
      Serial.print("\t");
    }
    Serial.println();
    char digit = detect_digit(spectrum);
    Serial.println(digit);
//  }
  z++;

  ADCSRA |= _BV(ADIE);       // Resume sampling interrupt
}

ISR(ADC_vect) {
  uint16_t sample = ADC;

  samples[samplePos++] = sample;

  if(samplePos >= N) {
    ADCSRA &= ~_BV(ADIE); // Buffer full, interrupt off
  }
}

font8x8.h:
const byte IMAGES[16][8] = {
{
  B00001000,
  B00011000,
  B00001000,
  B00001000,
  B00001000,
  B00001000,
  B00001000,
  B00011100
},{
  B00111100,
  B01000010,
  B01000010,
  B00000100,
  B00011000,
  B00100000,
  B01000000,
  B01111110
},{
  B00111100,
  B01000010,
  B00000010,
  B00000100,
  B00000100,
  B01000010,
  B01000010,
  B00111100
},{
  B00010100,
  B00100100,
  B00100100,
  B01000100,
  B01111110,
  B00000100,
  B00000100,
  B00000100
},{
  B00111110,
  B01000000,
  B01000000,
  B01111100,
  B00000010,
  B00000010,
  B01000010,
  B00111100
},{
  B00111100,
  B01000010,
  B01000000,
  B01111100,
  B01000010,
  B01000010,
  B01000010,
  B00111100
},{
  B00111110,
  B01000010,
  B00000100,
  B00000100,
  B00001000,
  B00001000,
  B00010000,
  B00010000
},{
  B00111100,
  B01000010,
  B01000010,
  B00111100,
  B01000010,
  B01000010,
  B01000010,
  B00111100
},{
  B00111100,
  B01000010,
  B01000010,
  B01000010,
  B00111110,
  B00000010,
  B01000010,
  B00111100
},{
  B00111100,
  B01000110,
  B01001010,
  B01010010,
  B01010010,
  B01010010,
  B01100010,
  B00111100
},{
  B00000000,
  B01010100,
  B00111000,
  B01111100,
  B00111000,
  B01010100,
  B00000000,
  B00000000
},{
  B00101000,
  B00101000,
  B11111110,
  B00101000,
  B11111110,
  B00101000,
  B00101000,
  B00000000
},{
  B00011100,
  B00100010,
  B00100010,
  B01000010,
  B01111110,
  B01000010,
  B01000010,
  B01000010
},{
  B01111100,
  B01000010,
  B01000010,
  B01111100,
  B01000010,
  B01000010,
  B01000010,
  B01111100
},{
  B00111100,
  B01000010,
  B01000000,
  B01000000,
  B01000000,
  B01000000,
  B01000010,
  B00111100
},{
  B01111000,
  B01000100,
  B01000110,
  B01000010,
  B01000010,
  B01000010,
  B01000010,
  B01111100
}};

I use LedControl.h library but inside is uses only digitalWrite, no timing, interrupts.
Can somebody explain what is the problem?
UPD
This is what IDE tells me about the sizes:
Sketch uses 5602 bytes (17%) of program storage space. Maximum is 32256 bytes.
Global variables use 1048 bytes (51%) of dynamic memory, leaving 1000 bytes for local variables. Maximum is 2048 bytes.

This is LedControl library I'm using

Please update your question with more information. Can you give a link to the LedControl library and tell us what the compiler says about flash and ram usage. Start looking for an other arduino board, for example an arduino mkr or a arduino compatible board with a esp8266 or esp32.

How much static RAM does your program use, according to the compiler? Seems to me that should be close to 1 K, leaving little more than 1 K for the stack. Your goertzel() function alone uses more than 1 K of stack, so you could well be smashing the stack against the BSS.

Thx, @EdgarBonet I haven't even though about these constraints. I'll try to move constants to flash memory and replace floats to fixed point.

From your recent edit:

Global variables use 1048 bytes (51%) of dynamic memory, leaving 1000
  bytes for local variables. Maximum is 2048 bytes.

Your goertzel() function defines this
float v[N + 2];

where N is 256. This alone takes 258×4 = 1032 bytes of
stack and you only have 1000 bytes available. Then, as I suspected,
you are smashing the stack against the .bss section, effectively
overwriting some of your global variables with the local ones.
It is hard to predict what can happen in such circumstances. The program
is corrupting its memory: you can only expect it to act erratically.


text:
Where does the sound come from this board?
As the question says, i can't figure out where the sound comes from on this board that i bought, nothing on the manuals and can't see any speaker on the board... It is a "RFID Proximity Entry Door Secure Lock Access Control System"
Thanks.

What component is under the "Remove Seal After Washing" seal? Is it a buzzer?

@VE7JRO Updated the post :)

all you have to do is to put your finger on the component when it is making a sound and you will quickly discover if you are touching the correct component

this is a PCB mountable piezo buzzer. it makes sound in your "RFID Proximity Entry Door Secure Lock Access Control System"

That looks like a piezo buzzer, the component that had the sticker on it. It's likely louder now, with the sticker removed.


text:
Serial read SSID and PASSWORD WiFI connection failed in ESP32
Trying to get Wifi SSID and password dynamically from serial monitor and connecting to WiFi, tried the below program, but wifi is always in Connecting state only, it is not getting connected after receiving input from serial monitor.
#include <WiFi.h>

#define BAUDRATE 115200

char ssid[50];
char pass[50];

void setup() {
  Serial.begin(BAUDRATE);
  Serial.println();
  Serial.print("Enter your WiFi credentials.\n");
  Serial.print("SSID: ");
  while (Serial.available() == 0) {
    // wait
  }
  Serial.readBytesUntil(10, ssid, 50);
  Serial.print(ssid);
Serial.print("donessid");

  Serial.print("PASS: ");
  while (Serial.available() == 0) {
    // wait
  }
  Serial.readBytesUntil(10, pass, 50);
  Serial.print(pass);
 Serial.print("donepass");

  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print("Connecting....");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
void loop()
{}

And what results do you actually get on the serial monitor?

Hi Majenko, I got a result like this image.see this screenshot..    https://imgdb.in/gJ6K

You really should learn to use println() so you don't get everything on one line. I suspect your problem is that you have your line ending set to CR & NL but you're only looking for NL (10) so you get extra character 13s in your strings.

Is your Serial Monitor setting set to "Both NL and CR"? Change it to "Newline" should works.
What happened is if your Serial Monitor has a setting of "Both NL and CR", when your press Enter, it generates a \r\n, the Serial.readBytesUntil(10, ssid, 50) picked up that \r at the end of the array, when you use it as SSID, it is not a valid SSID.

Thanks hcheung.. it worked.

Glad I this help. Appreciated if you could accept the answer by click on the tick on the left side of the answer.


text:
Websockets with the ESP8266 using arduino uno board
I'm trying to make an iot device that connects to my wifi, establishes a socket connection with my golang backend and then starts to send sensor data from the ardunio.
I've got an ardunio uno board and this ESP8266:

I found this websockets library but I don't know if I can import the .h files if I have "arduino uno" selected in the IDE
My question:
Is it possible to establish a WebSocket connection with my go backend using the esp model that I have? If so, how can I import the required libraries in the arduno IDE? I would be happy if you could give me some directions.

can you communicate with the AT firmware on the module?

The library you linked is not for Uno with esp8266 module.
It is possible to use the ESP-01 with Uno for WebSockets client for example with ArduinoHttpClient library over the WiFiEsp library.
Better option is to use only an esp8266 development board programmed with Arduino IDE without the Uno.


text:
Convert Hex to Decimal from signed 2's complement
I am reading data from a meter over dlms protocol and I am getting hex values from there. I want to convert that hex string to signed decimal value. For example - ff9d denotes a value of -99 [reference].
My hex to decimal code is:
unsigned int hexToDec(String hexString)
{
  unsigned int decValue = 0;
  int nextInt;

  for (int i = 0; i < hexString.length(); i++)
  {
    nextInt = int(hexString.charAt(i));
    if (nextInt >= 48 && nextInt <= 57) nextInt = map(nextInt, 48, 57, 0, 9);
    if (nextInt >= 65 && nextInt <= 70) nextInt = map(nextInt, 65, 70, 10, 15);
    if (nextInt >= 97 && nextInt <= 102) nextInt = map(nextInt, 97, 102, 10, 15);
    nextInt = constrain(nextInt, 0, 15);
    decValue = (decValue * 16) + nextInt;
  }
  return decValue;
}

Can anyone please help me how to do it in Arduino IDE?

Have you tried googling something like "C++ convert hex string to int"?

Yes, I have converted hex string to decimal. But can't figure out the signed part. I can share that code if you want?

Yes, please share the code. You can edit your question for including it.

I have edited my question @chrisl

You do not want to convert the number to decimal: you want to convert it to binary. An int is represented in binary. Decimal is used for representing integer literals in the source code, but the compiler converts them to binary and, at runtime, every number is in binary.

Any code snippet you have on how to do this in Arduino @EdgarBonet ?

For example – ff9d denotes a value of -99

The function you wrote returns an unsigned integer which, being
unsigned, cannot be negative. The simple fix is to declare it as
int hexToDec(String hexString)

That should be enough to get it working as expected. Note that the local
variable decValue still has to be unsigned, otherwise you would get a
signed overflow, which is undefined behavoir (i.e. “forbidden”) in
C++. Returning an unsigned number from a function that is supposed to
return a signed number is perfectly fine: you get an implicit conversion
which is guaranteed to do the right thing.
Now, if I may provide some more feedback about this function:

Use, if you can, plain C strings (char *) instead of String
objects, as the latter are not very friendly to your Arduino's memory.
Use fixed-length integers (uint16_t if your protocol dictates 16-bit
integers) instead of the generic int, otherwise your code will fail
if you move to a 32-bit platform, such as an ARM-powered Arduino.
Use character literals ('0' instead of 48) instead of hard-coding
ASCII code points, as that makes the code more readable.
Use a simple subtraction (nextInt - '0') instead of the quite
expensive map() function.

Here is my take at it. Note that it has a “classic C” accent you do not
need to replicate. You may prefer using indices to crawl the string.
int16_t hex2int(const char *hex)
{
    uint16_t value;  // unsigned to avoid signed overflow
    for (value = 0; *hex; hex++) {
        value <<= 4;
        if (*hex >= '0' && *hex <= '9')
            value |= *hex - '0';
        else if (*hex >= 'A' && *hex <= 'F')
            value |= *hex - 'A' + 10;
        else if (*hex >= 'a' && *hex <= 'f')
            value |= *hex - 'a' + 10;
        else
            break;  // stop at first non-hex digit
    }
    return value;
}

Example usage:
Serial.println(hex2int("ff9d"));  // prints "-99"

Edit: As revealed by the comments, the whole question is an XY
problem. You are asking help about your misguided solution rather
than your actual problem. The data you have is not hex: it's binary.
You have a 16-bit signed integer stored in a byte array, most
significant byte first. You figured out you can convert that to an
integer by converting it first to a string representation as
hexadecimal, then converting that representation back to a binary
number. Of course you can do that, but it's an overly complicated and
expensive way of doing something trivial.
The canonical way to recover an integer from a byte array is by
assembling the bytes together using bitwise logic and bit shifts. In
this case:
int16_t reactive_power = (uint16_t) data[dataSize - 5] << 8
                       | data[dataSize - 4];

How should I pass ff9d as string in the hex2int function?

@Prateek: See the example I added.

I am doing this:
String reacP = String(data[dataSize - 5], HEX) + String(data[dataSize - 4], HEX);
Serial.println(hexToInt(reacP)); but I am getting the error: cannot convert 'String' to 'const char' for argument '1' to 'int16_t hexToInt(const char)'**

@Prateek: Looks to me like you are converting binary data to hex string, only to convert it back to binary. Please edit your question showing how you get the data. Most importantly: what is the data type of data?

That datatype of data is unsigned char as in void ReactivePower(unsigned char data[], int dataSize).

I solved the issue by adding .c_str() in the hex value. Thanks a lot @edgarbonet once again!

@Prateek: This is a very bad solution. See the amended answer.

Ohh, is that the case. Let me then check your ammended answer. Just out of curiosity why is using .c_str() a bad idea ?

@Prateek: Converting to a string in the first place is a bad idea. Representing numbers as strings of ASCII digits is useful for human consumption, but useless in your situation. Your problem is the kind that can be trivially solved by moving a couple of bytes around. Instead, you are taking a very long, memory costly and CPU intensive diversion.

I realized the mistake @edgarbonet. Your method worked perfectly. Thanks mate!

Which mode of DLMS you are you using?

IEC 61107 or currently IEC 62056-21, was an international standard for a computer protocol to read utility meters. It is designed to operate over any media, including the Internet. A meter sends ASCII (in modes A..D) or HDLC (mode E) data to a nearby hand-held unit (HHU) using a serial port. IEC 62056

In your question you mentioned:

hex string

which means a string of hex characters using ASCII (modes A to D).
However, in the comments you mentioned:

void ReactivePower(unsigned char data[], int dataSize)
String reacP = String(data[dataSize - 5], HEX) + String(data[dataSize - 4], HEX);

which means an array of bytes obtained from a stream of bytes using HDLC (mode E).
ASCII (Modes A to D)
For ASCII (modes A to D), there is a simple transformation to get the digit value from the hex character.
              ASCII
 Hex   --------------------                            Digit
 char  Decimal  Hexadecimal    Op1    Low nibble  Op2  Base 10
-----  -------  -----------  -------  ----------  ---  -------
 '0'      48        30        & 0x0F       0              0
 '1'      49        31        & 0x0F       1              1
 '2'      50        32        & 0x0F       2              2
 '3'      51        33        & 0x0F       3              3
 '4'      52        34        & 0x0F       4              4
 '5'      53        35        & 0x0F       5              5
 '6'      54        36        & 0x0F       6              6
 '7'      55        37        & 0x0F       7              7
 '8'      56        38        & 0x0F       8              8
 '9'      57        39        & 0x0F       9              9
 'A'      65        41        & 0x0F       1       +9    10
 'B'      66        42        & 0x0F       2       +9    11
 'C'      67        43        & 0x0F       3       +9    12
 'D'      68        44        & 0x0F       4       +9    13
 'E'      69        45        & 0x0F       5       +9    14
 'F'      70        46        & 0x0F       6       +9    15
 'a'      97        61        & 0x0F       1       +9    10
 'b'      98        62        & 0x0F       2       +9    11
 'c'      99        63        & 0x0F       3       +9    12
 'd'     100        64        & 0x0F       4       +9    13
 'e'     101        65        & 0x0F       5       +9    14
 'f'     102        66        & 0x0F       6       +9    15

For characters '0' to '9', simply AND with 0x0F.
For characters 'A' to 'F' and 'a' to 'f', AND with 0x0F and add 9.

char ch = '1';
byte b = 0;
if (ch >= '0' && ch <= '9')
{
  b = ch & 0x0F;
}
else if ((ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'))
{
  b = (ch & 0x0F) + 9;
}

It's also important to know whether the transformation was successful, e.g. the first character could be bad (either a null terminator or non hex character), so this needs to be tested for during the transformation. Also, there are four nibbles in an int16 so the transformation needs to quit when a maximum of four hex characters have been processed:
void setup()
{
  pinMode(13, OUTPUT);
  Serial.begin(115200);
}

void loop()
{
  char string[] = "A";
  //char string[] = "Waffle";
  //char string[] = "ff9d";
  int16_t the_int = 0;
  int count = AsciiToInt16(string, the_int);

  Serial.print(string);
  Serial.print(",  ");
  if (count)
  {
    Serial.print("Ok,  ");
    Serial.print(count);
    Serial.print(",  ");
    Serial.println(the_int);
  }
  else
  {
    Serial.println("Bad");
  }
}

int AsciiToInt16(const char* ch, int16_t& value)
{
  int count = 0;
  byte nibble = 0;

  // Stop after 4th nibble or null terminator.
  for(int i = 0; i < 4 && ch[i] != 0; i++)
  {
    if (AsciiToNibble(ch[i], nibble))
    {
      value <<= 4;
      value |= nibble;
      count++;
    }
    else
    {
      break;  // Stop after non hex digit.
    }
  }
  return count;
}

bool AsciiToNibble(const char ch, byte& b)
{
  if (ch >= '0' && ch <= '9')
  {
    b = ch & 0x0F;
    return true;
  }
  else if ((ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'))
  {
    b = (ch & 0x0F) + 9;
    return true;
  }
  return false;
}

Output
A,  Ok,  1,  10
Waffle,  Bad
ff9d,  Ok,  4,  -99

HDLC (Mode E)
For HDLC (mode E), simply do:
void ReactivePower(byte data[], int dataSize)
{
  uint16_t reacP = (data[dataSize - 5] << 8) | data[dataSize - 4];
  Serial.println(dataSize);
  Serial.println(reacP);
}
. . .
  byte data[] = { 1, 3, 5, 2, 4, 8 };
  ReactivePower(data, sizeof(data));

Output
6
773


text:
Send data from GSM module to cloud server like firebase
I am trying to search for anything to send my sensor data from Arduino + GSM SIM900A to a cloud server, preferably firebase. Does anyone know how can I achieve this operation to firebase or any other cloud database?


text:
Unstable analog sensor readout
I have the Arduino Uno (non-original replica) board, general SPI lcd, and GUVA-S12SD analog UV sensor module.
The board (powered via USB) reads the data from the analog pin 0, converts it to voltage (multiplying the readout by (5.0/1023.0) ) and prints out to the LCD.
Being illuminated with an UV-flashlight, the sensor gives unstable readouts varying for around 0.03-0.04 V each readout cycle. I am a complete noob in electronics, so I want to ask how can I check where the problem is? Is this my error in wiring, faulty module, just normal behaviour of an analog sensor or something else?
Mine sensor module isn't from Adafriut and looks a bit different, the one in the diagram is just to show the general wiring.
Thanks!
(Sensor module description: https://www.electroschematics.com/11509/guva-s12sd-uv-sensor-module-circuit/ )
The code of the sketch is:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
int sensorValue;
float sensorVoltage;
LiquidCrystal_I2C lcd(0x27,16,2);  // display setup
void setup() {
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("");
}

void loop() {
  sensorValue = analogRead(A0);
  sensorVoltage = sensorValue * (5.0 / 1023.0);
  lcd.setCursor(0, 0);
  lcd.print(sensorVoltage/0.1); // rather low voltage is expected
  delay(1000);
}

Update: I tried to measure the output with a multimeter (as Vasekdvor suggested in answers) and it showed very similar results: continuous 0.04-0.07 V oscillations. Their magnitude seems to grow along with the intensivity of the illumination.
With sensor being dark, multimeter shows 0.006 V (changing to 0.007 V occasionally) between A0 pin and the ground.

post your code in the question so we can check that too

The code is added to the question.

I know you said that your sensor looked different from the fritzing one in the diagram..... but are you sure it’s connected with the output to A5?    Most of these I see for sale have the output on the leftmost pin.

Try to measure an output of this sensor with an multimeter, not with an arduino. According to your posted link of description of this sensor, there should be something between 0V to 1V. That way we can find out, if there is an problem with an sensor or in code.

Yes, exactly, mine sensor has output on the outer pin instead of the middle one, and that pin is connected to Arduino's A0 analog in.

Thanks for the idea! I'll check the output as soon as I get a multimeter, tomorrow or a day later maybe.
I suppose the sensor can give a bit more than 1V under the strong UV light, but with the atmosphere-filtered Sun as the UV source it shouldn't go beyond that.

yes, you are right, it should give 1170 mV and more, if there is a really strong UV light.

Keep in mind that it is unlikely your flashlight puts out UV light.  If you can see with your eyes the light coming from your flashlight then it's not UV.  The purple flashlights that look similar to a black light are typically putting out near-UV and your sensor may not be very sensitive to this wavelength.  Test your sensor out in direct sunlight.

I tried to measure the output with a multimeter, and it showed very similar results: continuous 0.04-0.07 V oscillations. I've added a little update to my question post.

The sensor reads approximately 1.7 V with the flashlight being around 40cm away, so I assume it gives enough of the light within the sensitivity spectrum of the sensor. I'll try the direct sunlight of course, but there's rather cloudy and dark weather outside now.

@NickL so there is probably something wrong with your chip.

@Greenonline I know that, but due to restrictions on StackExchange (not enough rank), i didn't have a permision to write a comment below his post, now i have, so if you want to do that change your (StackExchange) policy.

the sensor gives unstable readouts varying for around 0.03-0.04 V each
  readout cycle

If your sensor outputs 0 to 5V and you're only getting 0.03 to 0.04 variance then I would say that it's working pretty well.  You can get a more stable output by averaging several readings before printing them.
Additionally, for even more stable readings consider powering your Audrino from a battery.  USB power can induce a considerable amount of noise if it's coming from a PC or Laptop USB port.  Also, there is a low noise mode where you can put the Arduino to sleep during your ADC reading (and it wakes up afterwards) which helps a lot with ADC noise reduction.

Thanks for the averaging idea!
Arduino was powered by usb phone charger (Samsung travel adapter, 5V 2A output) for one of the tests and by the laptop USB port for the rest of the attempts. Should I try powering it by a powerbank, or should I take ordinary batteries without any charge/discharge controllers?

Batteries will likely give you the quietest power source but if you have to go through a switching voltage regulator there will be some ripple on the 5V.  A travel adapter or PowerBank will likely be better than a PC's USB port.  The only way to tell for sure is to look at the 5V supply with an oscilloscope.  Linear voltage regulators have the lowest noise but at the cost of wasted power which can be concern for battery powered devices.

I've tried using powerbank to power the board, but nothing changed (at least visibly or measurable). Didn't find enough AA batteries to power arduino yet.
I think I'll just average the readings, the only concern is is the sensor itself ok and working more or less correctly.

After averaging 10 or 15 measurements the output looks pretty stable, so I think this is a nice solution, thanks!


text:
ESP8266 WebServer not responding (connection time out)
My web server running on ESP8266, stop working after while.
I cannot connect to it - browser shows connection time out error.
No error, no crash... nothing.
Have you any idea how to fix it?
My code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ESP8266mDNS.h>
#include <FS.h>

#include "console.h"
#include "tictactoe.h"
#include "main.h"

#define L_GREEN 2
#define L_YELLOW 0
#define L_ORANGE 4
#define L_RED 5

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

int requests = 0;
String IPs = "[";

IPAddress staticIP86_10(192,168,0,115);
IPAddress gateway86_10(192,168,0,1);
IPAddress subnet86_10(255,255,255,0);

ESP8266WebServer server(80); //Server on port 80

String getContentType(String filename);
bool handleFileRead(String path);

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "1.sk.pool.ntp.org", 60*60, 60*1000);

//===============================================================
// Game Data
//===============================================================

/*String ticPlayer1 = "";
String ticPlayer2 = "";
String ticClick = "-1";
int ticReset = 0;*/

//===============================================================
// LEDs
//===============================================================
void LEDblink(int pin) {
  requests++;
  digitalWrite(pin, HIGH);
  delay(10);
  digitalWrite(pin, LOW);
}
//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleNotFound(){
  if(server.uri().indexOf(".php")>-1) {
    Serial.print("404 "+server.uri()+": "+server.client().remoteIP().toString()+" (Blocked)\n");
    return;
  }
  Serial.print("404 "+server.uri()+": "+server.client().remoteIP().toString()+"\n");
  String s = HTML_Pro_notFound;
  server.send(404, "text/html", s);

  LEDblink(L_YELLOW);
}
void sendFile(String path, String type) {
  Serial.print(server.client().remoteIP().toString()+": "+server.uri()+"\n");
  if (SPIFFS.exists(path)) {                            // If the file exists
    File file = SPIFFS.open(path, "r");                 // Open it
    size_t sent = server.streamFile(file, type);        // And send it to the client
    file.close();                                       // Then close the file again
  }
}
//===============================================================
void reboot() {
 server.send(200, "text/plain", "true");
 LEDblink(L_RED);
 digitalWrite(15, LOW);
 digitalWrite(0, HIGH);
 digitalWrite(2, HIGH);
 ESP.restart();
}
void admin() {
 if(!server.hasArg("user") || !server.hasArg("pass") || server.arg("user") == NULL || server.arg("pass") == NULL || server.arg("request")=="login") {
    String expire = "";
    if(server.arg("remember")=="on"){expire="30";}else{expire="0";}
    server.send(200, "text/html", "<!DOCTYPE html><meta charset='UTF-8'><title>ProTools.tk | Please Wait</title><link rel='stylesheet' type='text/css' href='/main.css'><form class='center' action='/admin' method='post' style='display:none;'><input class='a' type='text' name='user'><input class='a' type='password' name='pass'><input class='a' type='text' name='request' value='panel'><button class='a' type='submit'></button></form>

");
    //server.sendHeader("Location","/login");
    //server.send(303);
 }
 if((server.arg("user")=="***")&&(server.arg("pass")=="***")) {
   if(server.arg("request")=="data") {
     String c = "{\"uptime\":"+String(millis(),DEC)+",\"req\":"+String(requests)+",\"ips\":"+IPs+"]}";
     server.send(200, "text/json", c);
   }
   else if(server.arg("request")=="panel") {
     server.send(200, "text/plain", "Admin panel here");
   }
   else {
    server.send(400, "text/plain", "400 Bad Request");
   }
 }
 else{
   server.sendHeader("Location","/login");
   server.send(303);
 }
 LEDblink(L_RED);
}
void console() {
 Serial.print("Console :"+server.client().remoteIP().toString()+"\n");
 String s = HTML_console;
 server.send(200, "text/html", s);
 LEDblink(L_ORANGE);
}

//===============================================================
/*void minesPage() {
 String s = HTML_mines;
 server.send(200, "text/html", s);
 LEDblink(L_YELLOW);
}
void minesScript() {
 String s = JS_mines;
 server.send(200, "text/javascript", s);
 LEDblink(L_YELLOW);
}
void minesStyle() {
 String s = CSS_mines;
 server.send(200, "text/css", s);
 LEDblink(L_YELLOW);
}*/

//===============================================================

/*void ticPage() {
 String s = HTML_tictactoe;
 server.send(200, "text/html", s);
 LEDblink(L_YELLOW);
}
void ticScript() {
 String s = JS_tictactoe;
 server.send(200, "text/javascript", s);
 LEDblink(L_YELLOW);
}
void ticStyle() {
 String s = CSS_tictactoe;
 server.send(200, "text/css", s);
 LEDblink(L_YELLOW);
}

void ticData() {
 Serial.print("TicTacToe: "+server.client().remoteIP().toString()+"\n");
 String user = server.arg("user");
 String clicked = server.arg("click");
 String request = server.arg("request");
 String leave = server.arg("leave");
 if(user != "") {
  if(user == "get") {
   server.send(200, "text/plain", "{\"Player1\":\""+ticPlayer1+"\", \"Player2\":\""+ticPlayer2+"\"}");
  }
  else if(ticPlayer1 == "") {
   ticPlayer1 = user;
   server.send(200, "text/plain", "player1");
  }
  else if(ticPlayer2 == "") {
   ticPlayer2 = user;
   server.send(200, "text/plain", "player2");
  }
  else {
   server.send(200, "text/plain", "Full");
  }
  if(ticPlayer1 != "" && ticPlayer2 != "") {
   ticClick = "0";
  }
  digitalWrite(L_ORANGE,HIGH);
  delay(500);
  digitalWrite(L_ORANGE,LOW);
 }
 else if(leave != "") {
  if(leave == ticPlayer1) {
   ticPlayer1 = "";
  }
  else if(leave == ticPlayer2) {
   ticPlayer2 = "";
  }
  ticClick = "-1";
  server.send(200, "text/plain", leave+" left");
 }
 else if(clicked != "") {
  ticClick = clicked;
  server.send(200, "text/plain", "OK: "+ticClick);
 }
 else if(request != "") {
  if(request == "checkClicked") {
   server.send(200, "text/plain", ticClick);
  }
  if(request == "reset") {
   ticReset++;
   if(ticReset == 2) {
    ticPlayer1 = "";
    ticPlayer2 = "";
    ticClick = "-1";
    ticReset = 0;
    server.send(200, "text/plain", "Reseted");
   }
   else {
    server.send(200, "text/plain", "Verification required");
   }
  }
 }
 LEDblink(L_YELLOW);
}*/
//==============================================================
//                  SETUP
//==============================================================
void setup(void){
  Serial.begin(9600);

  //Onboard LED port Direction output
  pinMode(L_GREEN,OUTPUT);
  pinMode(L_YELLOW,OUTPUT);
  pinMode(L_ORANGE,OUTPUT);
  pinMode(L_RED,OUTPUT);

  digitalWrite(L_RED, HIGH);

  WiFi.hostname("ESP8266");

  WiFi.begin(ssid, password);     //Connect to your WiFi router

  MDNS.begin("ESP8266");
  MDNS.addService("http", "tcp", 80);

  digitalWrite(L_RED, LOW);
  // Wait for connection
  digitalWrite(L_ORANGE, HIGH);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  digitalWrite(L_ORANGE, LOW);
  digitalWrite(L_YELLOW, HIGH);

  WiFi.config(staticIP86_10, gateway86_10, subnet86_10);

  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP

  SPIFFS.begin();

  server.on("/", []() {                                          // root
    sendFile("/page.html", "text/html");
    LEDblink(L_YELLOW);
  });
  server.on("/main.css", []() {                                  // main.css
    sendFile("/main.css", "text/css");
    LEDblink(L_ORANGE);
  });
  server.on("/page.css", []() {                                  // page.css
    sendFile("/page.css", "text/css");
    LEDblink(L_ORANGE);
  });
  server.on("/page.js", []() {                                   // page.js
    sendFile("/page.js", "text/javascript");
    String ip = server.client().remoteIP().toString();
    if(IPs=="["){
      IPs+="{\"time\":"+String(timeClient.getEpochTime(),DEC)+",\"ip\":\""+ip+"\"}";
    }else{
      IPs+=",{\"time\":"+String(timeClient.getEpochTime(),DEC)+",\"ip\":\""+ip+"\"}";
    }
    LEDblink(L_YELLOW);
  });
  server.on("/login/style.css", []() {                           // login/style.css
    sendFile("/login/style.css", "text/css");
    LEDblink(L_ORANGE);
  });
  server.on("/cookies.js", []() {                                // cookies.js
    sendFile("/cookies.js", "text/javascript");
    LEDblink(L_ORANGE);
  });

  server.on("/translator", []() {                                // translator
    sendFile("/translator/page.html", "text/html");
    LEDblink(L_ORANGE);
  });
  server.on("/translator/style.css", []() {                      // translator/style.css
    sendFile("/translator/style.css", "text/css");
    LEDblink(L_ORANGE);
  });
  server.on("/translator/script.js", []() {                      // translator/script.js
    sendFile("/translator/script.js", "text/javascript");
    LEDblink(L_ORANGE);
  });

  server.on("/login", []() {                                     // login
    sendFile("/login/page.html", "text/html");
    LEDblink(L_ORANGE);
  });
  server.on("/admin", admin);
  server.on("/reboot", reboot);
  server.on("/console", console);

  /*server.on("/minesweeper", minesPage);
  server.on("/minesweeper/script.js", minesScript);
  server.on("/minesweeper/style.css", minesStyle);

  server.on("/tictactoe", ticPage);
  server.on("/tictactoe/script.js", ticScript);
  server.on("/tictactoe/style.css", ticStyle);
  server.on("/tictactoe/data", ticData);*/

  server.onNotFound(handleNotFound);

  server.begin();                  //Start server
  timeClient.begin();
  Serial.println("HTTP server started");
  digitalWrite(L_YELLOW, LOW);
  digitalWrite(L_GREEN, HIGH);
}
//==============================================================
//                     LOOP
//==============================================================
void loop(void){
  timeClient.update();
  server.handleClient();          //Handle client requests
}

what version of the esp8266 arduino package you use?

hmm... I am not sure what version do you mean but in Arduino Board Manager I have installed ESP8266 of version 2.0.0 Please specify more where I can find that version if this is not what are you want.

What mime type is text/plane? Are you trying to transfer an aircraft?

use the latest version 2.4.2

@Majenko oops :D thanks for warning! I wrote it wrong and copy it to whole code, but its works good xD

@Juraj Its looks like it working. Thanks!

have you tried resetting your esp8266 ?

Use the latest version of Arduino esp8266 core package (2.4.2 or higher).


text:
Assigning array variables to int variables
I need to control thousands of rgb leds.To make animations I want to assign led numbers(addressable led strip) to arrays.For example floor[2]room[14]=106 106 is the number of led,there are many floors and rooms.I want to change floor or room numbers with that way I will make animations.
  We can say its 92x30 pixel monitor.I tried to create list of floor and rooms but I couldnt make it.
  I'm new to programming,help please!
Solved with this way #define LEDNO(FLOOR, ROOM) ((ROOM) + (FLOOR * 92))

Are the LEDs in floor/room sequence? I.e., is floor[2]room[15] going to be LED 107?

yes,exactly.every floor has 92 rgb,and there is 30 floors.

Your Arduino has more than 8 K or RAM, right?

yes I'm using arduino due.

I'm already controlling all of leds,but I couldnt calibrate them.

sounds like you need to check out these guys (and similar projects) https://makezine.com/2012/11/18/worlds-biggest-led-cube/

are the LEDs ordered? LED number 1 in first room on first floor, no 2 in second room on first floor etc and the last number in the last room on the last floor? or is the mapping more complicated?

LEDs are ordered exactly as you said Juraj.

and on every floor is a same count of rooms?

yes,92 pixel on every floors

You really don't need to maintain a list.
Just calculate the LED index from the location:
int room = 14;
int floor = 2;

const int rooms = 92;

int led = room + (floor * rooms);

That is, each floor below the current one (floors and rooms count from 0) is a full row of rooms (92 * floors), and there are "room" extra rooms on this floor to add to it.
You could make a macro:
#define LEDNO(FLOOR, ROOM) ((ROOM) + (FLOOR * 92))

Then your LED number is just:
int led = LEDNO(2, 14);

Here's an example taken from your code:
void floorsup(){

  FastLED.setBrightness(brightness);

  for(int a=1;a<255;a+=40){
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds2[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds3[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
  }
}

but with this way I cant light up many leds at the same time

What does this have to do with how many LEDs you can light up at once? This just gives you an LED number. What you do with that is up to you. I would use it to set an LED colour in the NeoPixel library. I don't think you quite understand exactly what you want to achieve with this.

yes but if I wanted to light whole fourth floor its gonna be easy with assigning them number.

They already have a number. What do you want to "assign"?

okay its long but I'm gonna share my code,you will understand what I mean

You have absolutely no need for your array for that code. Most of it can be replaced with a couple of loops and the macro I show above.

I have used a chunk of your code (the longest most wasteful portion) to demonstrate how you'd use it. The code is now readable.

ahhh now I got it! yes its really such a shame I know,I make like that with hurry.Let me obligate  more your code.At the first time I thought I'm gonna identify with int all numbers.

ohh man you just save me from a lot of works :D now I dont have to calibrate leds with python,I saw from another programmer in my company at the other project with the array way,so I thought I should make like that way.But with your way its saving me from a lot of works..

I'm talking too much sorry but I have one more question.How can I convert any image to RGB color code arrays?For example from uploaded image I will get RGB color codes for 92x30 pixels.Is it possible with python?

I have no idea about python. If I were scripting it I would do it in PHP since it has image functions right there for you - however I never need to these days, since the latest beta version of UECIDE has it all built in.

Something like this would work:
#define MAX_FLOORS  92
#define MAX_ROOMS   30

struct floor_str {
  int Room[MAX_ROOMS];
} Floor[MAX_FLOORS];

You would then access an individual LED address like:
Floor[2].Room[14] = 106;

yes,I can take all led numbers from python on this format,but I wasnt know how to assign them.Thank you!

btw does it should be like struct floor_str {   int room[MAX_ROOMS];  floor[MAX_FLOORS]; } ?

No. You make a struct of rooms as an array and make an array of them as floors.

I already figure out with another way but I would like to learn your method also.Could you check your code again? its giving error.

The syntax was correct but 'floor' appears to be already defined as something else.  An easy solution is to use 'Floor' instead.  (edited the solution above)


text:
SPI Connections to DAC
I'm hoping to construct a feedback loop for a laser using an Chipkit UC32 and an analog-digitial converter ( the one of I have is an AD5780 evaluation board). I've been reading through Digilint's  SPI library but I admit I am pretty lost.
( I believe this is on topic to Arduino because I am using an Arduino API. The micro-controller I use is basically an Arduino so I see no difference. )
I'd like to output something simple like a digital AC voltage to the DAC and have it convert it, but as I understand it from here, I am just using the digitalWritecommand which is basically binary. How do transfer something more complicated to have the DAC convert it?
Likewise, how do I get the DAC to do the reverse, ADC, where it reads in a voltage and sends the Arduino a digital signal through SPI pins?

What does this have to do with Arduino? It seems to me that you have this UC32 which has a PIC32 microcontroller on it and you need to write a library for the AD5780 using the chip's SPI peripheral.

Also why would you write your own driver if Analog Devices has a reference driver at https://wiki.analog.com/resources/tools-software/uc-drivers/renesas/ad5780#driver_description where you only have to implement SPI_Init, SPI_Write and SPI_Read yourself using your board / platform's SPI lib? :)

@MaximilianGerhardt chipKIT uses the Arduino API. It's as Arduino as the esp8266 or teensy.

@MaximilianGerhardt Have you tried to use the AD Driver before? I'm here becauseI tried that and it seems broken. It requests files that aren't included. They don't seem to be useful but even if you remove those #include commands, it references a lot of undefined functions. Perhaps its just the missing file but seems unusable. If you have any experience with this, I could open another thread and try to fix it.

@AndrewHardy Sure, I'll download the lib and interface with the Arduino SPI class so that in theory you can drop-in the result straight away. I'll let you know if I encounter a problem. If the lib requires functions beyond that what they say, it's kind of a bad lib..

@AndrewHardy Done. https://github.com/maxgerhardt/arduino-ad57xx-driver

So there's something you're compiling or doing differently that I don't understand. When I hit Verify for your code, I get errors https://imgur.com/BKsIk2K of undefined references to commands in the Drivers. This is different than errors if I just don't have the file, so I don't know what they mean.

You must put the ad57xx_generic_driver folder https://github.com/maxgerhardt/arduino-ad57xx-driver/tree/master/lib folder in your Arduino's library folder for this to work. (This is originally a PlatformIO project btw) @AndrewHardy

No, that's not the problem. If it wasn't in the libraries folder, I would get an error at the #include<AD57XX.h> line. I have had to remove those files from the "include" directory to have Arduino recognize it. https://imgur.com/a/QVxW0hi This is my file structure currently

@AndrewHardy Then for some reason it's not compiling the cpp files. It finds the headers but doesn't compile in the implementation of it. Something is still wrong with the folder structure. Try to put all the sources and headers directly into one filder like shown in https://www.arduino.cc/en/hacking/libraries

@MaximilianGerhardt, https://imgur.com/a/WPskxYP I went away from this to work on some other things, but I'm back now. Hooking up the DAC, I get a sin function. It doesn't seem to be responsive to the numbers I change in the example code you gave. How would I go about debugging these sorts of things? I take this image is not what I am supposed to see.

I'd like to output something simple like a digital AC voltage to the DAC and have it convert it, but as I understand it from here, I am just using the digitalWritecommand which is basically binary. How do transfer something more complicated to have the DAC convert it?

SPI is a communication protocol.  It uses digital signals, coupled with time, to transfer information.
To use DSPI you need to first define an SPI object
DSPI0 SPI;

From then on it's the same as using the Arduino SPI library.
Start it
SPI.begin();

Then transfer the correct commands (found in the DAC datasheet) to set the voltage of the output
digitalWrite(10, LOW);
SPI.transfer(0x43);
SPI.transfer(0x1A);
digitalWrite(10, HIGH);

The values there are just examples. The 10 is the chip select pin for the DAC, and the values used in the transfers (however many are needed) need to be found in the datasheet.
If you only want to use the pins associated with DSPI0 you can use the SPI library instead (which only supports one SPI channel - the uC32 has two), in which case it is identical to working with the Arduino SPI library.

Likewise, how do I get the DAC to do the reverse, ADC, where it reads in a voltage and sends the Arduino a digital signal through SPI pins?

You don't. DACs are DACs and ADCs are ADCs. They aren't interchangeable.
For ADC functionality just use any of pins A0 through A11 and the analogRead() function.

thanks for responding! You've helped me before so I appreciate the patience. I've been reading for a while, so can I run some things by you? I didn't find anything in the Data Sheet, but what bytes I write are just getting bit_number = (Pos REF V - Neg REF V ) / 2^(18) and convert to bytes? There doesn't seem to be a command for the actual conversion either? From what I've read when I send bytes it automatically converts to an analog voltage and outputs it?

Secondly, do you think it is worth trying to get the AD Drivers running? The missing file is ior5f100le.h . Is this a standard Arduino library I'm missing? The driver has commands for reading data from the register too, which I don't quite understand the point of.

That DAC uses a 3-byte (24 bit) control protocol. Page 21 onwards in the datasheet describe the commands. You need to first send the correct commands to turn the DAC on (using the "Control Register"). Once on you send a value to a specific register (not a real register, so it's not listed with the registers), and toggle LDAC (either the pin or the register bit) to output that value.  I have never heard of ior5f100le.h. Probably something to do with a specific development board.


text:
Attaching Microcontroller to DAC evaluation board
For an independent undergraduate research project I'm trying to construct a digital feedback loop. I have never used an Arduino, or done much electrical/computer engineering, so I'm just taking things one thing at a time.
I've been given this
microcontroller
and this DAC eval board, and now I'm just trying to put them together.
From reading, I need to  attach jumper cables from #16 here to

the pins on the Eval Board here,

but I don't know where to find information on them, so I don't know which to plug into what. Any advice?

Your DAC uses the SPI protocol.  For that you want to connect it to the SPI header. That's the 6-pin (3x2) header numbered 11 on the uC32.
Connect:

The uC32's SCK pin to the DAC's SCLK
The uC32's SDO pin (MOSI) to the DAC's SDIN pin.
The uC32's SDI pin (MISO) to the DAC's SDO pin.

The other pins (I am not sure what they all do off hand, but the datasheet details them) can connect to any GPIO pins you like (except pins 11-13 which duplicate the SPI header - so you could use those instead if you prefer - 11=MOSI, 12=MISO, 13=SCK).

Where would I read about if I need to ground the DAC to the microcontroller? I've edited the post to have the right DAC evaluation board, but the guide for the EVALAD5780 also does not explain their acronyms for the pins.

The pins are all defined in the AD5780 datasheet.  Of course you have to connect the grounds together, otherwise you don't have a circuit.

OK, I think a better question would be where should I read to learn about setting up a serial circuit like this? For example, the DAC has two DGND pins so I don't know where to ground. Also, the J8 pins which are the SPI do not seem to be labeled so idk which is which, can I just use 11-13 since they're duplicates?

Yes, you can use 11-13. The SPI pins are detailed in the uC32 user guide. Connect all ground pins together.

just checking back in, don't I need a Slave Select, SS or SYNC pin somewhere? I can connect the SYNC to the micro-controller and  just set that Low via any pin right?

Yep, any pin at all.

Complete shot in the dark here, but if you're able to look here, I have more questions. I don't know how to debug my SPI connections. https://electronics.stackexchange.com/questions/428571/operating-ad5780-eval-board-via-microcontroller


text:
problem related to arduino
first of all, I am not very good at English. if I have done a mistake during describe the problem apologize me. I want to combine both ultrasonic sensor code and mpu6050 sensor. can anyone tell me how to combine both codes in one code?
#include <Wire.h>
//I2C communication library for MPU6050
#include <I2Cdev.h>
//MPU6050 interfacing library
#include <MPU6050_6Axis_MotionApps20.h>
//Processing incoming serial data
#include <CmdMessenger.h>
//Contain definition of maximum limits of various data type
#include <limits.h>

//Creating MPU6050 Object
MPU6050 mpu(0x68);
//Messenger object
CmdMessenger Messenger_Handler = CmdMessenger(Serial);

///////////////////////////////////////////////////////////////////////////////////////
//DMP options
//Set true if DMP init was successful
bool dmpReady = false;
//Holds actual interrupt status byte from MPU
uint8_t mpuIntStatus;
//return status after each device operation
uint8_t devStatus;
//Expected DMP paclet size
uint16_t packetSize;
//count of all bytes currently in FIFO
uint16_t fifoCount;
//FIFO storate buffer
uint8_t fifoBuffer[64];

#define OUTPUT_READABLE_QUATERNION
////////////////////////////////////////////////////////////////////////////////////////////////

//orientation/motion vars
Quaternion q;
VectorInt16 aa;
VectorInt16 aaReal;
VectorInt16 aaWorld;
VectorFloat gravity;

//Euler angle container
float euler[3];

//yaw/pitch/roll container and gravity vector
float ypr[3];

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

/////////////////////////////////////////////////////////////////
//Motor Pin definition
//Left Motor pins

#define A_1 3
#define B_1 4

//PWM 1 pin number
#define PWM_1 6

//Right Motor
#define A_2 4
#define B_2 5

//PWM 2 pin number
#define PWM_2 5

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Ultrasonic pins definition
const int echo = 24, Trig = 23;
long duration, cm;

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////
//Motor speed from PC
//Motor left and right speed
float motor_left_speed = 0;
float motor_right_speed = 0;
/////////////////////////////////////////////////////////////////

//Setup serial, encoders, ultrasonic, MPU6050 and Reset functions
void setup()
{

  //Init Serial port with 115200 baud rate
  Serial.begin(115200);

  //Setup Motors
  SetupMotors();
  //Setup Ultrasonic
  SetupUltrasonic();
  //Setup MPU 6050
  Setup_MPU6050();

  //Set up Messenger
//  Messenger_Handler.attach(OnMssageCompleted);

}

void SetupMotors()
{

 //Left motor
 pinMode(A_1,OUTPUT);
 pinMode(B_1,OUTPUT);

 //Right Motor
 pinMode(A_2,OUTPUT);
 pinMode(B_2,OUTPUT);

}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Setup UltrasonicsSensor() function
void SetupUltrasonic()
{
 pinMode(Trig, OUTPUT);
 pinMode(echo, INPUT);

}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Setup MPU6050 function

void Setup_MPU6050()
{

    Wire.begin();
   // initialize device
    Serial.println("Initializing I2C devices...");
    mpu.initialize();

    // verify connection
    Serial.println("Testing device connections...");
    Serial.println(mpu.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");

    //Initialize DMP in MPU 6050
    Setup_MPU6050_DMP();

}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Setup MPU 6050 DMP
void Setup_MPU6050_DMP()
{

     //DMP Initialization

   devStatus = mpu.dmpInitialize();

   mpu.setXGyroOffset(220);
   mpu.setXGyroOffset(76);
   mpu.setXGyroOffset(-85);
   mpu.setXGyroOffset(1788);

   if(devStatus == 0){
         Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);
    //mpu.setDMPEnabled(true);

//    pinMode(PUSH2,INPUT_PULLUP);
//    attachInterrupt(PUSH2, dmpDataReady, RISING);

    mpuIntStatus = mpu.getIntStatus();

    dmpReady = true;

    packetSize = mpu.dmpGetFIFOPacketSize();

   }else{

     ;
     }
}

void loop() {

 //Read from Serial port
    Read_From_Serial();

    //Send ultrasonic values through serial port
    Update_Ultra_Sonic();

    //Send MPU 6050 values through serial port
    Update_MPU6050();

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Read from Serial Function

void Read_From_Serial()

{
   while(Serial.available() > 0)
    {

       int data = Serial.read();
//       Messenger_Handler.process(data);

    }

}

void Update_Ultra_Sonic()
{
  digitalWrite(Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(Trig, LOW);
  // The echo pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  duration = pulseIn(echo, HIGH);

  //Sending through serial port
  Serial.print("u");
  Serial.print("\t");
  Serial.print(cm);
  Serial.print("\n");

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Update MPU6050

void Update_MPU6050()
{

  int16_t ax, ay, az;
  int16_t gx, gy, gz;

    ///Update values from DMP for getting rotation vector
    Update_MPU6050_DMP();

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Update MPU6050 DMP functions

void Update_MPU6050_DMP()
{

 //DMP Processing
 // if programming failed, don't try to do anything
    if (!dmpReady) return;

     // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {

        ;

          }

// reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    //get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount > 512) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
    }

// otherwise, check for DMP data ready interrupt (this should happen frequently)
else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);

            Serial.print("i");Serial.print("\t");
            Serial.print(q.x); Serial.print("\t");
            Serial.print(q.y); Serial.print("\t");
            Serial.print(q.z); Serial.print("\t");
            Serial.print(q.w);
            Serial.print("\n");

        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif

        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif

    }

}

What exactly is the problem with your combined code? And please format the code correctly by selecting it and click the {} button in the editors toolbar or press Ctrl+k

I want to read mpu6050 and ultrasonic sensor both. but it this is the error                       Initializing I2C devices...
Testing device connections...
MPU6050 connection successful
Enabling DMP...
u 0

Have you tried to get the ultrasonic Sensor to work alone to be sure, that it works correctly?

yes. it worked. when both sensor test individually it work.

How did you connect a 3.3v sensor to a 5v board?

mpu6050 gy-521 work with 5v

No, it does not. It has no level shifters for sda and scl.

In the function Update_Ultra_Sonic() you do the measurement and save the result in the variable duration. Then you print the variable cm, but you haven't calculated the value for this variable yet. You have to calculate the number of cm from the echos duration and save the result in cm. When you don't do this, the variable stays at zero.


text:
Sanity check for dual IR LED circuit
If the intent is to drive the two LED's with 200-400mA (using PWM @ 38Hz), is there anything wrong with this solution?

Perhaps this is a better solution, as it ensures the current is exactly the same for the two LED's (so that they are not out of phase with each other):

I would use a single transistor rated at minimum 1A continuous (a MOSFET by choice), and have both LEDs switched in parallel with their own resistor.  By having them in series as in your second schematic you are limiting the input voltage to a minimum of 2×Vf which could be as high as 5.2V, and thus more than your power source can provide.

simulate this circuit – Schematic created using CircuitLab
This gives the same result as your first circuit, but only uses one transistor for the switching. You can add more LED+Resistor pairs in parallel as you like as long as the total current is below that which the chosen MOSFET can handle.
You should rate the MOSFET to handle the maximum continuous current, not the pulse current, in case the output of the Arduino should be set continuously HIGH instead of sending PWM.
You should also note that the pulse current of an LED is usually rated at 1% duty cycle.
Also note that as the voltage of your power source drops, so will the voltage across the resistors, and thus the current flowing through them (and your LEDs) making the LEDs dim.  It may be beneficial to first pass your battery power through a high-efficiency 3.3V switch-mode regulator to keep the voltage stable whilst wasting the minimum amount of power in the regulation.

Thanks @Majenko.  I read about using MOSFET's vs BJT's and came across one statement that asserted that BJT's can switch faster, which I thought would be relevant in my case since I'm pulsing at 38KHz...but perhaps the MOSFET's are plenty fast enough so it's not a concern.  I have already ordered some 30A/60V NPN MOSFET's...are those a good choice in your opinion?  Thanks again.

Yes, BJTs switch faster. But by faster we're talking high MHz and GHz not just a few kHz.  The critical parameter for a MOSFET is the threshold voltage. You need it to be fully turned on at a voltage below he output of your Arduino.  Aim for <3V threshold voltage. Check the graphs in the datasheet.

Also you should realise that the output of the Arduino is MOSFETs anyway, so they must be able to switch fast enough. In fact the entirety of the Arduino internals are MOSFETs. And that can run at up to 20MHz.  38kHz is nothing to a MOSFET...  I regularly work with MCUs at 200MHz. Still 100% MOSFETs internally...  Even your swanky 3.8HGz computer is MOSFETs...  Teeny tiny MOSFETs...

Gate threshold is 1-2V, if I'm reading the datasheet correctly.  (It has 1 in the Min column and 2 in the Max column, but nothing in the Typical column.)  Thanks for the tip about Arduino's internal MOSFET's!  Very cool to know...

There should be a graph of gate voltage vs drain-source current. Shaped like a curve. Find 5V on the gate voltage axis and see what the current flow is. It should be on the almost vertical section of the graph.

However 1 min and 2 max sounds good to me.

I wanted to paste the chart in the comments, but I'm thinking that's not possible.  Link to datasheet below if you'd like to take a look.
I can't interpret that chart and any way I try it seems to indicate that if the transistor is fully saturated (at 4.2-5V) then a large amount of current will be going through my circuit.
I must not be reading it right.
https://www.sparkfun.com/datasheets/Components/General/RFP30N06LE.pdf

At 5V gate voltage the MOSFET has 0.047Ω resistance ("Drain to Source On Resistance" in the table). If you put 15V directly across it (Vdd annotation on the graph) you would see about 80A flow through it (assuming your voltage source could provide it of course).  It's just a representation of the resistance of the MOSFET (R_DSON as it's called) as profiled using their test conditions.


text:
Controlling LED and Button with single pin
I am trying to use an ATTINY85/Ardunio Uno to turn an LED on and listen to a button input. I don't mind if the LED turns on when the button is used.
I am have found this thread from a couple of years ago however it doesn't seem to work at low voltage (3V) due ending up with floating pins due to the forward voltage of the LED. I was wondering if anyone had a soltion or if they could check to see if my solution would be suitable.
Many Thanks

simulate this circuit – Schematic created using CircuitLab

I think this is what you want...

simulate this circuit – Schematic created using CircuitLab
To check for button, set pin to INPUT and enable pullup. If pin is LOW, then the button is pushed.
To light LED, set pin to OUTPUT and LOW.

Ah this is the one I tried to link, OP has been updated. The issue I am having with this one is the drop in voltage of the LED is 1.6V so it's causing it to float and go in-between input states.

@Archie why is it "floating in-between input states"? if you enable the pull-up, either the button is not pressed (and so the pin floats to 3.3V, even if the LED is not conducting anymore, since there is a pull-up) or it is pressed (and so it is capable of pulling low both the pull-up and the LED, and it goes to GND). Please note that the LED is put not in the same position as your circuit, but it is in the upper part, while the button is in the low part

Ahh the internal pull ups were not enabled. Thank you very much.


text:
Why does the program size increase so drastically with these switch-cases?
EDIT: The problem is my op-code catch is op >= 0x20 || op <= 0x2F rather than op >= 0x20 && op <= 0x2F and so most of the switch-case was being optimised away!
This is a really difficult question to ask, because I cannot make a minimal-verifiable version of it as its own sketch.
For fun, I'm writing an ATtiny85 byte-code interpreter. It reads op codes from EEPROM and executes them. Keeping my eye on the program size, I've been completely stumped by what's happening in the following.
I really must stress though - I could not recreate this in a minimal sketch :(
//_mem[] is a uint8_t[] for RAM allocation
//_pMem is a moveable pointer to _mem[]
//NextByte() retreives the next byte from EEPROM

//Before this is if-else statements catching ranges of similar op codes
  ...
//This one catches similar math functions (mem op= num1):
  } else if (op >= 0x20 || op <= 0x2F) {
    uint8_t num1 = _mem[NextByte()];
    if      (op == 0x20) *_pMem += num1; //1A
    else if (op == 0x21) *_pMem -= num1; //1S

//For all other op codes:
  } else {

//These can mostly be ignored

    switch (op) {
      case 0x00: J(*_pMem);                                break; //J_
      case 0x01: _o = NextWord();                          break; //JA
      case 0x0A: ++_pMem;                                  break; //MI
      case 0x0B: --_pMem;                                  break; //MD
      case 0x0C: _pMem += NextByte();                      break; //MA
      case 0x0D: _pMem -= NextByte();                      break; //MS
      case 0x10: *_pMem = NextByte();                      break; //S_
      case 0x11: _mem[NextByte()] = _mem[NextByte()];      break; //CP
      case 0x12: *_pMem = _mem[NextByte()];                break; //V_
      case 0x13: _mem[NextByte()] = *_pMem;                break; //_V
      case 0x80: SV();                                     break; //SV
      case 0xFF: noHalt = false;                           break; //HT
    }

The program in total, when in this configuration, is 2030 bytes.
However, when I instead put just the two op codes, 0x20 and 0x21, into the switch-case, the program balloons to 2680 bytes! Code:
      //the if-else statement for 0x20 and 0x21 is completely removed
      ...
      case 0x13: _mem[NextByte()] = *_pMem;                break; //_V
      case 0x20: *_pMem += _mem[NextByte()];               break; //1A
      case 0x21: *_pMem -= _mem[NextByte()];               break; //1S
      case 0x80: SV();                                     break; //SV
      ...

Immediately, I thought "it must be something to do with replacing num1 with _mem[NextByte()] each time", but when I tried the same thing in the if-else configuration, it was only 2044 bytes.
Obviously there's waaay more code besides this out-of-context slice, and I'd be happy to share the whole sketch, but why does it even matter? I cannot imagine why there is a 600+ byte jump, other than maybe the logic behind the switch(). Hence I'm asking!
It's not as if it's suddenly using floating point or any other gotcha...
While trying to make a minimal sketch, the if-else and switch statement configurations were only several bytes different in size, even while propping up various parts with unoptimisable code.
Thank you for all your time.

I can only guess, but my guess is that those two lines break the optimization (perhaps a number of optimizations). Perhaps not just the switch-case but the memory pointers as well. The switch-case can be efficient and it can be not efficient. Therefor, you can only get this behaviour with the switch-case statement. Perhaps there are compiler options that can be useful, but I don't know any for the switch-case. What was the size with a if-else chain with and without those two lines?

@Jot, it's one of 3 until the unconditional else - it's the 2nd one to use a range match.

I meant, if you convert the complete switch-case to a if-else-if chain, then what is the difference in code size with and without those two lines? That should be normal. A if-else-if chain is compiled in a normal way, the switch-case is known to cause such things, although 600 bytes is really a lot. I can't believe that the compiler generates a full table (or two tables) with a jump table for 256 16-bit addresses. If removing the switch-case helps, then stay away from it. You could have a look at the binary code with avr-objdump.

don"t you need break in cases of the switch?

@Jot, I believe converting that whole switch-case into an if-else was smaller by 2 bytes, so I decided to keep it as a switch-case for readability. This 600+ byte problem isn't actually affecting me for now, but I'd just like to know what's going on :)

@Juraj, the breaks are aligned just before the comments

Smaller by 2 bytes? You mean after the size increased to 2680, turning the complete switch-case into a if-else-if chain reduced the size to 2678? What was the size with and without those two lines?

sorry, I didn't see them on phone

Sorry to waste everybody's time! We can see exactly what's happened... my op-code catch is op >= 0x20 || op <= 0x2F rather than op >= 0x20 && op <= 0x2F, so the whole switch-case was being optimised away.

Compilers can be smart that way. Too smart for us humans to understand why.

Sorry that I didn't see that. There is a warning for unused variables. Is there a warning for unused code? Sometimes I put this pragma at the beginning of sketch: #pragma GCC diagnostic warning "-pedantic"


text:
Arduino Uno: avrdude: stk500_recv(): programmer is not responding
I have an original Arduino Uno board purchased directly from the official arduino website. I have used it successfully with IDE v1.8.5 on my Windows 10 laptop for various projects in the last 6 months.
Recently my laptop stopped working and I tried shifting the IDE to my old windows 8 laptop. I installed the latest IDE v1.8.8 on it. But whenever I am trying to upload the sample blink code to the arduino, I am getting the following - "stk500_recv(): programmer is not responding" error.
I have verified that the I have selected the right board - "Arduino/Genuino Uno" in the IDE. I can also see the driver installed in the windows "Device Manager" with COM3 as the port. I have selected COM3 as the port in the IDE as well.
Thinking that its a bit old windows 8 laptop, I tried installing the IDE on two other newer laptops (windows 7 and 10) along with the same troubleshooting steps as above. But unfortunately, same results.
I looked at the many links on internet and tried the following steps, but no luck so far.

Resetting the board: It flashes the LED on the pin 13 twice which means the chips are ok and resetting the board. This where I think the board is functioning well.
Tried using both "Upload" and "Upload using programmer" mode from IDE.
Restarting laptops multiple times.
Unplugging USB cable between laptop and arduino several times.
Reinstalled arduino ide version 1.8.5 which was on my old laptop.

Do I need to choose Tools --> Programmers? I guess this is not needed as I am using USB to upload code, but please advice. What else can I try? Please help !!
Here is the complete error:
================================================================
avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\Anurag\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf"

         Using Port                    : COM3
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: reading input file "C:\Users\Anurag\AppData\Local\Temp\arduino_build_337690/Blink.ino.hex"
avrdude: writing flash (930 bytes):

***Writing | avrdude: stk500_recv(): programmer is not responding
######avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding***
================================================================

UPDATE 1:
In the meanwhile -

I also changed my USB cable.
Tried on a MAC laptop as well.

No luck with these approaches as well.
I also tried the Arduino loopback test with my board and it is giving me positive results which suggests that my board is processing the data. May be the problem is only when uploading the code. I have updated my original post as well with these steps.
Still need help!
Thanks in advance,
Anurag

Have you tried to test with another Arduino?

@MatsK - Thanks for looking at this query. Unfortunately, I do not have another Arduino board to check. I have ordered a clone on ebay and expecting to receive it in a couple of days. Will try that as well.

@Matsk ... In the meanwhile, I also changed my USB cable and tried on a MAC laptop as well. No luck with these approaches as well. I also tried the arduino loopback test with my board and it is giving me positive results which suggests that my board is processing the data. May be the problem is only when uploading the code. I have updated my original post as well with these steps.

The output shows that avrdude (the uploading program) can contact your Arduino and is able to detect some settings. But as soon as it tries to upload it doesn't get the correct answers. Seems like the bootloader is damaged. Try to burn a new bootloader (you need an ICSP programmer for that, another Arduino with a special sketch and some basic hardware might do the job too).

A Programmer connects to the ICSP header. There are two - one for the 328P, with 2x3 male header pins. The 2nd is near the Aref header, is usually just holes (or solder filled holes), that is the one for the Atmega16U2 for the USB interface.  Select Upload using Programmer does nothing if you do have a Programmer connected to the 328P's ICSP header.

@Pylon - Thanks for looking at this query ! Yes, apart from trying a new Arduino, I guess putting a new boot loader is the only other option. I have seen some articles for this which used Arduino and some jumper wires. Is there a special sketch involved too? Do you have any good reference which I can try? Also, is this another arduino approach different than using ICSP programmer? Should I try both of the first does not work?

@CrossRoads - Thanks for the info about the programmers. Actually, I have not used any programmer so far. On one internet post, I saw someone trying that too, hence I also tried. At that time, I thought "programmer" is some internal software. But of course, it did not work as I was not using an actual hardware programmer at all.

Using an Ardiuno as a programmer to reload the 16U2 should supposedly work. I don't use any cards that use 16U2, I prefer FT232 for USB interface, so I go with ProMinis and plug on an FTDI Basic for downloading and debugging, then remove it when I use the ProMini (I don't do projects needing fulltime internet access for example). The 16U2 sketch is available in the Arduino folders somewhere.