text:
Keyboard.write writing ASCII integer value as a String
I have the following code:
#include <SoftwareSerial.h>
#include <Keyboard.h>

SoftwareSerial ttySerial(10, 11); // RX, TX
void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Native USB only
  }

  Serial.println("Serial Initialized");

  //Set the data rate for the SoftwareSerial port
  ttySerial.begin(115200);
  ttySerial.println("tty Initialized");

  Keyboard.begin();
}

void loop()
{
  while (ttySerial.available())
    //Serial.write();
    Keyboard.write(ttySerial.read());

//    if (Serial.available())
//      ttySerial.write(Serial.read());
}

my problem is that ttySerial.read() is an int and I thought that the Keyboard.write method could hand integer arguments: Keyboard.write(32) should write "< space >" not "32".
Any ideas what is going on?

i do not see Keyboard.write(32) in your code ... what are you doing to send byte 32 to the sketch?

@jsotola thats because I am writing byte 32 to the RX Pin using SoftwareSerial. The ttySerial.read() is where I recover that and want it to be written using Keyboard.write. Simply put ttySerial.read() == byte 32 (but can also take on the form of other bytes)

And what is the problem? Is this program misbehaving? If so, what it it doing? What behavior do you expect instead?

it writes 32, because you send "32". Send 32 or ' ' to simulate space bar press.

@Juraj How can I convert "32" as received fromstring to int? I tried using ttySerial.read().toInt()) but I get a compilation error

@EdgarBonet The keyboard is writing the ASCII integer values instead of the ASCII character corresponding to that integer. My expectation is a write of the ASCII character

two separate characters are received. you can print debug messages to Serial Monitor while using HID

@Juraj should I be using ttySerial.readString() then? How can I read the two separate characters into a single integer value? Note sometimes the integer will be 1 digit, sometimes 2, sometimes 3

you could use parseInt. or send bytes not text. what is the sender? send ' ' not "32"

@Juraj Yes it looks like parseInt() is what I am looking for, thanks! Ill try it out tonight. Unfortunately the js serial-port library I am using only allows transmission of buffers and strings, not integers. Also, handling modifiers could become difficult by not sending the ASCII integer value. It looks like parseInt() will read chars and automatically convert the data type to int so that should be perfect.

why not send the characters you want to press and not the ascii codes?

@Juraj > "handling modifiers could become difficult by not sending the ASCII integer value"

You can send arbitrary data with a JavaScript buffer. For instance, both Buffer.from([32]) and Buffer.from(' ') will give you a buffer holding a single byte with the numeric value 32.

@EdgarBonet for some reason that isnt working but I will mess around with it some more

@Juraj parseInt() works but is incredible slow - any alternatives? Edit: it's a little faster now idk why

it is not slow. it waits a second for the next character, because it doesn't know which is last. you could use ttySerial.setTimeout(100); (in setup)

write will treat an int as a number and assume you want it converted to ascii.  Try casting that to char:
Keyboard.write((char)ttySerial.read());

The print class treats char variables as if they are already ascii codes.

Are you saying I should try Keyboard.print(...)? Or .write as you have?

I'm saying that either way you have to feed it a char if it is an ascii code.  And yeah, I'd probably use print there.

Well I tried (char)... at one point but the behavior still wasn't write but I didn't do it using .print not sure if that would make the difference - I'll have to try it out next week but I'll let you know

Delta_G, read the comments please


text:
Differences between Arduino Uno SMD and Uno DIP
I just bought an Arduino Uno (SMD version) from W11Stop and want to know whether there is any other difference between Arduino UNO DIP and Arduino UNO SMD besides knowing that the SMD version doesn't have a DIP chip which can be replaced?
I am just a beginner so please help me if I am wrong!

Afaik, the SMD version actually has two extra analog pins. But they may not be accessible on your Arduino board (ADC6 & ADC7). The PDIP has 28pins TQFP has 32 pins (check the datasheet). But the internals should be the same by design.

As far as I know there is no real difference, at least not directly related to the SMD.
There are many clones which sometimes have slightly different behavior or protection.
But for the SMD the only disadvantage is it cannot (easily) be replaced.
I have one original one (with DIP) and several clones and so far I did not found any difference, except for having mini USB instead of normal USB.

mini USB instead of USB-B is just a chinese version of it. Many clones of Arduino bought from china have either MINI, MICRO or B-type usb port, you can actually choose. But none original(UNO) has ever had a mini USB on it.

Actually, there are no different on the functionality. But you may can't go through some features, because the ATmega can be remove it manually without any special tools. One of the useful case as ArduinoISP for burning bootloader to another ATmega328p AVR.
For personal suggestion, you just needed one piece of PDIP/DIP version UNO, others boards you can consider the lower cost, such as Nano, Pro Mini(Without USB-to-TTL), UNO(SMD).
For the USB-to-TTL, there are many options in the market, watch this video to explain what are they different.

alright... at least as a starter we could keep continuing the dev under any arduino ....

There's no actual difference, but just the "look". Neither version of it should bother you at anything, but there are 2 things, worth mentioning.

The IC can fall out of DIP socket: I've been told a few times this already, but never had experienced such behaviour or been at occasion, where that happened.
So here's a disadvantage for DIP cases.
DIP has also possibility of changing waaaaaaaaaay easier the microprocessor in case of failure. You simply grab it off (even might with a help of a screwdriver) and you're ready to put in a new one. So this is an advantage nr. 1.
I also like to use an Arduino in projects, but not the whole board. I just take the IC (atmega328) and use 2 ceramic caps with 16MHz quartz and I've got my own arduino on other PCB - in this case, you can use Arduino UNO board as a programmer. This is how to avoid installing FTDI or CH340 chip on other boards.
Advantage nr. 2.

source: Stack Exchange

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

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

sort: votes


text:
Servo only going one direction till it reach limit
I have a ATTiny85 with a standard servo motor attached to it. I would expect the following sketch to make the servo to oscillate between position 60 and 100 but instead it just to to it's limit (180) and grinds there...
Any ideas ?
#include <avr/power.h>
#include <Adafruit_SoftServo.h>

Adafruit_SoftServo servo;

#define MOTOR_PIN 0

bool flip = true;

void setup() {
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  // Set up the interrupt that will refresh the servo for us automagically
  OCR0A = 0xAF;            // any number is OK
  TIMSK |= _BV(OCIE0A);    // Turn on the compare interrupt (below!)

  servo.attach(MOTOR_PIN);
  servo.write(90);           // Tell servo to go to position per quirk
  delay(15);
}

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

  delay(500);

}

// We'll take advantage of the built in millis() timer that goes off
// to keep track of time, and refresh the servo every 20 milliseconds
volatile uint8_t counter = 0;
SIGNAL(TIMER0_COMPA_vect) {
  // this gets called every 2 milliseconds
  counter += 2;
  // every 20 milliseconds, refresh the servos!
  if (counter >= 20) {
    counter = 0;
    servo.refresh();
  }
}

Thanks.

!flip doesn't really do anything and will probably be optimized out by the compiler. You need to save the result: flip = !flip;
You can simplify the code a bit:
void loop() {
    if(flip) {
        servo.write(60);
    }
    else {
        servo.write(100);
    }
    flip = !flip;
    delay(650);
}

Or, get rid of the delay altogether:
uint32_t last_millis = 0;
void loop() {
    if (millis() - last_millis >= 650) {
        servo.write(flip ? 60 : 100);
        flip = !flip;
        last_millis = millis();
    }
}

That was part of it (must be doing too much Ruby these days).
The other part is that I was compiling with an outdated Arduino core library... Updated and all is good now. Thanks.

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


text:
ESP8266-12E and MCP23017 , unable to identify the application
After googling much I have found that MCP23017 can be used with esp8266-12e for more number of output pins.
I have tried all the programs from different tutorials on internet but could not make it work.
Basically my question is , i want to control all the 16 leds connected to GPA0-7 AND GPB0-7 individually , hence i need a program snippet for make it work.
I am using AP mode for esp8266-12e and sending get methods with params to identify which led to turn on/off.
Even i have written the basic program , can anyone help me completing the entire program. thanks for the help in advanced.
Pins i have connected are
ESP8266-12E    |   MCP23017
−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−
GPIO-14 (scl)  |  PIN-12 (SCL)
GPIO-2 (sda)   |  PIN 13 (SDA)
GND            |  A0,A1,A2

My code:
#include <Wire.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

void handleRoot() {
    server.send(200, "text/html", "
You are connected
");
}

void setup() {
    delay(1000);
    Serial.begin(115200);
    Serial.println();
    Serial.print("Configuring access point...");
    WiFi.softAP(ssid, password);

    IPAddress myIP = WiFi.softAPIP();
    Serial.print("AP IP address: ");
    Serial.println(myIP);
    server.on("/", handleRoot);

    server.on("/led1", [](){});
    server.on("/led2", [](){});
    server.on("/led3", [](){});
    server.on("/led4", [](){});
    // up to 16 leds i have written same method.

    server.begin();
}

void loop() {
    server.handleClient();
}

You have an MCP23017 which connects to the device using the I2C protocol, which means you need the  library.  You also need to ensure that SCL and SDA are 'pulled up' using 4.7Kohm resistors between the data lines and the +ve line.
You will then need to send commands to the device to initialise it and set the pins to OUTPUT.  (See http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf).
When running you will need to update the state of this pins by sending messages such as  0x09 0xFF to turn them all on.
It is going to be worth looking for a library that already does all this, but writing your own shouldn't be too hard.  You will be able to use an Arduino library on an ESP8266.
These chips are the easiest ones to use and learn about I2C, so its worth looking at the manual and trying to write your own "library" (Just start by writing a C++ class within your sketch folder.)

A very useful link and the description you have provided Matt.
I need to read and understand whats written in the docs and implement it. it will take time for me to do it. But thanks for the guidance. I think i will need more ahead.

hi , i tried to connect 4.7k and 22k resistors for sda , scl
sda --22k-- Vcc(+5v) And
scl --22k-- vcc(+5v)
but still not getting anything.
i have been trying to program this since a lot of days , but not be able to do it.
can u please help me more in this.
i am using this code in arduino
https://github.com/pedrominatel/esp8266-arduino-examples/blob/master/mcp23017/mcp23017_esp8266.cpp

the changes in this example i have done are line 152 : MCP23017_init(u8_MCP23017_address, 4,5);
i tried this too becuase in some datasheets it has 4=sda and 5=scl

any guidance please.

Step 1 Try using I2CScanner http://playground.arduino.cc/Main/I2cScanner rather than your own code to make sure that the hardware is functioning.  ESP pins number in the code do not match the pin number on the boards usually.  Find an image (on Google) of your ESP board with the pin numbers listed and use the GPIO_n numbers.

i tried 4 i2cscanner programs , but none of them are detecting the  i2c address. also tried to connect wires to different pins for trial and error , still not working.
please guide.

If I2CScanner can't find it you either have a circuit wiring problem, or faulty hardware.  Just use  the Arduino and MCP IC and minimal wires and 2 pull up resistors.

Wired whole thing again.
the result in i2c scanner i got is ;
I2C device found at address 0x38  !
whats next???

@KarmaCoding - Now you need to write a handler function for you on handlers to call.  You could do it from scratch http://tronixstuff.com/2011/08/26/tutorial-maximising-your-arduinos-io-ports/ or you could use a library https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library.  All you are doing is sending a one byte address and some data to the chip (using wire.write) and you should have flashing Leds in no time.  Once you get the hang of this you will understand just about all I2C devices.


text:
Can we use analog input pins as a parameter of analogWrite() for PWM?
int led = A1;

void setup() {
   pinMode(led, OUTPUT);
}

void loop() {
  analogWrite(led, 188.7);
  delay(100);
  analogWrite(led ,0);
  delay(100);
}

Like this and it works! I mean I am getting the exact voltage as calculated while mapping 5V between 0-255

you say it works ... so what is your question?

analogWrite doesn't take float value. the second parameter is int

On the Nano, only the pins D3, D5, D6, D9, D10 and D11 are PWM-capable.
If you try to analogWrite() to any other pin, you will get either
0 V (if you write any value less than 128) or 5 V (for any
other value).
If you get 3.7 V when 5 V is expected, that's because either
your power supply is too weak, or you are putting too a heavy load on
the pin.

How do I use the analog IO pins for giving an analog output on the Nano?

@AaronJohnSabu: You don't. The nano cannot give analog output, only PWM.

PWM output works for my case. But does this mean that the analog pins of an Arduino Nano can only take input and not give an output at all?

@AaronJohnSabu: The analog pins can provide output, but only logic (either LOW or HIGH) output.

Exactly :). How do we do that? Can you point me to an answer that talks of the same?

@AaronJohnSabu: Like any other logical output: pinMode(A0, OUTPUT); digitalWrite(A0, HIGH);


text:
How can if resolve this conflict between matrix keypad library and neopixel library?
I'm trying to use a 4x3 matrix keypad as a user interface to control parameters of a Neopixel strip control program.
I'm using Adafruit's Neopixel library and This Keypad library.
Both work fine on their own and none of my code, outside this instantiation of the keypad library, interferes with the programs functionality.
The code is around 400 lines so I'm only including a snippet:
I've now included all functions which are called in setup, as well as the one we are supposed to land on in loop() as a result of the switch statement.
#include "math.h"
#include "Adafruit_NeoPixel.h"
#include "Keypad.h"
#ifdef __AVR__
#include "avr/power.h"
#endif

#define PIN 9 //Neopixel data pin
#define NUMPIXELS 300 //currently 300

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
    {'1','2','3'},
    {'4','5','6'},
    {'7','8','9'},
    {'*','0','#'}
};

byte rowPins[ROWS] = {8, 7, 6, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {4, 3, 2}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

//f=1/p period should be between 1s and 10s so...
//frequencies should be somewhere between 0.1Hz and 1Hz
int period[NUMPIXELS];

float twoPI = 2 * PI;

int rainbowNow = 0;
unsigned int xOff = 0;

int switcha = 0;

byte hue = 192;
float sat = 0;
float lum = 1;

float lumSave;

int *rgb;

char select = '5';
char hueInc = '6';
char hueDec = '4';
char lumInc = '2';
char lumDec = '8';
char satInc = '3';
char satDec = '1';
char onoff = '0';

boolean holdFlag = 0;

void setup(void) {
  //create array of period lengths for each pixels sine wave
  randomSeed(10);
  for (int i = 0; i < NUMPIXELS; i++) {
    period[i] = random(2, 20);
  }
  Serial.begin(9600);

  strip.begin();
  strip.show(); // Initialize all pixels to 'off'

  //showOff();
  fadeIn();
  sparkle();
}

void loop(void) {

  char key = keypad.getKey();
  change(key);

  switch(switcha) {
    case 0: solidColour(); break;
    case 1: rainbow(); break;
    case 2: twinkle(); break;
    case 3: satSine(); break;
    case 4: hueSine(); break;
    case 5: rainbowCycle(); break;
  }
}

void solidColour() {
  rgb = Wheel(hue, sat, lum);
  for(int i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, strip.Color(rgb[0], rgb[1], rgb[2]));
  }
  strip.show();
  delay(20);
}

void fadeIn() {
  Serial.println("FADE IN");
  for(float j=0; j<1; j+=0.16) {
    rgb = Wheel(hue, sat, j);
    for(int i=0; i<NUMPIXELS; i++) {
      strip.setPixelColor(i, strip.Color(rgb[0], rgb[1], rgb[2]));
    }
    strip.show();
    delay(100);
  }
}

void sparkle() {
  Serial.println("SPARKLE");
  rgb = Wheel(hue, sat, lum);
  strip.setPixelColor(0, strip.Color(rgb[0], rgb[1], rgb[2]));
  for(int i=1; i<NUMPIXELS; i++) {
    int blnk = random(0, NUMPIXELS-1);
    strip.setPixelColor(blnk, strip.Color(0, 0, 0));
    strip.show();
    delay(40);
    strip.setPixelColor(blnk, strip.Color(rgb[0], rgb[1], rgb[2]));
    strip.show();
  }
}

//will create pseudo-Saturation by reducing white with increasing sat
//brightness will be achieved by scaling all by a constant
// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
int* Wheel(byte WheelPos, float pseudoSat, float pseudoLum) {
  static int rgb[3];
  WheelPos = 255 - WheelPos;
  if (WheelPos < 85) {
    rgb[0] = (255 - WheelPos * 3) * pseudoLum;
    rgb[1] = 0;
    rgb[2] = (WheelPos * 3) * pseudoLum;
  } else if (WheelPos < 170) {
    WheelPos -= 85;
    rgb[0] = 0;
    rgb[1] = (WheelPos * 3) * pseudoLum;
    rgb[2] = (255 - WheelPos * 3) * pseudoLum;
  } else if(WheelPos >= 170) {
    WheelPos -= 170;
    rgb[0] = (WheelPos * 3) * pseudoLum;
    rgb[1] = (255 - WheelPos * 3) * pseudoLum;
    rgb[2] = 0;
  }

  return rgb;
}

void change(char key) {
  if(key == select) { //select
    if(switcha < 5) {
      switcha++;
    } else {
      switcha = 0;
    }
  } else if(key == hueDec) { //fwd
    if(hue > 0) {
      hue--;
    } else {
      hue = 255;
    }
  } else if(key == hueInc) { //back
    if(hue < 255) {
      hue++;
    } else {
      hue = 0;
    }
  } else if(key == lumInc) { //up
    if(lum < 1) {
      lum+=0.05;
    } else {
      lum = 0.05;
    }
  } else if(key == lumDec) { //down
    if(lum > 0.05) {
      lum-=0.05;
    } else {
      lum = 1;
    }
  } else if(key == onoff) {
    if(lum != 0) {
      lumSave = lum;
      lum = 0;
    } else if(lum == 0) {
      lum = lumSave;
    }
   } else if(key == satInc) { //play
    if(sat < 1) {
      sat+=0.025;
    } else {
      sat = 0.025;
    }
  } else if(key == satDec) {
    if(sat > 0.025) {
      sat-=0.025;
    } else {
      sat = 1;
    }
  }
}

So long as I comment out the line Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );, the code runs as expected and the Neopixel strip lights up in the way I have programmed.
However, with that line, nothing lights up at all. The code still reaches all the functions, (I have checked with Serial.print).
(EDIT: It also works with the Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); included so long as I comment out the switch statement in loop(). How can a statement in loop affect the setup function?!)
I think it must have something to do with either interrupts, or a polling frequency within the Keypad library with interferes with the 'delicate' timing of the Neopixels.
The massively frustrating this is that I have solved this problem before on this exact hardware but the code was lost and I'm having to reconstruct it for a repair job.
If you could help me specifically identify the problem, or suggest how I might implement my keypad interface with the neopixels I would be very grateful.
Arduino ide2:1.0.5 (EDIT: also used 1.8.9 with no different result)
Arduino Nano Board
Sodial 4x3 Matrix Keypad
ws2812b rgb 300 neopixel 5M strip

Are you saying IDE version 1.0.5? That is ancient. Upgrade to something current.  I think 1.8.9 is the latest.  www.arduino.cc

The used keypad library doesn't use interrupts, so the problem must lie at another place. Please create a short working example, that shows your problem, so that we can see the whole code, that isn't working. That is better than cutting parts of the code out.

I've added the extra functions to make it (should be) working code. Lights fade in, lights blink, lights go solid colour. Hope that gives you more context.

In some cycles you iterate to NUMPIXELS. In some - to strip.numPixels(). Why the discrepancy? Are they the same?

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


text:
Why are LED's receiving different voltages connected to Arduino
I have four LED's all connected the exact same way to four pins via four 150OHM resistors. (ignore the sensors, they are doing nothing currently) The code is very simple in the loop:
  digitalWrite(blue1, HIGH);
  digitalWrite(green1, HIGH);

  digitalWrite(blue2, HIGH);
  digitalWrite(green2, HIGH);

Here's a photo of the setup, notice how the LED's all light up differently. They are receiving the following voltages from left to right (2.48, 1.72, 3.02, 2.15):

Why is this happening and how do I get them all to light up the same?

Note that, apart from the pinMode issue, blue and green LEDs are likely to have very different forward voltages and quite possibly also different brightness, so balancing their light output is going to be nontrivial anyway.

After trying another Arduino I realized the problem. I did not use pinMode in the setup for all of the pins. Darn.

Good point, I've been bitten by this mistake once and it took me quite some time to find out what mistake I had done.

Yep.  By writing to a digital pin that hasn't been specifically set to an output you are actually controlling the internal pullup resistor of the input pin.  That allows a small amount of current through, but not much (so a dim glow), and the actual resistor value varies wildly from pin to pin (they don't need to be accurate for pullups), so you get different (dim) brightnesses.


text:
which is the most efficient way to save power with battery using Arduino UNO?
I am working with a ArduinoUNO - 2100 mA battery, and a solar Charger shield. I use a temperature reader that sends info every half hour with GPS-GSM shield called LONET (http://www.seeedstudio.com/wiki/LoNet_-_GSM/GPRS/GPS_Breakout for more info).
I want to save all the energy i can, i am trying to put Arduino UNO and LONET on Sleep mode.
LONE has its own mode via “AT+CSCLK=1”.
But for Arduino UNO i haven seen a library called Narcoleptic (https://code.google.com/p/narcoleptic/ for more info) wich can solve the problem.
My question is:
Is there any other method that can help me to save Battery with Arduino uno? is it a good approach to use Narcoleptic or there is another method to do it?
Thanks for your time/help and sorry for my English.
Any feedback could be welcome.

The uno board isn't very power efficient. There is the USB-to-serial chip that doesn't sleep. And the voltage regulator (I've heard) isn't very efficient. Sleeping the ATMega doesn't really help a lot. Better go with something like a Arduino Mini, and use an external programmer.

Thanks you for the answer, i will try to search info about Arduino Mini.

The regulator is horribly inefficient, especially when paired with the power steering circuitry in the Uno.

There is an even greater article on this topic: http://www.gammon.com.au/power
It shows how to reduce your power usage for the Uno from about 50mA to 350nA (0.000350mA) - at this point, you need to factor in the natural drain of batteries.
Also, I have had good success with a project that was activated by a pushbutton, by using a latch - the push button turned the power on; once the power is on, it latched. Then the Arduino can switch itself off, using one of it's pins. As far as I can tell from a simulator, there is no leakage (while it is off, to within the accuracy of the simulator, assuming a perfectly spherical transistor in a vacuum ;) ).
Just in case anyone is interested, my latch circuit can be seen at: https://i.sstatic.net/Uf9sX.png - the two resistors and the switch at the bottom represent the Arduino - +5V coming in the top, GND at the bottom, and one of the pin to switch it off is the switch - this pin should be INPUT to keep the power on; when you are ready to switch of, set it to output -> high. You should get switched off immediately. The switch at the top will switch it on. In the startup part of your sketch, set the pin to INPUT first.

There's a great article on that topic: https://www.openhomeautomation.net/arduino-battery/


text:
ESP8266: Client Server Based Home Automation System
I am working on a home automation project in which I am trying to use Star Topology, where one esp8266 acts as a server and can be accessed from web browser to receive commands from the user, while two or more esp8266 acts as clients which are connected to relays. Upon the request of user, server esp8266 sends command to the respective client to trigger the relay and the client esp8266 replies with the current status of the relay.
Connections isn't a problem so I am keeping those things aside. So far

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

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

ESP8266WebServer server(80);
String webPage = "";

void handleRoot() {
  server.send(200, "text/html", webPage);
}

void setup() {
  webPage += "
ESP8266 Web Server
";
  webPage += "
Socket #2 <button>ON</button>
 <button>OFF</button>
";

  delay(1000);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println();
  while (WiFi.status() != WL_CONNECTED) {
   delay(500);
    Serial.print(".");
  }
  Serial.print("Configuring access point...");
  WiFi.softAP(ssid, password);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  server.on("/", handleRoot);
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}

This is the code for server side. I cannot think of how to program for client side. Any help would be appreciable.
And yes. I have been through many articles, tried out many things which i found on the internet. But nothing could help me. So i am here for few more suggestions with better elaboration.

I got your point. N it seems absolutely fine for my type of project. Can i do the same thing on my web host instead of making a server on my pc? And it would be very helpful if you could share some references for the same.

ESP8266 APs can only handle 4 incoming clients, so they aren't good stand-alone servers.

dandavis --> what should be my approach to achieve the completion of my project. Hope the vision of my project is clear. There are going to be n no. of nodes

I'm voting to close this question as off-topic because to OP really just wants someone to write the code for him

I agree with most of 'Look Alterno's comment.  So here it is explained in more detail.
Each ESP runs a web server.
Each ESP will handle

GET /root/status
POST /root/change?device=x,state=y

When a client requests /root/status information on each relay managed by the device will be displayed.  For satellite ESPs this will mean displaying live data and for the central on it will mean displaying the last known state (it could also request an update at this time).  If you use an array then presenting this information will be quite simple.
When a client posts a change to a device then the satellite ESPs will change the relay state and the central ESP will forward the message onto the satellite.  It should probably also request a status update to check that the change has occurred.
If you steer clear of hardcoding things and use arrays rather than variable1, variable2, variable3 you should be able to make this expandable.  The biggest problem you will have is registering the satellites with the central device, but you could get around that for now by adding a configure page which had a HTML form that allowed you to enter the IP address of the central device and enter the name of the satellite and the name of the things connected to the relay.
Personally I wouldn't use a PC web server, yes it gives you more processing power, but I don't think you really need it for this, I was surprised how good they were.  If you have issues look at using an ESP32 instead of a ESP8266 for the central node.
I hope that helps

can u please share some references so that i could learn how to achieve this? Im just 14. I am not aware of much of programming

www.w3schools.com/html would be the best place to start.  You already know how to convert a html file into string, you've done that already.  Look at forms for posting examples and GET is the default that you know how to do.

Code Gorilla --> i have learned the html. I am aware of GET & POST method of html form. But i cant conclude this to implement this thing to my project.

Look Alterno --> I have been studying MQTT since the time you suggested. It seems great. Hope this takes me to the solution i am waiting for. Any relevant references or tutorials will be highly appreciated

Also i have found a great visual tool "Node-Red". I believe Node-Red, MQTT, Esp8266 will accomplish my needs. Correct me if i am wrong

Look Alterno --> MQTT is great stuff but it becomes necessary to use a third party broker. So it is definitely not my cup of tea. I want to build a system without any third party involvement

@RohitMathur - You have already implemented a handler for GET in the code you posted above.  A handler for POST is quite similar and there are lots of examples out there.  Or are you asking me to do it for you?

@CodeGorilla --> that would be a pleasure :P help me with the code please. i am heading nowhere to implement these methods.

Is this the thing you were guiding me on?
HTTPClient http;
http.begin("IP of Client ESP");
http.addHeader("Content-Type", "text/plain");
int httpCode = http.POST("Message from esp8266");
String payload = http.getString();
http.end();

#include<ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
String i;
long newvar;
String httpurl;
String TheHiddenAnswerOfClient;
HTTPClient http;
String SendWithAnswer(String IPcache, String monmessagecache)
{
  httpurl = "http://";
  httpurl += IPcache;
  httpurl += monmessagecache;
  http.begin(httpurl);
  http.GET();
  TheHiddenAnswerOfClient = (http.getString());
  http.end();
  return TheHiddenAnswerOfClient;
}

void setup() {
  // put your setup code here, to run once:
  i = "";
  newvar = 0;
  Serial.begin(9600);
  WiFi.disconnect();
  delay(3000);
  Serial.println("START");
  WiFi.begin("electromodule", "electromodule@456");
  while ((!(WiFi.status() == WL_CONNECTED)))
  {
    delay(300);
    Serial.print("..");
  }
  Serial.println("Connected");
}

void loop() {
  // put your main code here, to run repeatedly:
  i = (SendWithAnswer("192.168.0.2", "YES"));
  Serial.println("Before Clear");
  Serial.println(i);
  i.remove(0, 25);
  i.remove(i.length() - 11, 11);
  Serial.println("After clear");
  Serial.println(i);
  newvar = i.toInt();
  Serial.println((2000 + newvar));
}

This is the codefor clent side.the ip of the server will be provided in the code so that the server and clent are connected .Also include client header file in the program


text:
Send String to a function inside a class
I made a little class for handling menus. When creating a new instance, I pass a reference to the oled object made in main.cpp. Yet when I want to render a string using a variable, it throws an error. But I can pass a string directly to the render function with no problems. See comments in the code for what is working and what is not.

#include "Arduino.h"
#include "U8glib.h"
#pragma once

class Menu {
  U8GLIB_SSD1306_128X64& oled;

  public:
    Menu(U8GLIB_SSD1306_128X64& oled): oled(oled) {
      this->oled = oled;
    };
    void render() {
      this->oled.firstPage();
      do {
        String text = "test2";
        this->oled.setFont(u8g_font_unifont);
        this->oled.setPrintPos(0, 20);
        this->oled.drawStr(text); // not working
        this->oled.drawStr(text.c_str()); // not working
        this->oled.drawStr("works"); // works
      } while (this->oled.nextPage());
    }
  };

In the case of this->oled.drawStr(text); the error is:
error: no matching function for call to 'U8GLIB_SSD1306_128X64::drawStr(String&)

In case of this->oled.drawStr(text.c_str()) the error is:
error: no matching function for call to 'U8GLIB_SSD1306_128X64::drawStr(const char*)

How I create the instance in main.cpp:
U8GLIB_SSD1306_128X64 oled(U8G_I2C_OPT_NONE);
Menu menu(oled);
menu.render();

I can find no mention of a drawStr function in the current U8glib library that takes only one parameter. What version are you using and where did you get it?

I udated to u8g2 lib, passed 3 parameters (int int c_str) and I'm still getting the same error

@MartinVelinský if you updated it, then edit the question and ADD the new code, otherwise it is impossible to properly answer

Forget the String class.  It wastes memory on a system that is already constrained by memory.  Define your strings as const char * and you won't have any problems.
const char* t1 = "Grow";
const char* t2 = "Room";
u8g2.firstPage();
do {
  u8g2.setFont(u8g2_font_logisoso24_tf);
  u8g2.drawStr(32, 24, t1);
  u8g2.drawStr(32, 60, t2);
} while(u8g2.nextPage());


text:
ESP8266 - AP+STA mode not working properly
I'm trying to have an ESP8266 ESP-12 to serve as Access Point and Station at the same time, delivering the same webpage in both cases.
This is what I have:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <EEPROM.h>
#include <DNSServer.h>
#include <ESP.h>

const byte DNS_PORT = 53;
DNSServer dnsServer;

MDNSResponder mdns;
ESP8266WebServer server(80);

String ssid = "";
String password = "";
String webPage = "";

void setup(void){

  IPAddress Ip(192, 168, 1, 1);
  IPAddress NMask(255, 255, 255, 0);
  WiFi.softAPConfig(Ip, Ip, NMask);
  WiFi.softAP(conf_ssid.c_str());
  WiFi.mode(WIFI_AP_STA);
  Serial.begin(115200);
  delay(1000);
  Serial.println("");
  Serial.println("Soft AP Started");
  Serial.println("");

  /* Setup the DNS server redirecting all the domains to the Ip */
  dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
  dnsServer.start(DNS_PORT, "www.example.com", Ip);

  //connectToWifi();
  getCredentials(); //Reads Home WiFi credentials from the EEPROM
  if (ssid != "" and password != ""){
    WiFi.begin(ssid.c_str(), password.c_str());
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    WiFi.mode(WIFI_AP_STA);
  }
  server.begin();

  // When no password is present
  if ((ssid == "" and password == "") or (ssid == "Error")){
    // ****** MAIN PAGE ******
    server.on("/", [](){ /* HANDLES CREDENTIAL INPUT */   });
    server.begin();
  }
  else // If we have ssid and password -- check if we have connection
  {
    webPage += "
Main Webpage
";
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
    server.begin();
    //if (mdns.begin("esp8266", WiFi.localIP())) {
     // Serial.println("MDNS responder started");
    //}

    server.on("/", [](){
      server.send(200, "text/html", webPage);
    });
    Serial.println("HTTP server started");
  }
}

void loop(void){
  dnsServer.processNextRequest();
  server.handleClient();
}

Basically, it reads the credentials from the EEPROM, if there is no credential, a WiFi configuration page is displayed, otherwise it also connects to the WiFi serving the Main Webpage to both AP and Station.
The issue is that, even though I can see the AP and a ping from my PC to the WiFi Station's Ip works, I can only access the webpage if I'm connected via AP, not via Station.
Any thoughts?
Many thanks.

how did you find out the IP address of STA?

would not one server.begin() at the end of setup be enough?

The STA IP is retrieved via serial console. And having only one server.begin() gives the same result, that was just me trying something different when I tried to reset the esp whenever the configuration changed

You know https://github.com/tzapu/WiFiManager  ?

What is the IP and default gateway of your PC?

@Juraj I'm gonna check that.

@Code Gorilla, why do you need that?what are you thinking?

I was wondering if it could be a simple routing issue rather than actually a problem with you code.  When you connect via the station I guess there is another access point involved and unless you have got the routing write it will do what you describe.  (Yeah I don't actually want you IP and gateways address - well done for not posting them :) )

@Code Gorilla thanks, I'm not sure that I followed your thought, but I'll try playing around with gateways and stuff and came back with the results

@CodeGorilla I've been thinking on your solution, but I think that this is not the case, since I can connect through my PC when I don't try to make both connections work at the same time. Any other idea?

Some additional information: the only goal on this is to be able to know the IP of the ESP so I can find it on the net, if there is any other solution to this, please let me know. Thanks


text:
Copying String into another String
I have an array of Strings in my code:
String BitSequence [257];

Each string will have 23~64 characters. At one point in my code, I have to use "myString.remove()" command and I don't want to apply any changes to my original strings. I need to make a copy and perform my commands on the copied string. I did:
MycopyString = BitSequence [1];

but it doesn't work. What tricks do I need to do here to make a copy?

What does "it doesn't work" mean? What did you expect and what actually happened?

don't use String class at all. https://majenko.co.uk/blog/evils-arduino-strings

try strcpy......

@chrisl "What does "it doesn't work" mean? " resulting String is empty.

The Arduino Nano does not have enough RAM to store 257 single-character Strings.

@EdgarBonet I think you are wrong it has 256KB ram which is a lot and could successfully store 1500 Strings each having 64 characters.

"Arduino-Nano" is perhaps a confusing tag then, what device are you talking about?

@DataFiddler sorry for confusion mine is Nano 33 BLE

Edited the tag.

Do not work with the String class on Arduino. That said what to do?
Use char arrays (what an individual String is internally). Then you work with pointers or pointers to pointers. Guessing from the fragments (what type is MycopyString?) you gave, you create a pointer (?) to the element in the array.Working with String class has two disadvantages.

You have to look into the lib to see what a function really does and
by reserving and releasing memory it fractures on the long (most of the time short) run your heap causing your AVR/ESP to crash.

The possibility to create two dimensional arrays
i = 257;
char myTwoDimArray [i][64] = {'\0','\0'}// 64 ... 63 chars + 1 terminator(!)

and then you operate with pointers either to the entry (i) or in the specified char array itself.
How to remove an entry You just write:
i = 23;
myTwoDimArray [i][0] = '\0';

by writing a zero terminator to the first index (starts with 0) of the 24th (!) element (again the index starts with 0) its deleted.
Commands to look for when operating with chars
strcpy (targetChar, charToAdd); // Initializes the targetChar starts at index 0
strcat (targetChar, charToAdd); // Appends to the targetChar starts at current index

converting numeric values to chars:
  char numBuffer [16] = {'\0'}; // Helper buffer for conversions

 itoa (myNumberValue,numBuffer,10);  // converts an integer to a base 10 (decimal) char
itoa (myNumberValue,numBuffer,2);  // converts an integer to a base 2 (binary) char
itoa (myNuberValue,numBuffer,16);  // converts an integer to a base 16 (hex) char

itoa initilizes a char array so we need the helper array:
strcat (targetChar, numBuffer);

to convert float we use
dtostrf(floatVariable, StringLengthIncDecimalPoint, numVarsAfterDecimal, numBuffer);

to convert chars back to int use
int16_t myIntVar = atoi(numBuffer);

to convert chars back to floats use
float myFloatVar = atof(numBuffer, decimalsToShow); // using just atof(numBuffer)
gives you standard x.XX only 2 decimals

Hope this comprehensive intro to chars helps you for your current and future projects.

Ever checked  the result of 64 * 257 ? @Afshin mentions an Arduino Nano.
You're right: Strings are much worse, of course.

Yes I checked but the OP probably not and chars will make him aware ;-) -hopefully

Amazing explanation. It has been a week I started programming Arduinos for a project of mine, and I am kind naive. Thanks a lot.

I don't want to apply any changes to my original strings

You should read about PROGMEM and/or the __FlashStringHelper ( F-Macro ) . Probably you can even handle that vast amount of constant texts on your Nano controller, which is meant to be a controller, not a text processing computer.

You are right! but I need to receive a large file and then process it. I found using string provides me the fastest communication bit rate, maybe I am wrong since I am just a new programmer! Also, Nano BLE has 256KB of ram so, I thought,  this shouldn't be a problem.

Arduino String is never fastest nor least memory consuming. OK, Nano is an atmega328-based Arduino Nano for me (2kB RAM) so my concern might not apply here. Sorry

I had to clarify that I am using Nano 33 BLE. Sorry for confusion

Thank you for all the helpful answers.
I think also found a way to copy strings. Using "myString.substring(from,to)" I could resolve my problem. The command works on array strings as well.
mynewcopystring =mystring[2].substring(0,mystring[2].length());

String has a constructor that takes other strings.
String mycopyString(BitSequence[1]);

will create a new String object named mycopyString with its value initialized to the value of BitSequence[1].
See https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/ for more details


text:
Smoothing hx711 readings with atmega328
I am making a 50kg weighing scale using HX711 ADC. My project includes Atmega328 along with 74HC595 for driving 5 7segment displays(multiplexed). I am using the function scale.get_units()to fetch the data and the values are very well displayed on the 7segments. The problem I am facing is the readings on the 5th digit (right most 1's) are unstable. Now, if I use scale.read_average(5), my display scanning gets slow. I was wondering if there is a way to average the readings in a loop like the conventional way. I tried it but with no luck! It keeps showing random added numbers. Any help would be highly appriciated. Below is the code inside the loop. Let me know if full code is needed. Thanx in advance!
if (scale.is_ready()) {
    weight = scale.get_units();
    finalWeight = weight * 1000;
}
for (int i = 0; i < 10 ;i++) {
    sum += finalWeight;
}
average = sum / 10;
if (average < 0) {
    break_number(0);
} else {
    break_number(average);
}
display_number();
delay(1);

First of all, this code:
for (int i = 0; i < 10 ;i++) {
    sum += finalWeight;
}
average = sum / 10;

does not average multiple readings. Instead, it takes the single reading
stored in finalWeight, multiplies it by ten (by means of successive
additions), then divides it by ten to get back the same value.
If you want to reduce the noise, you have to take multiple readings and
average them. The reading-taking code must thus be inside the loop. A
simple option may be like this:
void loop() {
    sum = 0;
    for (int i = 0; i < 10; i++) {
        while (!scale.is_ready()) {}  // wait for the scale to be ready
        sum += scale.get_units();
    }
    weight = sum / 10;  // compute the average
    display(weight);    // and display it
}

Note that I have simplified things a bit by removing the scaling
factors. You can take this as simple inspiration and adapt to your
specific needs.
The code above has one problem though: as the code is blocking while
waiting for the scale to be ready, the display is not refreshed. You
could fix this by explicitly refreshing the display within the waiting
loop:
void loop() {
    sum = 0;
    for (int i = 0; i < 10; i++) {
        while (!scale.is_ready()) {  // wait...
            display(weight);         // ...while refreshing the display
        }
        sum += scale.get_units();
    }
    weight = sum / 10;
    display(weight);
}

This should work, but I would however suggest instead a third approach:
write non-blocking code. This is code that never blocks: instead, if
something can be done right now, it does it. If not, it moves along:
void loop() {
    if (scale.is_ready()) {  // if something useful can be done NOW:
        sum += scale.get_units();
        count++;
        if (count >= 10) {
            weight = sum / count;  // update the value to be displayed
            sum = 0;               // reset the averaging variables
            count = 0;
        }
    }

    display(weight);  // unconditionally refresh the display
}

This way, your loop() always runs fast, and you can add code that will
not be blocked by the stuff you wrote earlier.
Edit: As suggested by chrisl in a comment, a moving average may
better serve your needs. I would try the exponentially-weighted version,
as it is lightweight and simpler to implement. You may want to explore
this path.

In addition: Here a moving average might be a good choice, like in the second answer to this question

Thanx a lot!! I will try it.


text:
Multiple variable shared between threads?
I got 4 threads running on ESP32 (dual core):

1 thread running on 1st core which is related to the WiFi.
1 thread running on 2nd core which is related to the touchscreen.
1 thread running on 2nd core which is related to the display.
1 thread running on 2nd core which is related to the sensors.

Some of the threads execute almost instantly, while for instance the one handling the sensors can take a few seconds per interaction, and no blocking should occur meanwhile for the rest of the threads.
Anyway, with the growing of the program, a lot of variables started to be involved in data transfers between the cores, and since the whole thing is about to be redone, I have the following questions, to clear the things up for myself, since I found quite a lot of confusing, even contradictory information in examples and explanations on the internet:

Is the "volatile" keyword really sufficient for exchange of data between threads (no ISR)?
Should "volatile" always be between "noInterrupts()" and "interrupts()", even when there is no ISR function?
What approaches should be used when exchanging a lot of variables between the threads (currently about 40 variables, but the number will probably grow)?
Is xQueueSend / xQueueReceive blocking in case it is put all around the threads with different variables?

probably happened during copy.

Is the "volatile" keyword really sufficient for exchange of data
between threads (no ISR)?

No - "volatile" just tells the compiler that the variable may change value due to something other than the immediate code being generated and informs the code-generator not to rely on the value remaining static when it would otherwise expect so. When copying the value to a register for instance, it would normally expect that register value to continue to represent the value of the variable in memory but if the variable is volatile, that assumption doesn't hold. This would be used to indicate that an ISR might change it at any time; that the variable is an input register and may be changed from the outside at any time; or that another thread may change it, again, at any time (assuming pre-emptive multi-threading or multi-tasking).
Should "volatile" always be between "noInterrupts()" and "interrupts()", even when there is no ISR function?

No - volatile just describes an attribute about the variable over time

What approaches should be used when exchanging a lot of variables between the threads

Use a semaphore here. A thread that wants access to one of - or the collection of - shared variables asks for the semaphore. The RTOS either returns it immediately, or (because another thread already holds it) suspends the task until it becomes available, and returns it then. The thread holding the semaphore may access the variables (or whatever shared resource this semaphore controls), then returns the semaphore on completion. Semaphores are usually built in to the RTOS.
(As I'm not familiar with your particular RTOS, I'll leave your fourth question for someone who is).

Thank You for the points JRobert. I am using FreeRTOS ( Espriff IDF )


text:
Stuck In While Loop

So I'm a beginner at Arduino and I have to light up an LED grid to show digits from 0-9. I wrote a bit of code (with the help of some people) and it's like 90% done but there's this ONE problem. I used a switch case to light up the LEDs (so if the user writes a 5 then the switch case will make the LEDs show the digit 5) but it only shows up for like a SPLIT second.Any fixes for this?
#define ROW_1 3
#define ROW_2 4
#define ROW_3 5
#define ROW_4 6
#define ROW_5 7

#define COL_1 8
#define COL_2 9
#define COL_3 10
#define COL_4 11
#define COL_5 12
#define COL_6 13

const byte rows[] = {
    ROW_1, ROW_2, ROW_3, ROW_4, ROW_5
};

byte Zero[]  = {B011110, B010010, B010010, B010010, B011110};
byte One[]   = {B001100, B000100, B000100, B000100, B000100};
byte Two[]   = {B011110, B000010, B011110, B010000, B011110};
byte Three[] = {B011110, B000010, B001110, B000010, B011110};
byte Four[]  = {B010010, B010010, B011110, B000010, B000010};
byte Five[]  = {B011110, B010000, B011110, B000010, B011110};
byte Six[]   = {B011110, B010000, B011110, B010010, B011110};
byte Seven[] = {B011100, B000100, B000100, B000100, B000100};
byte Eight[] = {B011110, B010010, B011110, B010010, B011110};
byte Nine[]  = {B011110, B010010, B011110, B000010, B011110};

void setColumns(byte b) {
    digitalWrite(COL_1, (~b >> 0) & 0x01);
    digitalWrite(COL_2, (~b >> 1) & 0x01);
    digitalWrite(COL_3, (~b >> 2) & 0x01);
    digitalWrite(COL_4, (~b >> 3) & 0x01);
    digitalWrite(COL_5, (~b >> 4) & 0x01);
    digitalWrite(COL_6, (~b >> 5) & 0x01);
}

void  drawScreen(byte buffer2[]){
    for (byte i = 0; i < 5; i++) {
        setColumns(buffer2[i]);
        digitalWrite(rows[i], HIGH);
        digitalWrite(rows[i], LOW);
    }
}

void setup() {
    Serial.begin(9600);
    for (byte i = 2; i <= 13; i++)
        pinMode(i, OUTPUT);
}

void loop()
{
    int digit;
    if(Serial.available()) {
        digit = Serial.read();
        Serial.println(digit);
    }
    switch (digit) {
        case 48:
            drawScreen(Zero);
            break;
        case 49:
            drawScreen(One);
            break;
        case 50:
            drawScreen(Two);
            break;
        case 51:
            drawScreen(Three);
            break;
        case 52:
            drawScreen(Four);
            break;
        case 53:
            drawScreen(Five);
            break;
        case 54:
            drawScreen(Six);
            break;
        case 55:
            drawScreen(Seven);
            break;
        case 56:
            drawScreen(Eight);
            break;
        case 57:
            drawScreen(Nine);
            break;
    }
}

Please post schematics and code here directly. Linking to a site where you have to sign up to access your code / schematic is not particularly friendly to us.

48 is the ASCII code for the text character 0

We cannot see your code at tinkercad. It is not publicly available. Please put your code directly into your question. Then we surely can give you a good answer

Thanks for the tips! I edited the question a bit because I deleted the while loops.

Your drawScreen() function executes very quickly and therefore, lights the LEDs once, very briefly. There are a few choices; here are a couple to try:
One is to write surround the existing for{} loop in drawScreen() with another one, to redisplay the digit enough times to make it visible. Experiment with the count of the outer loop starting with, maybe, 50000 (guessing here...), until you have something you like.
Another is to use a while( Serial.available() == 0 ){} loop, exactly the same way, which will have the effect of maintaining the displayed digit until you type a new one.

That last one sounds really good, sooo how exactly should I implement it? Could you write the lines of code for me? Would be awesome!

Good sir, you are a LIFE SAVER!

If you want the display to persist, you should call drawScreen() on
every loop iteration. You will need a variable for “remembering” what
glyph you should draw. Then, the serial-processing code has only to
update this variable when a new character is received:
// Remember which glyph we should draw.
byte *glyph = Zero;

void loop() {
    if (Serial.available()) {
        char digit = Serial.read();
        Serial.println(digit);
        switch (digit) {
            case '0': glyph = Zero;  break;
            case '1': glyph = One;   break;
            case '2': glyph = Two;   break;
            case '3': glyph = Three; break;
            case '4': glyph = Four;  break;
            case '5': glyph = Five;  break;
            case '6': glyph = Six;   break;
            case '7': glyph = Seven; break;
            case '8': glyph = Eight; break;
            case '9': glyph = Nine;  break;
        }
    }
    drawScreen(glyph);
}

The glyph variable is a “pointer to byte” because what is what an
array of byte decays to when it is assigned to a variable.


text:
Adafruit_LSM303 tilt compensated compass
I am having troubles with tilt compensating my compass.
I am using the LSM303DLHC accelerometer/compass in combination together with the Adafruit_LSM303_U.h.
I was able to get my compass to the right direction withthis little snippet:
  float heading = (atan2(event.magnetic.y,event.magnetic.x) * 180) / Pi;

I also was able to get my roll and tilt angle with converting my X and Y of my accelerometer to angles:
   headingNew = asin(eventA.acceleration.x/10);
   float tilt = headingNew*180/PI/90*100;
   headingNew = asin(eventA.acceleration.y/10);
   float roll = headingNew*180/PI/90*100;

Now I need to compensate my angle to get a new x and y for inside my heading calculation but the problem is that I can't seem to get the right functions.
Online I found the functions below from a large tutorial about the sensor but this gives me completely wrong values.
    //Xh = event.magnetic.x*cos(tilt)+event.magnetic.z*sin(tilt);
    //Yh = event.magnetic.x*sin(roll)*sin(tilt)+event.magnetic.y*cos(roll)-event.magnetic.z*sin(roll)*cos(tilt);

or in the code itself:
   Xh = event.magnetic.x*(eventA.acceleration.z/10)+event.magnetic.z*(eventA.acceleration.x/10);
   Yh = event.magnetic.x*(eventA.acceleration.y/10)*(eventA.acceleration.x/10)+event.magnetic.y*(eventA.acceleration.z/10)-event.magnetic.z*(eventA.acceleration.y/10)*(eventA.acceleration.z/10);

I actually get the right angle on a flat surface. But it is even more inaccurate at an angle as the normal heading.
Does anybody have any experience with this sensor? Already a big thanks for the help.

Via this Youtube movie I found a different library and made this code:
#include <SPI.h>
#include <Wire.h>
#include <LSM303.h>
const int centreX  = 160;
const int centreY  = 120;
const int diameter = 100;
#define STMPE_CS 8
#define TFT_CS 10
#define TFT_DC 9

int last_dx, last_dy, dx, dy;
LSM303 compass;
void setup(){
Serial.begin(9600);
Serial.println("meters Test"); Serial.println("");
Wire.begin();
compass.init();
compass.enableDefault();

compass.m_min = (LSM303::vector<int16_t>){-602, -704, -511}; //values from
cailbration.
compass.m_max = (LSM303::vector<int16_t>){+557, +436, +529}; //values from
cailbration.
last_dx = centreX;
last_dy = centreY;
}
void loop() {
compass.read();
double angle;
float heading = compass.heading();

angle= heading; //use heading from compass
dx = (diameter * cos((angle-90)*3.14/180)) + centreX;    // calculate X position
dy = (diameter * sin((angle-90)*3.14/180)) + centreY;    // calculate Y position
last_dx = dx;
last_dy = dy;
Serial.print("angle:"); Serial.println(angle);
Serial.println("tilt:"); Serial.println(compass.a.x);
delay(25);
}

Now everything works. Sometimes you just need to choose your battles.

can you explain those value const int centreX = 160;
const int centreY = 120;
const int diameter = 100;

Those values are to help the Unity application that takes in the data from the device over serial connection. For example when our installation gets turned I can just change these values instead of rebuilding the "desktop application"

The sin() and cos() functions expect their arguments to be in
radians. If you feed them with anything else, be it degrees, percent
slope, or whatever, expect the result to be just crap.

Edit: The OP changed the question, invalidating my answer. So here
comes a new answer...
You have mistaken eventA.acceleration.y for cos(tilt),
eventA.acceleration.x for sin(tilt), and so on. They are not the
same. You may think they are the same up to some multiplicative factor,
and that's right. However, the factor doesn't cancel out as soon as you
do computations like sin(roll)*sin(tilt). Don't rush your math: if you
want to transform known-good formulas to more practical ones, check every
step of the transformation carefully.

Actually for the sinus of the tilt I use my Accelerometer.x, for the cosinus of tilt the accelerometer.y.
Also for the sin of the roll I use the accelerometer.Y.
These are values from 0 to 1 that are the same as the cos/sin of a unit circle

@Roel: Re “for the cosinus of tilt [I use] the accelerometer.y”: I can't see that in the code you posted. If you are asking a question about a different piece of code, then please edit the question and make sure the code you show is the one that matches your question.

I edited the question to show you how the code really looks like in my project.

I just want to know what Is wrong with the final function because I am not able to get the right result.

@Roel: What's wrong: it uses eventA.acceleration.y instead of cos(tilt), etc. Solution: use the formula as published, with the angles in radians.

I changed it in my code and in the question. It didn't help me out. cos(tilt) = eventA.accel.z now. Didn't help me out

Reviewed everything. If you could check again.
I actually get the right angle on a flat surface. But it is even more inaccurate at an angle as the normal heading.


text:
Modifying a code
I use this code to turn on/off a small 5v dc motor. How can I modify it so that the arduino writes the potentiometer value to the motor when it is in ON state ?
int speed = analogRead(pot) / 4;
ButtonState = !digitalRead(Switch);

if (ButtonState != lastButtonState)
{
     if (ButtonState == 1)
     {
         if (motorstate == 1)
         {
             motorstate = 0;
         }
         else
         {
             motorstate = 1;
         }
     }
     lastButtonState = ButtonState;
}

digitalWrite(enable, motorstate);
delay(20);

It depends on whether enable is a pin capable of PWM or analogWrite(enable,speed).

yes it is. i tried removing the last output statement and replaced it with
if (motorstate == 1) analogWrite ( enable , speed );

but it doesnt work.

(this is not an answer, but just a comment, used to use code alignment).
This sketch (which I aligned in your code) can be rewritten to
int speed = analogRead(pot) / 4;
ButtonState = !digitalRead(Switch);

if (ButtonState != lastButtonState)
{
     if (ButtonState == 1)
     {
         motorstate = (motorstate == 1 ? 0 : 1);
     }

     lastButtonState = ButtonState;
}

digitalWrite(enable, motorstate);
delay(20);

I suggest the best way to proceed is to add print statements and use the serial monitor to check what values you get and see what you expect (which is not fully clear).

oh i just figured it out :D i used this statement analogWrite ( enable , motorstate*speed)


text:
Red LED not turning off on Adafruit Circuit Playground Classic
When using the traditional Blink example program, the light blinks as expected. Even when writing from scratch digitalWriteing pin 13 to high and low repeatedly works fine. The problem is when I try to use CircuitPlayground.redLED(false). That has no effect, and the Circuit Playground specific Hello_Blink example doesn't work at all. The LED is just constantly on no matter what I do.
I've looked through the source code for the CircuitPlayground library and it's also using pin 13, and doing essentially the same thing as the traditional blink program.
Not sure what else could be causing this.
This is the Blink sketch that's working:

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

And this is the Hello_Blink sketch that is not working (LED remains on permanently):
#include <Adafruit_CircuitPlayground.h>

void setup() {
  CircuitPlayground.begin();
}

void loop() {
  CircuitPlayground.redLED(HIGH);
  delay(500);
  CircuitPlayground.redLED(LOW);
  delay(500);
}

Changing HIGH and LOW to true and false does nothing.
I also have noticed two other strange things. The speaker does an audible click when the board resets when using the Hello_Blink sketch (or any other sketch that uses the CircuitPlayground library), as if pin #5 is being held high as well. Also, I added these two lines
pinMode(6, OUTPUT);
digitalWrite(6, HIGH);

to the setup() of both programs and then probed #6 with a multimeter. Pin #6 is not connected to anything. The traditional blink program allows the pin to go high as expected. The CircuitPlayground sketch, however, the pin stays low.
I am using this library with a atmega32u4.

This appears to be a bug in the Circuit Playground library. An issue was opened here.
https://github.com/adafruit/Adafruit_CircuitPlayground/issues/40
Edit: This indeed was a bug, it is now fixed in the library version 1.8.4.


text:
Building mocoLUFA under OSX & Linux
I am attempting to build mocoLUFA under OS X el Capitan 10.11.6.
[Editor: mocoLUFA (MIDI firmware for Arduino Uno)]

I am using the specified LUFA version (LUFA101122) and I have tried building with both brew avr-gcc and also Crosspack-AVR.
The problem I am facing isn't with the build or the install. It's just that as soon as I install the hex file, I get no midi messages at all.
What does work - the OSX machine recognises the MIDI device and the MIDI device appears in DAW's, however MIDI Monitor registers no messages at all.
I have tried downloading a custom-built mocoLUFA and I am able to install this and it works fine. I see midi messages coming across from my sketch.
Crosspack-AVR installs avr-gcc 4.8.1.
My question is - what is the correct build environment in order to achieve a working mocoLUFA under OSX? I have tried both mocoLUFA and dualMoco and I get the same result with each.
My purpose for this is to modify mocoLUFA so that it can support sending MTC over USB. At present, it appears that mocoLUFA does not support System Common messages.
UPDATE: Built fresh Ubuntu VM. Installed avr-gcc, avr-libc, LUFA-100807 and mocoulfa. Same result. hex builds fine, no response from the atmega16u2. TX light flashing, sketch on the 2560 running, but no midi messages down the usb cable.

This is Franco, from Yaeltex, the guys who put up that site for custom MocoLUFA compiling.
Our site works on an Ubuntu server, and the build environment can be seen at the bottom of the site, which is as follows:

Ubuntu Server Setup

avr-gcc: avr-gcc (GCC) 4.9.2
avrdude: Version 6.3, compiled on Mar 15 2016 at 21:26:45
LUFA: 100807
dualMocoLUFA: custom Yaeltex based on 2013/09/22

On the other hand, I use Windows 10 to build locally in my computer, and I have a similar setup with sligthly older versions of avr-gcc and avrdude:

Windows 10 Server Setup

avr-gcc: avr-gcc (GCC) 4.3.3
avrdude: Version 5.10, compiled on Mar 15 2016 at 21:26:45
LUFA: 100807
dualMocoLUFA: custom Yaeltex based on 2013/09/22

Here is a link to the fork we made to mocoLUFA, it has minor changes, that were very useful to us and our hardware.
Regarding your problem, I am really lost on the cause of it, but we can start with some questions to get closer to a solution.

What kind of MIDI messages are you trying to send/receive?
Can you share the code you are using?
Are you using Arduino MIDI Library (Last version is v4.3.1)?
If not, are you sure you are using 31.250 bps as baud rate?
Do you have something else connected to TX or RX lines in your circuit?

Let's start with these. Cheers!

Midi Messages are currently sysex, although eventually will be MTC Quarter Frame msgs.
Arduino MIDI library is 4.3.1
OLED display on pins 20 & 21 (i2c) however "your" hex file works fine with this connected anyway, so I discount any effect of this.
I'll share code to a pastebin as my sketch is actually moot in relation to this question.
https://pastebin.ca/3867422

I note that my OSX box does not recognise the midi device at all when I change HW_CDC_BULK_{IN|OUT}_SIZE to 16

I see that you are reading the MIDI messages from your iPad. If so, it is to be noted that LUFA reports 500mA for power requirements. So you could try self powering your USB-HUB.
Source: http://morecatlab.akiba.coocan.jp/morecat_lab/MocoLUFA.html


text:
ESP8266 light sleep - can't wake up
I am attempting to implement a light sleep mode on an esp8266 (feather huzzah) which, when a button is pressed, wakes the system up so that it can continue its normal task.
I cobbled together some code from this post, which I've slightly modified:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#define WAKE_PIN 5

extern "C" {
    #include "gpio.h"
}

extern "C" {
    #include "user_interface.h"
}

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

    pinMode(WAKE_PIN, INPUT_PULLUP);
    gpio_init(); // Init GPIO pins
}

void loop(){
    Serial.println("Do something...");
    Serial.println(digitalRead(WAKE_PIN));
    delay(500); //random delay for that stuff to be done

    if(!digitalRead(WAKE_PIN)){ //if we don't detect pin, sleep
        sleep();
    }
    delay(1000);

}

void sleep(){
    Serial.println("Going to sleep...");
    delay(10);
    wifi_fpm_set_sleep_type(LIGHT_SLEEP_T); // set sleep type
    gpio_pin_wakeup_enable(GPIO_ID_PIN(WAKE_PIN), GPIO_PIN_INTR_LOLEVEL);  //LO OR HI?
    wifi_fpm_open(); // Enables force sleep
    wifi_fpm_do_sleep(5000); //Sleep for short time
    delay(100);
    Serial.println("Woke up!");
}

Here is how I have things wired:

So the setup function works as expected, as well as "do something". The button reads high (1) when it is unpressed, and when I push it, it reads low (0) - which sends the ESP to sleep. In the serial monitor, I see:
Going to sleep...
Soft WDT reset

ctx: cont
sp: 3ffef7a0 end: 3ffef9a0 offset: 01b0

>>>stack>>>
3ffef950:  0001260d 00000600 3ffee970 4021fc84
3ffef960:  00001388 402020ba 402020b1 402020a1
3ffef970:  00000000 00000000 3ffee944 40202115
3ffef980:  3fffdad0 00000000 3ffee968 402027d4
3ffef990:  feefeffe feefeffe 3ffee980 40100710
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,6)

 ets Jan  8 2013,rst cause:4, boot mode:(1,6)

wdt reset

I'm not very experienced with Arduino or Electric Engineering, so I'm not exactly sure what is happening vs. what should happen, but this is my interpretation:
I read somewhere that reset causes are as follows:
reset causes:
    0:
    1: normal boot
    2: reset pin
    3: software reset
    4: watchdog reset

boot device:
    0:
    1: ram
    3: flash

In which case, if soft reset is considered light sleep for the esp, then the rst cause:2 is expected behavior, as it means it was triggered by pin 5. The rst cause: 4 i'm not sure about though - watchdog reset. Seems to be a protective mechanism for the device, in which case maybe the reset of this must coincide with the reset triggered by sleep mode and is normal? Or does it indicate a crash? In any case, I have no idea what all the stack stuff is, but the system does not restart - I cannot get any further readings from the serial monitor after this.
I'm not sure whether GPIO_PIN_INTR_LOLEVEL should be high or low - I couldn't find documentation on this (though I did see it in the [GPIO header source file] on git.5
I read something where someone else had a similar problem and someone made a reference to adding resistors and making sure GPIO 0 should be high, and 15 should be low. The link they posted was dead, but it made me think of something I read about deep sleep, in which you have to wire RST to 0. I actually tried running a wire between RST and holding to the #0 pad that's right by the USB port on the feather huzzah, and after that, the code would actually go to sleep, then wake itself up automatically and resume the normal loop function - but what I want is for only the button to wake up the ESP.
I'm stuck from here. Anyone have any ideas of what might be happening and how to fix it?

what does #include "gpio.h" do?

Includes the GPIO library which allows access to gpio_pin_wakeup_enable - as far as I know.

You can make the ESP8266 wake from deep sleep by just pulsing RST low briefly. Crudely you can just use your switch to connect it to GND perhaps with a pullup resistor to +v. If you want to be a bit more elegant you could use a small capacitor to smooth out the switch bounce so your code only restarts once. I use this on an ESP8266 that is solar-powered. Most of the time it is in deep-sleep. It wakes up, connects to MQTT and deep sleeps again only when the sensor it is monitoring changes state.


text:
GSM incoming bytes from UART not complete
I have used AT commands to read incoming bytes from serial buffer from SIM900A but I cannot get the complete message using the code below:

while(ss.available()>0)
{
 inChar=ss.read();
 inString+=inChar;
}

Serial.println("Received messaged: ");
Serial.println(inString);

inString="";

However this one below works:
if(ss.available()>0)
{
  inString=ss.readString();
}

Serial.println("Received messaged: ");
Serial.println(inString);

inString="";

I wonder what is the difference?

How big is inString? Could you please post a Minimal, Reproducible Example

The data arrive over serial very slow compared to MCU speed. In the first snippet you stop reading at first gap between bytes (available is 0). In the second snippet the function readString will wait for the next byte until a second (at default).


text:
Can't drive servo
I purchased a 20KG Digital Servo, DS3218MG with a Control Angle of 270° .
I am trying to get it to rotate with the following code:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

int restingVal = 0;
int keyDown = 80;

void loop() {
  int minutesDelay = 1;
  Serial.print("Value");
  Serial.println(restingVal);

  delay(10000/2);

  myservo.write(keyDown);
  delay(500);
  myservo.write(restingVal);

}

It makes a small "clicking" noise, but it never moves.  I have tried:

powering it from the arduino using a USB cable
powering it using a power cord plugged into an electrical outlet
powering it with 4 AA batteries in a battery pack (power from the battery pack to the servo with it's ground to the Arduino's ground and the arduino plugged into an outlet)
using a 470uF capacitor and then tried a 680uF capacitor.

What am I doing wrong?  Is there something else I could look at?
update:
changed code to:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo.write(60);
  delay(2000);
  myservo.write(120);
}

int restingVal = 0;
int keyDown = 80;

void loop() {

}

I get the same problem.
The power cord I'm using to connect the arduino is 12V DC 1A.
Here is a photo of the wiring in one configuration (with the battery pack and the wall outlet):

Orange wire goes to GND on arduino, the long green goes to ~9, yellow goes to VCC on battery pack.

It can require a peak of 1.8 A. Can the batteries do that? Try a small common servo motor.

When I replace it with a tiny servo, it works fine.

You should proivde schematic. It's unclear from given image

The batteries are perhaps too weak, the wires too thin and the breadboard can not handle those currents. Perhaps with a 5v 2a power supply, with good wires, and good connections it will work. Keep the grounds connected. @SilvioCro, I was able to follow the wires from the photo, the wiring is okay.

@Jot Look at orange wire. Looks like it's plug into GTND rail.

@SilvioCro both orange wires are gnd-wires. They connect the arduino gnd to the battery gnd to the servo gnd.

The DS3218MG servo motor is a strong servo motor and it requires more current than normal servo motors.
With a normal servo motor the peak current can be 500 mA or even 1 A. This DS3218MG is specified somewhere at 1.8 A stall current (only 80 to 100 mA during normal operation). However this YouTube video measures a stall current of 2.3 A.
During normal operation, the average current will not even be near the stall current. The peak current on the other hand can be close to the stall current. The peak current occurs at the moment that the servo motors starts to move.
You need a 5 V 2.5 A power supply for that servo motor, together with wires and connectors that are suitable for that current.
You could cheat a little by adding a capacitor. I suggest 2200 µF or 4700 µF.
It is a common mistake to underestimate the current of a servo motor. A power supply is often more expensive than the servo motor.
If a lot of torque is required, perhaps a geared motor is easier to use.

My guess is that the servo is drawing too much current from the Arduino 5v pin which can provide up to ~450mA when powered from USB and ~650mA from power jack.
Try providing 5v from an other source to the servo while keeping the GND of that power source and the Arduino common.

I guess he uses power from two differend sources

This may be a really simple question, but what kinds of other sources are available? I added the 4xAA battery pack to provide dedicated power to the servo, hoping it would help.  I thought about using a 9v battery, but the servo says "DC 4.8-6.8v"


text:
Why does the official tutorial for LED matrix scanning writes column pin twice?
I was following the official tutorial and confused by the source code.
Arduino Official built-in example: RowColumnScanning
// when the row is HIGH and the col is LOW,
// the LED where they meet turns on:
digitalWrite(col[thisCol], thisPixel);
// turn the pixel off:
if (thisPixel == LOW) {
  digitalWrite(col[thisCol], HIGH);
}

Here is my understanding:

If thisPixel is LOW, the pin col[thisCol] would be HIGH.
If thisPixel is HIGH, the pin col[thisCol] would still be HIGH.

Question
Because it col[thisCol] is always HIGH regardless of thisPixel, does it make sense to have an extra if statement?
In case the URL is dead

/*
  Row-Column Scanning an 8x8 LED matrix with X-Y input

  This example controls an 8x8 LED matrix using two analog inputs.

  This example works for the Lumex LDM-24488NI Matrix. See
  https://sigma.octopart.com/140413/datasheet/Lumex-LDM-24488NI.pdf
  for the pin connections.

  For other LED cathode column matrixes, you should only need to change the pin
  numbers in the row[] and column[] arrays.

  rows are the anodes
  cols are the cathodes
  ---------

  Pin numbers:
  Matrix:
  - digital pins 2 through 13,
  - analog pins 2 through 5 used as digital 16 through 19
  Potentiometers:
  - center pins are attached to analog pins 0 and 1, respectively
  - side pins attached to +5V and ground, respectively

  created 27 May 2009
  modified 30 Aug 2011
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/RowColumnScanning
*/

// 2-dimensional array of row pin numbers:
const int row[8] = {
  2, 7, 19, 5, 13, 18, 12, 16
};

// 2-dimensional array of column pin numbers:
const int col[8] = {
  6, 11, 10, 3, 17, 4, 8, 9
};

// 2-dimensional array of pixels:
int pixels[8][8];

// cursor position:
int x = 5;
int y = 5;

void setup() {
  // initialize the I/O pins as outputs iterate over the pins:
  for (int thisPin = 0; thisPin < 8; thisPin++) {
    // initialize the output pins:
    pinMode(col[thisPin], OUTPUT);
    pinMode(row[thisPin], OUTPUT);
    // take the col pins (i.e. the cathodes) high to ensure that the LEDS are off:
    digitalWrite(col[thisPin], HIGH);
  }

  // initialize the pixel matrix:
  for (int x = 0; x < 8; x++) {
    for (int y = 0; y < 8; y++) {
      pixels[x][y] = HIGH;
    }
  }
}

void loop() {
  // read input:
  readSensors();

  // draw the screen:
  refreshScreen();
}

void readSensors() {
  // turn off the last position:
  pixels[x][y] = HIGH;
  // read the sensors for X and Y values:
  x = 7 - map(analogRead(A0), 0, 1023, 0, 7);
  y = map(analogRead(A1), 0, 1023, 0, 7);
  // set the new pixel position low so that the LED will turn on in the next
  // screen refresh:
  pixels[x][y] = LOW;

}

void refreshScreen() {
  // iterate over the rows (anodes):
  for (int thisRow = 0; thisRow < 8; thisRow++) {
    // take the row pin (anode) high:
    digitalWrite(row[thisRow], HIGH);
    // iterate over the cols (cathodes):
    for (int thisCol = 0; thisCol < 8; thisCol++) {
      // get the state of the current pixel;
      int thisPixel = pixels[thisRow][thisCol];
      // when the row is HIGH and the col is LOW,
      // the LED where they meet turns on:
      digitalWrite(col[thisCol], thisPixel);
      // turn the pixel off:
      if (thisPixel == LOW) {
        digitalWrite(col[thisCol], HIGH);
      }
    }
    // take the row pin low to turn off the whole row:
    digitalWrite(row[thisRow], LOW);
  }
}

It prevents ghosting when the next row is brought high ... also reduces the overall current  because only one LED is lit at any one time

Would you mind to copy the complete sketch into your question, please? External resources tend to vanish... and we like to help future readers understand the issue completely.

@thebusybee Thanks for the reminder. I have updated the question.

You are right, the if does not make sense. Not all tutorials are correct, and even if, they are often not very good.
The reason for the second digitalWrite() is to switch the pixel off after it was potentially on. If it stays on when the row is changed, you could see ghosting.
However, I would switch all pixel of a row, delay a bit, and then in a second loop, switch them all off again, before I process the next row.

I'm going to split this answer into two parts, the first about matrix displays in general, and the latter considering this particular dubious example.
The fundamental idea of a matrix display is that the LEDs don't need to be on continuously. If they are illuminated sufficiently often and for a sufficient proportion of the time, then the human eye will average things out.
Exactly what "sufficiently often", and a "sufficient proportion" of the time are can be hard to pin down. The former depends on the particular person viewing, but I would aim for at least 100Hz. The latter depends mostly on how bright your LEDs are when turned on (more on that later).
This is useful because it saves you a lot of IO lines, if you wanted individual control of 256 LEDs you would need 256 IO lines. By using a row/column matrix you only need 16. Of course with a row/colum matrix, it isn't possible to illuminate all combinations of LEDs at the same time, but that doesn't actually matter because as long as you illuminate each active LED sufficiently often the human eye won't notice the difference.
It's good practice to turn off the LEDs that you have turned on for one row before moving on to the next row. Otherwise you can get "ghosting" where an unintended LED illuminates. How much of a problem ghosting is in practice depends heavily on the specifics of your matrix drive code.

Several things however set this example apart from a "Normal" matrix drive implementation.

This example only lights a single LED at a time. Most matrix drive implementations light a whole row (or column) at a time. That means the LEDs are illuminated a much greater proportion of the time, it does have downsides though, it means your row drivers have to have enough current drive capacity to drive a whole row at once.
This example has no series resistors! the current through the LEDs is limited only by the internal resistance of the LEDs and the IO pin drivers in the AVR. This likely results at the LEDs and the GPIO pins operating significantly above their nominal max current!
There is nothing to control the timing in the code, and the LED on time is very short. Depending on how well the compiler optimizes the code, it may only be a few clock cycles.

Some of these factors cancel each other out, the drive current is likely very high, but it's only applied very briefly and only to one LED at a time. So the overall result is likely that nothing gets fried and the display has a usable brightness.
But nevertheless, I think it's the sort of example that gets Arduino a bad name. It presumably works (or it wouldn't have been posted), but it's driving components out of specification, and the brightness of the display is totally at the mercy of poorly specified internal resistances and code execution speed.


text:
LED brightness control problem
My first question here.
As an example, I'm using https://howtomechatronics.com/tutorials/arduino/how-to-control-ws2812b-individually-addressable-leds-using-arduino/ code to control my lighting, which I'm going to install to my car, just my code was a bit simplified, but I left the line, where brightness is being controlled and here's the fun part. When trying to change the brightness, it changes inconsistently. When increasing, it gets a bit brighter then a bit dimmer and at some spots it just turns off, when it should be bright. I'm also new to Arduino, so don't really know how Arduino reads these values, but maybe there is some other way to control brightness?
#include <SoftwareSerial.h>
#include <FastLED.h>
#define NUM_LEDS 20
#define PIN 5
CRGB leds[NUM_LEDS];
int brightness = 155;
//int fadeAmount = 5;
SoftwareSerial BT(0,1);
String dataIn = "";

void setup() {

  FastLED.addLeds<WS2811, PIN, GRB>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
  FastLED.setBrightness(brightness);
  Serial.begin(9600);
  BT.begin(9600);
  setAll(50, 50, 50);
}

void loop() {

  if (BT.available() > 0) {
    dataIn = BT.readString();
    delay(10);
    FastLED.show();
  }
    if (dataIn.startsWith("0")) {
        setAll(0,0,0);
        delay(10);
    FastLED.show();
    }
    else if (dataIn.startsWith("w")) {
        setAll(255,255,255);
        delay(10);
    FastLED.show();
    }
    else if (dataIn.startsWith("r")) {
        setAll(0,255,0);
        delay(10);
    FastLED.show();
    }
    else if (dataIn.startsWith("g")) {
        setAll(255,0,0);
        delay(10);
    FastLED.show();
    }
    else if (dataIn.startsWith("b")) {
        setAll(0,0,255);
        delay(10);
    FastLED.show();
    }
    else if (dataIn.startsWith("y")) {
        setAll(200,255,0);
    }
    else if (dataIn.startsWith("1")) { //This is the brightness lines
      String stringBrightness = dataIn.substring(dataIn.indexOf("1") + 1);
      brightness = stringBrightness.toInt();
      FastLED.setBrightness(brightness);
      FastLED.show();
    }
  }

void showStrip() {
   FastLED.show();
}

void setPixel(int Pixel, byte red, byte green, byte blue) {
   leds[Pixel].r = red;
   leds[Pixel].g = green;
   leds[Pixel].b = blue;
}

void setAll(byte red, byte green, byte blue) {
  for(int i = 0; i < NUM_LEDS; i++ ) {
    setPixel(i, red, green, blue);
  }
  showStrip();
}

A couple of comments: 1) why are you using a software serial? If you use pins 0 and 1 use the hardware serial, otherwise if you must use other pins set them correctly. 2) Are you saying that even if you are setting all the leds to the same color some of them have different brightness than the other? It seems to me this is a power supply issue rather than a control one.. Are all the LEDs the same ones, from the same strip?

@frarugi87 I guess it would be best to make a short video to show what I mean, because I dont know how to say that for everyone to understand correctly. I'll put a link later today, because now I have to go to work.

Using BT.readString() is asking for trouble, as the result is dependent on the timing of the serial data stream. Try using linefeed delimited commands instead.

For sure use the hardware serial rather then software serial, but before you even mess with getting the serial figured out, make sure the LED's work as you expect.  In the setup function do something like:    setAll(255,0,0); delay(1000);setAll(128,0,0);delay(1000);setAll(10,0,0); delay(1000);    Does this make them all start out bright red and then go half bright and then very dim or off?  If this is not producing the expected results then you need to work on that.  Once you can make it work as you want by directly coding it that way, then introduce the ability to control it via commands.

Another gotcha: I assume \these LEDs use PWM to get different brightness levels for each color channel. If the cycle rate is slow enough, the pulsing of the LEDs can create strange light trail effects when the light source is moving across the field of view of the observer. You can see this effect if you take an LED calculator and sweep it rapidly across your field of view. Very high frequency PWM usually solves the problem, but since these are LEDs that are controlled using a serial interface (I2C?) you likely don't have any control over the PWM frequency used to drive them.

youtu.be/WcQ11pYzJnc So here's the video. @ChadG Yes, that works and it starts bright, then dimmer and then very dim.

@EdgarBonet maybe that why there's that delay between commands? because if I press some colors faster it chooses just the first one that was pressed.

@frarugi87 to answer your question why I use software serial, because I haven't learn't any coding before and this is my start, so I even didn't knew of hardvare serial


text:
How to create a Arduino socket server to receive messages
From linux I can send a socket message using netcat
echo "Hello" | nc 88.109.110.161 100

But I don't know how to setup the socket server for listening incoming messages using the ethernet shield.
What I have so far is one from a lot of examples I tried but still not showing anything
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

EthernetServer server(1000);

void setup() {
  Ethernet.begin(mac);
  Serial.begin(9600);
// Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }

  // start the server
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // listen for incoming clients
 EthernetClient client = server.available();
 if (client) {
   Serial.println("Client");
   // an http request ends with a blank line
   boolean currentLineIsBlank = true;
   while (client.connected()) {
     while(client.available()) {
       char c = client.read();
       // if you've gotten to the end of the line (received a newline
       // character) and the line is blank, the http request has ended,
       // so you can send a reply
       if (c == '\n' && currentLineIsBlank) {

// Here is where the POST data is.
         while(client.available())
         {
            Serial.write(client.read());
            //Serial.println(c);
         }
         Serial.println();

         Serial.println("Sending response");
         // send a standard http response header
         //client.println("HTTP/1.0 200 OK");
         //client.println("Content-Type: text/html");
         //client.println();
         client.println("OK");
         client.stop();
       }
       else if (c == '\n') {
         // you're starting a new line
         currentLineIsBlank = true;
       }
       else if (c != '\r') {
         // you've gotten a character on the current line
         currentLineIsBlank = false;
       }
     }
   }
   Serial.println("Disconnected");
 }
}

have you confirmed that your ethernet shield is functional?

see the ChatServer example

Where is your Ethernet.begin? Surely you still need one of those. have a look at the setup() in the docs here: EthernetServer Example

the shield is fully functional, I'm able to receive http post requests, that's how I figure it out, but I still needing the socket server, just to receive raw messaages

I updated the code, that's how actually receives http requests

What do you mean by "needing the socket server" and "to get the raw request"?
I would have thought that your are already doing that. After all, your loop is reading the incoming socket data character by character and assembling it into a string. You are dealing with the low level http protocol (in the example above) by checking the new lines. How much lower do you "need" to go?

Maybe a typo but you send your message to Port 100 and the Arduino is listening to Port 1000 ;)

I am learning to use the arduino library about sockets and I spent an hour detecting why your example was not working for me, I ended up noticing that you have one line wrong
if (c = '\n' && currentLineIsBlank) {

should be:
{ if (c != '\n' && !currentLineIsBlank) {

And you still have an error you are missing a return character because you are not printing it in the second loop.
Anyway thanks for your contributions.

there is == and that is right


text:
Arduino 3.5" TFT Display going blank after sending data through I2C
I'm trying to use I2C to send and receive commands between an Arduino UNO R3 and an Arduino Mega R3, with a 3.5" TFT display connected to the Mega. I have verified that my display is fully functional without using I2C by running the MCUFRIEND_kbv graphics tests where they perform exactly as I expect, but when I try to use I2C in combination with the TFT shield, I run into an issue where the display goes completely white and does not change. Could this be caused by the I2C interrupting the tft functions causing it to fail? Any advice would be greatly appreciated!
Here is the i2c code on the mega:
void sendInputs(){
  for(int i = 0; i < NUM_BUTTONS; i++){
    btnArr[i] = digitalRead(btnPinArr[i]);
    Wire.write(btnArr[i]);
  }
  digitalWrite(13, HIGH);
  p = ts.getPoint();
  digitalWrite(13, LOW);
  tsArr[0] = p.x;
  tsArr[1] = p.y;
  tsArr[2] = (p.z > MINPRESSURE && p.z < MAXPRESSURE);
  for(int i = 0; i < NUM_TS_INPUTS; i++){
    Wire.write(tsArr[i]);
  }
}

void getDrawData(){
 graphicsBufferSize = Wire.read();
 for(int i = 0; i < graphicsBufferSize; i++){
    graphicsBuffer[i] = Wire.read();
 }
 drawGraphicsBuffer();
}

Where drawGraphicsBuffer(); parses the array of ints into draw functions
The I2C code on the Arduino UNO is:
void sendGraphics(){
     Wire.beginTransmission(slaveID);
      Wire.write(graphicsBufferSize);
      for(int i = 0; i < graphicsBufferSize; i++){
        Wire.write(graphicsBuffer[i]);
      }
      Wire.endTransmission();
      graphicsBufferSize = 0;
    }

void getInputs(){
  Wire.requestFrom(8, NUM_BUTTONS + NUM_TS_INPUTS);
  for(int i = 0; i < NUM_BUTTONS; i++){
    btnArr[i] = Wire.read();
  }
  for(int i = 0; i < NUM_TS_INPUTS; i++){
    tsArr[i] = Wire.read();
  }
}

void loop(){
  getInputs();
  delay(1000);
  if(btnArr[0]){
    screen.addFillScreen(0);
  }
  if(btnArr[1]){
    screen.addCircle(50, 50, 50, 50);
  }
  screen.sendGraphics();
}

Where the screen methods just populate the graphicsBuffer array to be sent to the Arduino mega.
Edit:  Here is the exact screen I'm using

I ran into a very similar problem. I used an UNO. I simply replaced a TFT from a different brand, and it worked perfectly. Some brands have conflicting i2C pins I guess.

Can you recommend me a brand to try?

I used this one


text:
MAX7219 only displaying on first digit
I'm trying to display a scrolling number on my MAX7219 display using the LedControl library, but can only ever get the first digit (digit 0) updating. When I reference digits 1-7 the 7 segments don't light up.
This also happens even with the example sketch LCDemo7Segment. Is there an issue with my display unit perhaps?
Using an Uno board and this module. Using pin 11 for DataIn, 13 for CLK, and 12 for Load.

Can you post more data on the display you are using (model, schematic, picture, link)?

Done now :) I know the link doesn't provide a great deal of data but it's all you get from the supplier

Did you try the software the producer is giving you, of course making the connections suggested by him (DIN 4, CS 5, CLK 6)?

Alright I get all displays lighting up now, so it's not a hardware issue, just software. Is there anything I can change in the LedControl library to restore function?

honestly I do not know that library. Maybe you can try comparing the two codes, and make changes until the library works...

Maybe you should ask the author of the library by creating an issue on the Github repository


text:
Need help in writing a function
I am reading an accelerometer using arduino. Basically i receive positive values and I need to get only first row of negative values.
E.g. I receive values > -0.5 , then I start to have values < -0.5 (which i put them into an array , and then in case I get again values greater than -0.5 I want to stop it.
Also if in 30 seconds it should stop anyway.
This is what I did till now but is not working like expected
void reading_mpu_brake(){
          unsigned long StartTime = millis();

      float acc[500];
      int read_time[500];

      byte arrayIndex = 0;

    while(1){
      unsigned long CurrentTime = millis();
      if (CurrentTime - StartTime < interval) {
        mpu.update();
        if (mpu.getAccX() < -0.05){
          total_acc = sqrt((pow((mpu.getAccX() - offsetx), 2) + pow((mpu.getAccY() - offsety), 2) + pow((mpu.getAccZ() - offsetz), 2) ));

          acc[arrayIndex] = total_acc;
          read_time[arrayIndex] = millis();

          Serial.print(acc[arrayIndex]);
          Serial.print(" | ");
          Serial.print(mpu.getAccX());
          Serial.print(" | ");
          Serial.println(read_time[arrayIndex]);
          Serial.println(arrayIndex);
           arrayIndex++;
        }
      }
      else if (CurrentTime - StartTime > interval)
      {
        Serial.println("Over time");
        break;

      }

    }

Now is working and get values less than -0.5 but if after several good values if I get positive values and then again negative it will put in array also the last one which I don t.
So basically I need to stop it after first bunch of good values...
Any help appreciated
Thank you!
L.E.
Seems I miss a good explanation so I will try again.
1 - I call the function and it start monitoring values for 30 seconds.
Case 1 :
I receive 0.6 , 0.7 , 0.4 , 0.2 , -0.2 , -0.6 , -0.7 , -0.8 , -0.4 , 0.3 , 0.5 ...etc
In this case I get into acc array values : -0.6 , -0.7 , -0.8
then after 30 sec gone the function exit
That is OK partially .
Case 2 :
I receive 0.6 , 0.7 , 0.4 , 0.2 , -0.2 , -0.6 , -0.7 , -0.8 , -0.4 , 0.3 , 0.5 , -0.6 , -0.7 , 0.6...etc
In this case I get into array values -0.6 , -0.7 , -0.8  and if the 30 secs are not gone I also get -0.6 , -0.7 .
What I want is function to exit after get first bunch of good values (-0.6 , -0.7 , -0.8) .
Hope now is more clear

I edited and added more explanations. By "row of negative values" mean first bunch of values that met criteria to be < -0.5

it is clear what you are trying to do ... it is unknown what happens when you run the code ... not working as expected does not mean anything specific

float acc[500];
int read_time[500];

Right, so a float is 4 bytes on this platform, so that array takes 2000 bytes. And an int is 2 bytes, so that other array is another 1000 bytes.
The Uno has 2KB of RAM, so those two declarations alone take up more RAM than the device has.
I'm a little surprised it works at all, but certainly "not working as expected" is indeed an expected outcome here.