text:
Attiny85 code on Attiny84
I made OLED timer/watch using Attiny85, but as internal clock isnt accurate i need external crystal. On Attiny85 im short on pins so i am switching to Attiny84 but i have problems to compile/upload same code to Attiny84. Even if i stay on Attiny84 8mhz internal clock as on Attiny85 i still cant compile.
Im using Arduino UNO as ISP.
Error what i have:
WDT_Time.cpp: In function 'void setup_watchdog(uint8_t)':
WDT_Time.cpp:272: error: 'WDTCR' was not declared in this scope
WDTCR |= (1 << WDCE) | (1 << WDE);
^
In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\io.h:99:0,
             from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\pgmspace.h:88,
             from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:28,
             from WDT_Time.cpp:12:
WDT_Time.cpp:276: error: 'PCIE' was not declared in this scope
   sbi(GIMSK, PCIE); // Turn on Pin Change interrupts (Tell Attiny85 we want to use pin change interrupts (can be any pin))
              ^
WDT_Time.cpp:276:3: note: in expansion of macro 'sbi'
   sbi(GIMSK, PCIE); // Turn on Pin Change interrupts (Tell Attiny85 we want to use pin change interrupts (can be any pin))
   ^
WDT_Time.cpp:277: error: 'PCMSK' was not declared in this scope
   sbi(PCMSK, PCINT3);
       ^
WDT_Time.cpp:277:3: note: in expansion of macro 'sbi'
   sbi(PCMSK, PCINT3);
   ^
'WDTCR' was not declared in this scope

There are slight differences between registers, register names and registers bit names:

WDTCR is named WDTCSR
PCIE doesn't exist in GIMSK as there are two IO ports, so there are two pin change channels: PCIE0 and PCIE1
and PCMSK is similar to PCIE. There'll be two of them too.

Basically you have to look into both datasheets and compare what you are using and check if it's correct.

In code i changed: WDTCR to WDTCSR

and other changes:
GIMSK  = bit (PCIE0);   sbi(GIMSK, PCIE0); // Turn on Pin Change interrupts (Tell Attiny85 we want to use pin change interrupts (can be any pin))   PCMSK0 = bit (PCINT1) | bit (PCINT2);   sbi(PCMSK0, PCINT1);
Now its working. Thanks!


text:
nrf24 does not show all characters in the receiver
I am using Arduin mega (with RTC and DH22) and I wanna receive this values in receiver (UNO R4). The main problem is that in the receiver serial monitor does show all characters. When I increase the size of the payload or text in both, does not make change. Here are my code: The only way to include humidity and the rest of the characters is to delete some of the previous characters for example deleting Data or time or some of the empty characters in between.
[#include](tg://search_hashtag?hashtag=include) <SPI.h>
[#include](tg://search_hashtag?hashtag=include) <nRF24L01.h>
[#include](tg://search_hashtag?hashtag=include) <RF24.h>
[#include](tg://search_hashtag?hashtag=include) <DHT.h>
[#include](tg://search_hashtag?hashtag=include) <RtcDS1302.h>

RF24 radio(33, 32); // CE, CSN

const byte address[6] = "00001";

[#define](tg://search_hashtag?hashtag=define) DHTPIN 35     // Digital pin connected to the DHT sensor
[#define](tg://search_hashtag?hashtag=define) DHTTYPE    DHT22     // DHT 22 (AM2302)

DHT dht(DHTPIN, DHTTYPE);

ThreeWire myWire(39, 41, 37); // IO, SCLK, CE
RtcDS1302<ThreeWire> Rtc(myWire);

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

  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MAX);
  radio.stopListening();

  dht.begin();

  Rtc.Begin();

  Serial.print("compiled: ");
  Serial.print(DATE);
  Serial.println(TIME);

  RtcDateTime compiled = RtcDateTime(DATE, TIME);
  printDateTime(compiled);
  Serial.println();

  if (!Rtc.IsDateTimeValid()) {
    Serial.println("RTC lost confidence in the DateTime!");
    Rtc.SetDateTime(compiled);
  }

  if (Rtc.GetIsWriteProtected()) {
    Serial.println("RTC was write protected, enabling writing now");
    Rtc.SetIsWriteProtected(false);
  }

  if (!Rtc.GetIsRunning()) {
    Serial.println("RTC was not actively running, starting now");
    Rtc.SetIsRunning(true);
  }

  RtcDateTime now = Rtc.GetDateTime();
  if (now < compiled) {
    Serial.println("RTC is older than compile time!  (Updating DateTime)");
    Rtc.SetDateTime(compiled);
  } else if (now > compiled) {
    Serial.println("RTC is newer than compile time. (this is expected)");
  } else if (now == compiled) {
    Serial.println("RTC is the same as compile time! (not expected but all is fine)");
  }
}

void loop() {
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  RtcDateTime now = Rtc.GetDateTime();

  // Convert temperature, humidity, date, and time to strings
  char temperatureStr[6];
  dtostrf(temperature, 4, 2, temperatureStr); // Format: "%.2f"

  char humidityStr[6];
  dtostrf(humidity, 4, 2, humidityStr); // Format: "%.2f"

  char dateString[12];
  sprintf(dateString, "%04u/%02u/%02u", now.Year(), now.Month(), [now.Day](https://now.day/)());

  char timeString[9];
  sprintf(timeString, "%02u:%02u:%02u", now.Hour(), now.Minute(), now.Second());

  // Print date, time, temperature, and humidity in one line
  Serial.print(dateString);
  Serial.print(" ");
  Serial.print(timeString);
  Serial.print(" T:");
  Serial.print(temperatureStr);
  Serial.print("°C H:");
  Serial.print(humidityStr);
  Serial.println("%");

  // Construct message payload
  char payload[500];
  sprintf(payload, "%s %s T:%s°C H:%s%%", dateString, timeString, temperatureStr, humidityStr);

  // Send payload via NRF24L01
  radio.write(&payload, sizeof(payload));

  delay(1000); // Adjust delay as needed
}

void printDateTime(const RtcDateTime& dt) {
  char datestring[50];
  snprintf_P(datestring,
            sizeof(datestring),
            PSTR("%04u/%02u/%02u %02u:%02u:%02u"),
            dt.Year(),
            dt.Month(),
            [dt.Day](https://dt.day/)(),
            dt.Hour(),
            dt.Minute(),
            dt.Second() );
  Serial.print(datestring);
}

My Reciever:
[#include](tg://search_hashtag?hashtag=include) <SPI.h>
[#include](tg://search_hashtag?hashtag=include) <nRF24L01.h>
[#include](tg://search_hashtag?hashtag=include) <RF24.h>

RF24 radio(7, 8); // CE, CSN

const byte address[6] = "00001";

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MAX);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    char text[500] = ""; // Increase the buffer size to ensure it can hold the entire payload
    [radio.read](https://radio.read/)(&text, sizeof(text));

    // Print the received payload
    Serial.println(text);

  }
}

Serial monitor:
sender:
2024/05/07 15:02:07 T:25.90°C H:48.90%

receiver:
2024/05/07 15:02:12 T:25.90°C H

It has fixed maximum packet size and for its payload it's around 32B

source: Stack Exchange

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

sort: votes


text:
atmega32u4 connect PC
I made a custom PCB with C-type USB and atmega32u4 (arduino leonardo). But my PC doesn't recognize the atmega32u4.
Here are my schematic.
Why my PC doesn't recognize the pcb in schematic?

What code did you put on the chip?

Have you bootloaded the microcontroller?

This answer lists some potential issues with your design. It is not exhausting.
Software prerequisites
An ATmega32u4 without a program that sets up the USB module will not respond to any USB request from a USB host like a PC. Therefore the PC will not "see" it.
You need to flash a working program, for example a boot loader.
Hardware prerequisites
The ATmega32u4 needs a working clock. You connected the crystal mainly correctly. But its capacitors need to be between CRYSTAL1 and GND, and CRYSTAL2 and GND, respectively.

There should be preflashed factory DFU bootloader. What I wonder about more is how weirdly is the crystal connected...

@KIIV Thanks for pointing out the hardware issue. -- Concerning the preflashed bootloader, does Microchip deliver its MCUs always preflashed? I would not expect this.

AFAIK only for USB capable chips, everything else is blank. At least that was a case few years ago (but in previous work I just created shield for RPi with push button, dual ISP and it just flashed 16u2 and mega2560 and then used usb to upload final FW :D).

Whether or not the ATmegaXu4 comes from the factory with a bootloader (and which clock option fusing) depends on the exact ordering code. The -MU (QFN) parts like the one shown in the schematic are shipped without a bootloader.

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


text:
Maximum SPI devices with Arduino Mega
I am planning to connect

5 SPI based LS7366R counter ICs,
3 SPI connected stepper motor driver feedback ICs and
1 SPI connected W5500 ethernet controller

through SPI of Arduino Mega 2560.
So total of 9 devices.
Will this be ok to work with this way? Is there a way to reduce data consistency risks ?

This is a problem of bus length/resistance rather than number of nodes.

Welcome to SE/Arduino! Please take the [tour] to learn how this site works, it is not a forum. Please read "[ask]" and other pages of the [help], too. Then come back and address all comments by [edit]ing your question. -- Why are you expecting data consistency risks? What reasons do you have in mind causing these risks? -- You will need the data sheets of all devices to check the fulfillment of their requirements.

Each SPI device requires a separate CS pin. The Arduino Mega has several digital pins available, so you can assign each device its unique CS pin. Your setup should work with 9 SPI devices if you manage the CS lines properly.


text:
having problems with my arduino bluetooth car project(with L298n Motor Driver)
so the scenario is i am making a bluetooth controlled car(voice control)+obstacle avoidance function.I am using Arduino UNO with L298n motor driver and a HC-05 BT module in the sensors i am using the ultrasonic sensor and a IR sensor for the back and a servo motor is also used to rotate the ultrasonic sensor.so the problem is when i am sending command "turn left" the servo moves left and nothings happens and the other command i.e turn right,move backward,move forward are not working at all.
circuit diagram and code is given if i have done  something wrong with the code or else my motor driver or wiring is creating the issue

#include <NewPing.h>
#include<Servo.h>
#define TRIGGER_PIN A1
#define ECHO_PIN A0
#define MAX_DISTANCE 300
#define IR A2

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

Servo myservo;

String voice;

void setup() {
  Serial.begin(9600);
  myservo.attach(8);
  myservo.write(90);
  pinMode(IR, INPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode( 9, OUTPUT);

}

void loop() {
  int distance = sonar.ping_cm();

  if (Serial.available() > 0) {
    voice = "";
    delay(2);
    voice = Serial.readString();
    delay(2);
    Serial.println(voice);

    if (voice == "turn left") {
      left();
    } else if (voice == "left") {
      left();
    } else if (voice == "turn right") {

    } else if (voice == "right") {

    }

  }
  while (voice == "move forward") {
    forward();
  }
  while (voice == "move backward") {
    backward();
  }
}

void forward() {
  int distance = sonar.ping_cm();

  if (distance < 10) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);
    voice = "";
  } else {
    digitalWrite(12, HIGH);
    digitalWrite(10, HIGH);
  }
}
void backward() {
  int IR_Sensor = digitalRead(IR);
  if (IR_Sensor == 0) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);
    voice = "";
  } else {
    digitalWrite(11, HIGH);
    digitalWrite( 9, HIGH);
  }
}
void left() {
  myservo.write(180);
  delay(500);
  myservo.write(90);
  delay(500);
  int distance = sonar.ping_cm();

  if (distance < 10) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);
    voice = "";
  } else {
    digitalWrite(12, HIGH);
    delay(700);
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);

  }
}

void right() {
  myservo.write(0);
  delay(500);
  myservo.write(90);
  delay(500); {
    int distance = sonar.ping_cm();

    if (distance < 10) {
      digitalWrite(12, LOW);
      digitalWrite(11, LOW);
      digitalWrite(10, LOW);
      digitalWrite( 9, LOW);
      voice = "";
    } else {
      digitalWrite(10, HIGH);
    }
    delay(700);
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);
  }
}

void Stop() {
  digitalWrite(12, LOW);
  digitalWrite(11, LOW);
  digitalWrite(10, LOW);
  digitalWrite( 9, LOW);
}

start at the begining ... write a sketch that runs one motor in one direction for one second, stops the motor for one second, then repeats

The code seems to have a few missing lines for logic. Here's a corrected version from my understanding.
#include <NewPing.h>

#include<Servo.h>

#define TRIGGER_PIN A1
#define ECHO_PIN A0
#define MAX_DISTANCE 300
#define IR A2

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

Servo myservo;

String voice;

void setup() {
  Serial.begin(9600);
  myservo.attach(8);
  myservo.write(90);
  pinMode(IR, INPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);

}

void loop() {
  int distance = sonar.ping_cm();

  if (Serial.available() > 0) {
    voice = "";
    delay(2);
    voice = Serial.readString();
    delay(2);
    Serial.println(voice);

    if (voice == "turn left") {
      left();
    } else if (voice == "left") {
      left();
    } else if (voice == "turn right") {
      right();
    } else if (voice == "right") {
      right();
    } else if(voice == "move forward"){
      forward();
    } else if(voice == "move backward"){
      backward();
    }

  }

}

void forward() {
  int distance = sonar.ping_cm();

  if (distance < 10) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
    voice = "";
  } else {
    digitalWrite(12, HIGH);
    digitalWrite(10, HIGH);
  }
}
void backward() {
  int IR_Sensor = digitalRead(IR);
  if (IR_Sensor == 0) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
    voice = "";
  } else {
    digitalWrite(11, HIGH);
    digitalWrite(9, HIGH);
  }
}
void left() {
  myservo.write(180);
  delay(500);
  myservo.write(90);
  delay(500);
  int distance = sonar.ping_cm();

  if (distance < 10) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
    voice = "";
  } else {
    digitalWrite(12, HIGH);
    delay(700);
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);

  }
}

void right() {
  myservo.write(0);
  delay(500);
  myservo.write(90);
  delay(500); {
    int distance = sonar.ping_cm();

    if (distance < 10) {
      digitalWrite(12, LOW);
      digitalWrite(11, LOW);
      digitalWrite(10, LOW);
      digitalWrite(9, LOW);
      voice = "";
    } else {
      digitalWrite(10, HIGH);
    }
    delay(700);
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
  }
}

void Stop() {
  digitalWrite(12, LOW);
  digitalWrite(11, LOW);
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
}


text:
Why is Wire.onReceive() called during requests?
I'm building a complex I2C-based networking protocol and have noticed that the Wire.onReceive() handler is called both for I2C read and write operations. When the master writes to the slave, it is called as you'd expect. But it also seems to be invoked when the master reads from the slave which is unexpected.
Ideally, I'd like a transaction with both a read and a write - e.g. the master writes a value (for instance a variable argument) and then reads back from the slave the result (for instance, the lookup of that variable.)
Compiled on the SAMD21 ArduinoCore, the following programs generate this result:
1400,700
>>> x is
<<< hello
>>>
>>> x is
<<< hello
>>>
1404,702
>>> x is

Showing that the onReceive is called twice as often as onRequest.
I don't see this behavior documented anywhere.
Master:

    #include
void setup()
{
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
}

void loop()
{
  Wire.beginTransmission(4); // transmit to device #4
  Wire.write("foobar");        // sends five bytes
 // Wire.write(3);              // sends one byte
  Wire.endTransmission(true);    // stop transmitting

  Wire.requestFrom(4, 6);    // request 6 bytes from slave device #2

  while(Wire.available())    // slave may send less than requested
  {
    char c = Wire.read(); // receive a byte as character
    Serial.print(c);         // print the character
  }

  delay(500);
}

Slave
#include <Wire.h>

void setup()
{
  Wire.begin(4);                // join i2c bus with address #4
  Wire.onReceive(receiveEvent); // register event
  Wire.onRequest(requestEvent);
  Serial.begin(9600);           // start serial for output
}

long inCount = 0;
long outCount = 0;

void loop()
{
  char c[200];
  snprintf( c, 200, "%d,%d\n", inCount, outCount );
  Serial.print( c );
  delay(1000);

}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
inCount++;

  Serial.print( ">>> ");
  while(1 < Wire.available()) // loop through all but the last
  {
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }

  Serial.println();         // print the integer
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent()
{
  Serial.println( "<<< hello ");

  outCount++;
  Wire.write("hello "); // respond with message of 6 bytes
                       // as expected by master
}

The Wire.onReceive is not called when the Master is reading data. If you encounter that, it is a bug, write a minimal sketch and start an issue at Github. Please don't use any Serial function inside receiveEvent or requestEvent. In the receiveEvent you can use 'howMany' for the number of received bytes, there is no need for the strange while(1 < Wire.available()). I know that is in an example, but that is a terrible example. The 'inCount' and 'outCount' should be volatile. The sprintf format should perhaps use %ld a long, but I suppose that is also 32-bit for a SAMD21.

@jot: +1 for the hint, not to use any Serial function within the event handler.

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


text:
Arduino Zero - Stepper control (interrupt)?
I have a stepper controller board that I need to pulse every 40 uS or so.
I also have I2C sensors and Serial writes to preform.
Currently I run an update call in a tight loop, but the I2C sensors and Serial writes cause considerable delays which makes the motors stutter and come to a halt.
I would like to use an ISR to call the motor update method periodically.
However I cannot for the life of me figure this timer stuff out.
Here's my current attempt:

void TC4_Handler() {
  Stepper::updateAll();
}

void setup() {

  // Timer stuff
  // Set up the generic clock (GCLK4) used to clock timers
  REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                    GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                     GCLK_GENCTRL_GENEN |         // Enable GCLK4
                     GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                     GCLK_GENCTRL_ID(4);          // Select GCLK4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  // Feed GCLK4 to TC4 and TC5
  REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                     GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                     GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_TC4_COUNT16_CC0 = 0x000F;                      // Set the TC4 CC0 register as the TOP value in match frequency mode
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

  //NVIC_DisableIRQ(TC4_IRQn);
  //NVIC_ClearPendingIRQ(TC4_IRQn);
  NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
  NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

  REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
  REG_TC4_INTENSET = TC_INTENSET_OVF;             // Enable TC4 interrupts
  // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

  REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV1024 |   // Set prescaler to 1024, 48MHz/1024 = 46.875kHz
                   TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                   TC_CTRLA_ENABLE;               // Enable TC4
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization
  // ...
}

As Stepper::updateAll(); isn't shown I don't know what it does.  For accurate timing it would make sense to use hardware-operated output-compare output pins like TIOAx and TIOBx, instead of running some code to drive the pins when an interrupt occurs.
If you need to control several wires per motor – such that a pulse on a single output line isn't enough – you might consider using a 74HC595 (or other shift register) to transfer the bits.  Thus, each time an output compare occurs, the  TIOAx and TIOBx line would pulse the ST_CLK (store-clock) line of the SR, to transfer bits from the shift chain flipflops to the output flipflops; then, at its leisure the interrupt routine can shift the next set of bits out to the '595, ready to be transferred at the correct moment, when the next output compare occurs.
During stepper acceleration or deceleration, the timer count-limit would also need to be updated within the ISR.

I'm using this driver https://www.pololu.com/product/2975, all Stepper::updateAll() does is to check if the step pin needs to be pulsed.

In that case, you should use a TIOAx or TIOBx line to pulse the A4988, and should calculate timer count-limits for the ISR to set.  In other words, don't “check if the step pin needs to be pulsed” – which amounts to trying to run the stepper using polling, which is a bad idea – but instead calculate when the step pin needs to be pulsed, set timer accordingly, and have the timer pulse the A4988.


text:
How to use a rotary encoder on NodeMCU with Arduino code?
I have a standard 5 ping rotary encoder (3 pins for encoder, 2 pins for button).
I'm trying to get a working code that manages to read the rotary encoder.
I began with the code I found here: http://bildr.org/2012/08/rotary-encoder-arduino/
My problem is that the interrup method never being called.
I read that all the GPIO pins on NodeMCU support interrupts (except D16).
Here's my code:
volatile int lastEncoded = 0;
volatile long encoderValue = 0;

long lastencoderValue = 0;

int lastMSB = 0;
int lastLSB = 0;

void setup() {
  Serial.begin(115200);
  delay(10);

  pinMode(D0, INPUT);
  pinMode(D3, INPUT);

  digitalWrite(D0, HIGH); //turn pullup resistor on
  digitalWrite(D3, HIGH); //turn pullup resistor on

  attachInterrupt(D0, handleInterrupt, CHANGE);
  attachInterrupt(D3, handleInterrupt, CHANGE);
}

void handleInterrupt() {
  int MSB = digitalRead(D0); //MSB = most significant bit
  int LSB = digitalRead(D3); //LSB = least significant bit

  int encoded = (MSB << 1) |LSB; //converting the 2 pin value to single number
  int sum  = (lastEncoded << 2) | encoded; //adding it to the previous encoded value

  if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
  if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;

  lastEncoded = encoded; //store this value for next time
}

void loop() {
    Serial.print("Encoder: ");
    Serial.println(encoderValue);
    delay(1000);
}

My initial thought is that if this code is where the problem is then you would be better off in the Arudino SE. You  did not provide a schematic though- do you have pullup resistors on the A/B pins and is the common grounded?

Check that interrupts are working with some simpler code, eg. use void handleInterrupt() {    encoderValue ++; } instead of the more complex handler code. Then you will either know interrupts are happening, or their is a bug in the handler.

@SpehroPefhany I have the same wiring as in the blog article I linked. So I found that I need a debounce circuit to make this work flawlessly.

Different RotaryEncoders work in different ways. Mine connects the two outputs sequentially to the Gnd or + inputs, depending on the rotation direction. The resultant phase changes need to be detected and decoded by the processor.
I took your code and ran it on a LoLin NodeMCU using my 5-pin RotaryEncoder.
I connected (NodeMCU to RotaryEncoder):

D0 to Clk;
D3 to DT;
GND to GND; and
3V to +.

I ran the code, and it worked: the printed value went up when I rotated it in one direction, and down when it rotated in the other. The "bounce" was terrible though - getting just a single increment or decrement for one "detent" was difficult; I typically got 2-4.
Because of my encoder, I was able to remove the two digitalWrite(..., HIGH); lines and it continued to work. Perhaps that's what your problem is? Did you connect the + input? You mention the two switch pins: perhaps there's only one switch pin, that connects to the Gnd pin?

EDIT: The code!
So I went away and wrote a RotaryEncoder polling library, rather than the interrupt code that the original question was based on. The idea is that you can poll a rotary encoder (relatively) infrequently, and stil "catch" the transitions as it rotates. Of course this won't work if you poll it too slowly - your mileage may vary!
But here are three files:

The header and library source for the RotaryEncoder module; and
An example usage of the module.

RotaryEncoder.h:
//
// RotaryEncoder.h
//
// This library manages a Keyes KY-040 Rotary Encoder by sampling the
// appropriate pins when requested. It is NOT interrupt driven, so you'll need
// to sample often.
//
// The encoder has five pins in a 0.1" row, so you can directly plug it into
// an Arduino's data-pin sockets. The sequence of pins matches the order of
// parameters in the constructor - use ascending (or descending) numbers for
// ease.
//
// If you pass in NoPin for gnd, vcc, or sw (the switch), then that parameter
// is ignored. You'll need to organise those pins yourself! Of course, NoPin is
// not valid for dt or clk.
//

#ifndef RotaryEncoder_h
#define RotaryEncoder_h

class RotaryEncoder {

public: // Typedefs and enums

   typedef byte Pin;

   typedef signed char OptPin;

   enum Pins : OptPin {
      NoPin = -1
   }; // Pins

public: // Methods

   // Define which pins to use for the various functions.
   // If Optional Pins are "NoPin", then they won't be initialised
   RotaryEncoder(OptPin gnd, OptPin vcc, OptPin sw, Pin dt, Pin clk);

   // Start RotaryEncoder with optional maxBias (call Rebias() periodically)
   void Begin(byte maxBias=1);

   // Returns true if switch is currently pressed
   bool Switch() const;

   // Returns 0 for no change, +ve for clockwise, -ve for counter-clockwise
   int Get();

   // Call this periodically to reduce the bias
   void Rebias(int delta=1);

private: // Variables

   const OptPin gndPin;

   const OptPin vccPin;

   const OptPin swPin;

   const Pin dtPin;

   const Pin clkPin;

   byte maxBias;

   byte bias;

   bool clk;

   bool dt;

}; // RotaryEncoder

#endif // RotaryEncoder_h

RotaryEncoder.cpp:
//
// RotaryEncoder.cpp
//

#include <Arduino.h>
#include "RotaryEncoder.h"

RotaryEncoder::RotaryEncoder(OptPin gnd, OptPin vcc, OptPin sw, Pin dt, Pin clk) :
               gndPin(gnd),
               vccPin(vcc),
               swPin(sw),
               dtPin(dt),
               clkPin(clk),
               maxBias(1),
               bias(1),
               clk(false),
               dt(false) {
} // RotaryEncoder::RotaryEncoder(gnd, vcc, sw, dt, clk)

void RotaryEncoder::Begin(byte maxBias) {
   this->maxBias = maxBias;
   if (gndPin!=NoPin) {
      pinMode(gndPin, OUTPUT); // Let's power the device,
      digitalWrite(gndPin, LOW);  // Power -ve with 0
   } // if
   if (vccPin!=NoPin) {
      pinMode(vccPin, OUTPUT); // ,with both - and +
      digitalWrite(vccPin, HIGH); // Power +ve with 1
   } // if
   if (swPin!=NoPin) {
      pinMode(swPin, INPUT_PULLUP); // They pushed it!
   } // if
   pinMode(dtPin,  INPUT); // One half
   pinMode(clkPin, INPUT); // The other half
} // RotaryEncoder::Begin(maxBias)

bool RotaryEncoder::Switch() const {
   return swPin!=NoPin ?
          digitalRead(swPin)==LOW :
          false;
} // RotaryEncoder::Switch()

int RotaryEncoder::Get() {
   bool clkNew = digitalRead(clkPin);
   if (clk!=clkNew) {
      clk = clkNew; // Clock's changed; sample data
      bool dtNew = digitalRead(dtPin);
      if (dt!=dtNew) {
         dt = dtNew; // Data's changed; remember it!
         if (clk) {  // Only pay attention to Clk Low-High
            int temp = bias;
            bias = maxBias;
            if (dt) {
               return -temp;
            } // if
            else {
               return +temp;
            } // else
         } // if
      } // if
   } // if
   return 0;
} // RotaryEncoder::Get()

void RotaryEncoder::Rebias(int delta) {
   if (bias<=1) {
       return;
   } // if
   bias -= bias>delta ? delta : bias-1;
} // RotaryEncoder::Rebias()

RotaryBlinker.ino:
//
// RotaryBlinker
//
// This example changes how fast the built-in LED blinks by using the
// RotaryEncoder library.
// It starts with an intermediate value (80h).
// * If you rotate it left, it slows down (then it jumps to the fastest).
// * If you rotate it right, it speeds up (then it jumps to the slowest).
// The jumps are because there is no logic to handle wrap-around - an exercise
// for the reader!
//
// Also note that a bias feature has been included. The faster you turn the knob, the
// exponentially quicker the rate changes. This is done by setting a fast rate on
// every detent, then when the millisecond has changed it re-biases the knob lower.
//
// To handle the knob correctly, it needs to INCREASE the time interval when
// dialling LOWER - hence you'll see a negative number in the code.
//
// It also checks for the switch. If it's pressed, it simply turns the LED full on.
//

#include <RotaryEncoder.h>

// Choose pins that are convenient for the RotaryEncoder's pins
#if defined(ESP8266)

const byte LED = D5;                   // No built-in LED! Choose... this one!
const unsigned baud = 115200;
const RotaryEncoder::OptPin GND = -1; // Use GND pin
const RotaryEncoder::OptPin VCC = -1; // Use V+ pin
const RotaryEncoder::OptPin SW  =  D4; // Switch
const RotaryEncoder::Pin    DT  =  D3; // Data
const RotaryEncoder::Pin    CLK =  D2; // Clock

#elif defined(ADifferentBoard) // Put the board's definition here

// And then change these assignments
const byte LED = LED_BUILTIN;
const unsigned baud = 57600;
const RotaryEncoder::OptPin GND =  8; // Need 0V
const RotaryEncoder::OptPin VCC =  9; // Need +V
const RotaryEncoder::OptPin SW  = 10; // Switch
const RotaryEncoder::Pin    DT  = 11; // Data
const RotaryEncoder::Pin    CLK = 12; // Clock

#else // Arduino Uno default

const byte LED = LED_BUILTIN;
const unsigned baud = 57600;
const RotaryEncoder::OptPin GND =  8; // Need 0V
const RotaryEncoder::OptPin VCC =  9; // Need +V
const RotaryEncoder::OptPin SW  = 10; // Switch
const RotaryEncoder::Pin    DT  = 11; // Data
const RotaryEncoder::Pin    CLK = 12; // Clock

#endif // Boards

// Tell library which pin does what. Note Optional Pins can be -1
RotaryEncoder encoder(GND, VCC, SW, DT, CLK);

// Setup the board for these definitions
void setup() {
    Serial.begin(baud);
    pinMode(LED, OUTPUT); // Want to see it working

    encoder.Begin(10); // Start, with a re-bias of 10
} // setup()

bool ledON = false;  // Current LED state
byte repeat = 0x80;  // How quickly to restart, in ms
byte count = repeat; // Count down 'til next time!

unsigned last = 0;   // Last time millis() was recorded

void loop() {
    // Have switch override pulsing - turn it hard ON
    if (encoder.Switch()) { // Hard override!
        ledON = false; // Pretend LED is now OFF
        digitalWrite(LED, HIGH);
    } // if
    else {
        int value = encoder.Get(); // Returns positive for clockwise turn
        repeat += -value;   // We want to INCREASE time to slow down blinking
        if (value!=0) {     // Did it change?
            Serial.print(value);    // Print latest value
            Serial.print('=');
            Serial.println(repeat); // Print new result
        } // if
    } // else

    // Is it time to blink the LED again?
    unsigned latest = millis();
    if (last!=latest) {
        last = latest;
        encoder.Rebias();    // Re-bias encoder, to decelerate rotation
        if (--count==0) {    // Reached zero yet?
            ledON = !ledON;  // Yes! Toggle LED
            digitalWrite(LED, ledON ? HIGH : LOW);
            count = repeat;  // Count for next time
       } // if
    } // if
} // loop()

So I wired everything together again and now I have the same effect as you described. The bounce is really bad. So it seems the code is okay. The hardware needs more attention. Can you suggest a good debounce circuit?

Actually, the easiest way to debounce the device is to not interrogate it so often. Using interrupts on every single change is just asking for trouble... I don't know the rest of your code, but does it loop reasonably quickly? Rather than read the results of the interrupt, could you simply poll the device? A rotation, even a fast one, gives pulses in the order of 10s of milliseconds, so if you could poll the encoder as to its current status every 5-10 ms, you'd get debounce for free.

One more question though : the device I'm building is an IoT device. What if I'm rotating the encoder while I'm downloading/uploading something to the Internet? That takes hundreds of milliseconds. Not easy to create a code that loops quick enough. How would you accomplish that?

Agreed: that's the problem with switch bounce. You've got three options: remove the bounce in hardware (add capacitors - difficult for a Rotary Encoder); don't interrogate as often; or get each and every bounce, but ignore those that happen "too quickly". One technique is, on every switch, to get the current value of micros(). Compare that to the last saved value, and if too recent, simply ignore it. Otherwise, remember the new time as the last time, and process the change. The problem is that micros() may not update quickly enough...

Fix to make the code inc/dec on every step instead of every second step:

Comment out this line in cpp
if (clk) {  // Only pay attention to Clk Low-High

2.Change the next conditional to:
if (dt^clk)

did you try a different pin? (D2, D1) should work..
Seems like D0 does not have interrupt
https://opensprinkler.com/wp-content/uploads/2016/03/NODEmcuPinOut.png
also there is a rotary encoder library so try using that
..
The library i use is able to work without interrupts
Encoder by Paul Stoffregen available from Arduino Library Manager or
https://www.pjrc.com/teensy/td_libs_Encoder.html

Which library is that?

See the link above

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


text:
How to reduce sketch size?
How to reduce sketch size?
I got an error that “Sketch uses 30,044 bytes (104%) of program storage space. Maximum is 28,672 bytes.”
I can't reduce function in sketch.I can't change ATmega32u4,now.
The sketch has function of measuring sensor,logging on SD,connection with BLE module.
So please tell me hack.
Or,how to increase flash memory size?
I tried to change type of String to Char.

Impossible to answer without seeing the sketch in question. Some things (like long long data types) use a very large amount of program memory. You can't increase the flash memory size (on a particular processor).

Thank you.
I agree.But I think that putting the whole sketch is not good idea. because It's hard for you to read.(and comment are Japanese mainly.)
So,I will put Structure like that include,setup,loop,other method.
How about that?

If you can find some place to post the whole thing that would be better (it will be probably too big to fit here). I don't care about the comments personally because I usually ignore them.

This has 32516 characters.

Now,I pleased that I heard generic techniques from @JRobert,@dannyf,@dda,@Michel Keijzers,too. Because I'd like to know "how to reduce sketch size" for making sketch in the future.

I'm sorry that I couldn't upload code.I'm in trouble at other points, so I correspond to that.I want time, a bit more.

I bought a lot of 32u4 board. So, I wanted to use them. Therefore, I was asking this question.

Some generic techniques you can try:

Remove duplicate code and put it in a function.
If you have duplicate code that is ALMOST duplicate, parameterize it (i.e. add a function, make the difference a parameter(s) of the function and call from various locations with different argument(s).
Use a micro controller with more Flash memory.
Minimize the data storage, limiting array sizes for example (if these are in flash RAM).
If you use precalculated arrays, remove them and create a function calculating them real time (this will be a performance cost of course).
Check for dead code inside functions. A smart compiler will already remove uncalled functions, but do not check inside functions.
Remove or minimize debug/print statements. Each character cost a byte, which adds up quickly with many strings.
Try to remove complete libraries, like removing the Serial for print statements used only for debugging.

I made code the function,in some cases this increase sketch size.So,It's difficult for me.
I knew for the first time that
A smart compiler will already remove uncalled functions, but do not check inside functions.
For me, it became very helpful as well.
Thank you!

How to reduce sketch size?

without your code, tough to be specific. but generally:
1) try not to use floating pointmath;
2) try not to use printf() or its derivative;
3) try to minimize large arrays;
4) use functions instead of macros;
5) use modular programming;
...

Or,how to increase flash memory size?

1) use a bigger chip;
2) use onboard eeprom;
3) use outboard eeprom / flash / fram / ....
4) divide up the tasks among multiple chips;
...

I don't know these point.Thank you for explaining very clearly

If you're using donated libraries to run your hardware (such as the Dallas Temperature library) or provide software features (like SimpleTimer), the authors often provide a full complement of features, some of which you may not need. I often make my own versions of these libraries that provide the functionalities I must have, and cut out the others. I can always add one or two of them back into whichever sketch needs them, without burdening other sketches with their overhead.
In SimpleTimer, for instance, I seldom have need for enable/disable timer or for a timer that runs N-times and then stops, so I have a version of the library with those functions removed.
If you've declared some text strings or other data to live in Flash, and you have more spare RAM than spare Flash, let some of those objects live in RAM instead. Or reduce the length of output strings that are stored in Flash by writing more tersely, even at the cost of clarity in the output, or eliminating that outpu altogether (which eliminates not only the string data but the code to print it, as well).
Can you reduce any code segments or algorithms with more space-efficient code? Can you eliminate some functionality to save code space?
Note that trimming buffers and arrays won't help because those are in RAM, and data packing, such as storing a number of booleans as distinct bits within a word, will actually increase your code size (this is a common way to reduce RAM requirements when you can afford the code to do the packing/unpacking, but you have the opposite problem!).

I learned from specific example very much.
I used to Metro library,SoftwareSerial,etc.So I can use the solution.
I did not understand this difference. (this is a common way to reduce RAM requirements when you can afford the code to do the packing/unpacking, but you have the opposite problem!). Therefore, I will be able to distinguish decreasing solution between Flash and RAM from now on.
Thank you!

There's no magic bullet. You have to work through your code and see what you can remove safely. If you have duplicate code, put it in a function and call this. If you Serial.print a lot of text, considering saving up on that. etc etc etc

Yes,I decrease Serial.print.Thank you!


text:
How to interface Arduino with NXP PCA8561 LCD segment driver?
I've just bought few NXP PCA8561AHN LCD segment drivers to do some tests which unfortunately did not went as expected.
I'm familiar with expanders and segment LED displays but LCDs seem to be way more complicated than I thought and there are no libraries or articles to start with.
According to the datasheet, everything is connected correctly, as follows:

VLCD: +3.3V
VDD: +3.3V
VSS: GND
RST: pulled down by a 1K resistor
A0: unconnected
SCL: pulled up by a 1K resistor and connected to A5/SCL on MCU
SDA: pulled up by a 1K resistor and connected to A4/SDA on MCU
PORE: unconnected
SEG0 to SEG13: LCD segments
COM0: LCD pin 1 (backplane #1)
COM1: LCD pin 18 (backplane #2)

PCA8561 draws 35uA when RST is pulled down so it seem to be "active".
Here's how I've tried to initialize the i2C communication with the driver:
#include <Wire.h>

#define address 0x38

const byte numbers[10] = {
  B01000000,
  B01111001,
  B00100100,
  B00110000,
  B00011001,
  B00010010,
  B00000010,
  B01111000,
  B00000000,
  B00010000
 };

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

  Wire.begin();

  Wire.beginTransmission(address);
  Wire.endTransmission();
}

void loop() {

  Wire.beginTransmission(address);

  Wire.write(numbers[5]);

  while (Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }

  Wire.endTransmission();
  delay(250);
}

PCA8561 datasheet
PCA8561 pinout

    .
LCD pinout

Update
void setup() {
  Wire.begin();

  Wire.beginTransmission(address);

  Wire.write(0x00);
  // Wire.write(00000000);
  Wire.write(00101100);
  Wire.write(0x0);

  Wire.write(0x01); // Display_ctrl command (address 01h)
  // Wire.write(00011100);
  Wire.write(010); // frame frequency selection: 96Hz

  Wire.write(0x02); // Display_ctrl_1 command (address 02h)
  // Wire.write(00001100);
  Wire.write(11); // static mode

  Wire.endTransmission();
}

void loop() {
  Wire.beginTransmission(address);

  /*
     Static drive mode
     Using a single backplane, COM0
  */
  Wire.write(0x04); // SEG0 to SEG 7
  Wire.write(B11111111); // all segments ON
  Wire.write(0x05); // SEG8 to SEG15
  Wire.write(B11111111); // all segments ON

  Wire.endTransmission();
}

Few things:

Wiring - the datasheet says in 8.3.3:  "At power-on the PCA8561 can be reset (...) by pulling pin RST low". By pulling it to GND you asking your LCD to stay in Reset state.
You miss display initialisation. Where is your settings for Device_ctrl,  Display_ctrl_1,  Display_ctrl_2 registers?

@smajli , first of all, thank you for taking your time to read the datasheet, I really appreciate the effort. Second, I've managed to write some code for a correct(i hope) start sequence and finally, i can see 10 segments lit on LCD. I think there are some pads unsoldered which I will take care of later. Still not sure if the start sequence can be written in a more efficient way so if there is something I can improve, please let me know. Thanks a lot for your help

good effort. I'm glad I could help. Little things for your code: you may use #define Display_ctrl 0x01 at the beginning of your code, and later instead Wire.write(0x01) place Wire.write(Display_ctrl). Make it with all display commands and registers you are planning to use. This will make your code human friendly.  Later you may think about placing these into separate file thus making it ready for writing a library.


text:
When Raspberry Pi is preferred over Arduino
We are doing some projects in class. One of my friends is doing a weather and humidity station using raspberry Pi with a couple of sensors and LCD. I have a little experience in Arduino. So I asked her, why doesn't she do it using an Arduino? She said Pi is more 'powerful'. In what aspects, is it more powerful than Arduino? When should I go for Raspberry Pi over Arduino?

It is more powerful indeed. Yet an overshoot for a "weather station". RPi is a full featured computer. Arduino is a pretty stupid and weak microcontroller.

As explained in the answers, each has its own strengths. Some projects can even benefit from using both. See the answers to this somewhat related question: Why connect arduino with Rasberry pi?

@EugeneSh. Yet it always beats Pi on uptime, power consumption, GPIO output current, has ADC, and the driver libraries for WiFi shields don’t break in operation. Try keeping a live WiFi  link with a Pi for two weeks...

Arduinos usually also beat a Pi in terms of security, a full OS most certainly has more exploits than a Nano running a few hundred lines of code. :D

Somewhat of an opinionated question but I'll give some feedback. It depends on various things:

How much UX and UI you want to give to your client
How easily can you program it
Which is a cheaper solution
How fast do you want the program to run
What is more durable and how long do you want to use the device

To prevent this answer from being lengthy, I'll do a quick comparison from my experiences with both.
Arduino: Cheap, easy to program, capable of flexibility with UX and UI but has very limited memory. The Arduino is typically good for something that can just complete tasks on their own. I've written state machines and have used it for PLCs with an Arduino. It's a good device for a cheaper budget. Arduino is pretty fragile, however.
Raspberry Pi: More expensive, a lot more powerful in terms of processing speed, has a lot more memory, extremely good for UX and UI devices that are being developed, good for artificial intelligence, state machines, PLCs, etc. Also really good for data logging, image processing, and radio frequency applications. You can also boot an operating system on it (e.g. Linux/Unix). In other words, a Raspberry Pi can used as a computer while the Arduino... well I guess it depends how you define, "computer" LOL.
So if you're trying to do something as simple as using sensors and LEDs, I'd go for the Arduino Uno.

Raspberry pi is more powerful but a micro controller is more consistent. If you need to be pushing a value down a wire with very specific timings the you will need an arduino because having a full OS on the raspberry pi means sometimes there will be delays from the OS scheduling other tasks first.

The claim that the Pi is more "powerful" is a bit misleading. What does "powerful" really mean? And is it relevant to making a weather station?
I made a temperature and humidity sensor as described here using an Atmega328P (the processor that is in the Arduino Uno). The estimated average power consumption is 42 µA which has allowed it to run from 3 x AA batteries for a couple of years before they needed replacing. I think you'll find that the Pi with its more "powerful" processor and extra components would not be able to do that.
I see from a quick search that the Pi consumes 80 mA to 240 mA when idle (depending on the model). This would make a Pi-powered weather station eat through batteries 2000 times as quickly. Perhaps that would be a consideration.
The Pi is really a Unix PC on a board, which means it goes through the normal boot sequence with a possibility of errors occurring during booting. To see what those errors are you need to connect up a keyboard and screen, or connect via a network to it from another PC.
I don't want to run down the Pi - it's a nice cheap Unix computer on a small board. But the Arduinos (many of them) are somewhat simpler to program. You don't need to worry about the operating system for a start. For a weather station, taking a reading every 5 minutes, who cares if the Pi can take the reading "50 times faster"?

Speed of recovery from sleep
I have an answer about letting serial data wake an Arduino - after some experimenting I was able to get the Atmega328P to wake from its deepest sleep (260 nA - yes 0.260 µA!) within 6 clock cycles (750 ns). I doubt you could achieve that on the Pi, either the low power consumption, or waking up in under a microsecond.
This was fast enough to detect the start bit in serial data at 9600 baud, process the start bit, and then the rest of the incoming byte without losing data.

The errors point is pretty good. Because the pi is doing all the normal linux stuff like writing to storage, it it loses power it could end up breaking the OS where as an arduino should be able to be powered off and on with no issues.

As opposed to the Arduino boards, the Raspberry Pi is a single-board computer with a quad-core CPU, a GPU, on-board RAM, and many peripherals. The main difference between the Pi and the Arduino (or any basic microcontroller) is the operating system. The Pi runs many Linux distributions (Debian being the official one), enabling the user to execute complex computing tasks that would be impossible to run on Arduino without external circuitry. Hence, the Raspberry Pi would be adequate for any software requiring significant CPU/GPU power or memory. Keep in mind that most Arduino's can be interfaced with the same type of peripherals that are found on the Raspberry Pi, although processing power might be lacking. Also, low-level interfacing with analog signals is much more convenient with Arduino, since it has integrated ADCs (analog-to-digital converters).

In "pure hardware" based systems, real time systems, you can always prefer Arduino over Pi with OS. Power consumption, price are other plus points for UNO. Pi is always the better one in complex computing tasks, where its OS simplifies those tasks. But you don't wanna use a "computer" for sensor related projects for sure !


text:
How to power a Seeeduino Stalker v2.3 - water proof with charger instead of solar panel
I am currently coding on a Seeeduino Stalker v2.3 - water proof kit.
http://www.seeedstudio.com/wiki/Seeeduino_Stalker_-_Waterproof_Solar_Kit
It is sold with a solar panel to recharge the battery. Unfortunately, I will not have a lot of light where my sensor will be installed and I would like to power the board with a charger from 110V-220V plug and keep the battery only for potential power shortage.
My questions are:

What is the best option for connection and charger?
I have a previous Arduino Uno charger (9V-1A). Would it work with some linear regulator? What wiring should I use?
Any recommendation for a Li-Ion battery that could I buy and that would last longer than this 3.7 V at 1000mA?

Thank you for your help :)

To be as little invasive as possible, I'd remove just the solar panel and replace it with a power supply with the same typical voltage (5.5V) and at least the same typical power output (0.5W). It should not be too difficult, nor too expensive. Any USB charger that can provide 5V should do. You can just cut the USB connector and attach the wires to the board. Or be more elegant and create an adapter. Either way should work. And the price should be about a couple of bucks.
Yes, I think it would work, although linear regulators 9V -> 5V are really inefficient. See my proposed solution from the previous point.
On ebay there's plenty of options, but they might not fit in the box of the seeduino. You have to compare the dimensions of the battery vs whatever extra space might be available.

You can charge the battery and power the board, via USB. The CN3063 requires between 4.4V to 6V, so not a huge range of options besides a 5v wall-wart
No. 9V would be too high.
How many mains power failures / brownouts do you get, where you live?

About point 2: @Somarinho proposed to use a linear regulator. While that would be highly inefficient, it could work.


text:
Is there a pullup on I2C?
I am using an Arduino Uno R3.
It is not clear on the schematic whether there are pullups on the A4 and A5 I2C pins.
Are there hardwired pullups or do I have to add them myself?

There are very weak internal pullups, but they are not strong enough to be considered compliant with I2C specs. Supply your own external 2.2k-10kohm pullup resistors.

No. There are potential internal pullups, but not AFIK activated.
You can quite safely connect I²C to Raspberry P1 (3.3V).


text:
Communication between two Arduinos using ENC28J60?
How can I connect and send data between two Arduinos using ENC28J60 ethernet adapters on both of them? Is there any guide or example code for me to take a look from or any library I can use to achieve this communication?
I have one Arduino connected to an ultrasound sensor and the other to a relay module so that one Arduino measures the distance between certain objects and send the distance to the other Arduino, which then processes it to check if it is within a certain limit. If not then it turns on the relay. I could have used two ESP32 with one in AP mode but the range is not enough and serial communication is not possible, as the cables are fragile and the distance is too large. Also I couldn't find another way of sending the data.
I'm open to any suggestion, even changing the method of communication. Or using of any other ethernet module.

You can use my EthernetENC library. See the examples of Arduino Ethernet library on how to use Ethernet libraries for Arduino.
EthernetClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. EthernetServer listens on a port. If server is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a EthernetClient object wrapping the socket. Everything you write or print to a EthernetClient is send to that one remote socket.
If the client board creates a EthernetClient and connects it to IP address and port of the EthernetServer on your 'server' board, then you get there a EthernetClient from server.available() and this two EthernetClient objects are connected. What you write/print on one side you read only from the EthernetClient object on the other side.
client socket
   if (client.connect(serverIP, PORT)) {
     client.print("request\n");
     String response = client.readStringUntil('\n');
     Serial.println(response);
     client.stop();
   }

server side
   EthernetClient client = server.available();
   if (client && client.connected()) {
     String request = client.readStringUntil('\n');
     Serial.println(request);
     client.print("response\n");
     client.stop();
   }

You will need a crossover cable.


text:
Serial communication with HC-05 - Arduino UNO
I am new to the site and this is my first question. I'm going to try to describe my issue the best I can.
I got the following code for my project, which consists basically of getting a car to have 2 driving modes, automatic and manual.
As far as I can tell, I got it all working except it's not. I got an HC-05 connected to my L293D motor shield (attached to an Arduino UNO), as well as 2 DC motors, an ultrasonic sensor HC-SR04 and a LED. The circuit part is not the problem, I’ve managed to connect it all and it's working (I tested the obstacle avoiding part by itself, before adding the mode selection code, so I know the motors and sensor do their job). I should also mention that I’m sending the information through the BT from an app I made in App Inventor. The app is working fine, and I do receive the correct data in the Serial Monitor.
What’s puzzling me is, why can’t I get to assign the Serial.read(); value to my response variable (resp)? I’m going to try to explain this a bit further.
In my serial monitor I get the intended chars from the app buttons, however, my “resp” variable doesn’t seem to be getting any value from Serial.read(); for some reason, because when it gets to the switch statement, even though the char is printed on the monitor, the cases don’t start. For instance, and I might be completely off here, once I get ‘1’ on the monitor I should also start getting the distance measurement printed in the monitor and it’s not.
For what I gather, I believe the issue is between the Serial.write() and the Serial.println()/.read();, since the serial.write() seems to be taking priority over all others, since setting these lines as comments don’t affect the writing in the monitor:
if(Serial.available()>0){
//resp = Serial.read();
//Serial.println(resp);

I’m out of ideas, so any help or guidance towards the right direction will be greatly appreciated.
//Incluir librerias para controlar motor shield y sensor ultrasonico.
#include <AFMotor.h>
#include <NewPing.h>
#include <SoftwareSerial.h>

//Definir constantes y variables.
#define TRIG_P A4
#define ECHO_P A5
#define MAX_DIST 300
#define MAX_Vel 200
int led = A0;
int speedSet;
int iteraciones = 5;
float distancia, duracion;
char resp;

//Inicializar objetos del sensor y motores.
NewPing sonar(TRIG_P, ECHO_P, MAX_DIST);
AF_DCMotor motorD(2);
AF_DCMotor motorI(1);
SoftwareSerial BTSerial(A1, A2); // RX | TX

void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  BTSerial.begin(9600);
}

void loop() {

  //Lee información del BT y la escribe en el monitor serial.
  if (BTSerial.available()){
    Serial.write(BTSerial.read());
    Serial.write('\n');
  }

  delay(24); //Tiempo maximo que tarda en recibir una medición.

      /*Calcular la distancia frente al sensor utilizando la duración de la señal,
      la cual mide ida y vuelva por lo cual se divide entre 2
      y se multiplica por la velocidad del sonido (343 m/s).
      */

      duracion = sonar.ping_median(iteraciones);
      distancia = (duracion/2)*0.0343;

  if(Serial.available()>0){
    resp = Serial.read();
    Serial.println(resp);

    switch(resp){

      case '1':

      delay(24); //Tiempo maximo que tarda en recibir una medición.

      /*Calcular la distancia frente al sensor utilizando la duración de la señal,
      la cual mide ida y vuelva por lo cual se divide entre 2
      y se multiplica por la velocidad del sonido (343 m/s).
      */

      duracion = sonar.ping_median(iteraciones);
      distancia = (duracion/2)*0.0343;

      Serial.print("Distancia: ");
      Serial.print(distancia);
      Serial.println(" cm");

      if(distancia!=0 && distancia<=20){
        digitalWrite(led,HIGH);
        ALTO();
        delay(100);
        REVERSA();
        delay(400);
        IZQUIERDA();
        delay(100);
      }else
        digitalWrite(led,LOW);
        ADELANTE();
      break;

      case '2':
      ALTO();

        switch(resp){

          case 'A':
            ADELANTE();
          break;
          case 'R':
            REVERSA();
          break;
          case 'I':
            IZQUIERDA();
          break;
          case 'D':
            DERECHA();
          break;
          case 'O':
            ALTO();
          break;
        }
        break;
       }
    }
 }

  // Inician metodos que definen las acciones del carro.

void ADELANTE(){
   motorD.run(FORWARD);
   motorI.run(FORWARD);
    for (speedSet = 0; speedSet < MAX_Vel; speedSet +=2){
      motorD.setSpeed(speedSet + 20);
      motorI.setSpeed(speedSet - 20);
    }
  }

void REVERSA(){
   motorD.run(BACKWARD);
   motorI.run(BACKWARD);
    for (speedSet = 0; speedSet < MAX_Vel; speedSet +=2){
      motorD.setSpeed(speedSet + 20);
      motorI.setSpeed(speedSet - 20);
    }
  }

void DERECHA() {
   motorD.run(RELEASE);
   motorI.run(FORWARD);
   delay(300);
   motorD.run(FORWARD);
   motorI.run(FORWARD);
  }

void IZQUIERDA() {
   motorD.run(FORWARD);
   motorI.run(RELEASE);
   delay(300);
   motorD.run(FORWARD);
   motorI.run(FORWARD);
  }

void ALTO(){
   motorD.run(RELEASE);
   motorI.run(RELEASE);
  }

Here is an image of what I get on my serial monitor.

UPDATE:
As suggested by @chrisl, I'm now looking at it from a different approach.
I was sending the BT information to the serial monitor, when the idea in the first place is having the car run around without being connected to the PCat all.
So instead of sending the information to serial monitor and trying to take it from there, I simply assigned the value from BTSerial to my variable and it kinda works as intended now.
"Automatic mode" is working, my switch statement recognises the resp value and starts measuring and prints the distance. However, once I push '2', the first command activates and the motors stop but none of the other instructions work. I even changed my second switch statemate to ifs but that didn't help either.
Here's my new Serial output (9600 / Newline / COM5):
1
Distancia: 46.84 cm
Distancia: 154.74 cm
Distancia: 154.33 cm
Distancia: 154.68 cm
Distancia: 154.33 cm
Distancia: 155.70 cm
Distancia: 13.09 cm
Distancia: 12.74 cm
Distancia: 155.16 cm
Distancia: 155.77 cm
Distancia: 155.22 cm
Distancia: 154.81 cm
Distancia: 155.29 cm
Distancia: 155.22 cm
Distancia: 155.22 cm
2
A
R
I
@
D
O
1
Distancia: 155.43 cm
Distancia: 155.50 cm
Distancia: 155.57 cm
Distancia: 155.50 cm
Distancia: 155.09 cm
Distancia: 155.50 cm
Distancia: 155.09 cm
Distancia: 156.32 cm
Distancia: 155.57 cm
Distancia: 155.16 cm
Distancia: 155.09 cm
Distancia: 155.09 cm
Distancia: 155.50 cm
2

And my updated code:
//Incluir librerias para controlar motor shield y sensor ultrasonico.
#include <AFMotor.h>
#include <NewPing.h>
#include <SoftwareSerial.h>

//Definir constantes y variables.
#define TRIG_P A4
#define ECHO_P A5
#define MAX_DIST 300
#define MAX_Vel 200
int led = A0;
int speedSet;
int iteraciones = 5;
float distancia, duracion;
char resp;

//Inicializar objetos del sensor y motores.
NewPing sonar(TRIG_P, ECHO_P, MAX_DIST);
AF_DCMotor motorD(2);
AF_DCMotor motorI(1);
SoftwareSerial BTSerial(A1, A2); // RX | TX

void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  BTSerial.begin(9600);
}

void loop() {

  //Lee información del BT y la escribe en el monitor serial.
  if (BTSerial.available()){
    resp = BTSerial.read();
    Serial.println(resp);
  }

//  if(Serial.available()>0){
//    resp = Serial.read();
//    Serial.println(resp);

    switch(resp){

      case '1':

      delay(24); //Tiempo maximo que tarda en recibir una medición.

      /*Calcular la distancia frente al sensor utilizando la duración de la señal,
      la cual mide ida y vuelva por lo cual se divide entre 2
      y se multiplica por la velocidad del sonido (343 m/s).
      */

      duracion = sonar.ping_median(iteraciones);
      distancia = (duracion/2)*0.0343;

      Serial.print("Distancia: ");
      Serial.print(distancia);
      Serial.println(" cm");

      if(distancia!=0 && distancia<=20){
        digitalWrite(led,HIGH);
        ALTO();
        delay(100);
        REVERSA();
        delay(400);
        IZQUIERDA();
        delay(100);
      }else
        digitalWrite(led,LOW);
        ADELANTE();
      break;

      case '2':
      ALTO();

       if(resp == 'A'){
         ADELANTE();
       } else if (resp == 'R'){
         REVERSA();
       } else if (resp == 'I'){
         IZQUIERDA();
       } else if (resp == 'D'){
         DERECHA();
       } else if (resp == 'O'){
         ALTO();
       }
      break;
       }
    }
// }

  // Inician metodos que definen las acciones del carro.

void ADELANTE(){
   motorD.run(FORWARD);
   motorI.run(FORWARD);
    for (speedSet = 0; speedSet < MAX_Vel; speedSet +=2){
      motorD.setSpeed(speedSet + 20);
      motorI.setSpeed(speedSet - 20);
    }
  }

void REVERSA(){
   motorD.run(BACKWARD);
   motorI.run(BACKWARD);
    for (speedSet = 0; speedSet < MAX_Vel; speedSet +=2){
      motorD.setSpeed(speedSet + 20);
      motorI.setSpeed(speedSet - 20);
    }
  }

void DERECHA() {
   motorD.run(RELEASE);
   motorI.run(FORWARD);
   delay(300);
   motorD.run(FORWARD);
   motorI.run(FORWARD);
  }

void IZQUIERDA() {
   motorD.run(FORWARD);
   motorI.run(RELEASE);
   delay(300);
   motorD.run(FORWARD);
   motorI.run(FORWARD);
  }

void ALTO(){
   motorD.run(RELEASE);
   motorI.run(RELEASE);
  }

I guess the main problem is, that you write your commands from the bluetooth app, but the HC-05 module is connected to BTSerial. Here you are reading from it and forwarding the data to Serial (serial monitor on your PC):
if (BTSerial.available()){
    Serial.write(BTSerial.read());
    Serial.write('\n');
}

You are not doing anything else with the bluetooth serial data, so you cannot change the resp variable over bluetooth. Instead you are doing this with Serial (not BTSerial). But as long, as you don't type the commands into the serial monitor, that code will never run. Thus the distance code will never be executed.
If you want to control the program from the bluetoooth app, you need to actually work with the data from the right serial interface.

Btw: Your serial monitor is configured for a newline as line ending character. Your Serial code does not discard these, so you might get undesired behavior there, when resp becomes \n.

About your new problem: This problem actually existed also with the old code, but you couldn't see it, because the you were reading from the wrong serial interface. Try to read this (compressed) snipped of your (old) code:
switch(resp){
   case '1':
       ...
       break;
   case '2':
       switch(resp){
           case 'A':
               ...

With the first switch statement you are checking the value of resp. If it is '2', you will enter the second case. In there you are again checking the value of resp for the values 'A', ... . But when you already know, that resp is equal to '2', how can it ever be equal to 'A' or one of the other subcommands, since you don't change resp in between. Thus the code inside the second switch statement is unreachable.
What to do now? I guess you want the first switch statement to handle the modes and the second one to handle the move commands, while in second mode. For that you need to restructure your code, in the best case to an FSM (Finite State Machine). I already once wrote a good descriptions of how an FSM works in my answer to this question.
Introduce a state variable, which gets used in the first switch statement, and a command variable, that gets used in the second one. I would suggest a structure like this:
enum State {AUTOMATIC_MODE, MANUAL_MODE};

State state = AUTOMATIC_MODE;
char command = 0;

void loop(){
    if(BTSerial.available()){
        resp = BTSerial.read();
        Serial.println(resp);
        switch(resp){
            case '1':
                state = AUTOMATIC_MODE;
                break;
            case '2':
                state = MANUAL_MODE;
                break;
            case 'A':
            case 'R':
            case 'I':
            case 'D':
            case 'O':
                command = resp;
                break;
        }
    }

    switch(state){
        case AUTOMATIC_MODE:
            ...
            break;
        case MANUAL_MODE:
            switch(command){
                case 'A':
                    ...
            }
            break;
    }
}

Here the serial input will be put into the state or command variable, depending, on what exactly was send. The part with the main code comes after that. Depending on the state, the corresponding code is executed. When in manual mode, the code will look at the command variable to check, which function to execute.

I see, perhaps I got it all wrong then, because the intention is to have the car run around without being connected to the pc, and therefore not conected to the serial monitor in the first place. So, should I simply asign the recieved information to my resp variable without writing it to the serial monitor at all?

With Serial (UART) writing and reading is  independent. You can see the bluetooth data on the serial monitor, if you write it to Serial, but that doesn't mean, that you can read it back from there. You can only read from Serial, what is actively send by the serial monitor. You read the important command data from BTSerial, so you should use that data for assigning to resp. You can still additionally send the data to the serial monitor for debugging purpose.

@GenaroBasoria I added a part to my answer about the problem with the manual mode


text:
Arduino Uno Serial.write() how many bits are actually transmitted at once by UART and effect of baudrate on other interrupts
With Arduino Uno Rev3, I am trying to maintain a delicate timing while handling data transmission. I want to send 6 bytes at a time, which takes around ~44 us when I time Serial.write(). The time it takes from Arduino Serial to computer is irrelevant in my case. I only mind the run time of the function.
My idea is sending not all 6 bytes but a few at a time, so that the total sending time overhead would be distributed between time-sensitive tasks. Note that I will never be exceeding the buffer size, so the Serial.write() will never wait for actually transmission to be completed.
const uint8_t MSG_LEN = 6;
uint8_t snd_buffer[MSG_LEN];
uint32_t us_now = 0L;
uint8_t snd_byte_cnt = MSG_LEN;
uint8_t dummy_var = 0;

void setup() {
  Serial.begin(115200);
  delay(1000);
}

void loop() {
  us_now = micros();

  operation_dummy();

  com_dummy();

  //the aim is to use no delay functions
}

void com_dummy(){ //ex communication
  if (snd_byte_cnt < MSG_LEN){ //bytes need to be sent
    Serial.write(snd_buffer[snd_byte_cnt]); //send the target byte
    snd_byte_cnt++; //move to the next byte ind
  } //else nothing to be sent
}

void operation_dummy() { //ex operation
  dummy_var++; //do something (time sensitive in reality)
  if (snd_byte_cnt == MSG_LEN){ //if no data pending to be sent
    * (uint32_t *) &snd_buffer[1] = us_now; //modify buffer between 1st and 5th bytes (both inclusive)
    snd_buffer[MSG_LEN - 1] = dummy_var;
    snd_byte_cnt = 0; //trigger start sending
  } //else wait for next cycle to send
}

My question is, how many bytes should be used with Serial.write() at a time?
I've heard the Serial library processes 16 bits (2 bytes) at a time. What happens if I try to send a single byte? Does it wait a certain time for the second byte and if doesn't arrive then it pushes a single byte? (Edit: this turned out to be a misunderstanding and only the FIFO pointer is 16 bits, not the data to be sent. * Source: https://forum.arduino.cc/t/serial-write-time/233360/23 )*
Would never calling a sleep function and using micros() OR the baudrate affect my time keeping? I think micros() and actually transmission uses interrupts. So different baudrates may delay micros() calls differently since both need to disable interrupts.

Which Arduino board are you using?

the UART transmits one bit at a time ... that's how serial communication works ... the title of your post does not match the rest of the post

Pure USART would send 10bit per byte (8N1) at desired baudrate, however whenever you use USB-To-Serial or CDC (on boards with native USB), it'll be completely dependent on USB

Since you did not say what Arduino you use, at what baudrate, and at what rate you send the 6 bytes, we can only answer generally. Please [edit] your question to add that information. Please add also a reference to the claim of processing two bytes - it is nonsense.

Why did you tag "softwareserial", do you use it?

thanks for the feedback. I've edited the question accordingly.

The Arduino Serial writes one byte at a time. There is a method for
writing a buffer of arbitrary length, but all this method does is
repeatedly call write(uint8_t) for each byte within the
buffer:
size_t Print::write(const uint8_t *buffer, size_t size)
{
  size_t n = 0;
  while (size--) {
    if (write(*buffer++)) n++;
    else break;
  }
  return n;
}

Notice that there is no waiting between the bytes.
If you do not fill the transmit buffer, this should be very fast: all
write(uint8_t) does is push the byte into a ring buffer. Unless your
timings are at the microseconds level, you can just send the six bytes
at once.

I've heard the Serial library processes 16bits (2bytes) at a time?

Very dubious. Do you have a reference for this statement?

Edit: If you are struggling with microsecond-range timings, you
could send the bytes by directly writing to the UART data register,
instead of relying on the Arduino core library to do so. In order to do
this, you would:

Disable the "USART, Data Register Empty" interrupt, which is the
interrupt used by the Arduino core for sending the bytes to the port.

Before sending a byte, test the "USART, Data Register Empty" flag in
order to know whether the UART is ready to accept a byte for sending.

Write the byte you want to send directly into the UART data register,
thus completely bypassing the TX buffer used by the Arduino core.

By bypassing the ring buffer and associated interrupt, you should be
able to win a few microseconds this way.
Here is a version of your example code using this approach:
const uint8_t MSG_LEN = 6;
uint8_t snd_buffer[MSG_LEN];
uint32_t us_now = 0L;
uint8_t snd_byte_cnt = MSG_LEN;
uint8_t dummy_var = 0;

void setup() {
  Serial.begin(115200);
  UCSR0B &= ~_BV(UDRIE0); //disable "USART, Data Register Empty" interrupt
  delay(1000);
}

void loop() {
  us_now = micros();

  operation_dummy();

  com_dummy();

  //the aim is to use no delay functions
}

void com_dummy(){ //ex communication
  if (snd_byte_cnt < MSG_LEN && bit_is_set(UCSR0A, UDRE0)){ //bytes need to be sent and can be sent
    UDR0 = snd_buffer[snd_byte_cnt]; //send the target byte
    snd_byte_cnt++; //move to the next byte ind
  } //else nothing to be sent
}

void operation_dummy() { //ex operation
  dummy_var++; //do something (time sensitive in reality)
  if (snd_byte_cnt == MSG_LEN){ //if no data pending to be sent
    * (uint32_t *) &snd_buffer[1] = us_now; //modify buffer between 1st and 5th bytes (both inclusive)
    snd_buffer[MSG_LEN - 1] = dummy_var;
    snd_byte_cnt = 0; //trigger start sending
  } //else wait for next cycle to send
}

Except for the UNO-R4.  It blocks for the entire length of the serial transmission.

@Delta_G: Wow! That seems silly. Do you have an idea why they would do that?

Maybe it's just a basic implementation without optimizations.

@EdgarBonet, I'm not sure why they did it this way.  I see they were trying to use the FSP UART implementation and I think they just got confused at how to do it.  I've got a PR in to fix it but it has been ignored for a long time.  https://github.com/arduino/ArduinoCore-renesas/pull/304

@Delta_G I wondered why is your code so misaligned at some points in diffs and there is mixture of tabs and spaces... Super anoying as there is always someone with different tabstop :D

Because I don't have the right formatting set up in vs code and couldn't find a style guide or a consistent form to follow.

I lean heavily on autoformat but if I used it then it would make changes in existing lines and mess up the PR.  I'm new to the game there so I didn't know how to handle it.  Maybe someone could format it before it gets merged.

@Delta_G you can set it up by "Insert spaces" in settings. PR will be merged as is, there is nobody who fix that for you.

You are right about 16 bits, apparently I misunderstood this post: https://forum.arduino.cc/t/serial-write-time/233360/23

Ok, I will just leave the serial line as blocking then since I can't get vsc to get the formatting right.  I didn't realize that was more important.  I will just keep the non-blocking version for myself I guess.

I've edited the question to make it clearer.

what a neat hack with bypassing the buffer! thanks.

I want to send 6 bytes at a time, which takes around ~44 us when I time Serial.write().

You are timing the time it takes for Serial.write to put bytes into an internal buffer (which holds 64 bytes), not the time taken to transmit them. You haven't said what baud rate you are using, but I doubt you are transmitting at 1363652 bits per second.
6 bytes in 44 µs is one byte in 7.3333 µs.
Each byte consists of 10 bits (start bit, 8 data bits, stop bit)
Therefore you are talking about 0.7333 µs per bit.
1/7.333e-6 = 1363652 bits per second.

A quick test shows that it does indeed take 48 µs (on my Uno and my IDE) to put 6 bytes into the serial buffer.
Changing the write to write only one byte improves the time taken from 48 µs to 12 µs so that is less time fiddling with copying data into that buffer.
The actual transmission is done by the hardware, and it fires an interrupt when each byte has been sent, and commences sending the next byte. During the sending of the byte your code is free to continue doing its stuff.
There would be some overhead (I'm not sure the exact amount) for each byte to be pulled from the buffer and sent to the hardware.

I've heard the Serial library processes 16 bits (2 bytes) at a time.

That's nonsense. It would help if you specified what Arduino you have, however.

What happens if I try to send a single byte?

A single byte will get put into the buffer, which will take slightly less time, as I explained above.
If timing is very critical I would be tempted to suggest turning interrupts off, but of course then you can't transmit any bytes at all.
This sounds a lot like an XY problem to me. You are getting bogged down on how long it takes to transmit one byte, but haven't explained:

What Arduino you have
What baud rate you are using
What your code is
What is this highly timing-critical thing you are trying to achieve.

As for your question title:

how many bits are actually transmitted at once by UART

One bit would be transmitted "at once" - that's how serial communications work.

Would never calling a sleep function and using micros() OR the baudrate affect my time keeping?

A sleep function? What is the purpose of that here?
Unless you disable interrupts, or take other steps (like cancelling Timer 0) then micros will work as it basically returns the contents of the hardware timer (0) plus an overflow count. It would also be reasonably fast. Running the timer itself will cause the occasional interrupt (about every millisecond).
A different baudrate wouldn't affect timing much, except that the interrupts which occur when the sending buffer empties would happen more or less often.

I think micros() and actually transmission uses interrupts. So different baudrates may delay micros() call differently since both needs to disable interrupts?

micros() doesn't use interrupts directly (except as noted below), however the accumulation of timer overflows is done in an interrupt. Note that micros() briefly turns off interrupts in order to obtain the overflow count without it changing during the few clock cycles that it makes a copy of it.
See hardware/arduino/avr/cores/arduino/wiring.c for the actual code in micros() and millis().
Note that because of the way Timer 0 is configured, micros() has a resolution of 4µs. In other words, you won't be able to tell the difference between a 2µs and 3µs interval.
In response to a comment, I'll just clarify that turning off interrupts just defers the processing of that interrupt until such time as they are turned on again.

Thanks! I have an Uno (in the title) rev3. My baudrate is 115200 to ensure all OS compatibility.
About my concern of 16 bits being sent, you are right, I confused that Serial FIFO pointer being 16bits as mentioned here https://forum.arduino.cc/t/serial-write-time/233360/23.
Finally, this is exactly what I wanted to know. I wanted to minimize the time it takes to write to Serial buffer so that I can "thread" without any operation taking more than ~50us. The communication is already very light and not frequent that I can assume Serial write will never block due to being filled fully.

I've edited the question to make my point better.

Regarding the Uno part, I glanced at the tags, where people usually put which Arduino they have. I added the Uno tag for you.

I've responded to your edited points.

I mentioned Running the timer itself will cause the occasional interrupt. I didn't say, or intend to imply, that turning off interrupts would drop an interrupt service, clearly it doesn't. However while interrupts are turned off they will not be serviced. For more information see my page about interrupts.

Also: https://arduino.stackexchange.com/questions/30968/how-do-interrupts-work-on-the-arduino-uno-and-similar-boards/30969#30969

I've added another sentence to cover that. Thanks for the suggestion. :)


text:
How to clear output buffer of Arduino Uno?
I have coded arduino for DHT11 which used to print humidity in first and temperature in second line. But some times when I open SerialPort I get absurd data.

Possible duplicate of https://stackoverflow.com/questions/10105666/clearing-the-terminal-screen

I am sending this data from arduino to pi serially and from pi to cloud. So some times I used to receive humidity as 6767.0 on the cloud. I am printing on console just for showing an example.

You can't.
The data you are seeing has already been sent by the previous execution of the sketch before the main MCU was reset. That data resides in a small buffer within the USB interface chip (or even within the USB CDC/ACM / USB UART driver itself, depending on your OS) to which you have no access.
You just have to ignore that data. The simplest way is to put a marker at the start of your program to indicate that whatever is receiving the data should start its receiving from this point on. Something like:
Serial.println();
Serial.println("START");

You could disable reset, by adding a capacitor between GND and RESET. Though this make uploading new code less convenient.

@Gerben It also means that you can start reading partway through a line of digits giving you similar garbage at the start of your reception. Doesn't really cure the problem. Better is to use a proper protocol rather than plain ASCII text.

Good point. Didn't think of that.

I am sending this data from arduino to pi serially and from pi to cloud. So some times I used to receive humidity as 6767.0 on cloud. I am printing on console just for showing an example. So is there no way to clean output buffer of arduino when ever it starts.?

I've circumvented this issue by sending a byte to the Arduino whenever I'm ready to receive data using this quick-and-dirty method:
if(Serial.available() > 0) {  // At least one byte is available
  Serial.println(millis());
  Serial.read();  // Read the (one) character to empty the buffer
}


text:
LED and Switch Compolation Error Arduino 101
I'm getting an error on line 9 for some reason, (digitalWrite(Sender, HIGH);), and I just cant figure out why. My goal is to have two sets of flashing patterns, one for each switch state. I don't know how important this is but I'm using an Arduino 101. This is also my first day programming so the answer could be staring me right in the nose, (in fact, I would prefer that haha). Thank you for your time!
// Starting this by declairing intigers
int Sender = 2; // Switch Out on pin two
int LedG = 10; // LED Green out on pin ten
int LedR = 11; // LED Red out on pin eleven
int Reader = 12;  // Switch Input on pin twelve
//configuring I/O
pinMode(Sender = OUTPUT); // Setting pin two to output
pinMode(Reader = INPUT); // Making pin 12 set to read switch data
digitalWrite(Sender, HIGH); //Making pin two hot
//main loop
void loop() {
  if (digitalRead (Reader) == HIGH) { // if Switch input is reading on than do pattern A
    digitalWrite(LedG, HIGH); //turning on green led
    delay(50); //delay next instruction
    digitalWrite(LedG, LOW); //turn green led off
    digitalWrite(LedR, HIGH); //turn red led on
    delay(50); //delay next instruction
    digitalWrite(LedR, LOW); //turn red led off
  }
  else { //if switch input is readion off than play pattern b
    digitalWrite(LedR, HIGH); //turn red led on
    delay(1000); //delay next instruction
    digitalWrite(LedR, LOW); //turn red led off
    digitalWrite(LedG, HIGH); //turning on green led
    delay(1000); //delay next instruction
    digitalWrite(LedG, LOW); //turn green led off
  }
}

I notice that your pinMode function calls are not quite correct:
pinMode(Sender = OUTPUT); // Setting pin two to output
pinMode(Reader = INPUT); // Making pin 12 set to read switch data

Should be:
pinMode(Sender, OUTPUT); // Setting pin two to output
pinMode(Reader, INPUT); // Making pin 12 set to read switch data

Refer to https://www.arduino.cc/en/Reference/PinMode for more information.
And the whole section where you configure your I/O should be wrapped inside the setup() function.
//configuring I/O
void setup()
{
    pinMode(Sender, OUTPUT); // Setting pin two to output
    pinMode(Reader, INPUT); // Making pin 12 set to read switch data
    digitalWrite(Sender, HIGH); //Making pin two hot
}

Incidentally, my if statement doesn't seem to be functioning correctly.  Is (if (digitalRead (Reader) == HIGH)) the correct way to check if an input is true?

Never mind, sorry.


text:
Physical safety: Prevent linear actuator from crushing my fingers
Our project consists of an old wooden barrel, whose top lid is opened/closed with a simple linear actuator. I am a bit afraid that it might crush somebody's fingers while closing.
How could I detect trapped objects effectively?
Elevators often have light barriers, but the problem here is that the opening has a 360° border.
Force sensitive resistors seem to be an option too. However, since the border is a circle, I guess applying them would not work too well (folding issues) and look bad on a vintage barrel.
I'm very sorry if I maybe created a duplicate here and I would like to encourage me to provide links to similar questions. I simply couldn't come up with useful search words for my problem.

Surely detecting objects that might become trapped would be a better idea?

Preventing would be the best option, but detecting it while it is happening is good enough too. E.g. force sensors cannot foresee it, but they enable us to stop and go backwards before things are getting crushed.

Some work was done, IIRC, with leaky fibre optics on the top of electric car windows. Pressure makes the light leak out and the window stops moving.

I think the saw emergency brake works with conductivity. It goes in the same direction as force sensitive resistor strips

sounds like a good use case for those new cheap microwave radar motion sensors, partially shielded to cover just opening.

The easiest way to prevent things becoming trapped is to take reasonable steps to prevent things getting near the "danger zone", so a barrier 2 metres around the barrel would be a good start.  Probably it would be an impractical idea, but...
A physical barrier of some sort would be the best idea, because that is less likely to suffer a failure than an electronic system (well assuming it has been designed right).  If you are using an electronic system then it needs to "fail-safe", when it suffers a failure it must adopt its safe state (barrel open).
You could surround the lid with IR lights and receivers in the lip.  They would need to be spaced at a distance where an arm/finger couldn't get between the lid and lip without breaking a beam.  This solution would only work over the last few inches, because of the angle of the beams.  If all receivers had a signal the it would be safe to close.  The problem is the receivers would need to be close together to prevent transgression.
Monitoring the current drawn by the actuator and the position of the actuator might be another.  I am assuming that there is an increase in current draw when the lid actually closes, and a similar increase in draw when something is trapped.  If the lid isn't fully closed when the current increases then something is trapped.
The final way I can think of is probably the most effective.  As the barrel closes don't close it the last few inches, allow it to 'fall' as the actuator descends.  This means if there is an object in there the actuator isn't pulling the lid down and the object will hold the lid against gravity.  This would be done by having a channel in the mounting block for the actuator 'pin'/ connection point to slide up and down.

OK Its not an electrical solution.

I really like the last idea. I have to check what type of actuator I have, because I was under the impression that it holds the position when unpowered which would make "sliding down" impossible.

I don't think I phrased that very well.  When the actuator first pull the lid it will be at the bottom of the 'channel'.  Once gravity takes over the lid will 'jerk' downwards as the channel moves and the actuator pin slides to the top of the channel (you might want to damp that with a spring to make it look slicker).  Then the actuator's downward movement will slow the effect of gravity and it will effectively be controlling the fall.  If you stick you arm in the lid will stop on your arm, and your arm will prevent gravity closing the lid.  [Continued....]

The actuator's pull will now move the pin down the channel until it reaches the end of its normal movement effectively doing nothing.  The channel height needs to be at least the same size as the largest object that a person is going to stick in the way.    Obviously you can't cater for every object and if someone sticks their head in, well a little chlorine in the gene pool every now and then is a good idea. :)

Thinking about it, if little Joey does stick his head in your barrel you might want to have a cut off if the actuator starts drawing to much current as well as a backup.  I suspect the change in current draw will not be enough to prevent saw fingers, but it will just give him a sore head to remind him not to be so stupid in future.

Hmm did I understand the channel concept correctly: It is about the bottom mounting of the actuator (bottom of the barrel) to have vertical leeway, so that if something blocks the lid, the actuator would pull it's lower end up instead of the lid down?

That wasn't what I meant, but I think your idea is a much better idea.  It hides the ugliness much better.

Ah now that I think about it, that would actually enable me to watch for the lower end of the actuator raising, e.g. with a physical switch or a plug which the actuator would tear off! And I could implement it inside the barrel, well hidden!


text:
Setup arduino uno with ESP8266 ESP-1
Iam trying to set up the arduino uno with the wifi module ESP8266. I use this schematic setup:

I have followed this tutorial: Tutorial ESP8266
Thereby I removed the Mega328P Chip like it says above, I can communicate trough my terminal in the arduino IDE with the ESP-module but when I want to upload an simple test file like this:
#include <SoftwareSerial.h>

SoftwareSerial ESP8266(0, 1); // RX = 8 en TX = 9

boolean FAIL_8266 = false;

void setup() {
  // put your setup code here, to run once:
   do {
    ESP8266.begin(115200); // start communicatie met esp8266

    //Wait Serial Monitor to start
    while (!Serial);

    ESP8266.print("AT\r\n");

    delay(500);

    if (ESP8266.find("OK")){
        ESP8266.print("ready");
    }

   } while (FAIL_8266);
}

void loop() {
  // put your main code here, to run repeatedly:

}

Than it keeps throwing me this error: avrdude: stk500_getsync() attempt x of x: not in sync: resp=0x20 is it because I removed the Mega328P Chip?
Thereby I've tried the test code from the tutorial here is an link to the code: LINK.
There it keeps saying that Serial2 was not declared in scope
I'll hope someone can help me out on this one and run an simple test script to communicate with the ESP8266 WIFI Module

Why are you trying to upload code to a board without a chip? And where did that tutorial say to use software serial on hardware serial pins? It doesn't seem like you followed that tutorial at all.

No I plugged it at digital pin 8 and 9 instead of rx and tx. And is it not nessecary to remove the chip?

You can't upload a program to a chip, if it's not there.

@gre_gor - He doesn't want to upload a program into ATmega328 but is trying to upload the program into ESP8266 using the Arduino's onboard USB --> RS232 IC. In that case ATmega328 has to be either removed or held under reset and the connection between Arduino board and ESP8266 must be TX to TX and RX to RX. Se my detailed explanation here.

You must have your microcontroller in place if you are uploading code to it.
You can talk to ESP8266 via serial monitor because you are connected directly to the pins of your USB-UART bridge.
Place your uC back, change this line of code:
SoftwareSerial ESP8266(0, 1);
to this one:
SoftwareSerial ESP8266(8, 9);
and change your wires accordingly(what was on pin 0, now connect to pin 8, pin 1 to pin 9).
Now your Atmega can talk to ESP8266 after you upload the code.
btw. "Serial2" is Serial port for more advance Arduino boards, it won't work on Atmega328 based board.

I did put the chip back and switched the 0,1 pins to 8 and 9 but when I run the code it doesn't print ready..

@Beginnerprogrammer you are printing ready back to the ESP8266 not to the PC.

No, ATmega328 has to be either removed or held under reset and TX to TX&RX to RX is OK. See my comment under the question.

The first, most obvious issue (besides needing the MCU on the Arduino board!) is that you need to cross-connect the RX and TX lines between the two boards. You have both RXes connected together, and both TXes connected together. The ESP's RX has to listen to the Arduino's TX, and vice-versa.
An easy way to remember which ESP pins are RX and TX is that the pin nearest the free ends of the antenna is the RX pin; the TX pin is diagonally opposite it.
A second, potential problem, is that the ESP board may draw more power than the Arduino's 3.3v regulator can provide. If it is making brief and not too frequent transmissions, you may get away with it, but the ESP can easily out-draw the regulator and it's 3.3v supply will sag.

That is not the case, TX to TX&RX to RX in this case is OK. See my comment under the question.


text:
Make RFID Tag as a variable
I want to make RFID Tag as a variable, and push it to the web server. But I struggle to do the Serial.read function.
Any solutions?
Here is my code

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

/* wiring the MFRC522 to ESP8266 (ESP-12)
SDA(SS) - D4 (GPIO2)
SCK - D5 (GPIO14) (hw spi)
MOSI - D7 (GPIO13) (hw spi)
MISO - D6 (GPIO12) (hw spi)
IRQ -
GND - G
RST - D3 (GPIO0) (FLASH)
3.3V - 3V
*/

#define RST_PIN D3 // RST-PIN für RC522 - RFID - SPI - Modul GPIO5
#define SS_PIN D4 // SDA-PIN für RC522 - RFID - SPI - Modul GPIO4

const char *ssid = "Keluarga"; // change according to your Network -
cannot be longer than 32 characters!
const char *pass = "batikpekalongan11"; // change according to your
Network

String a;

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
WiFiServer server(80);

void setup() {
Serial.begin(115200); // Initialize serial communications
delay(10);
Serial.print(F("Booting...."));

SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522

WiFi.begin(ssid, pass);

int retries = 0;
while ((WiFi.status() != WL_CONNECTED) && (retries < 10)) {
retries++;
delay(500);
Serial.print(".");
 }
if (WiFi.status() == WL_CONNECTED) {
Serial.println(F("WiFi connected"));
}

Serial.println(F("Ready!"));
Serial.println(F("Scan for Card and print UID:"));
Serial.print("IP address: ");
Serial.println(WiFi.localIP());

// Start the server
server.begin();
Serial.println("Server started");
  }

void loop() {
 // Check if a client has connected
 WiFiClient client = server.available();
 if (!client) {
 return;
 }

 // Look for new cards
   if ( ! mfrc522.PICC_IsNewCardPresent()) {
delay(50);
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
delay(50);
return;
}
// Show some details of the PICC (that is: the tag/card)
  Serial.print(F("Card UID:"));
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  a = Serial.readString();
  Serial.println("kakak");
  Serial.println(a);

// Wait until the client sends some data
Serial.println("new client");
 while(!client.available()){
 delay(1);
 }

// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();

// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); //  do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");

client.print("Card UID:");
client.print(a);
client.println("</html>");
//delay(1);
//Serial.println("Client disonnected");
//Serial.println("");
}

I've add my code to the the questions. Thank you~

What you already have on the Serial.read ? I cannot see a line. And what you try to read?

What makes you think Serial.read() has anything at all to do with the card data?

I'm sorry if my code didn't look so good. I'm still a beginner in this. I'm trying to read the RFID tag. I thought with Serial.read(), I could read the serial data on serial monitor, from the tagged RFID Card and transform it into a variable. My purpose is to send the RFID tag data to the web server. ~Thankyou (sorry for my bad english)

Reading from the serial port does not read back what you wrote to it. It looks like the data you want is in mfrc522.uid.uidByte, so try to get that into a. You'll need to format it - you might find clues in your dump_byte_array function.