text:
What is touch_pad_get_status() supposed to return?
What I want to do:
I have 7 touch buttons on my board (ESP32 TTGO T-Display) and I want to attach interrupts to everyone, calling the same function.
In this function I would like to use touch_pad_get_status() or other to get which button was touched. Then a switch case would do the rest.
What I'm facing:
This code
  Serial.print("Button ");
  uint32_t touch = touch_pad_get_status();
  Serial.println(String(touch));

always returns 0, no matter what.
What I've tried:
Including this part of code to the setup
  touch_pad_init();
  touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER); //tried the SW MODE too
  touch_pad_io_init(TOUCH_PAD_GPIO15_CHANNEL);

But nothing seem to work. I don't want to make 7 different functions...
Thanks in advance.

have you tried the example code that is included with the library?

@jsotola yes, but none uses this function. There was one example that was similar to this application, but it implemented one function for each button :(

See: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/touch_pad.html
See part 'Touch Detection' and 'Touch Triggered Interrupts'.

@MichelKeijzers You're saying the touchAttachInterrupt(...) cannot be used in this scenario? Also I don't know what a intr_handler_t is, there isn't any example online.

I don't know exactly, however https://github.com/espressif/esp-idf/tree/6e77694/examples/peripherals/touch_pad_interrupt seems to be an example.

touch_pad_get_status() is supposed to be used from within a touch interrupt. Full documentation: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/touch_pad.html

Thank you all, I'll post an answer to my own question as now I have solved this problem.

As pointed out from people in the comments, things need to be different.
If you use the function touchAttachInterrupt, things are a bit simpler.
The example that comes with the ESP32 library is enough to make you understand.
If you want to do what I did, this is how:
  touch_pad_init();
  touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER);
  touch_pad_config(TOUCH_PAD_GPIO2_CHANNEL, 500);
  touch_pad_config(TOUCH_PAD_GPIO15_CHANNEL, 500);
  touch_pad_config(TOUCH_PAD_GPIO13_CHANNEL, 500);
  touch_pad_isr_register(TouchButton, NULL);
  touch_pad_intr_enable();

Put this code in the setup(). Of course needs the init(), but also needs to be set to timer mode, or otherwise you're going to need to start() probably.
The config() is to configure the pin as an interrupt. I've set 500 in the threshold because the readings of touch_pad_read() told me it went from 800 untouched to 50 touched, so the midterm I chose 500.
isr_register is the function that tells to call TouchButton(), with NULL as argument to it.
void TouchButton(void *arg)
{
  uint32_t touch = touch_pad_get_status();
  touch_pad_clear_status();
  Serial.print("Button ");
  Serial.println(String(touch));
}

This is the declaration of the callback function I've done. It should be noted that clear_status() should be called as soon as possible after the get_status(), preventing the system from panicking (that's the name). You'll also see in the serial monitor that each button represents a power of 2. That's because the get_status() returns the pin mask in binary. So just do something similar to this
for (int i = 0; i < TOUCH_PAD_MAX; i++) {
    if ((pad_intr >> i) & 0x01) {
        s_pad_activated[i] = true;
    }
}

and you'll get a vector of which one was pressed.

Upvoted for the detailed answer and helping others.

And one give you a little nudge over the comment everywhere threshold sooner rather than later.  In a few days you'll be able to mark your own answer as accepted.


text:
Input from serial monitor to control stepper direction coding problem
I am attempting to create a simple code that will home the motor then wait for input for direction.  I have the homing function working, however the loop that reads the data from the serial monitor and returns it to the program is acting really buggy.  If I enter a 1 the stepper will rotate one turn in the CCW direction, hit the home mark then reverse and go CW.  If I enter a 0 the stepper will make one turn in the CW direction then repeat that move.  I added a bit of feedback so I could see what my direction variable is doing, it will hold a "1", make the move, rehome and show a "0".  I know the problem is in the loop, but for the life of me I can't seem to figure it out.  I am new to coding, so for the love of god, go easy on me!  I have added my full code so someone a little higher up in the coding world will see what I am doing.  This is just some code so I can try and learn a little something and make some strange stuff in the future.  Gotta start somewhere.  If this question is better asked on a different thread, please direct me to it.
    // Connections
#define HALL_SENSOR      3
#define DIR      10
#define STEP      11

void homefunction() {

  while (digitalRead(HALL_SENSOR) == 1) {

    digitalWrite(DIR, LOW);
    digitalWrite(STEP, HIGH);
    delayMicroseconds(4000);
    digitalWrite(STEP, LOW);
    delayMicroseconds(4000);
  }

}

void setup() {

  // Setup the stepper controller pins as Outputs
  pinMode(DIR, OUTPUT);
  pinMode(STEP, OUTPUT);

  // Setup the Hall Effect switch as an Input
  pinMode(HALL_SENSOR, INPUT_PULLUP);

  // Home the motor
  homefunction();

  // Sets up serial monitor
  Serial.begin(9600);

}

void loop()

  {int Direction; //Use to get the direction from the serial monitor
    Serial.println("What Direction would you like the motor to spin?"); //Input data
    while (Serial.available() == 0) //Wait for data
    Serial.read();
       Direction = Serial.parseInt();

 {
  // Read motor direction
  digitalWrite(DIR, Direction);
  Serial.println(Direction);

  // Spin motor
  for(int x = 0; x < 200; x++)
  {
    // while (Direction==0) //Added to hold value
    digitalWrite(STEP, HIGH);
    delayMicroseconds(4000);
    digitalWrite(STEP, LOW);
    delayMicroseconds(4000);
    //Serial.println(x);
  }}}

debug your code ... sprinkle Serial.println() statements throughout your code so that you can see what is executing when ... i think that you will discover quickly the source of your problem

source: Stack Exchange

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

sort: votes


text:
TFT Screen & ATMEGA168
I have a Arduinio nano and a ATMEGA168. I'm using the ST7789 library. The sample code which comes with the library runs perfectly and runs the display when using the Nano, but the same code does nothing on the ATMEGA168. I'm using the official pin mappings, so I sure it isn't the pins. Any suggestions I could try, or will a ATMEAG168 not drive a TFT?
EDIT:
I'm using the library written for adafruit.
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>             // Arduino SPI library

on the nano I'm using:

D13 -> SCL
D11 -> SDA
D9 -> DC
D8 -> RES

on the ATmega:

19 (PB5) -> SCL
17 (PB3)-> SDA
15 (PB1)-> DC
14 (PB0)-> RES

ANSWER TO COMMENTS:
Yes I mean the exact same code without changing the pin numbers. The pin numbers I use on the ATmega are just the same pins connected via the official atmega mapping here: https://www.arduino.cc/en/Hacking/PinMapping168
Yes the ATMega is running, I've used a logic probe on the output pins and there is output on the pin. I've run numerous other programs more sophisticated than blinking LED's and the chips are fine. The clock source is PB0 (pin 14) of the atmega. Reference pinouts in the above link.
I'm not using AC power, high frequencies, or switching subcircuits, so I didn't believe I needed any decoupling. Why do you believe there should be, and where do you believe they should be located?
EDIT: MORE INFO FOR COMMENTORS:
I'm just trying to use the terminology written on the PCB. :)
This is the best I can do and stay under the 2 meg limit for images.
EDIT 3:
Yes, I thought the same and swapped the screens. I also tried swapping all the wires, just in case, and moving everything to a different breadboard and power supply. In addition, I swapped out the atmega since I have a couple of them. It is perplexing.

/*
 * Interfacing Arduino with ST7789 TFT display (240x240 pixel).
 * Graphics test example.
 * This is a free software with NO WARRANTY.
 * https://simple-circuit.com/
 */
/**************************************************************************
  This is a library for several Adafruit displays based on ST77* drivers.

  Works with the Adafruit 1.8" TFT Breakout w/SD card
    ----> http://www.adafruit.com/products/358
  The 1.8" TFT shield
    ----> https://www.adafruit.com/product/802
  The 1.44" TFT breakout
    ----> https://www.adafruit.com/product/2088
  as well as Adafruit raw 1.8" TFT display
    ----> http://www.adafruit.com/products/618

  Check out the links above for our tutorials and wiring diagrams.
  These displays use SPI to communicate, 4 or 5 pins are required to
  interface (RST is optional).

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 **************************************************************************/

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>             // Arduino SPI library

// ST7789 TFT module connections
#define TFT_CS    10  // define chip select pin
#define TFT_DC     9  // define data/command pin
#define TFT_RST    8  // define reset pin, or set to -1 and connect to Arduino RESET pin

// Initialize Adafruit ST7789 TFT library
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

float p = 3.1415926;

void setup(void) {
  Serial.begin(9600);
  Serial.print(F("Hello! ST77xx TFT Test"));

  // if the display has CS pin try with SPI_MODE0
  tft.init(240, 240, SPI_MODE2);    // Init ST7789 display 240x240 pixel

  // if the screen is flipped, remove this command
  tft.setRotation(2);

  Serial.println(F("Initialized"));

  uint16_t time = millis();
  tft.fillScreen(ST77XX_BLACK);
  time = millis() - time;

  Serial.println(time, DEC);
  delay(500);

  // large block of text
  tft.fillScreen(ST77XX_BLACK);
  testdrawtext("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur adipiscing ante sed nibh tincidunt feugiat. Maecenas enim massa, fringilla sed malesuada et, malesuada sit amet turpis. Sed porttitor neque ut ante pretium vitae malesuada nunc bibendum. Nullam aliquet ultrices massa eu hendrerit. Ut sed nisi lorem. In vestibulum purus a tortor imperdiet posuere. ", ST77XX_WHITE);
  delay(1000);

  // tft print function!
  tftPrintTest();
  delay(4000);

  // a single pixel
  tft.drawPixel(tft.width()/2, tft.height()/2, ST77XX_GREEN);
  delay(500);

  // line draw test
  testlines(ST77XX_YELLOW);
  delay(500);

  // optimized lines
  testfastlines(ST77XX_RED, ST77XX_BLUE);
  delay(500);

  testdrawrects(ST77XX_GREEN);
  delay(500);

  testfillrects(ST77XX_YELLOW, ST77XX_MAGENTA);
  delay(500);

  tft.fillScreen(ST77XX_BLACK);
  testfillcircles(10, ST77XX_BLUE);
  testdrawcircles(10, ST77XX_WHITE);
  delay(500);

  testroundrects();
  delay(500);

  testtriangles();
  delay(500);

  mediabuttons();
  delay(500);

  Serial.println("done");
  delay(1000);
}

void loop() {
  tft.invertDisplay(true);
  delay(500);
  tft.invertDisplay(false);
  delay(500);
}

void testlines(uint16_t color) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(0, 0, x, tft.height()-1, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(0, 0, tft.width()-1, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(tft.width()-1, 0, x, tft.height()-1, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(tft.width()-1, 0, 0, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(0, tft.height()-1, x, 0, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(0, tft.height()-1, tft.width()-1, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(tft.width()-1, tft.height()-1, x, 0, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(tft.width()-1, tft.height()-1, 0, y, color);
    delay(0);
  }
}

void testdrawtext(char *text, uint16_t color) {
  tft.setCursor(0, 0);
  tft.setTextColor(color);
  tft.setTextWrap(true);
  tft.print(text);
}

void testfastlines(uint16_t color1, uint16_t color2) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t y=0; y < tft.height(); y+=5) {
    tft.drawFastHLine(0, y, tft.width(), color1);
  }
  for (int16_t x=0; x < tft.width(); x+=5) {
    tft.drawFastVLine(x, 0, tft.height(), color2);
  }
}

void testdrawrects(uint16_t color) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color);
  }
}

void testfillrects(uint16_t color1, uint16_t color2) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=tft.width()-1; x > 6; x-=6) {
    tft.fillRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color1);
    tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color2);
  }
}

void testfillcircles(uint8_t radius, uint16_t color) {
  for (int16_t x=radius; x < tft.width(); x+=radius*2) {
    for (int16_t y=radius; y < tft.height(); y+=radius*2) {
      tft.fillCircle(x, y, radius, color);
    }
  }
}

void testdrawcircles(uint8_t radius, uint16_t color) {
  for (int16_t x=0; x < tft.width()+radius; x+=radius*2) {
    for (int16_t y=0; y < tft.height()+radius; y+=radius*2) {
      tft.drawCircle(x, y, radius, color);
    }
  }
}

void testtriangles() {
  tft.fillScreen(ST77XX_BLACK);
  int color = 0xF800;
  int t;
  int w = tft.width()/2;
  int x = tft.height()-1;
  int y = 0;
  int z = tft.width();
  for(t = 0 ; t <= 15; t++) {
    tft.drawTriangle(w, y, y, x, z, x, color);
    x-=4;
    y+=4;
    z-=4;
    color+=100;
  }
}

void testroundrects() {
  tft.fillScreen(ST77XX_BLACK);
  int color = 100;
  int i;
  int t;
  for(t = 0 ; t <= 4; t+=1) {
    int x = 0;
    int y = 0;
    int w = tft.width()-2;
    int h = tft.height()-2;
    for(i = 0 ; i <= 16; i+=1) {
      tft.drawRoundRect(x, y, w, h, 5, color);
      x+=2;
      y+=3;
      w-=4;
      h-=6;
      color+=1100;
    }
    color+=100;
  }
}

void tftPrintTest() {
  tft.setTextWrap(false);
  tft.fillScreen(ST77XX_BLACK);
  tft.setCursor(0, 30);
  tft.setTextColor(ST77XX_RED);
  tft.setTextSize(1);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_YELLOW);
  tft.setTextSize(2);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_GREEN);
  tft.setTextSize(3);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_BLUE);
  tft.setTextSize(4);
  tft.print(1234.567);
  delay(1500);
  tft.setCursor(0, 0);
  tft.fillScreen(ST77XX_BLACK);
  tft.setTextColor(ST77XX_WHITE);
  tft.setTextSize(0);
  tft.println("Hello World!");
  tft.setTextSize(1);
  tft.setTextColor(ST77XX_GREEN);
  tft.print(p, 6);
  tft.println(" Want pi?");
  tft.println(" ");
  tft.print(8675309, HEX); // print 8,675,309 out in HEX!
  tft.println(" Print HEX!");
  tft.println(" ");
  tft.setTextColor(ST77XX_WHITE);
  tft.println("Sketch has been");
  tft.println("running for: ");
  tft.setTextColor(ST77XX_MAGENTA);
  tft.print(millis() / 1000);
  tft.setTextColor(ST77XX_WHITE);
  tft.print(" seconds.");
}

void mediabuttons() {
  // play
  tft.fillScreen(ST77XX_BLACK);
  tft.fillRoundRect(25, 10, 78, 60, 8, ST77XX_WHITE);
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_RED);
  delay(500);
  // pause
  tft.fillRoundRect(25, 90, 78, 60, 8, ST77XX_WHITE);
  tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_GREEN);
  tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_GREEN);
  delay(500);
  // play color
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_BLUE);
  delay(50);
  // pause color
  tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_RED);
  tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_RED);
  // play color
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_GREEN);
}

"will a ATMEAG168 not drive a TFT?".  An ATMega168 can be used with all kinds of displays.  But somehow I don't think that's the question you actually wanted answered.  To give a useful answer beyond that, more details are needed.  Which exact library? What version of it? Which example? How exactly did you wire it?

If you say "the same code", do you mean without changing the pin numbers in the source?

Do you know if your ATMega168 is actually even running? How are the fuses configured? What is your clock source? Also: where are your decoupling capacitors? I think the problem is not that it can't control the screen, but that it just can't run full-stop. Start by making the 168 blink an LED...

You appear to be confusing I2C and SPI terminology.  What you're calling SCL and SDA are SCK and MOSI respectively.  The wiring image is very low resolution.  Not useless, but pretty bad.  It is a good angle and everything is in frame.  If you could replace with a better resolution image and show what code you're using that would be helpful.

Well, I've been through your wiring and through the library, and if you have the same sketch running on both, I'm not seeing why it wouldn't work.  As a sanity check you might swap the displays and make sure the problem doesn't follow the display.  I don't have a good reason for thinking that it will, but is a very simple test to rule that out.

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


text:
String comparison problem
I have this callback function in my Firmata sketch. It receives a string as a character array and does something with it. The problem is, that the string is being sent to the Arduino in T\0h\0i\0s\0 form - after each character there is a \0 terminator. As you can see, my function is switching the d13 LED on if the string incoming is COMMAND. I had tried to use several comparison methods:

strcmp(myString, "COMMAND") == 1;
myString == "COMMAND";
strcmp(myString, "COMMAND\0") == 1;
myString == "COMMAND\0";
strcmp(myString, "C\0O\0M\0 M\0A\0N\0D\0") == 1;
myString == "C\0O\0M\0 M\0A\0N\0D\0";
== with saving the COMMAND to a char array variable;
strcmp with saving the COMMAND to a char array variable;
last two things with converting both the incoming and the needed to a String instance;
comparing a String instance with a directly stated "COMMAND"...

Nothing works. How can I compare the strings workably?
Full Arduino sketch:
#include <Firmata.h>

void stringCallback(char *myString)
{
  if (strcmp(myString, "COMMAND") == 1) {
    digitalWrite(13, HIGH);
  }
  Firmata.sendString(myString);
}

void sysexCallback(byte command, byte argc, byte *argv)
{
  Firmata.sendSysex(command, argc, argv);
}

void setup()
{
  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
  Firmata.attach(STRING_DATA, stringCallback);
  Firmata.attach(START_SYSEX, sysexCallback);
  Firmata.begin(57600);
  pinMode(13, INPUT);
}

void loop()
{
  while (Firmata.available()) {
    Firmata.processInput();
  }
}

Full code of the desktop program:
import pyfirmata, time

class CustomArduino(pyfirmata.Arduino):
    def __init__(self, port: str):
        pyfirmata.Arduino.__init__(self, port)
        self.iterator = pyfirmata.util.Iterator(self)
        self.iterator.start()

        self.add_cmd_handler(0x71, self.receiveString)

    def receiveString(self, *args, **kwargs):
        print(f'Raw: {args}\n'
              f'Received: {pyfirmata.util.two_byte_iter_to_str(args)}')

    def sendString(self, data):
        self.send_sysex(0x71, pyfirmata.util.str_to_two_byte_iter(data))

    def send_sysex(self, sysex_cmd, data=[]):
        """
        Sends a SysEx msg.
        :arg sysex_cmd: A sysex command byte
        : arg data: a bytearray of 7-bit bytes of arbitrary data
        """
        msg = bytearray([pyfirmata.pyfirmata.START_SYSEX, sysex_cmd])
        msg.extend(data)
        msg.append(pyfirmata.pyfirmata.END_SYSEX)
        self.sp.write(msg)

print('STRING TESTER\nPlease input your COM port: ', end = '')
myCom = str(input())
device = CustomArduino(myCom)

while True:
    device.sendString(input('Send: '))
    time.sleep(1)

Strange detail: my Arduino is on the COM6 COM-port. If I connect it via my program and send com6 to the arduino, the D13 LED turns on!

Comments are not for extended discussion; this conversation has been moved to chat.

As @timemage stated, strcmp returns 0 for equal. Sincerely in the provided code, while you send a message, which contents are not COMMAND, the LED will be turned on.
To get what we need, we must compare strcmp return value with 0! If it equals, then the strings match, and your suggested code is being executed:
void stringCallback(char *myString)
{
  if (strcmp(myString, "COMMAND") == 0) {
    digitalWrite(13, HIGH);
  }
  Firmata.sendString(myString);
}

the strcmp function is 50 years old and documented in many places. a fix of your code is not a useful resource on a Q&A site


text:
Difference between char array and unsigned char array
I have written a small test code for Arduino Uno which is as follows:
unsigned char tes[4];
char testing[4];

void setup() {
    Serial.begin(9600);
    for (int i = 0; i < 4; i++) {
        testing[i] = i;
        tes[i] = i;
    }
    for (int i = 0; i < 4; i++) {
        Serial.print("unsigned char is: ");
        Serial.println(tes[i]);
        Serial.print("char is: ");
        Serial.println(testing[i]);
    }
}

void loop() {
}

and the output which I get is as follows
unsigned char is: 0
char is:
unsigned char is: 1
char is:
unsigned char is: 2
char is:
unsigned char is: 3
char is:

Can someone help me out why is the difference in output.

Why is this off-topic? Isn't the observed behaviour based on how the Arduino library in particular implements different type overloads and produces different outputs for char and unsigned char? Unlike e.g. what standard iostream seems to do: both unsigned char uc = 0x41; cout << uc << endl; and char c = 0x41; cout << c << endl; output A.

tl;dr : Since unsigned char is represented as a byte value, the output to the serial is the byte representation, not the char
I re-wrote the code you had for reference:
#define CHARS 255
#define BAUD 115200

unsigned char unsChar[CHARS];
char sinChar[CHARS];

void setup() {
  Serial.begin(BAUD);
  Serial.println("~~Setup~~");
  for(int i = 0; i < CHARS; i++) {
    unsChar[i] = (unsigned char)i;
    sinChar[i] = (char)i;
  }
}

void loop() {
  Serial.println("~~Loop~~");
  for(int i = 0; i < CHARS; i++) {
    Serial.print("INDEX        : ");
    Serial.println(i);
    Serial.print("unsigned char: ");
    Serial.println(unsChar[i]);
    Serial.print("         char: ");
    Serial.println(sinChar[i]);
    Serial.println("---------------------");
  }
  delay(10000);
}

When you run this you'll see the unsigned char is simply printed to the serial like any other byte value but the char value is printed as a character according to the ASCII chart.
If you compare the documentation for unsigned char

An unsigned data type that occupies 1 byte of memory. Same as the byte datatype.

The unsigned char datatype encodes numbers from 0 to 255.

For consistency of Arduino programming style, the byte data type is to be preferred.

versus a normal (signed) char:

A data type used to store a character value. Character literals are written in single quotes, like this: 'A' (for multiple characters - strings - use double quotes: "ABC").Characters are stored as numbers however. You can see the specific encoding in the ASCII chart. This means that it is possible to do arithmetic on characters, in which the ASCII value of the character is used (e.g. 'A' + 1 has the value 66, since the ASCII value of the capital letter A is 65). See Serial.println reference for more on how characters are translated to numbers.The size of the char datatype is at least 8 bits. It’s recommended to only use char for storing characters. For an unsigned, one-byte (8 bit) data type, use the byte data type.

So size wise an array of chars and unsigned chars are going to be the same. It's more about the representation of the underlying number (byte) and what works best for your use case.

An unsigned char is treated as a number, and a signed char as a character.
See the https://simple.wikipedia.org/wiki/ASCII table for the result.

This is not quite right. In C++, "char", "signed char" and "unsigned char" are THREE different types, not two. Of course in some sense "char" must be the same as one of the other two types, but  which two types are the same is implementation-dependent. Only "char" is interpreted as character data by default.

@alephzero thanks for the addition. Mostly it's better to cast to be sure.


text:
IR receiver receives only 0
I am trying to decode IR codes of my Samsung tv remote
But the receiver always receiving "0"
Schematics:

Code:
#include <IRremote.h>

int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;

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

void loop()
{
  if (irrecv.decode(&results))
    {
    int value = results.value;
    Serial.println(" ");
    Serial.print("Code: ");
    Serial.println(results.value);
    Serial.println(" ");
    irrecv.resume();
    Serial.println("*****************");
    }
}

Please help me to decode my IR codes

The most current version of IRremote doesn't have any arguments for the decode function. To get the result you'd use irrecv.results to get the results.

Next update with 3.1 of the library, you need to call irrecv.decodedIRData.decodedRawData to get the data. This code worked for me:
#include <IRremote.h>

int IRpin = 11;
IRrecv irrecv(IRpin);

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop()
{
  if (irrecv.decode())
    {
      Serial.println(irrecv.decodedIRData.decodedRawData); // Print the Serial
      irrecv.resume();   // Receive the next value
    }
}


text:
generate and using a precompiled library ESP32
I would like to ask you how I can generate a dot_a file for a given library for ESP32? I want to replace my .cpp file with a precompiled .a in the Arduino IDE.
Is that possible? Can you please guide me?

Welcome, next time don't use bold text for an entire text. Also check the shift key.

https://arduino.github.io/arduino-cli/latest/library-specification/#precompiled-binaries


text:
SSD1306 unable to display Text and waveform cohesively.Why?
Here is my code I am collecting data using an ECG sensor and trying to enhance the incoming data by stretching it across the x axis. Which results in this.

After this the screen eventually just goes black. What am I doing wrong?
This is my code.
#include <U8glib.h>
U8GLIB_SSD1306_128X64 u8g(12, 11, 8, 9, 10);
int Buffer[128];int Buffer2[128];int max=0;
//int largest;
void pageECG();     // Page-1

const int pageCount = 2;
int p;
void (*pages[pageCount])() = {pageECG};
int duration [pageCount] = {10000};
void setup() {

  u8g.setFont(u8g_font_unifont);
  u8g.setColorIndex(1);
  p = 0;
  Serial.begin(9600);

}

void loop()
{
u8g.firstPage();
  do {
    (*pages[p])();
  } while( u8g.nextPage() );
  delay(duration[p]);
  p = p+1;
  if (p == pageCount)
    p=0;
}
void pageECG() {
for(int x = 0;x < 128;x++)
{
Buffer[x] =(analogRead(A0)*0.075);//This loop takes data input
delay(5);
if(Buffer[x]<32&&Buffer[x]!=2)
x-=2;
if(Buffer[x]>32&&Buffer[x]!=62)
x+=2;
Serial.println(Buffer[x]);
}

for(int x = 0;x < 127;x++)
{
u8g.setFont(u8g_font_unifont);
u8g.drawStr( 0, 60, "ECG");
u8g.drawLine(x, Buffer[x], x,Buffer[x+1]); //OP to OLED for BP

}}

Can you explain me what you are doing in the for loop where the data is read in? You manipulate the index variable x in a way that it is possible you get negative indexes. Also only three cases store a value subsequentially, i.e when the read value is 2, 32 or 62. In all other cases the index is recomputed. It's complete unpredictable, what this algorithm does. And the output you showed us is possible. The drawLine is also suspectable to me, shouldn't it be u8g.drawLine(x, Buffer[x], x+1,Buffer[x+1]);. I changed the 2nd x to x+1. And, I don't see code to clear the page before redraw.

Well, one problem is this: You have made an array of pointer to function, but only initialized the first of the two, to pageECG.
const int pageCount = 2;
int p;
void (*pages[pageCount])() = {pageECG};

The last line there roughly equivalent to:
void (*pages[pageCount])() = {pageECG, nullptr};

Later in loop() you have:
  u8g.firstPage();
  do {
    (*pages[p])();
  } while( u8g.nextPage() );
  delay(duration[p]);
  p = p+1;
  if (p == pageCount)
    p=0;

After the first execution of loop(), p is 1.  Since it was not 2, it was not reset by your if (p == pageCount) p=0;  So on the next pass through loop(), (*pages[p])(); is     (*pages[1])();  where pages[1] is nullptr.
In practice, what you're doing is generating and executing an AVR icall (indirect call) instruction to address 0x0000 (nullptr representation) to the reset vector.  So, your sketch starts over almost like a reset, except the hardware has not been reset.  Importantly, the interrupts are still configured as they were and the global interrupt flag is on, which means all manner of potential weirdness if one of them manages to execute before you get back ground setup().  So, it's difficult to say exactly why you're seeing what you're seeing.  But, it doesn't surprise me as a potential outcome.  And it may not be the only problem; just a problem.


text:
Configure input pullup through registers
I can set pin mode to input or output through the DDRx registers. How can I enable the internal pullup resister through a register?

Credits to GoForSmoke.
Also see Gerben's comment below.
See: https://forum.arduino.cc/index.php?topic=286145.0
byte ddrcMask =       ~
(
        (1 << DDC0) |  // pinMode( 14, INPUT ); // Set to input
        (1 << DDC1) |  // pinMode( 15, INPUT ); // Set to input
        (1 << DDC2) |  // pinMode( 16, INPUT ); // Set to input
        (1 << DDC3)    // pinMode( 17, INPUT ); // Set to input
);

byte portcMask =
(
        (1 << PORTC0) |  // digitalWrite( 14, HIGH ); // Enable the pullup
        (1 << PORTC1) |  // digitalWrite( 15, HIGH ); // Enable the pullup
        (1 << PORTC2) |  // digitalWrite( 16, HIGH ); // Enable the pullup
        (1 << PORTC3)    // digitalWrite( 17, HIGH ); // Enable the pullup
);

byte pincMask = ( (1 << PINC0) | (1 << PINC1) | (1 << PINC2) | (1 << PINC3) );

void setup( void )
{
  // Configure the pins for input
  DDRC = DDRC & ddrcMask;

  // Enable the pullups
  PORTC = PORTC | portcMask;

  // Read all four inputs
  uint8_t Pdat = PINC & pincMask;
}

void loop( void )
{
}

For clarity. You are using the same register (PORTC) you would use to set an OUTPUT pin to HIGH. When the pin is an INPUT it will enable the pull-up resistor. So the function of the register depends on whether the pin is an INPUT or OUTPUT.

@Gerben thanks for the clarification (added a reference to your comment).


text:
Arduino Master SPI MISO Receive Data
I'm trying to interface an Arduino Mega with an AD7714 ADC. This ADC requires a command to be sent to the communications register (in my case 0x5C) in order to begin a read from the data register.
My question is how do I receive the data that is transmitted from the Slave ADC to the Master Arduino on the MISO line?
At the moment I have this code in an interrupt that is activated when the DRDY goes low:
byte dataIn;
byte dataOut = 0;
adc_write_reg(0x5C); //tell ADC to read data from data register
dataIn = SPI.transfer(dataOut); //transmit data in order to recieve data??

Thanks!

It seems like your more wondering the what and why of the sent data when your goal is to receive data.  Is that the case?

I'm not sure what you mean by the what and why :/ Simply put all I need to do is store the data recieved on the MISO line in a variable

Typically you need to do two SPI transactions, one for Writing data by setting the R/W bit of the Comm register to Write, and write the data with SPI.transfer(), close the transaction, then re-establish a SPI transition and set the Comm register with R/W bit as Read, and read in the data with another SPI.transfer(). BTW, don't do I/O data access within your Interrupt function. Keep your Interrupt function as short as possible by just set/reset a status...

The write is to send the command, the read is to get the data. Here is a library that I'm familiar for another ADI chip with similar mechanism that you could take a look on how the code looks like.

Sending 0x5c is just to tell the chip you want to read the data register. You can ignore the this first received byte. You then send two or three zero bytes (0x00), to get your 16-bit or 24-bit ADC result.


text:
Ethernet shield issues (defective shield?!)
I'm a newbie in using the Arduino Ethernet Shield v2 (Arduino product code A000024) and I'm experiencing some strange behaviours on a critical work with strict deadline.
The project involve some Arduino (both UNOs and MEGA2560s) sending sensor data via OSC to a couple of destination PCs for later processing.
To do that I'm using what it seemed to me to be a quite simple to use Arduino OSC library, the CNMAT one.
I've noticed this fact, which I think is related to some hardware malfunction.
I've found my code getting stuck even with a correct setup of the LAN. The code stops working, stops sending OSC messages, Ethernet shield is no more reachable with the ping. This persists also after loading again the code, or manually resetting the Arduino board. Initially I thought it was my fault but I've found that, substituting the shield with another one, the problem magically disappeared. On one of the problematic shield I've also experienced many continuous shutdowns and startups of the Arduino every 5 seconds (firmware restart from the setup)!
Are these ethernet shields known to be defective or having some issues?
The strange thing is that I've experienced this problem on 3 out of 8 of them: this is super critical!
Have you experienced something similar? Do you know of similar problems occurred before?

For debug purposes, here's a code test I've written and tried on a single Arduino UNO, always the same, using the same LAN setup (ethernet cable, IP addresses, Ethernet switch) switching two different Ethernet shields:
/* NET stuff ********************************************/
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
EthernetUDP Udp;

IPAddress ip(10, 3, 3, 210); // the Arduino's IP
byte mac[] = { 0xA8, 0x61, 0x0A, 0xAE, 0x83, 0xCE };

#define DELAY 1000

// SETUP //////////////////////////////////////////////////////////////////
void setup() {

  Serial.begin( 115200 );
  Serial.println("setup");

  // Ethernet and OSC utilities **************************
  Ethernet.begin(mac, ip);

  // Hardware status check
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.");
  }
  else if (Ethernet.hardwareStatus() == EthernetW5100) {
    Serial.println("W5100 Ethernet controller detected.");
  }
  else if (Ethernet.hardwareStatus() == EthernetW5200) {
    Serial.println("W5200 Ethernet controller detected.");
  }
  else if (Ethernet.hardwareStatus() == EthernetW5500) {
    Serial.println("W5500 Ethernet controller detected.");
  }

  //Tells you whether the link is active.
  // LinkOFF could indicate the Ethernet cable is unplugged or defective.
  if (Ethernet.linkStatus() == Unknown) {
    Serial.println("Link status unknown. Link status detection is only available with W5200 and W5500.");
  }
  else if (Ethernet.linkStatus() == LinkON) {
    Serial.println("Link status: On");
  }
  else if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Link status: Off");
  }

  while( Ethernet.linkStatus() == LinkOFF ) {
    delay( DELAY );
  }
}

// LOOP ///////////////////////////////////////////////////////////////////
void loop()
{

  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.print("Ethernet link broken!\t");
    Serial.println("please connect the Ethernet cable");
    delay( DELAY );
    return;
  }

  Serial.println("LOOP working as expected!");
  delay( DELAY );
}

When I try this code using the "defective" Arduino Ethernet shield the Serial monitor print something like this (note that I'm not doing anything, I'm leaving everything untouched):
[...]
14:25:17.906 -> setup
14:25:18.471 -> W5500 Ethernet controller detected.
14:25:18.471 -> Link status: On
[...]
14:26:41.545 -> LOOP working as expected!
14:26:42.542 -> LOOP working as expected!
14:26:43.538 -> LOOP working as expected!
14:26:44.535 -> Ethernet link broken!   please connect the Ethernet cable
14:26:45.531 -> LOOP working as expected!
14:26:46.561 -> LOOP working as expected!
14:26:47.558 -> LOOP working as expected!
14:26:48.555 -> LOOP working as expected!
14:26:49.552 -> Ethernet link broken!   please connect the Ethernet cable
14:26:50.549 -> LOOP working as expected!
14:26:51.546 -> LOOP working as expected!
14:26:52.543 -> LOOP working as expected!
14:26:53.540 -> LOOP working as expected!
14:26:54.570 -> LOOP working as expected!
14:26:55.567 -> Ethernet link broken!   please connect the Ethernet cable
14:26:56.564 -> LOOP working as expected!
14:26:57.561 -> LOOP working as expected!
14:26:58.557 -> LOOP working as expected!
14:26:59.553 -> Ethernet link broken!   please connect the Ethernet cable
14:27:00.550 -> Ethernet link broken!   please connect the Ethernet cable
14:27:01.546 -> LOOP working as expected!
14:27:02.576 -> Ethernet link broken!   please connect the Ethernet cable
14:27:03.572 -> LOOP working as expected!
14:27:04.569 -> LOOP working as expected!
14:27:05.566 -> LOOP working as expected!
14:27:06.563 -> LOOP working as expected!
14:27:07.560 -> LOOP working as expected!
14:27:08.557 -> LOOP working as expected!
14:27:09.587 -> LOOP working as expected!
14:27:10.583 -> Ethernet link broken!   please connect the Ethernet cable
14:27:11.580 -> LOOP working as expected!
14:27:12.577 -> LOOP working as expected!
[...]

In the meantime, the ping stops working and will not work again until I reboot the Arduino:
[...]
64 bytes from 10.3.3.210: icmp_seq=301 ttl=128 time=0.185 ms
64 bytes from 10.3.3.210: icmp_seq=302 ttl=128 time=0.171 ms
64 bytes from 10.3.3.210: icmp_seq=303 ttl=128 time=0.184 ms
64 bytes from 10.3.3.210: icmp_seq=304 ttl=128 time=0.229 ms
64 bytes from 10.3.3.210: icmp_seq=305 ttl=128 time=0.206 ms
64 bytes from 10.3.3.210: icmp_seq=306 ttl=128 time=0.278 ms
64 bytes from 10.3.3.210: icmp_seq=307 ttl=128 time=0.143 ms
64 bytes from 10.3.3.210: icmp_seq=308 ttl=128 time=0.229 ms
64 bytes from 10.3.3.210: icmp_seq=309 ttl=128 time=0.198 ms
From 10.3.3.165 icmp_seq=335 Destination Host Unreachable
From 10.3.3.165 icmp_seq=336 Destination Host Unreachable
From 10.3.3.165 icmp_seq=339 Destination Host Unreachable
From 10.3.3.165 icmp_seq=342 Destination Host Unreachable
From 10.3.3.165 icmp_seq=343 Destination Host Unreachable
From 10.3.3.165 icmp_seq=344 Destination Host Unreachable
[...]

As you see the "Link" seems to be on and than off repeatedly. I don't know why from the moment. I'm not modifying anything on my network setup (the LAN cable or anything like that).
I don't know why the ping stops working and will not work again even if the Serial monitor is telling the LINK is ON.
Let me know as soon as you can and thank you so much for your help and support.
bests
na
PS: I've posted a similar question on the Arduino forum but I had no way of understanding what kind of problem is this --> link
edit 11/02/2021
I've written a new code sketch to always print the status of the link. Here it is.
    /* NET stuff ********************************************/
    #include <SPI.h>
    #include <Ethernet.h>
    #include <EthernetUdp.h>
    EthernetUDP Udp;

    IPAddress ip(10, 3, 3, 210); // the Arduino's IP
    byte mac[] = { 0xA8, 0x61, 0x0A, 0xAE, 0x83, 0xD5 };

    #define DELAY 1000

    // SETUP //////////////////////////////////////////////////////////////////
    void setup() {

      Serial.begin( 115200 );
      Serial.println("setup");

      // Ethernet and OSC utilities **************************
      Ethernet.begin(mac, ip);

      // Hardware status check
      if (Ethernet.hardwareStatus() == EthernetNoHardware) {
        Serial.println("Ethernet shield was not found.");
      }
      else if (Ethernet.hardwareStatus() == EthernetW5100) {
        Serial.println("W5100 Ethernet controller detected.");
      }
      else if (Ethernet.hardwareStatus() == EthernetW5200) {
        Serial.println("W5200 Ethernet controller detected.");
      }
      else if (Ethernet.hardwareStatus() == EthernetW5500) {
        Serial.println("W5500 Ethernet controller detected.");
      }

      //Tells you whether the link is active.
      // LinkOFF could indicate the Ethernet cable is unplugged or defective.
      if (Ethernet.linkStatus() == Unknown) {
        Serial.println("Link status unknown. Link status detection is only available with W5200 and W5500.");
      }
      else if (Ethernet.linkStatus() == LinkON) {
        Serial.println("Link status: On");
      }
      else if (Ethernet.linkStatus() == LinkOFF) {
        Serial.println("Link status: Off");
      }

      while( Ethernet.linkStatus() == LinkOFF ) {
        Serial.println("\tplease connect the Ethernet cable");
        delay( DELAY );
      }
    }

    // LOOP ///////////////////////////////////////////////////////////////////
    void loop()
    {

      int LINK_STATUS = Ethernet.linkStatus();

      if ( LINK_STATUS == LinkOFF) {
        Serial.print("Ethernet link broken!\t");
        Serial.println("please connect the Ethernet cable");
        delay( DELAY );
        return;
      } else if( LINK_STATUS == Unknown ) {
        Serial.println("LINK_STATUS: Unknown");
        delay( DELAY );
        return;
      } else if( LINK_STATUS == LinkON ) {
        Serial.println("LOOP working as expected! (LINK_STATUS: ON)");
      }

      delay( DELAY );
    }

After a while, it gave me this output on the serial monitor (at the same time ping said "Destination Host Unreachable"):
[...]
10:57:21.207 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:22.203 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:23.200 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:24.197 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:25.195 -> Ethernet link broken!   please connect the Ethernet cable
10:57:26.192 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:27.188 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:28.186 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:29.216 -> Ethernet link broken!   please connect the Ethernet cable
10:57:30.213 -> Ethernet link broken!   please connect the Ethernet cable
10:57:31.210 -> Ethernet link broken!   please connect the Ethernet cable
10:57:32.207 -> Ethernet link broken!   please connect the Ethernet cable
10:57:33.204 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:34.202 -> Ethernet link broken!   please connect the Ethernet cable
10:57:35.198 -> Ethernet link broken!   please connect the Ethernet cable
10:57:36.194 -> Ethernet link broken!   please connect the Ethernet cable
10:57:37.224 -> Ethernet link broken!   please connect the Ethernet cable
10:57:38.221 -> Ethernet link broken!   please connect the Ethernet cable
10:57:39.219 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:40.216 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:41.213 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:42.210 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:43.207 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:44.236 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:45.232 -> Ethernet link broken!   please connect the Ethernet cable
10:57:46.228 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:47.225 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:48.222 -> LOOP working as expected! (LINK_STATUS: ON)
10:57:49.218 -> Ethernet link broken!   please connect the Ethernet cable
10:57:50.216 -> Ethernet link broken!   please connect the Ethernet cable
10:57:51.212 -> Ethernet link broken!   please connect the Ethernet cable
10:57:52.242 -> Ethernet link broken!   please connect the Ethernet cable
10:57:53.239 -> Ethernet link broken!   please connect the Ethernet cable
10:57:54.235 -> Ethernet link broken!   please connect the Ethernet cable
10:57:55.231 -> Ethernet link broken!   please connect the Ethernet cable
10:57:56.227 -> Ethernet link broken!   please connect the Ethernet cable
[...]

Adding some new elements here.
I've also noticed that, sometimes, even if the LINK status is ON, the ping is not working. It is almost clear to me that the two things are completely uncorrelated.
I've made some experiments in changing also the MAC address (setting a MAC address which is different from the one I see on the label on the shield). The "wrong" MAC address seems not to be cause of problems.
Can it be that a MAC address misconfiguration on the Arduino firmware can make the things work the wrong way?
I've also made many attempts in disconnetting and re-connecting the ethernet cable to the shield without powering the Arduino off and I've experinced a series of different behaviours.
1A) disconnecting the ethernet cable:

Serial monitor prints: "Ethernet link broken! please connect the Ethernet cable"
ping stops;

1B) re-connecting the ethernet cable:

on the Serial monitor LinkOn and LinkOff alternate between themselves, then, "LOOP working as expected! (LINK_STATUS: ON)" becomes stable;
ping still prints "Destination Host Unreachable";

2) reset of the Arduino Board (not the reset on the shield)

Serial monitor: "LOOP working as expected! (LINK_STATUS: ON)"
ping works again;

3A) Trying to repeat the same procedure as before (1A). Disconnecting the Ethernet cable:

Serial monitor prints "Ethernet link broken!  please connect the Ethernet cable";
ping stops;

3B) re-connecting the ethernet cable:

on the Serial monitor LinkOn and LinkOff alternate between themselves, then, "LOOP working as expected! (LINK_STATUS: ON)" becomes stable;
ping works again (which is a different behaviour from before!!!);

This problem is really difficult for me to debug. It seems we have a lot of variables to take into consideration here, which are not under my control: if I repeat the same procedure again and again, behaviour changes.
I'm not sure if it depends on the board, on the W5500 chip, maybe on other things happening on the net. Is it possible?
I don't know how to write a code to be capable of detecting these malfunctions.
Thank you so much for your help.
na

when your code prints "LOOP working as expected!", the actual status is not indicated, except that it is not LinkOFF

I've had similar issues with the Ethernet V2 shield, which were probably caused by the (unused) SD Card interface on the Ethernet V2 shield interfering with Ethernet functionality (both use the SPI bus). I've solved this by explicitly disabling the SD Card interface CS (by setting pin 4 to high) at the start of my setup() code with:
#define SDSelect  4
pinMode (SDSelect, OUTPUT);
digitalWrite (SDSelect, HIGH); This solved my issues.

Thank you @StarCat for your tip!
I've tried this on a "defective" shield and, in fact, things seem to be going a little better.
Now the Serial monitor is always reporting the link status as ON (without strange ON - OFF - ON status switching).
But today, after two days of continuous "ping" of the Ethernet shield bymy laptop, the console tells me icmp_seq=10493 Destination Host Unreachable.
Ping works again if I do a manual reset of the Arduino.
Why? Is there a sort of buffer on the W5500 that fills up over time and, because of this, prevents the ping from working?

I've had similar issues with the Ethernet V2 shield, which were probably caused by the (unused) SD Card interface on the Ethernet V2 shield interfering with Ethernet functionality (both use the SPI bus).
From what I could see in the Ethernet Shield2 schematics, there is no pull-up on the signal controlling the SD card Chip Select (D4/SD_CS), which means an unitialized I/O pin on the Arduino side could potentially cause random noise on the SD CS input.
My solution was to explicitly disable the SD Card interface CS, by setting pin 4 to high at the start of my setup() code.
I used the following code:
#define SDSelect  4

... Other initialization code

setup() {
    pinMode (SDSelect, OUTPUT);
    digitalWrite (SDSelect, HIGH);

    ... Code continues ...

This solved my issues with random crashing. I realize that I can't remember if there was an SD card present in the slot at the time.


text:
I'm desperate and need help with MFRC522 (stops working randomly)
I've made a light switcher that switches lights on for 15s after a correct tag is presented, and also when door is opened for 6 seconds (its for outside) so i can see a keyhole after leaving for a brief amount of time. It works perfectly, but the rfid reader stops reading tags after random amounts of time (sometimes after hour and sometimes after days) - I've tried i think everything in terms of software (except watchdog) and i simply ran out of ideas. I need it to work, so i draw all the connections in the picture below - if anyone got any ideas, please let me now.
Side note - everything is mounted and hidden outside so each even smallest hardware change is very hard to do so please, don't throw random ideas in this matter even tho every help is appreciated

EDIT: I made a photo of interior of the enclosure that holds relay, arduino and charger PCB and decided to add it here too

#include <SPI.h>
#include <MFRC522.h>

//blue
const byte UID1[] = {0xA7, 0x8C, 0x24, 0xD9};
//blacks
const byte UID2[] = {0x10, 0x84, 0xD2, 0x2A};
const byte UID3[] = {0xDC, 0x46, 0xB6, 0x91};
const byte UID4[] = {0xB0, 0xE8, 0xC4, 0x2A};
//reds
const byte UID5[] = {0x9E, 0xC8, 0xEA, 0xB3};
const byte UID6[] = {0xFE, 0xA5, 0xF7, 0xB3};
//const byte UID6[] = {0x70, 0xBA, 0x35, 0xA5};

#define RST_PIN 9
#define SS_PIN 10

MFRC522 rfid(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key key;
int in1 = 7;
int dooropen = 8;
int state = 0;
int testerbester = 0;
void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.PCD_Init();
  pinMode(in1, OUTPUT);
  pinMode(dooropen, INPUT);
  digitalWrite(in1, LOW);
  delay(2000);
}

void loop() {
  delay(200);
  state = digitalRead(dooropen);
  if (state == HIGH) {
    //Serial.println("Door Opened");
    testerbester = 1;
    digitalWrite(in1, HIGH);
  } else {
    if (testerbester == 1) {
      delay(6000);
      testerbester = 0;
      digitalWrite(in1, LOW);
    } else {
      digitalWrite(in1, LOW);
    }
    if ( ! rfid.PICC_IsNewCardPresent())
    {
      return;
    }
    if ( ! rfid.PICC_ReadCardSerial())
    {
      return;
    }
    if ((rfid.uid.uidByte[0] == UID1[0] &&
         rfid.uid.uidByte[1] == UID1[1] &&
         rfid.uid.uidByte[2] == UID1[2] &&
         rfid.uid.uidByte[3] == UID1[3]) ||
        (rfid.uid.uidByte[0] == UID2[0] &&
         rfid.uid.uidByte[1] == UID2[1] &&
         rfid.uid.uidByte[2] == UID2[2] &&
         rfid.uid.uidByte[3] == UID2[3]) ||
        (rfid.uid.uidByte[0] == UID3[0] &&
         rfid.uid.uidByte[1] == UID3[1] &&
         rfid.uid.uidByte[2] == UID3[2] &&
         rfid.uid.uidByte[3] == UID3[3]) ||
        (rfid.uid.uidByte[0] == UID4[0] &&
         rfid.uid.uidByte[1] == UID4[1] &&
         rfid.uid.uidByte[2] == UID4[2] &&
         rfid.uid.uidByte[3] == UID4[3]) ||
        (rfid.uid.uidByte[0] == UID5[0] &&
         rfid.uid.uidByte[1] == UID5[1] &&
         rfid.uid.uidByte[2] == UID5[2] &&
         rfid.uid.uidByte[3] == UID5[3]) ||
        (rfid.uid.uidByte[0] == UID6[0] &&
         rfid.uid.uidByte[1] == UID6[1] &&
         rfid.uid.uidByte[2] == UID6[2] &&
         rfid.uid.uidByte[3] == UID6[3]))
    {
      digitalWrite(in1, HIGH);
      delay(15000);
      digitalWrite(in1, LOW);
    }
    rfid.PICC_HaltA();
  }
}

"but the rfid reader stops reading tags".  Does it still respond to opening the door when that happens?

Yes, rest of "features" works 100% of time - only the reader stops responding :/.

Your sketch doesn't look very robust, what with long delays in the middle of the main loop. How long does the reader remain unresponsive? Did you make sure the door was closed when you scanned the card? What sort of enclosure did you use around the reader?

What sort of distance is there between the RFID reader and the Nano?

200ms delay at the start is to overall slow everything down, 6000ms one is a timer that starts when door is opened and then closed leaving lights turned on 6s (didn't have it before and problem was still there) and 15000ms one is for when correct tag is present so that light turns on for 15s. Reader stays unresponsive for (i think) forever until the reset. Door is closed 100%, because often when i come back and find it not working i just open the door without it and then light turns on. Enclosure for scanner is a 3D printed case. Relay, arduino and power share space in one separate enclosure

@timemage about 5-6 meters of cable (used ethernet cable for that)

Well, I'm not sure how to continue with this without turning it into a conversation or doing something what will probably trigger your "throw random ideas" clause, but suffice it to say I think that distance plays a role in the problem.

@timemage I mean it could be true, but why would it just stop working randomly like that, and how to solve/test it if thats the case (i can't have a shorter cable - this one is made as short as possible)

I refer you back to my previous comment.


text:
How to make Arduino react to serial information?
I want to write a program that allows me to control the LED connected to pin 13 of the Arduino. When the program is started, the LED should be off. The user should open the serial monitor to communicate with the Arduino. If the user sends the character '1' through the serial monitor then the LED should turn on. If the user sends the character '0' through the serial monitor then the LED should turn off.
So I tried:
void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  int bytenum = Serial.available();
  if (bytenum != 0)
  {
    int bval = Serial.read();
    if (bval != 0)
    {
        digitalWrite(13, HIGH);
    }
  }
  digitalWrite(13, LOW);
}

But when launching it the LED never light up:

Serial Monitor sends a character '0' with ASCII code 48. so 48 is not equal to 0. for other shortcomings read Michel's answer

Do you use real hardware or just a simulator like shown above? If you use real hardware, most Arduino UNOs have a build in LED at pin 13; no external LED is needed. If you use a simulator the ext. LED might be needed. The LED must be connected the right way anode to pin 13 and cathode (the side with the ring) to GND, did you check that? Michel explained you how to code it correctly and gve you tips how to connect an external LED, if your Arduino is missing the builtin LED or you wnat to try a different pin on real hardware.

I see two issues:
1. Sketch
The line:
digitalWrite(13, LOW);

is always executed, meaning the LED (which might be broken, see below), is on for a very small time, probably not enough to be visible.
You can use the next sketch (for 0 and 1 to switch it off/on):
const uint8_t LED = 13;

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

void loop()
{
  while (available_characters != 0)
  {
    switch (Serial.read())
    {
      case '0':
        digitalWrite(LED, LOW);
        break;

      case '1':
        digitalWrite(LED, HIGH);
        break;

      default:
        // Ignore
        break;
    }
  }
}

You can make this sketch smaller in case you want '0' for off, and anything else for on:
const uint8_t LED = 13;

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

void loop()
{
  while (Serial.available() != 0)
  {
    digitalWrite(LED, Serial.read() == '0' ? LOW : HIGH);
  }
}

2. Lack of a resistor
I think your LED is now broken, and hopefully only the LED and not your Arduino.
Always use a resistor just before or after the LED when connecting a LED. As a guideline, use e.g. 220R or 330R.
Remember as formula:  V = I * R
The tricky thing is that LEDs have a forward voltage (Vf), so the actual formula is:
 (V - Vf) = I * R

Now most LEDs can handle mostly 20 mA, but 10 mA is more than enough to make them bright.
Below is a list of typical values for the forward voltage. Let's assume it's 1.8V as you are using a red one in your example.

The MINIMUM resistor value to be used is:
(5 V - 1.8 V) = 0.01 A * R <=>
3.2 V = 0.01 A * R <=>
R = 320 ohm

So use a 330 ohm resistor. (note that 220 ohm will still result in less than 20 mA).


text:
UNO R3 + WiFi ATmega328P+ESP8266 (32Mb memory) USB-TTL CH340G For Arduino Uno - External ESP8266 Pins
This board have pins to ESP8266's GPIOs.
What is Tout pin ?
On the back of the board it label pins :GPIO12, GPIO02, and another GPIO02 ? a continuity test shows that they are not connected. So what is it ?

From esp8266 datasheet:

TOUT - ADC pin. It can be used to test the power-supply voltage of VDD3P3 (Pin3 and Pin4) and the input power voltage of TOUT (Pin 6). However, these two functions cannot be used simultaneously.

from the pinout PDF of the Uno+WiFi board:

so there is a GP1012 and GP1O0 ? what is it ?

these are io pins of the esp8266. for example you can wire RX/TX to some pins of ATmega328p to use SoftwareSerial to communicate with the esp8266

I understand that these pins belong to ESP8266, but observe the text carefully - it goes not say gpio12 is says gp1012 (lower case in purpose )

@Guy.D, it is the normal quality level of the Robotdyn docs

So it is GPIO : 02,10,12 ?

gpio 0, gpio 2, gpio 12 and gpio 16. but Espressif doesn't call them general purpose io, only io, because the pins have constraints

@Jurag - see text on attached pic

sorry, I skipped io 4. should I see something different then on the pinout from the PDF?

next to ground is io 0 not io 2. switch 7 and the ESP BOOT pull io 0 LOW for bootloader mode of the esp8266


text:
Serial Monitor stops working when using PinMode
I'm having a lot of trouble with my recent Arduino sketch. I need to reset an IC by setting a pin high then low. I also am using the serial monitor for some testing but as soon as I try and do a Serial.print, nothing appears. My Arduino is also on a custom PCB, where D7 is connected to the IC's (MAX3421) reset pin, and also to the Arduino's reset pin.
To try and make my issue clearer, ill post some code and the serial monitor output below:
void setup()
{
  Serial.begin(9600);

  pinMode(7, OUTPUT);
}

void loop()
{
  Serial.println("TEST");
}

[nothing in serial monitor]

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

  //pinMode(7, OUTPUT);
}

void loop()
{
  Serial.println("TEST");
}

[lots of TESTs]
Any help is appreciated,
Thomas

You are probably shorting or browning out something.  What exactly do you have attached to pin 7?

I'm using one of my custom PCBs with an Arduino and a MAX3421 for interfacing with USB peripherals.
Pin 7 is connected to MAX3421's reset pin which now I look, is also connected to the Arduino reset pin. I remember doing this because it was necessary to reset the MAX before starting. Is shorting the MAXs reset with the Arduino's reset doing this?

put another serial.print() in setup() ... that way you can tell if the arduino is resetting

I put a Serial.println("x"); before the pinMode and it didn't print anything which is puzzling

"Is shorting the MAXs reset with the Arduino's reset doing this?" In a word, yes.

@VosemMedia You would also need to insert a short delay after the print. The data is send out via interrupts after the print call. So you are resetting the Arduino before the UART interface has enough time to send the data out

Ah yes, I added a short delay and now only the x is being printed over and over. I am now wondering why my code doesn't work as shorting MAX Reset and Arduino Reset should work though i'm still getting the same OSC did not start. error.

Okay that's extremely weird, for some reason it just started working, then I unplugged everything and plugged in again and it no longer works.

This may seem kind of obtuse, but do you understand what RESET pin does on the UNO?

My understanding is that it re-executes the current program though that may be incorrect, just from my experience that's what it seems to do

Also, I fixed my main issue which was the MAX not getting enough power from the USB header, so I introduced a 9v battery which sorted it all. I would love to understand the reset pin more but if you don't think it's in the scope of this question don't worry :)

This normally not meant for discussion, so this is going to be a one-shot comment to address that:  When reset is active (low), the 328P is electrically disconnected from circuit and execution is halted.  When it comes out of RESET is essentially rebooted, like a computer. Owing to what the chip itself does and what the start code does, you've functionally (oversimplifying) lost all prior state.  If you really want to know about it, you want to read in the ATMega328P datasheet.

I appreciate the explanation, thankyou

My issue was that pin 7 was connected to the reset pin on the Arduino, meaning every time it was set to output, the Arduino was reset.
You can see this here:
void setup()
{
  Serial.begin(9600);

  Serial.println("a");

  delay(100);

  pinMode(7, OUTPUT);
}

void loop()
{
  Serial.println("test");
}

which outputs a stream of a's separated by 100ms (plus a bit)

I added more information to the question, and don't doubt others have had the same problem so I will keep the question/solution up.


text:
Help Convincing Wiimote a Nano is a WiiMotion Plus
I want to replace the outdated gyro in a wiimotion plus with a BNO055. Based off what I've read from wiibrew, and im currently trying to get the wiimote to recognize the nano as an extension over I2C. Theres a lot of things at play here, but this summarizes the parts related to my issue:

When playing a game that needs WiiMotion Plus (WMP), the wiimote will send out a request to a slave device with address 00x53 to read register 0xFE every ~8 seconds.
If there is an actual register there, and it has the correct two byte id (this case it should be 0x00, 0x05), it will write 0x04 to 0xFE, activating the WMP and it will subsequently start sending motion data

I got my register information by copying the registers of an actual wiimotion plus, so i know the information is correct, yet for some reason i receive the requests from the wii and it doesn't send the activation byte back, it ignores it and keeps asking for requests. Heres an outut from my code.
23:38:28.599 -> WM+ tester
23:38:37.628 ->
23:38:37.628 -> Recieving information...
23:38:37.628 -> Handling request to register 254
23:38:37.628 ->       Sending bytes: 0,5,254,0,0,0,0,159,1,255,0,44,1,236,1,93,1,59,1,79,1,0,0,0,0,201,2,190,2,218,2,148,
                                     ^^^ the extension id
23:38:37.675 ->
23:38:37.675 -> Recieving information...
23:38:37.675 -> Handling request to register 254
23:38:37.675 ->       Sending bytes: 2,183,2,164,2,149,2,13,10,0,72,97,110,100,108,105,110,103,32,114,101,113,117,101,115,116,32,116,111,32,114,101,
23:38:37.767 ->
23:38:37.767 -> Recieving information...
23:38:37.767 -> Handling request to register 254
23:38:37.767 ->       Sending bytes: 103,105,115,116,101,114,32,0,32,32,32,32,32,32,83,101,110,100,105,110,103,32,98,121,116,101,115,58,32,0,44,0,

Since the slave cant know the length of bytes requested, it sends the maximum of 32 and theoretically the wii should take what it needs. But as i noted, the wiimote doesn't accept this and keeps requesting bytes, moving up the registers as it goes. My code for these interactions is here (most of which is documentation for future use):
// All values are big-endian.
// Assume data is tightly packed.

// The i2c stream is 0x100 bytes long, and it is mirrored across the entire 16-bit address space up to 0xa4FFFF
// Peripheral Protocol is 400kHz "fast" I2C
// NOTE: the structure of this code does not allow for passthrough devices

// References:
// https://github.com/denizkoekden/arduino-wiimote
// http://wiibrew.org/wiki/Wiimote/Extension_Controllers
// http://wiibrew.org/wiki/Wiimote/Extension_Controllers/Wii_Motion_Plus
// http://randomhacksofboredom.blogspot.com/

#include "Wire.h"

#define EMPTY_BYTE 0xFF
#define SERIAL_BAUD 115200
#define CLOCK_FREQ 400000

byte wiimote_registers[0x100] = {0xB5,0x26,0x42,0x7F,0x7E,0x7E,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8,0xFF,0xFF,0x0,0x0,0xA4,0x20,0x0,0x5,0x7A,0x8A,0x77,0x2B,0x77,0x3A,0x31,0x48,0xD5,0x27,0x27,0xE6,0xC8,0x30,0xB1,0xF9,0x83,0x4D,0x78,0x45,0x78,0xE0,0x36,0xDA,0xD1,0xDC,0x2A,0xCC,0x2D,0x4F,0x48,0xCD,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x25,0xE0,0x8E,0xCE,0xFA,0x1E,0x25,0x8A,0x9F,0xCB,0x8B,0xFC,0x5,0x96,0xFF,0x1A,0xD3,0xC8,0x15,0x97,0xCF,0xAF,0xB7,0xCC,0x72,0x79,0x87,0x78,0x35,0x9B,0x27,0x6C,0x9C,0x6A,0x1C,0xD4,0x88,0x8E,0xD6,0xA,0xE1,0xDA,0xBD,0x38,0xA5,0xD5,0xB,0x9D,0x3A,0xAC,0x26,0x1A,0x4D,0xFA,0x5,0x21,0x24,0xD8,0x6A,0xA3,0xED,0x60,0xEB,0x1A,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8,0xFF,0xFF,0x0,0x0,0xA4,0x20,0x0,0x5,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8,0xFF,0xFF,0x0,0x0,0xA4,0x20,0x0,0x5,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8,0xFF,0xFF,0x0,0x0,0xA4,0x20,0x0,0x5,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8,0xFF,0xFF,0x0,0x0,0xA4,0x20,0x0,0x5,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8,0xFF,0xFF,0x0,0x0,0xA4,0x20,0x0,0x5,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x8,0xFF,0xFF,0x0,0x0,0xA4,0x20,0x0,0x5,0x55,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x2,0xFF,0xFF,0x0,0x0,0xA6,0x20,0x0,0x5};
static byte state = 0;

const byte inactive_expansion[2] = {0x00, 0x05};
const byte active_expansion[2] = {0x04, 0x05};

const byte inactive_address = 0x53; // starts at 0xa60000
const byte active_address = 0x52; // starts at 0xa40000

const byte inactive_id[6] = {0x00,0x00,0xA6,0x20,0x00,0x05};
const byte active_id[6] = {0x00,0x00,0xA4,0x20,0x04,0x05};

// IMPORTANT REGISTERS AND WHAT THEY SHOULD HOLD

const byte id_reg = 0xa600fa;
  // holds id, used to identify extension type

const byte activate_reg = 0xa600fe;
  // activates the wmp when 0x04 is written to it
  // activation changes the extension identifier and makes the wmp start reporting motion data
  // writing 0x05 or 0x07 to this register can also implement passthrough mode
  // but we wont allow for other extensions to be connected, making that feature useless

const byte deactivate_reg = 0xa400f0;
  // deactivates the wmp when 0x55 is written to it
  // writing 0x55 to it also activates whatever extesion is connected to the wmp
  // deactivation reverts whatever changes activation has made

const byte init_reg = 0xa600f0;
  // starts initialization of the wmp when 0x55 is written to it
  // initialization does little, except for changing init-shift and init_rand_shift registers

const byte init_reg_2 = 0xa500fb;
  // would normally start initialization process once 0x00 was written to it
  // however wmp games dont do this, so its useless

const byte init_shift_reg = 0xa600f7;
  // during initialization it changes from 0x02 to 0x04 to 0x08 to 0x0C to 0x0E then stays at 0x0E
  // yet wmp games dont read this, making it useless

const byte init_shift_rand_reg = 0xa60050;
  // after initialization, registers 0xa60050 to 0xa600cf will change briefly, but randomly, for a total of 128 bytes

const byte calibration_reg = 0xa60020;
  // 32 bytes of calibration information which are reported once activated

const byte motion_reg = 0xa40008;  // (or sometimes 0xa40000)
  // 6 bytes of gyro information which are reported once activated

/*
  This is a representation of the data to be stored in motion_reg and calibration_reg

  The motion data's bits of data are split into two parts.
  The first part is the first 0-7 bits of data
  The last part is the last 8-13 bits of data
  Unused Bytes are filled with 0x00

              struct motion_data {
                byte yaw_down_7_0;
                  // Byte 0, <7:0>

                byte roll_left_7_0;
                  // Byte 1, <7:0>

                byte pitch_left_7_0;
                  // Byte 2, <7:0>

                byte yaw_down_13_8;
                  // Byte 3, <13:8>
                  // Bit 1 reserved for Yaw Slow Mode & Bit 0 reserved for Pitch Slow Mode

                byte roll_left_13_8;
                  // Byte 4, <13:8>
                  // Bit 1 reserved for Roll Slow Mode & Bit 0 reserved for Extension Connected

                byte pitch_left_13_8;
                  // Byte 5, <13:8>
                  // Bit 1&0 are unused, Bit 1 is left as 1, and Bit 2 is left as 0
              };

  As for the calibration data,
  uid_1,2 seem to be just a unique ID.
  crc32_msb,lsb is a crc32 of all calibration data except the checksum bytes.

              struct calibration_block {
                // Gyro values at 0 deg/sec to 16 bits of precision.
                u16 yaw_zero;
                u16 roll_zero;
                u16 pitch_zero;

                // Gyro values at "scale" deg/sec.
                u16 yaw_scale;
                u16 roll_scale;
                u16 pitch_scale;

                // Angular velocity of the above scale values in deg/sec divided by 6.
                // e.g. A value of 45 would mean the "scale" values represent the gyro at 270 deg/sec.
                u8 degrees_div_6;
              };

              struct calibration_data {
                // Calibration for "fast" mode.
                calibration_block fast;

                u8 uid_1;
                u16 crc32_msb;

                // Calibration for "slow" mode.
                calibration_block slow;

                u8 uid_2;
                u16 crc32_lsb;
              };

*/

/*
 * This function pointer informs the Arduino that a byte has been
 * written to one of the registers corresponding to the Extension.
 * Specifically, if you assign the function foo to this pointer and
 * you write yy bytes starting at the register address 04a400xx of
 * the Wiimote, then this library will call foo(xx, yy).  The bytes
 * are written to the global array wiimote_registers.
 *
 * Note that count will always be less than eight.  If you write
 * eight or more bytes to the Wiimote, this callback will be
 * invoked several times.
 */
void (*wiimote_receive)(byte offset, byte count) = NULL;

static void receive_bytes(int count) {

  Serial.println("");
  Serial.println("Recieving information...");
  delay(100);

  if (count == 1) {
    state = Wire.read();
  }

  else if (count > 1) {
    byte addr = Wire.read();
    byte curr = addr;

    Serial.print("Recieved bytes to register ");
    Serial.println(addr);
    delay(100);

    Serial.print("Incoming bytes... ");
    for (int i = 1; i < count; i++) {
      byte d = Wire.read();
      wiimote_registers[curr++] = d;

      Serial.print(d);
      delay(100);
    }

    Serial.println("");
    if (wiimote_receive) {
      wiimote_receive(addr, (byte) count - 1);
    }
  }
}

static void handle_request() {

  static byte last_state = EMPTY_BYTE;
  static byte offset = 0;  // apparently offset starts at 0x08? im not sure if this is true

  Serial.print("Handling request to register ");
  Serial.println(state);
  delay(100);

  switch (state) {

  default:
    if(last_state == state) offset += 32;
    else {
      last_state = state;
      offset = 0;
    }

    Serial.print("      Sending bytes: ");
    for(int i = 0; i < 32; i++){
      Serial.print(wiimote_registers[state+offset+i]);
      Serial.print(",");

      delay(50);
    }
    Serial.println("");
    delay(100);

    Wire.write(wiimote_registers + state + offset, 32);
    break;
  }

}

void setup() {
  Serial.begin(115200);
  Serial.println("WM+ tester");

  Wire.begin(inactive_address);
  Wire.setClock(CLOCK_FREQ);

  Wire.onReceive(receive_bytes);
  Wire.onRequest(handle_request);
  delay(5000);
}

void loop() {
}

How can i get the wiimote to acknowledge the response and send the activation byte to 0xFE?


text:
4 Bit Counter up and down
we are asked to create an Arduino code that would run a 4 Bit Binary UP counter once a push button switch is pressed and then 4 Bit Binary Down counter on the second click. Then vice versa. This should be done using only one switch. I figured out the Count up portion but I don't know how to add the count down code for the same switch. Can someone help me with this. Thank you.
please see below for my program

int buttonState = 0;
int timer = 300;
int pin8 = 8;
int pin9 = 9;
int pin10 = 10;
int pin11 = 11;

void setup()
{
pinMode(7,INPUT);
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);

}

void loop()
{
digitalWrite(pin8, LOW);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
buttonState = digitalRead(7);

if(buttonState == HIGH)
{
digitalWrite(pin8, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
delay(timer); //bit 1
digitalWrite(pin9, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
delay(timer); //bit 2
digitalWrite(pin8, HIGH);
digitalWrite(pin9, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin9, LOW);
delay(timer); //bit 3
digitalWrite(pin10, HIGH);
delay(timer);
digitalWrite(pin10, LOW);
delay(timer); //bit 4
digitalWrite(pin8, HIGH);
digitalWrite(pin10, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin10, LOW);
delay(timer); //bit 5
digitalWrite(pin9, HIGH);
digitalWrite(pin10, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
delay(timer); //bit 6
digitalWrite(pin8, HIGH);
digitalWrite(pin9, HIGH);
digitalWrite(pin10, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
delay(timer); //bit 7
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin11, LOW);
delay(timer); //bit 8
digitalWrite(pin8, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 9
digitalWrite(pin9, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 10
digitalWrite(pin8, HIGH);
digitalWrite(pin9, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin9, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 11
digitalWrite(pin10, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 12
digitalWrite(pin8, HIGH);
digitalWrite(pin10, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 13
digitalWrite(pin9, HIGH);
digitalWrite(pin10, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 14
digitalWrite(pin8, HIGH);
digitalWrite(pin9, HIGH);
digitalWrite(pin10, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 15
}
}

why don't you just count a variable from 0 to 0x0F and decide the four bits into the LED outputs? ... the code would be simple and not repetitive

if(buttonState == HIGH)  means "as long as the button is pressed". You probably want to use a flag that changes, when the button is clicked.

Currently you are just setting the LEDs manually one after another in your code. That is not actually a binary counter (as it is most likely wanted by the exercise), but only looks like one.
First you need to understand, what a counter really is: Basically it is just a variable, that holds a number. Where exactly this variable is saved, is not important. For your case you would use a variable in your code. The Counter/Timer hardware in the Arduino uses a fixed SFR (Special Function Register) for it.
That the counter is 4bit, means, that its value is hold by only 4 bits. That gives you a value range from 0 to 15 (2^4 values). So a 4bit counter variable would count from 0 to 15. You could just have a counter variable, that you could increment or decrement (depending on the direction, that you want to count).
// Declare counter variable and initialize with zero
int counter_variable = 0;
// Increment
counter_variable++;
// or Decrement
counter_variable--;

For the "binary" part: Here it is important to understand, that the decimal number from 0 to 15 is already saved in the variable as binary (since microcontrollers/computers only know binary, nothing else). So you can write out the state of the 4 least significant bytes of the counter variable:
digitalWrite(pin8  ,counter_variable & 0b0001);
digitalWrite(pin9  ,counter_variable & 0b0010);
digitalWrite(pin10 ,counter_variable & 0b0100);
digitalWrite(pin11 ,counter_variable & 0b1000);

The & is a bitwise AND. The result of the operation will only leave bits set, when they are set on both sides. So here we are isolating the corresponding bits. digitalWrite() will interpret anything but zero as HIGH. Thus the pin is set HIGH, if the corresponding bit is set in counter_variable. But you see, that we are repeating us here. We could use a for loop and define our pins in an array:
// at global scope
int led_pins[4] = {8, 9, 10, 11};

// in the button if statement
for(int i=0; i<4; i++){
    digitalWrite(led_pins[i], counter_variable & (1 << i));
}

We have organized the pins of the LEDs in an array, so they can be easily indexed. Then we are looping through the pins array and setting the pins similar to the last version. But now we are using (1 << i). The << operator shifts the bits of the number before it by the number of digits, that comes after it. Decimal 1 is binary 0b0001. So, when i is 2 (for example), this would shift the bits 2 digits to the left, giving you 0b0100. We are just generating the same bit patterns as in the last version.
But we can even optimize further via direct port manipulation. Inside the microcontroller the output pins are controlled via simple Special Function Registers. They work somewhat like a variable. All output pins are organized into socalled "Ports" (groups of up to 8 pins). Each port has one PORTx registers (where x stands for the character associated with that port), which sets the state of the pins, if they are in output mode. Setting the corresponding bit in the correct PORTx register will set the pin to HIGH. Clearing the bit (setting to zero) will set the pin to LOW.
You are using the Arduino pins 8 to 11. If you look at a pinout diagram of the Arduino Uno, you will see, that these pins are also marked as PB0 to PB3, which stands for "Port B, pins 0 to 3 (inside that port)". The corresponding PORTx register is PORTB. So we can set all pins of the port at once by assigning a new value to that register. The following code would set an alternating on/off pattern for all 8 pins of PORTB:
PORTB = 0b10101010;

Now we only want to use the lowest 4 bits and set them to the values, that our counter variable has. So we are masking away the 4 higher bits with the bitwise AND operator and then assign that value to the register:
PORTB = counter_variable & 0b00001111;

So now the if statement in void loop() might look like this (using a for loop):
if(buttonState == HIGH){
    // count up counter variable
    for(int counter_variable=0; counter_variable < 16; counter_variable++){
        // write out to the pins
        PORTB = counter_variable & 0b00001111;
        // delay a bit to show the value
        delay(timer);
    }
}

And now we want that each consecutive button to count in the other direction than before. So we can declare another variable as direction and then use another if statement, to switch between two for loops:
// On global scope
int direction = 1;

// in void loop()

if(buttonState == HIGH){
    if(direction == 1){
        // count up counter variable
        for(int counter_variable=0; counter_variable < 16; counter_variable++){
            // write out to the pins
            PORTB = counter_variable & 0b00001111;
            // delay a bit to show the value
            delay(timer);
        }
        // change direction
        direction = -1;
    } else {
        // count up counter variable
        for(int counter_variable=15; counter_variable >= 0; counter_variable--){
            // write out to the pins
            PORTB = counter_variable & 0b00001111;
            // delay a bit to show the value
            delay(timer);
        }
        // change direction
        direction = 1;
    }
}

Note:

This is probably not the most efficient way, but I think it is quite understandable (which is also important).
This still uses much delay() calls, just as your code. That will make your button unresponsive. The counter must first finish, before the button will react again. That might be ok for you. If not, you need to restructure the program for using a non-blocking coding style like in the BlinkWithoutDelay example from the Arduino IDE (using millis()). There are lots of tutorials about that on the web.
When using a non-blocking coding style, you also need to check the button for the transition to HIGH, instead for the state high. Otherwise the code would run only, while the button is pressed.
Buttons bounce, when being pressed. So there are many transitions between HIGH and LOW for a few ms, when the button is pressed. In the code above this is not important, because the started counter needs so long, that every bounce is finished after the counter finished. With code, that needs less than a few ms, you might get into problems there. I would suggest the Bounce2 library for that. It handles the bounce detection for you.


text:
Why is my text inverted while using U8glib?
I am displaying text using this code.
#include <U8glib.h>
U8GLIB_SSD1306_128X64 u8g(12, 11, 8, 9, 10);
int Buffer[128];int Buffer2[128];int max=0;

void pageEMG();
void recordEMG();
void pageECG();
void recordECG();
void pageBP();
void recordBP();
void clear_screen();

const int pageCount = 10;
int p;
void (*pages[pageCount])() = {clear_screen,recordEMG,pageEMG,clear_screen,recordECG,pageECG,clear_screen,recordBP,pageBP,clear_screen};
int duration [pageCount] = { 100,5000,10000,100,5000,10000,100,5000,10000,100};
void setup() {

  u8g.setFont(u8g_font_unifont);
  u8g.setColorIndex(1);
  p = 0;
  Serial.begin(9600);

}

void loop()
{
u8g.firstPage();
  do {
    (*pages[p])();
  } while( u8g.nextPage() );
  delay(duration[p]);
  p = p+1;
  if (p == pageCount)
    p=0;
}
void recordEMG(){
for(int x=0;x<128;x++)
{
Buffer[x]=analogRead(A2)*.091;
Serial.println(Buffer[x]);
delay(35);
}
u8g.drawStr( 0, 20, "Reading EMG...");
}
void pageEMG() {

for(int x = 0;x < 127;x++)
{
u8g.setFont(u8g_font_unifont);
u8g.drawStr( 0, 20, "EMG");
u8g.drawLine(x, Buffer[x], x+1, Buffer[x+1]); //OP to OLED for BP

}}
void recordECG(){
for(int x=0;x<128;x++)
{
Buffer[x]=analogRead(A0)*.08;
Serial.println(Buffer[x]);
delay(35);
}
u8g.drawStr( 0, 20, "Reading ECG...");
}
void pageECG() {

for(int x = 0;x < 127;x++)
{
u8g.setFont(u8g_font_unifont);
u8g.drawStr( 0, 20, "BP");
u8g.drawLine(x, Buffer[x], x+1, Buffer[x+1]); //OP to OLED for BP

}}
void recordBP(){
for(int x=0;x<128;x++)
{
Buffer[x]=analogRead(A1)*.091;
Serial.println(Buffer[x]);
delay(35);
}
u8g.drawStr( 0, 20, "Reading BP...");
}
void pageBP() {

for(int x = 0;x < 127;x++)
{
u8g.setFont(u8g_font_unifont);
u8g.drawStr( 0, 20, "BP");
u8g.drawLine(x, Buffer[x], x+1, Buffer[x+1]); //OP to OLED for BP

}}
void clear_screen(void) {
  u8g.setColorIndex(0);
u8g.drawBox(1, 1, 64, 128);
}

And my text is coming inverted.
Why is this happening?

In u8x8.h change U8X8_DEFAULT_FLIP_MODE from 0 to 1. https://github.com/olikraus/u8glib/blob/master/u8g2/csrc/u8x8.h#L70

Try putting u8g.setRot180(); in the setup void.


text:
Calculate battery (18650 Li-ion) voltage using ESP8266-12E
i am trying to calculate the battery voltage using ESP-12E module. I am using a voltage divider circuit to calculate the same. Here is how my circuit looks like:

And here is how my code looks like:
float volt =0.0;
float temp=0.0;
float r1=320000.0;
float r2=100000.0;

void setup(){
    Serial.begin(115200);
    Serial.println(String(VoltageCalculator()).c_str());
}

float VoltageCalculator(){
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
  Serial.println(analogRead(A0));
  for(int i = 0;i<=10; i++){
    total = total - readings[readIndex];
    // read from the sensor:
    readings[readIndex] = analogRead(A0);
    // add the reading to the total:
    total = total + readings[readIndex];
    // advance to the next position in the array:
    readIndex = readIndex + 1;

    // if we're at the end of the array...
    if (readIndex >= numReadings) {
      // ...wrap around to the beginning:
      readIndex = 0;
    }

    // calculate the average:
    float analogvalue = total / numReadings;

    //  int analogvalue = analogRead(A0);
    temp = (analogvalue * 3.3) / 1024.0;
    volt = temp / (r2/(r1+r2));
  }

  if(DEBUG_ENABLE){
    Serial.println();
    Serial.print("Actual Voltage : ");
    Serial.print(volt);
    Serial.println();
  }

  float volt_percent;

  if(volt == 3.1){
    volt_percent = 0;
  } else{
    float volt_diff = volt - 3.1;
    volt_percent = (volt_diff/1.1)*100;
    if(DEBUG_ENABLE){
      Serial.println();
      Serial.print("Voltage percentage : ");
      Serial.print(volt_percent);
      Serial.println();
    }
  }
  return volt_percent;
}

When i use this circuit with NodeMCU it works very fine, but when it comes to ESP-12E module it do not show the proper voltage. on Serial.println(analogRead(A0)); always shows 1024.
Any suggestions why this is happening and how can i do this to achieve the most accurate value?

Everything was correct and my circuit is also good. The only difference i found is to this below line:
temp = (analogvalue * 3.3) / 1024.0;
Which should be
temp = (analogvalue * 1.0) / 1024.0;
We are multiplying because we are referencing the voltage from voltage divider circuit as 1 volt.
After doing this, i am getting the exact values battery voltage which then i convert to percentage.
Thank you!


text:
U8glib+ 7-pin SSD1306 gives moving text without explicitly specifying in code
This is my code.
#include <U8glib.h>
U8GLIB_SSD1306_128X64 u8g(12, 11, 8, 9, 10);
void clear_screen();
const int pageCount = 1;
int p;
void (*pages[pageCount])() = {clear_screen};
int duration [pageCount] = {2000};
void setup() {

  u8g.setFont(u8g_font_unifont);
  u8g.setColorIndex(1);
  p = 0;
  Serial.begin(9600);

}

void loop()
{
u8g.firstPage();
  do {
    (*pages[p])();
  } while( u8g.nextPage() );
  delay(duration[p]);
  p = p+1;
  if (p == pageCount)
    p=0;
}
void clear_screen()
{
  u8g.setFont(u8g_font_unifont);
u8g.drawStr( 0, 20, "BP");
  }

This is the output is a floating text which says BP starts at 20 y length and progresses towards the right after every page refresh. and moves 20 y length down as soon as it reaches the end of the OLED
Check this video out.
Video to the Error

I don't know the answer, but it's common to use the module (%) operator in p = p+1;  if (p == pageCount) p=0;. So you get p = (p + 1) % pageCount;

I have run your code, removing the (12, 11, 8, 9, 10) portion, because the display I used is I2C.  It does not show the behaviour you describe.  It shows "BP" in the upper-left corner where it remains indefinitely.

Do you understand how the code really work? Why do you call the function clear_screen while it is actually draw a string? why the need to use function pointer (*pages[p])(); when it can simply call clear_screen()? I don't use u8glib but I can tell from the code that it will always draw the string at fix location at 0, 20 as @timemage point out, if you want to screen moving across the screen, you need to pass-in a variable u8g.drawStr( 0, y, "BP");.


text:
Error Compiling for board Arduino Nano while using Adafruit GFX
Whys is this happening to me??
I have to meet a deadline please help!!
Here is my code.
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for SSD1306 display connected using software SPI (default case):
#define OLED_MOSI   11
#define OLED_CLK   12
#define OLED_DC    9
#define OLED_CS    8
#define OLED_RESET 10
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,
  OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);
void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint16_t color);
void setup()
{
  Serial.begin(9600);

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
}

  display.display();
  delay(2000);

  display.clearDisplay();

  display.drawPixel(10, 10, SSD1306_WHITE);

  display.display();
  delay(2000);
  display.invertDisplay(true);
  delay(1000);
  display.invertDisplay(false);
  delay(1000);

  }
void loop()
{
drawLine(20,60,5,50,256);

}

The Error

C:\Users\hp\AppData\Local\Temp\ccyB6dO1.ltrans0.ltrans.o: In function
loop': C:\Users\hp\Desktop\Sunfox\Sunfox\BP_Plus_ECG\February_11\OLED_Testing_w_Adafruit\Test_2\Test_2/Test_2.ino:51: undefined reference to drawLine(unsigned int, unsigned int, unsigned
int, unsigned int, unsigned int)' collect2.exe: error: ld returned 1
exit status exit status 1 Error compiling for board Arduino Nano.

Kind Sir @MichelKeijzers what does that even mean?

I will make an answer.

@MichelKeijzers But I am using Adafruits built in library. I thought they would have done that for me.

I thought initially that you want to create your own function, but I made an answer to use the library instead of your own function.

Currently, you defined a forward declaration for drawLine, however I assume you want to call the method (function) inside display.
So change
drawLine(20,60,5,50,256);

into
display.drawLine(20,60,5,50,256);

And you can remove the forward declaration, because this method is already defined in the library.
void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint16_t color);

Note, if you call drawLine without an instance (which is display), then the linker tries to find the drawLine function which it cannot find, so you get a linker error (see ld returned in your error, together with undefined reference).