text:
Read Internal Registers of RS485
I am trying to interface sele EM2M, I am using Arduino Mega with RS 485 module. I want to read the internal registers I am using ModbusMaster library. The data which I want to receive is in the internal registers but I am not getting how can I read Internal registers. When I use other software to read data I am getting the out
I also wanted to know the difference between Internal Registers and Holding Registers
Another questions how are the frames formed for communication in rs485 from the above image I can understand 01 04 but from where do they get 00 1A please explain the same.

I can't open the datasheet.

Ahh I am also having problems with the same sorry I will ask the manufacturer and then upload the datasheet

@Juraj now you can download the datasheet

it is an image, but looking at it I didn't see "internal registers"

https://gofile.io/d/qeQd1B link for datasheet I have added the same on selec EM2M
Yes internal registers are not present I forgot where I saw internal register but I guess internal and Input registers are one and the same

maybe read about Modbus on Wikipedia

@Juraj thank you for the time the issue is been resolved

The issue is been resolved.
I was reading the holding registers and also I tried to read the Input registers but I didn't received any output it was because the register address entered by me was wrong when I referred to a Simply Modbus Master software from where I was able to receive the data when I send a command, from the same software I came to know about the frame structure and how they were formed. So when I tried to enter those register address they were working fine.
Thank you everyone for your help

The RS485 has no internal registers, all of that is in your target unit. Hopefully the instructions for that will tell you how to do it.  Start by getting simple communications working then slowly progress from there.


text:
Serial Interrupt
I want to create a simple program, that responds to me sending a character over the Arduino IDE console. I am using an arduino UNO. Here is my program:
volatile bool MeasReceived=false;

ISR(PCINT2_vect){
  PCICR = 0b00000000;    // turn off port d
  MeasReceived=true;
}

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

  Serial.print("Hello PC");
  delay(1000);
  cli();
  PCICR |= 0b00000100;    // turn on port d
  PCMSK2 |= 0b0000001;    // turn on pins PD0 , PCINT16
  sei();

}

void loop() {

  if(MeasReceived==true){
    MeasReceived=false;
    inByte = Serial.read();

    if(inByte=='A'){   //A: PC requests measurement data from Arduino
       Serial.print('B');
    }
    else{
      Serial.print(inByte);
    }
  }
  PCICR = 0b00000001; // re-enable port d
}

What I do is that I set the RX pin as a pin change interrupt. After that, I send a character through the console, for example 'A'. The ISR kicks in, firstly disabling the interrupt, and after that, the flag is set true. That way, I enter the part of the code where I do the Serial.read() command, to find what character was sent to me via the console.
The problem is that, no matter the character I send, the result is always 255. That means that the value of inByte, after the Serial.read() is always 255. What goes wrong?
EDIT: Original question answered by me below. However, one interesting thing occured in the new code posted below. If I put the Arduino to sleep (powerDown Mode), and try to wake it up with the serial interrupt, if I send only one character, then the arduino does wake up, but does not enter the ISR! If I send two characters, then the ISR is accessed and the flags set, with the program working fine. Here is the code, to reproduce the issue:
volatile bool MeasReceived=false;
uint8_t inByte;

ISR(PCINT2_vect){
  PCMSK2 = 0b00000000;    // turn off port d
  MeasReceived=true;
}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);

  Serial.begin(9600);
  Serial.flush();
  Serial.print("Hello PC");
  delay(1000);

  cli();
  PCICR = 0b00000100;    // turn on port d
  PCMSK2 = 0b00000001;    // turn on pins PD0 , PCINT16
  sei();
}

void loop() {

  if(MeasReceived==true){
    MeasReceived=false;
    delay(2000);
    inByte = Serial.read();

    if(inByte=='A'){   //A: PC requests measurement data from Arduino
       Serial.print('B');
    }
    else{
      Serial.print(inByte);
    }
    PCMSK2 = 0b00000001;

  }

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);    //Set power down mode
  sleep_bod_disable();  //disable brown-out detection
  digitalWrite(LED_BUILTIN, LOW);
  sleep_enable();
  sleep_cpu();
  sleep_disable();
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  //int i=Serial.available();
  //Serial.print(i);
  delay(1000);

}

So, by sending one character, the Arduino wakes up, the LED shines, and after the two seconds, Arduino goes back to sleep, never entering the ISR and as a result not setting the flag. Furthermore, having sent one character, if I uncomment the Serial.available() printing, it prints "0"!
If I send two characters, the Arduino wakes up, and the program works fine.

have you seen this? ... https://www.arduino.cc/reference/en/language/functions/communication/serial/serialevent/

and this .. https://stackoverflow.com/questions/53104440/how-to-implement-interrupt-for-serial-usart-communication-for-atmega328p-arduino

Why do you want to use the pin change interrupt here? I don't see  why this should be done, since the Serial (UART) interface has its own interrupts.

@chrisl I need the best possible power saving, which is given by PWR_DWN mode. In order to wake up from that mode, I need to use pin change interrupt to my UART RX.

Your diagnostic about the interrupt handled too fast is correct. When a
byte arrives at the serial port, the start bit will trigger the
interrupt, but the byte is only available for reading once the UART
receives the stop bit, which is about one millisecond later.

to disable/re-enable the pin-change interrupt, the right way seems to
be to use the PCMSK register and not the PCICR.

The canonical procedure for enabling any edge-triggered interrupt is
to first clear the interrupt flag, then set the interrupt enable bit.
Note that the interrupt flag is cleared by writing a logic one to it.
For the PCINT2 interrupt that would be:
PCIFR =  _BV(PCIF2);  // clear interrupt flag
PCICR |= _BV(PCIE2);  // enable interrupt

This being said, there is no point in using a pin change interrupt in
the first place. You can instead use the canonical idiom
if (Serial.available() > 0) {
    char inByte = Serial.read();
    // ...
}

If you plan to sleep, you will likely want to do it with the serial port
enabled, in order for it not to miss the start bit. This means you will
use the IDLE sleep mode. Then, when the serial port receives a full
byte, it will wake up the CPU with its own interrupt, so you do not have
to take care of this yourself.

Edit 1: The simplest way to put the CPU to sleep until the next
interrupt is received is to call sleep_mode() at the end of loop(),
e.g.:
// Sleep until the next character is received.
set_sleep_mode(SLEEP_MODE_IDLE);
if (!Serial.available()) {
    sleep_bod_disable();
    sleep_mode();
}

There is, however, a race condition here: if the interrupt fires after
you test Serial.available() but before going to sleep, you will sleep
instead of handling the received character. The solution to this problem
is to do the test with interrupts disabled and then enable them right
before issuing the sleep instruction, as explained in the
documentation of the avr-libc:
set_sleep_mode(SLEEP_MODE_IDLE);
cli();
if (!Serial.available()) {
    sleep_enable();
    sleep_bod_disable();
    sei();
    sleep_cpu();
    sleep_disable();
}
sei();

Edit 2: answering the questions in the comments.

Pin change interrupt allows you to sleep deeper than IDLE, but if you
do so, the UART will be stopped and it will miss the start bit, which
could throw off its timing. I would rather stick with IDLE and use the
power_*_disable() functions to turn off the unneeded peripherals.

I have a theory, though I don't know if it's valid. Look at the
schematic of the PCINT detection. If the clock is stopped, a
change in the pin level will make the XOR gate switch to 1, which
presumably wakes up the MCU, but that will not be recorded by the
downstream flip-flops, which rely on the clock. If the pin returns to
its original level before the clock restarts (which takes some time when
coming out of PWR_DOWN), then the flip-flops never see the pin change
condition, and the interrupt flag does not rise.

Edit 3: I made a test that confirms that, when waking up from
PWR_DOWN by a pulse-triggered PCINT event, the ISR does not run if
the pulse is too short. The setup involves two Arduinos:

the “tester” Arduino:

sends pulses of various lengths through digital 8 = PB0
forwards on TX the data received on RX

the “DUT” Arduino:

sleeps in PWR_DOWN mode
wakes up by pin change interrupt on digital 8 = PB0 = PCINT0
reports whether the ISR ran on the serial port

The connections are:
DUT   Tester    PC
───────────────────
        USB --- USB
GND --- GND
+5V --- +5V
  8 --- 8
 TX --- RX

The “tester” program:
const uint32_t PULSE_PERIOD = 500;  // pulses every 500 ms

void setup() {
    DDRB |= _BV(PB0);  // digital 8 = PB0 as output
    Serial.begin(9600);
    Serial.println("Tester: ready");
}

void loop() {
    // Forward the serial communication.
    while (Serial.available())
        Serial.write(Serial.read());

    // Periodically send a pulse.
    static uint32_t last_pulse_time;
    if (millis() - last_pulse_time >= PULSE_PERIOD) {
        last_pulse_time += PULSE_PERIOD;

        // Send a pulse of 2^n microseconds.
        static uint8_t n = 0;
        uint16_t length = 1U << n;
        Serial.print("Tester: sending pulse of ");
        Serial.print(length);
        Serial.println(" us");
        Serial.flush();
        uint32_t now = millis();
        while (millis() == now) ;  // wait for the tick
        PORTB |= _BV(PB0);
        delayMicroseconds(length);
        PORTB &= ~_BV(PB0);

        // Next pulse size.
        if (++n >= 16) n = 0;
    }
}

The “DUT” program:
#include <avr/sleep.h>

// The PCINT ISR only sets a flag.
volatile bool isr_ran;
ISR(PCINT0_vect) { isr_ran = true; }

void setup() {
    // Setup interrupt.
    PCMSK0 = _BV(PCINT0);  // sense PCINT0 = PB0
    PCIFR |= _BV(PCIF0);   // clear interrupt flag
    PCICR  = _BV(PCIE0);   // enable PCINT0 interrupt

    // Avoid other interrupts.
    TIMSK0 = 0;         // avoid timer interrupt
    PORTD |= _BV(PD0);  // pull RX high to prevent USART_RX interrupt
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);

    Serial.begin(9600);
    Serial.println("DUT: ready");
}

void loop() {
    loop_until_bit_is_clear(PINB, PB0);  // wait for LOW input
    Serial.println("DUT: going to sleep");
    Serial.flush();
    isr_ran = false;
    sleep_mode();
    Serial.print("DUT: woke up, ISR ran: ");
    Serial.println(isr_ran ? "YES" : "NO");
}

And the results:
DUT: going to sleep
Tester: sending pulse of 1 us
DUT: woke up, ISR ran: NO
DUT: going to sleep
Tester: sending pulse of 2 us
...
Tester: sending pulse of 1024 us
DUT: woke up, ISR ran: NO
DUT: going to sleep
Tester: sending pulse of 2048 us
DUT: woke up, ISR ran: YES
DUT: going to sleep
Tester: sending pulse of 4096 us
DUT: woke up, ISR ran: YES
...

Conclusion: a pulse of 1024 µs or shorter wakes up the Arduino but
the ISR does not run. If the pulse is 2048 µs or longer, the ISR
does run.

Thank you for your answer! Two questions: 1) I was using serial.available, but pin change interrupt allows me to sleep deeper. Isn't that right? 2) I incorporated the correct way of enabling pin change interrupts, but the same problem persists. Sending one character wakes the uC, but the ISR is not accessed. Why is that?

To be clear, I do not understand how it is possible to wake up from sleep, and at the same time to not run the ISR code. That is what happens when I send one character from the Arduino IDE console.

@NickG: See updated answer.

Your explanation sounds good. I tested the code using the 'SLEEP_MODE_STANDBY' which only leaves the oscillator running, and it worked as expected. I will leave the question opened  for a few days, in case somebody else would like to add or check what we discussed

After more testing, it seems that the problem was that when I sent the character over the console, the interval between the time t1 that the change was noticed and the ISR was fired, and the time t2 that the Serial.read() happened, was very short, almost immediate. As a result, the byte (character) that I had sent over the serial console was not yet ready to be read, and the Serial.read() command returned plain '1's.
Furthermore, to disable/re-enable the pin-change interrupt, the right way seems to be to use the PCMSK register and not the PCICR. The initially posted code, had the extra problem that, when PCICR was re enabled (set to 0x01), the ISR was immediately fired again, reading an extra character (obviously all '1's). That was solved by disabling/ re-enabling the pin change interrupt using PCMSK register. Here is the corrected code, which seems to work fine:
volatile bool MeasReceived=false;
uint8_t inByte;

ISR(PCINT2_vect){   //ISR for pin-change interrupts occuring at PD0-PD7

  PCMSK2 = 0b00000000;    // turn off PD0 interrupt
  MeasReceived=true;      //Set char received Flag

}

void setup() {

  Serial.begin(9600);
  Serial.flush();
  Serial.print("Hello PC");
  delay(1000);

  cli();
  PCICR = 0b00000100;    // turn on port d pin change interrupts
  PCMSK2 = 0b0000001;    // turn on pin PD0 , PCINT16
  sei();
}

void loop() {

  if(MeasReceived==true){  //If ISR fired
    MeasReceived=false;    //Reset the flag
    delay(1000);           //Wait a while for the character to be set. 1000ms may be too much
    inByte = Serial.read();  // Read the character that was sent

    if(inByte=='A'){   //If the character was A, write B to console
       Serial.print('B');
    }
    else{   //else, write the ASCII code of the character received
      Serial.print(inByte);
    }
    PCMSK2 = 0b00000001;   //re-enable PD0 interrupt
  }
}

source: Stack Exchange

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

sort: votes


text:
Start / Stop Motor Run with Button State Change
I'm trying to understand Arduino with push buttons. But I can't get the test project I'm working on to work as how I want it to do.
Basically what I'm trying to do with the codes below is to make the push button either start or stop the servo motor. But so far, I couldn't get it to work. I'm also wondering why the servo motor won't run on loop? I tried several approach, but I couldn't get it working.
What am I missing here? Thanks.
By the way, I'm a beginner.
#include <Servo.h> //Servo Library.

int servoPin = 3; //Servo to Pin 2.
int led = 4; // LED to Pin 4.
int buttonState = 0;
int lastButtonState = 0;

Servo ServoOne; //Servo object created.

void setup() {
  Serial.begin(9600);
  ServoOne.attach(servoPin);
  pinMode(led, OUTPUT);
  pinMode(2, INPUT);
}

void loop() {
  buttonState = digitalRead(2);
  if (buttonState != lastButtonState) {
    servoRun();
  }
  lastButtonState = buttonState;
}

void servoRun() {
  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      Serial.println("Running.");
      ServoOne.write(0); //Servo resets to 0 degrees.
      digitalWrite(led, LOW); //LED turns on.
      delay (1000);
      ServoOne.write(90); //Servo turns to 90 degrees.
      digitalWrite(led, HIGH); //LED turns on.
      delay (1000);
      ServoOne.write(180); //Servo turns to 180 degrees.
      digitalWrite(led, LOW); //LED turns on.
      delay (1000);
      ServoOne.write(90); //Servo turns to 90 degrees.
      digitalWrite(led, HIGH); //LED turns on.
      delay (1000);
      ServoOne.write(0); //Servo resets to 0 degrees.
      digitalWrite(led, LOW); //LED turns on.
    } else {
      Serial.println("Off.");
      ServoOne.write(0);
      digitalWrite(led, LOW);
    }
  }
}

Edit:
I tried this new approach, but I can't get the button state change saved.
#include <Servo.h> //Servo Library.

//Constant.
const int pswitch = 2; //Switch to Pin 2.

//Variables.
int servoPin = 3; //Servo to Pin 3.
int led = 4; //LED to Pin 4.
int newState; //Current switch state.
int oldState = LOW; //Previous switch state.

Servo ServoOne; //Servo object created.

void setup() {
  Serial.begin(9600);
  ServoOne.attach(servoPin);
  pinMode(led, OUTPUT);
  pinMode(pswitch, INPUT_PULLUP);
}

void loop() {
  newState = digitalRead(pswitch);

  if (oldState == LOW && newState == HIGH) {
    Serial.println("ON and running.");
    ServoOne.write(90);
    digitalWrite(led, HIGH);
    delay(1000);
    ServoOne.write(0);
    digitalWrite(led, LOW);
    delay(1000);
    ServoOne.write(90);
    digitalWrite(led, HIGH);
    delay(1000);
    ServoOne.write(180);
    digitalWrite(led, LOW);
    delay(1000);
    ServoOne.write(90);
    digitalWrite(led, HIGH);
    delay(1000);
  } else {
    Serial.println("OFF.");
    delay(1000);
  }
  oldState = newState;
}

write a simple sketch that turn the motor on ... does the motor run?

what is the purpose of the first if statement in servoRun()?

So what I want it to do is to keep the servo running  from 0, 90, 180, 90 and back to 0 on loop. The first if checks the state of the button. If it's pressed, it should supposed to 0 degrees and turn the LED off.

Basically I wanted to create a toggle switch button using one button. Is it possible? To toggle the servo to turn on and turn off? If it's toggled on, it will continue doing the 0, 90, 180, 90, 0 on loop, and if it's toggled off, it will stop. And if it's toggled on again, it will continue doing its job from where it stopped?

So, you want one button press to start the motor and keep it turning until the next button press? As far as I can see, one button press will now start the motor, will do a full revolution and then stop. Pressing the button again will start the motor again due to the button bouncing (or it may do nothing if the button is debounced externally). Correct?

@StarCat -- Yes that's correct. Actually I want the motor to perform a different job (in this sample, I just want it to stop rotating for the sake of simplicity) when the button is pressed. But I can't get the button state change saved.

@StarCat, I edited the post to show you my current codes. I can't get the state change saved to "newState". How do I do that? Is it even possible?
Like for a simple example, on press, it will serial print "ON", and when pressed again it will print "OFF".

What do you mean you can't get the old state saved?  That's what the last line of loop does.  Or do you mean that there is some behavior that makes you think that's what's happening?

The way you have it written right now, it will detect a button is pressed, that satisfies the if statement.  Then it will follow the lines in that if block one after the other.  So first it prints, lights the led, moves to 90 degrees, sticks it's head in the sand for one second then goes to 0 degrees turn off the led stick head in sand for another full second, and on and on.  Finally when it gets to the end of all of that the loop repeats and it finally gets to check the button again.  So there's no way the button can stop it mid way because the button can't be checked in there.

@Delta_G -- Sorry for the confusion. Basically what I want the button to do is to make it perform another job. But I think my code is wrong, because it doesn't transfer the state change from newState to oldState so it can compare. So to explain it simpler, how can I make it (let's say) print ON on the first press of a button, and then print OFF on the second press? Like a toggle on and off switch?

@Delta_G or rather with a press of a button, it will rotate the servo to 180 or 0. Like on first press, it will rotate to 180 and hold its angle until pressed again -- which will rotate it back to 0 degrees.

Yeah.  I understood what you wanted.  I was explaining why it works now the way it does.   You’re wrong in thinking that you’re not assigning the value of the old state.  That’s what the last line in loop does.   That’s happening.  Get it out of your mind that this is the problem. It’s not.  The problem is that once the button is pressed your code does the entire movement before it checks the button again.  You have blocking code.  You need a non-blocking state machine.  Google that.

@Delta_G took me a while to figure out what's causing the problem. Turns out it was the delay. I didn't know it stops everything. Finally got it working using millis and adding another variable to check the value of the button. Button works instantaneously as I want it to be. Thanks!

Execution always runs one line at a time.  No line of code can ever run until the line before it gets executed.  Well that’s not entirely true but for our purposes it’s close enough.  It’s not just delay.  Any command that takes a long time to run is an issue.

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


text:
How to split a string received via a GSM module (message)
I am doing a motorcycle security system. In this system, I will receive a message from GSM in the form {password:operation (like start,stop,alarm):time}.
Example:(9990:start:30)
now i need to split  each term seperately (a=9990,b=start,c=30).help me to solve

You may need to say how you receive the message or how it's stored.   As is, the question is vague.  Also edit the question and add an explained example, like "{14:C:123}"

Simplest solution is to use sscanf().
  int password;
  char operation;
  int time;
  char* buf = "{14:C:123}";
  int n = sscanf(buf, "{%d:%c:%d}", &password, &operation, &time);
  Serial.print(F("n="));
  Serial.println(n);
  Serial.print(F("password="));
  Serial.println(password);
  Serial.print(F("operation="));
  Serial.println(operation);
  Serial.print(F("time="));
  Serial.println(time);

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


text:
compilation error in arduino
I'm new to arduino. I had found an interesting project to work on with, but unfortunately I'm held up at compilation error. I tried finding answers to this problem but not able to understand.
Here is my code:
    // Include Libraries
#include <Wire.h>
#include <Servo.h>
#include <Adafruit_TCS34725.h>

// Initialize Sensors
Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_4X);
Servo myservoRed;
Servo myservoGreen;
Servo myservoBlue;

int posRed = 0;
int posGreen = 0;
int posBlue = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("Color View Test!");

  if (tcs.begin()) {
    Serial.println("Found sensor");
  } else {
    Serial.println("No TCS34725 found ... check your connections");
    while (1); // halt!
  }

  //Attach servos to ouput pins
  myservoRed.attach(9);
  myservoGreen.attach(6);
  myservoBlue.attach(3);

  // Initialize Fan pin
  pinMode(7, OUTPUT);

}

void loop() {
  uint16_t clear, red, green, blue;
  tcs.setInterrupt(false);
  delay(60);  // takes 50ms to read
  tcs.getRawData(&red, &green, &blue, &clear);
  tcs.setInterrupt(true);
  Serial.print("C:\t"); Serial.print(clear);
  Serial.print("\tR:\t"); Serial.print(red);
  Serial.print("\tG:\t"); Serial.print(green);
  Serial.print("\tB:\t"); Serial.print(blue);

  // Map color to motor position
  posRed = map(red,100,10000,10,80);
  Serial.print("\tRedPos:\t"); Serial.print(posRed);
  posGreen = map(green,100,10000,10,80);
  Serial.print("\tGreenPos:\t"); Serial.print(posGreen);
  posBlue = map(blue,100,10000,10,80);
  Serial.print("\tBluePos:\t"); Serial.print(posBlue);
  Serial.println();

  // Write position to motor
  myservoRed.write(posRed);
  delay(100);
  myservoGreen.write(posGreen);
  delay(100);
  myservoBlue.write(posBlue);
  delay(100);

}

Here is the Wire.h:
/*
 * TwoWire.h - TWI/I2C library for Linux Userspace
 * Copyright (c) 2013 Parav https://github.com/meanbot.
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifndef TwoWire_h
#define TwoWire_h

#include "Stream.h"
#include "variant.h"

#define BUFFER_LENGTH 32
#define I2C2 0x4819c000
#define I2C1 0x00000000
#define WIRE_INTERFACES_COUNT 1

class TwoWire : public Stream {
public:
    TwoWire(void(*begin_cb)(void));
    void begin();
    void begin(uint8_t);
    void begin(int);
    void beginTransmission(uint8_t);
    void beginTransmission(int);
    uint8_t endTransmission(void);
    uint8_t endTransmission(uint8_t);
    uint8_t requestFrom(uint8_t, uint8_t);
    uint8_t requestFrom(uint8_t, uint8_t, uint8_t);
    uint8_t requestFrom(int, int);
    uint8_t requestFrom(int, int, int);
    virtual size_t write(uint8_t);
    virtual size_t write(const uint8_t *, size_t);
    virtual int available(void);
    virtual int read(void);
    virtual int peek(void);
    virtual void flush(void);
    void onReceive(void(*)(int));
    void onRequest(void(*)(void));

    inline size_t write(unsigned long n) { return write((uint8_t)n); }
    inline size_t write(long n) { return write((uint8_t)n); }
    inline size_t write(unsigned int n) { return write((uint8_t)n); }
    inline size_t write(int n) { return write((uint8_t)n); }
    using Print::write;

    void onService(void);

private:
    // RX Buffer
    uint8_t rxBuffer[BUFFER_LENGTH];
    uint8_t rxBufferIndex;
    uint8_t rxBufferLength;

    // TX Buffer
    uint8_t txAddress;
    uint8_t txBuffer[BUFFER_LENGTH];
    uint8_t txBufferLength;

    // Service buffer
    uint8_t srvBuffer[BUFFER_LENGTH];
    uint8_t srvBufferIndex;
    uint8_t srvBufferLength;

    // Callback user functions
    void (*onRequestCallback)(void);
    void (*onReceiveCallback)(int);

    // Called before initialization
    void (*onBeginCallback)(void);

    // Timeouts (
    static const uint32_t RECV_TIMEOUT = 100000;
    static const uint32_t XMIT_TIMEOUT = 100000;

    uint8_t adapter_nr;
    int i2c_fd;
    int i2c_transfer;
};

#if WIRE_INTERFACES_COUNT > 0
extern TwoWire Wire;
#endif
#if WIRE_INTERFACES_COUNT > 1
extern TwoWire Wire1;
#endif

#endif

Here is Wire.cpp:
/*
 * TwoWire.h - TWI/I2C library for Linux Userspace
 * Copyright (c) 2013 Parav https://github.com/meanbot.
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

extern "C" {
#include <string.h>
#include <i2c.h>
}

#include "Wire.h"

#include <Mux.h>
#include <trace.h>
#define MY_TRACE_PREFIX "Wire"

TwoWire::TwoWire(void(*_beginCb)(void)) : rxBufferIndex(0), rxBufferLength(0),
                      txAddress(0), txBufferLength(0),
                      srvBufferIndex(0), srvBufferLength(0),
                      onBeginCallback(_beginCb),
                      adapter_nr(-1), i2c_fd(-1),
                      i2c_transfer(0)
{
    // Empty
}

void TwoWire::begin(void)
{
    muxSelectI2c(0);
    if (onBeginCallback)
        onBeginCallback();
    if ((adapter_nr = i2c_getadapter(I2C2)) < 0) {
        return;
    }
    if ((i2c_fd = i2c_openadapter(adapter_nr)) < 0) {
        return;
    }

}

void TwoWire::begin(uint8_t address)
{
    if (onBeginCallback)
        onBeginCallback();
}

void TwoWire::begin(int address)
{
    begin((uint8_t) address);
}

uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop)
{
    if (quantity > BUFFER_LENGTH)
        quantity = BUFFER_LENGTH;

    /* Set slave address via ioctl  */
    i2c_setslave(i2c_fd, address);

    if(i2c_transfer) {
    /* Need to perform a combined read/write operation
     */
        i2c_transfer = 0;
        if (sendStop == false)
            return 0;
        i2c_add_to_buf(address, 1, rxBuffer, quantity);
        if (!i2c_readwrite(i2c_fd)) {
            rxBufferIndex = 0;
            rxBufferLength = quantity;
            i2c_transfer = 0;
            return quantity;
        } else
            return 0;
    }
    if (i2c_readbytes(i2c_fd, rxBuffer, quantity) < 0)
        return 0;
    // set rx buffer iterator vars
    rxBufferIndex = 0;
    rxBufferLength = quantity;

    return quantity;
}

uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity)
{
    return requestFrom((uint8_t) address, (uint8_t) quantity, (uint8_t) true);
}

uint8_t TwoWire::requestFrom(int address, int quantity)
{
    return requestFrom((uint8_t) address, (uint8_t) quantity, (uint8_t) true);
}

uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop)
{
    return requestFrom((uint8_t) address, (uint8_t) quantity, (uint8_t) sendStop);
}

void TwoWire::beginTransmission(uint8_t address)
{
    if (i2c_fd < 0 || adapter_nr < 0)
        return;
    /* set slave address via ioctl in case we need to perform terminating
     * write operation
     */
    i2c_setslave(i2c_fd, address);
    // save address of target and empty buffer
    txAddress = address;
    txBufferLength = 0;
}

void TwoWire::beginTransmission(int address)
{
    beginTransmission((uint8_t) address);
}

//
//  Originally, 'endTransmission' was an f(void) function.
//  It has been modified to take one parameter indicating
//  whether or not a STOP should be performed on the bus.
//  Calling endTransmission(false) allows a sketch to
//  perform a repeated start.
//
//  WARNING: Nothing in the library keeps track of whether
//  the bus tenure has been properly ended with a STOP. It
//  is very possible to leave the bus in a hung state if
//  no call to endTransmission(true) is made. Some I2C
//  devices will behave oddly if they do not see a STOP.
//
uint8_t TwoWire::endTransmission(uint8_t sendStop)
{
    int err;
    if (sendStop == true) {

        // transmit buffer (blocking)
        if (txBufferLength > 1)
            err = i2c_writebytes(i2c_fd, txBuffer, txBufferLength);
        else if (txBufferLength == 1)
            err = i2c_writebyte(i2c_fd, *txBuffer);
        else
        /* FIXME: A zero byte transmit is typically used to check for an
         * ACK from the slave device. I'm not sure if this is the
         * correct way to do this.
         */
            err = i2c_readbyte(i2c_fd);
        // empty buffer
        txBufferLength = 0;
        if (err < 0)
            return 2;
        return 0;
    } else {
    /* sendStop = false
     * pretend we have held the bus while
     * actually waiting for the next operation
     */
        i2c_add_to_buf(txAddress, 0, txBuffer, txBufferLength);
        i2c_transfer = 1;
        return 0;
    }
}

//  This provides backwards compatibility with the original
//  definition, and expected behaviour, of endTransmission
//
uint8_t TwoWire::endTransmission(void)
{
    return endTransmission(true);
}

size_t TwoWire::write(uint8_t data)
{
    if (txBufferLength >= BUFFER_LENGTH)
        return 0;
    txBuffer[txBufferLength++] = data;
    return 1;
}

size_t TwoWire::write(const uint8_t *data, size_t quantity)
{
    for (size_t i = 0; i < quantity; ++i) {
        if (txBufferLength >= BUFFER_LENGTH)
            return i;
        txBuffer[txBufferLength++] = data[i];
    }
    return quantity;
}

int TwoWire::available(void)
{
    return rxBufferLength - rxBufferIndex;
}

int TwoWire::read(void)
{
    if (rxBufferIndex < rxBufferLength)
        return rxBuffer[rxBufferIndex++];
    return -1;
}

int TwoWire::peek(void)
{
    if (rxBufferIndex < rxBufferLength)
        return rxBuffer[rxBufferIndex];
    return -1;
}

void TwoWire::flush(void)
{
    // Do nothing, use endTransmission(..) to force
    // data transfer.
}

void TwoWire::onReceive(void(*function)(int))
{
    onReceiveCallback = function;
}

void TwoWire::onRequest(void(*function)(void)) {
    onRequestCallback = function;
}

void TwoWire::onService(void)
{
}

#if WIRE_INTERFACES_COUNT > 0
static void Wire_Init(void)
{
}

TwoWire Wire = TwoWire(Wire_Init);

void WIRE_ISR_HANDLER(void) {
    Wire.onService();
}
#endif

#if WIRE_INTERFACES_COUNT > 1
static void Wire1_Init(void)
{
    if ((adapter_nr = i2c_getadapter(I2C1)) < 0) {
        return;
    }
    if ((i2c_fd = i2c_openadapter) < 0) {
        return;
    }
}

TwoWire Wire1 = TwoWire(Wire1_Init);

void WIRE1_ISR_HANDLER(void) {
    Wire1.onService();
}
#endif

Here is the error message i got:
libraries\Servo\Wire.cpp.o: In function `WIRE_ISR_HANDLER()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:186: multiple definition of `TwoWire::write(unsigned char)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:186: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::write(unsigned char const*, unsigned int)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:194: multiple definition of `TwoWire::write(unsigned char const*, unsigned int)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:194: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(unsigned char, unsigned char, unsigned char)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:204: multiple definition of `TwoWire::available()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:204: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::read()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:209: multiple definition of `TwoWire::read()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:209: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::peek()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:216: multiple definition of `TwoWire::peek()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:216: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::flush()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:223: multiple definition of `TwoWire::flush()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:223: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::TwoWire(void (*)())':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:32: multiple definition of `TwoWire::TwoWire(void (*)())'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:32: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::TwoWire(void (*)())':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:32: multiple definition of `TwoWire::TwoWire(void (*)())'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:32: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::begin()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:43: multiple definition of `TwoWire::begin()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:43: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::begin(unsigned char)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:57: multiple definition of `TwoWire::begin(unsigned char)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:57: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::begin(int)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:63: multiple definition of `TwoWire::begin(int)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:63: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(unsigned char, unsigned char, unsigned char)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:68: multiple definition of `TwoWire::requestFrom(unsigned char, unsigned char, unsigned char)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:68: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(unsigned char, unsigned char)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:100: multiple definition of `TwoWire::requestFrom(unsigned char, unsigned char)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:100: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(int, int)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:105: multiple definition of `TwoWire::requestFrom(int, int)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:105: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::requestFrom(int, int, int)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:110: multiple definition of `TwoWire::requestFrom(int, int, int)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:110: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::beginTransmission(unsigned char)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:115: multiple definition of `TwoWire::beginTransmission(unsigned char)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:115: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::beginTransmission(int)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:128: multiple definition of `TwoWire::beginTransmission(int)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:128: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::endTransmission(unsigned char)':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:146: multiple definition of `TwoWire::endTransmission(unsigned char)'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:146: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::endTransmission()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:181: multiple definition of `TwoWire::endTransmission()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:181: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::onReceive(void (*)(int))':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:229: multiple definition of `TwoWire::onReceive(void (*)(int))'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:229: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::onRequest(void (*)())':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:233: multiple definition of `TwoWire::onRequest(void (*)())'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:233: first defined here

libraries\Servo\Wire.cpp.o: In function `TwoWire::onService()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:238: multiple definition of `TwoWire::onService()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:238: first defined here

libraries\Servo\Wire.cpp.o: In function `WIRE_ISR_HANDLER()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:248: multiple definition of `WIRE_ISR_HANDLER()'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:248: first defined here

libraries\Servo\Wire.cpp.o: In function `WIRE_ISR_HANDLER()':

C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Servo\src/Wire.cpp:186: multiple definition of `Wire'

libraries\Wire\Wire.cpp.o:C:\Users\Danush\AppData\Local\Arduino15\packages\Intel\hardware\i686\1.6.7+1.0\libraries\Wire\src/Wire.cpp:186: first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

Looks like the Servo library has Wire source files in it for some reason. I checked my Servo library, and it doesn't have those, so not sure what's going on there, but maybe try removing Wire.cpp from Servo/src/? (keep in the file so you can put it back if necessary)

I agree with uint128_t - it looks like you have an improper installation. Somehow Wire.cpp is being compiled twice.

Thank you uint128_t. I found that the servo library had wire library files. Removed the files and things are working great.

Please mark this question as answered.

Looks like the Servo library has Wire source files in it for some reason. I checked my Servo library, and it doesn't have those, so not sure what's going on there, but maybe try removing Wire.cpp from Servo/src/? (keep in the file so you can put it back if necessary)
credits to uint128_t(in the comments)
Based on his suggestion i removed the
wire library files present in servo library folder and things worked just fine.

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


text:
Inexpensive way of connecting a lot of modules on a distance
I need to connect a lot (~100) of modules with a computer (Raspberry pi). The modules are based on Arduino micro and are very simple. They will be spread around, but for the two adjacent the distance would not be larger than 2 meters.
From time to time they receive information from the computer and also can send some data back. So bandwidth requirement is small.
My first idea was connecting them in one i2c network. It would be fine, except I have figured out that i2c is not good for a distances. Signal degrades and communication is unreliable if works in the first place.
Second idea is the nrf24 network (mash). But I am not sure how reliable communication is with them? Wired seams more reliable.
What would you recommend? It needs to be as cheap as possible, because of number of modules. Reliability of communication is important. The bandwidth requirement is very small (1Kbps is enough). Also modules are not battery powered so no need to be low power option.
What is the best way of doing this?
EDIT:
Network topology (it can be changed):

simulate this circuit – Schematic created using CircuitLab

I don't think I2C will necessarily be bad. You'd have to be a bit more considerate in applying it; like spreading the pull-up resistors and picking the correct values, and maybe do some termination to prevent ringing. Lowering the clock speed will also help. But I'm no expert here. You could read this paper. The first alternative to sprung to mind was RS485, which is pretty robust. PS what is the total length? Also how are they connected? All in a single line, or more like a tree?

There are lots of ways of doing that.  Wired can work if you do a daisy chain rather than a bus, but you do have to deal with wires.  Radio works too if you design your protocol well - you can get modules on-air compatible with the NRF24L01 for a dollar each.  You haven't specified the maximum distance from the pi to a node; if it is beyond expected radio range you do a mesh or forwarding scheme, at the cost of software complexity.  At a higher radio cost (~$10 in small quantities) there are also things like LoRa.

Yes, probably I2C could work, but still I am afraid it would be pretty unreliable. Or maybe I am too afraid. Maximum length is ~50m, so mesh would be needed. They would be connected like multiple rows connected in column (something like stretched star). Hope you understand. RS485 is only between two modules, no network? Need to daisy chain? I will read about it. LoRa looks too expensive (if could be avoided).

Added picture of network topology. Number of modules is larger, but this is basic idea.

Looks like RS485 is a good solution for wired communication over some distance. Which would you prefer nRf24 vs RS485?

nRF24-s are probably cheaper and easier to use than RS485 system.

What about reliability? Can nRf24 be sufficiently reliable. Do you have any experience with it?


text:
2 different operation modes for a motor
i want to press "unu" button of the remote, and the motor to rotate continuously, and when i press "sound" i want the motor to rotate untill the hall sensor detects a magnetic field. any ideas please?
in this configuration, even if i press "unu" or "sound", the motor rotates untill the hall sensor detects a magnetic field.

#include <TLE94112.h>
#include <Tle94112Motor.h>
#include <IRremote.h>

#define unu 0x1
#define sound 0x55

int RECV_PIN = 2;
int hallSensorPin1 = 3;
int state1;
int oldState1 = 1;

Tle94112 controller = Tle94112();
Tle94112Motor motor1(controller);

IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{ irrecv.enableIRIn();
  controller.begin();

  motor1.connect(motor1.HIGHSIDE, controller.TLE_HB1);
  motor1.connect(motor1.LOWSIDE, controller.TLE_HB2);
  motor1.setPwm(motor1.HIGHSIDE, controller.TLE_PWM2);
  motor1.setPwmFreq(motor1.HIGHSIDE, controller.TLE_FREQ200HZ);

  motor1.begin();
}

void loop()
{
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume();
  }//add bracket here

  if (results.value == unu || results.value == 0x801 || results.value == 0x2049) {
    motor1.start(63);
  }

  if (results.value == sound || results.value == 0x55 || results.value == 0x2103 || results.value == 0x837 || results.value == 0x37) {
    motor1.start(63);

    oldState1 = 1;
    state1 = digitalRead(hallSensorPin1);

    if (state1 == LOW && oldState1 == 1) {
      motor1.coast();

    }
  }
}

thanks for your observation. i fixed this.

the two if (results.value == statements execute the same code

yes, and i tried the configuration that you can see now in the initial post (i updated it) and this one works fine for continuous rotation, but when the magnetic field is detected, the motor receives small pulses without pressing any button, and again when its not detecting a magnetic field, rotates normally till it finds again the magnetic field.

introduce a layer of separation between if (results.value == and motor1.start(63); .... the if statement should only set two flags, motorOn and motorMode (you pick names) .... there should be only one code line that turns on the motor if (motorOn) { .... the hall sensor code should be wrapped in if (motorMode) {

you provided incomplete information ... i see nothing in your post about the serial monitor output

Serial.println(results.value, HEX); this is what you saying?

yes, that prints debugging information to serial monitor

its not showing anything in the serial monitor. im a beginner in arduino, i just used it with a couple of sensors before and this project it is too much for me now i think. anyway i figured out the problem. can i ask how that serial monitor output influence the program?

it should be printing something when you press a button on the remote control


text:
Displaying Keypad Input on TFT Display
For a project of mine I have always wanted to build an electronic load and I am mostly done. However I have found myself stuck at one part that I thought would be simple but has thus only caused headache.
The problem is that I have a keypad connecting along with a TFT display to an Arduino. I want to enter for example my current for the electronic load and display the value that I set on my display. I have tried the simple code for keypads that is available on tutorials all over the web but what happens is that it displays the key I press but if I press another one it erases the first and displays the second in the same spot. I want to be able to have 4 or 5 digits that can all show up in order. I have found some different code and modified it. I can now display multiple digits but the issue is that if I press for example 4 a 4 will show up but if I press a 5 another 4 will show up and then if I press a 5 again then a 5 will show up on and on.
Additionally it resets the screen even though I don't have a reset function in my code. So every time I press a key the screen will reset to white and then show the numbers. If anyone has time to help me out it would be greatly appreciated.
EDIT: Thank you for everyone's help and I have solved the problem. However I haven't found a way to incorporate a decimal point into it. This code is the code that works except for the decimal point.

  #include <Keypad.h>
#include <MCUFRIEND_kbv.h>
MCUFRIEND_kbv tft;

String v1;
String num;

const byte ROWS = 4;
const byte COLS = 4;

char hexaKeys[ROWS][COLS] = {
  {'1', '4', '7', '*'},
  {'2', '5', '8', '0'},
  {'3', '6', '9', '.'},
  {'A', 'B', 'C', 'D'}
};

byte rowPins[ROWS] = {31, 22, 23, 24};
byte colPins[COLS] = {25, 26, 27, 28};

Keypad kpd = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS );

#define BLUE    0x001F
#define WHITE   0xFFFF

#define DATAOUT 11//MOSI
#define DATAIN 12//MISO
#define SPICLOCK  13//sck
#define SLAVESELECT0 10//ss

void setup()
{
  uint16_t id = tft.readID();
  tft.begin(id);
  tft.setRotation(1);
  tft.fillScreen(WHITE);
  tft.setTextColor(BLUE, WHITE);
}

void loop() {
  v1 = GetNumber();
  v1.toInt();
}
String GetNumber()
{
  char key = kpd.getKey();
  // while (key != '#')
  {
    switch (key)

    {
      case NO_KEY:
        break;

      case '0': case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
        num = num + key;
        tft.setTextSize(5);
        tft.setCursor(10, 50);
        tft.print(num);
        break;
    }
    key = kpd.getKey();
  }
  return num;

}

Print your number tft.print(num); AFTER you append the key num=num + key, not before.

Your String num; is a local variable within the function, it get out of the scope when exit the function, you want to keep the value, declare it as a global variable.

do not combine keypress handling with display handling ... pressing a key should only update the value of a variable, nothing else ... the display function should only get its data from the variable

i think that you are not paying attention to what is in your code ... you complain about the screen turning white, and yet you have code like tft.fillScreen(WHITE); ... don't you think that you should be running the tft setup code like textColor and textSize only once?

Thank you for all who helped me. It is now working perfect. I only have one question: How would I implement a decimal point? I can't simply make another case for it because that would have to be a number. This is my new code

I couldn't put my new code in the comment so I updated the original code in the question. Thanks everyone!


text:
Looking for information and/or how to connect the RF433Mhz module (WL101-341/WL102-341)
I'm trying to find information about this 433MHz RF module: QIACHIP

Apparently it can be connected to an Arduino with the RadioHead library, but I don't have diagrams of how to connect them togheter in order to send/recieve data, becasue the module have 4 pins (Vcc, Gnd, Dat and En). I guess Dat pin should be connected to any Arduino pin, but as I only have one module I dont wanna risk it. I have no previous experience with RF modules :-(
I have found some Youtbe video, but the language of the video is in russian, and I don't know that langauge (I even ask the owner of the chanel for subtitles).
Please, if anyone have worker whit this module before, share:

How to connect the module with an arduino?
A simple example of how to send a simple word (let's say: "Hello") from the transmitter to the reciever

You're right not to just go ahead and wire things up. There's a couple of nuances that you need to take into account.
Transmitter

Ignore the EN pin - that does nothing on that module
The transmitter is 1 3.3V device. You need to power it from the 3.3V pin and use logic level (5V -> 3.3V) translation on the Data pin

simulate this circuit – Schematic created using CircuitLab
Receiver
The receiver is much simpler as it is a 5V device:

simulate this circuit
On the Arduino it shouldn't matter what IO pin you use, the Radiohead library should work fine with any of them.  These modules are pretty dumb - you raise DAT high on the TX and DO on the RX goes HIGH. Very simple.

Thanks! If you would't tell me about the Tx is a 3.3V device I surely would fried it! I think I have a shift converter laying around or could use the VoltageDivider as well. Thanks! I will try now

Hi @Majenko, I already connect everything as you draw it: Tx on a Nano 3V3 and DAT pin to HIGH (trough a VoltageDivider), Rx on an UNO, but when I read the D0 with the UNO I get only 0. Can you share how to make these Tx and Rx modules comunicate among them? Im trying to get some info, but the RadioHead library doesn't seem to be writen for these modules... It should work tho, cuz the russian guy for the Youtube vid I shared make them work...

Well, I make it work: I remove the VoltajeDivider and hook up the PIN12 in the NANO directly to the DAT pin on the Tx, using RadioHead library, and Im now able to send data from the Tx to the Rx...


text:
Unexpected result with the GSM module A6
I have a GSM A6 module, like this one.
I'm going to use an Arduino Nano as a bridge to communicate with it, I have an external power source (since I read that this module can consume up to 2A at its maximum consumption) (this power supply shares the GND with the module and the Arduino) and I upload the following code in the Nano:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11);

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and A6
  mySerial.begin(115200);

  Serial.println("Initializing...");
  delay(1000);

}

void loop()
{
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

I set the baud rate at 115200 of my SoftwareSerial port (connected to 10 and 11 pins on the ArduinoNano) because (even if the module says that it has auto-detect speed hability) doesn't work if I set the speed at 9600 (or any other), and I modified the SoftwareSerial library for expand the buffer from 64k to 512k (trying to solve this problem) following this page instructions (also: NICE WORK in this page!!!).
And it works ... it works relatively well, I mean:
The AT commands to test (according to the datasheet itself) are AT and ATI (in one I recieve "AT /r OK" and the last one give some usefull information like the OS and other things), and they work, only they do not show me the same answer always, I leave screenshots:

As you can see, the answers are not always exact, there is some garbage characters, and I need them to be exact, because my idea is to create a kind of alarm, in which the Arduino (One, Nano or Mega) sends and receives AT commands. I worked with the SIM900 module before and always received the same answer when I sent an AT command.
So... any help?!

Apparently the SoftwareSerial library have some limitations, so I change the baudrate communication in the moduel ussing this sentence:

AT+IPR=9600

And change the code that I upload to the Nano, changing the baudrate speed in the declaration, from:
mySerial.begin(115200);

to
mySerial.begin(9600);

And now all is well :D


text:
AT42QT1070 sensor output issues in standalone mode
Also when I am trying to see the data read on pins in serial monitor, it is not reading as required. The code i am using is as follows:
const int tuch_Pin0=18;
const int tuch_Pin1=19;
const int tuch_Pin2=21;
const int tuch_Pin3=22;
const int tuch_Pin4=32;

int State1=0;
int State2=0;
int State3=0;
int State4=0;
int State5=0;

void setup() {
  Serial.begin(38400);
  pinMode( tuch_Pin0,INPUT);
  pinMode( tuch_Pin1,INPUT);
  pinMode( tuch_Pin2,INPUT);
  pinMode( tuch_Pin3,INPUT);
  pinMode( tuch_Pin4,INPUT);
}

void loop() {

    State1= digitalRead(tuch_Pin0);
    State2= digitalRead(tuch_Pin1);
    State3= digitalRead(tuch_Pin2);
    State4= digitalRead(tuch_Pin3);
    State5= digitalRead(tuch_Pin4);

    if( State1!=0){

         Serial.println("Touch0 press");
    }
    else if(State2!=0)
    {
      Serial.println("Touch1 press");
    }
     else if(State3!=0)
     {
         Serial.println("Touch2 press");
     }

     else if(State4!=0)
     {
       Serial.println("Touch3 press");
     }
   else if ( State5!=0)
   {
    Serial.println("Touch4 press");
   }
   else
   {
    Serial.println("please press any key");
   }
   delay(100);
}

.....................the output it shows is... touch press 0.. without any touch and shows press any key when I touch any pin. Where I am wrong? Any solution, please?

Is it possible that multiple pads are touched at once? Then you shouldn't use else if but only if. Are you using a sensor board or did you build your own? What is the wireup? Do you maybe need to invert the logic so that 0 means pressed and 1 means unpressed?

it would make more sense to name the state variables State0, State1, etc


text:
Error After running Arduino code on Windows 10
After running the Arduino Program on my Windows machine I got the following error my code and error are as below.
Also the COM port was turned grey i.e. disbaled.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);

void setup()
{
  lcd.begin(16, 2);
}

void loop()
{
  lcd.print("Hello, World!");
  delay(500);
  lcd.clear();
  delay(500);
}

It displayed as shown below

Arduino: 1.8.14 (Windows 10), Board: "Arduino Uno" Sketch uses 1894
bytes (5%) of program storage space. Maximum is 32256 bytes. Global
variables use 59 bytes (2%) of dynamic memory, leaving 1989 bytes for
local variables. Maximum is 2048 bytes. Serial port not selected.

did you connect the Arduino to PC?

So you're saying there's nothing displayed under "Tools->Ports"?

Yes I connected to PC.  Under tools drop down box, Ports icon is greyed out

Can you check in device manager that when you plug the arduino if any COM ports are available or shown there

I have just done that now and it displayed: Device type- Unknown, Location-Port_#0002.Hub_#0002. Thanks

That means, that Windows has no appropriate driver for it. Do you have a cheap Uno clone? Then you need to install the ch340 driver (which is the USB interface chip on mist cheap Uno/Nano clones). Please try and report if that helps

I know this problem from Arduino Uno clones. You need a proper driver. Here are a few:

CH341 serial driver (e.g. for Vendor ID 1A86, Product ID 7523)
Holtek UART bridge (e.g. for Vendor ID 04D9, Product ID B534)
FTDI Drivers (e.g. for Vendor ID 0403, Product ID 60xx)
CP210x Drivers (e.g. for Vendor ID 10C4, Product ID EAxx)
Prolific PL2303 (e.g. for Vendor ID 067B, Product ID 23xx and AAxx)
Microchip MCP2221 (for Vendor ID 04D8, Product IDs 00xx and 020x)
Cypress CDC (e.g. for vendor ID 04B4, Product ID 00xx)

After installing the driver, Windows recognizes the board as a serial port and Arduino IDE will list the serial ports identified by Windows.
Look up the details in device manager. You'll find the IDs in the details of the device named Device instance path. It looks like ...VID_xxxx?PID_yyyy... where xxxx is the vendor ID and yyyy is the product ID. You can also install all drivers, if you don't know which one to choose.
Another (but rare) issue could be that you interrupted the driver setup during Arduino IDE installation. In that case, run the Arduino IDE installation again and make sure you allow the driver installations (for Vendor ID 2341 and 2A03, Product IDs 0043, 0001, 0243).
Any of these suggestions will require administrator permissions.


text:
Can a 12V sensor connected to a 5V output signal of an Arduino Uno
I am doing a project for object detection. But my problem is I'm using a 12V photoelectric OMRON sensor to connect with 5V Digital PWM port 3 on Arduino using normal coding. Do I need an extra circuit to step down the voltage to 5V? Can it work because the only connection between the sensor and Arduino is the output signal, the VCC and Ground are from external power. Link to the datasheet Please help me

sensors are not connected to outputs ... inputs are used for that

Can you share the Omron datasheet also so we can suggest to you the circuit required

I have shared the datasheet sir @Maaz Sk

Yes you need to step down the sensor voltage using any external circuit. Arduino GPIOs cannot bear that much voltage.

My favorite solution for such an application is to use an optoisolation module. In this case, the signal can have a voltage of 12 V and the output of the optoisolation module can be connected to the input of the Arduino, where the input is configured as INPUT_PULLUP.
Example of the optoisolation module:

In this way it is possible to connect other types of sensors and switches and the solution is universal also for other development kits, e.g. with 3V3 logic.

TQ so much. But can you explain it to me more detail sir. Are you implying i have to connect the 12V sensor to arduino port 3 normally, with the optoisolator is connected to the arduino input port? How does that works? Sorry for my bad understanding

@DeSafa Connect the sensor to the input of the optoisolator module (2 pos. terminal) – signal and GND. Connect the Arduino to the 3 pos. terminal – 5V pin, input pin (e.g. D2), and GND.

TQ sir for your help. May i have the source code? Or just copy online anywhere

Just google and use digitalRead() function.

Thank you so much again @JSC

For one, you need to connect the two grounds together.
Secondly, the 12V signal will indeed fry your Arduino. Lower the voltage to just below 5V, using a voltage divider circuit. You could for example use a combinations of a 2.2kOhm and a 1.5kOhm resistor, to get around 4.9V.

Don't use a voltage divider circuit whatsoever, you will probably damage the chip. Use a transformer or buck converter. Unless you calculate the load induced that will be induced on the voltage divider, you cannot guarantee the voltage divider will provide a steady 5v, as load changes the output voltage of a voltage divider.

@JamesBarnett I was talking about converting a 12V signal to a 5V signal. Not converting 12V to 5V, to be used to supply power. Since the output of the voltage divider goes into an Arduino INPUT pin, the current will be next to nothing, and will not affect the voltage.

Oh, makes sense. Sorry!


text:
Arduino Vin pin does not work, but Arduino 5v pin power works
I have a very weird problem, at least it seems to me that way. I have connected L298N motor driver, Arduino and a hobby servo with a 6v power supply (tested with both 4xAA and 9v alkaline batteries). And wrote a simple program to rotate the servo every 10ms. There are no other motors connected as of yet.

Power supply is connected to the L298N 12v and GND.
Arduino is connected to the 5v and GND of L298N driver with the Vin and GND of Arduino respectively.
Servo's power (red wire) is connected to L298N 5v, GND is connected to the L298N's GND, and, servo's control (orange wire) is connected to pin 9 of Arduino.

The problem is that the servo hardly moves when Arduino gets power supply gets from the Vin input. However, if I connect it to the 5v of the Arduino power it works as expected. But I was under the impression that 5v pin of Arduino was to for the output and not for the input power supply. Could you guys please tell me what am I doing wrong here?

Could you draw a simple drawing for your circuit ?

@R1S8K I have updated with a simple circuit. Please have a look.

OK, let articulate my answer in answers section, and let me know if there's something need to be modified in my answer.

The Vin pin on the Arduino Uno board is connected to the input of the 5V onboard voltage regulator of the Arduino board.
This voltage regulator needs an input voltage that’s about 1.5V above its (regulated) 5V output that will feed the Arduino.
Arduino - note the recommended values of the Input Voltage (7-12V)
If you feed 5V into Vin, the voltage drop on the internal regulator will cause the Arduino board to be supplied with only about 3.5V, which is probably enough to make it function, but not enough to control the servos.
The solution, as you already found out, is to feed the 5V from the L298N board directly into the 5V pin of the Arduino. Please take care to measure the actual voltage from the L298N before you do this (it should be 5 Volts). Alternatively you could connect 12V to the Vin pin of the Arduino, but again, make sure you know what you’re doing.

Yes, on researching about the issue, I saw Vin drops 1.5V, that is why I tried with a 9v battery hoping it would at least provide 7.5V. Now I'm thinking that 9V batteries awful. Am I correct?

@Kakar 9 V batteries are very good in smoke detectors where they only need to supply a few milliamps ... they are made of six AAAA cells in series

You are using Arduino to drive one servo motor and that's simple with only using arduino board with this setting:

5V supply pin
GND pin
any pwm pin

Now using the LM298N here isn't optimal. If you googled LM298N, you would get the main application of this driver which is to drive DC and stepper motors.
For driving multiple servo motors, you can use this module board to drive upto 16 servo motors.

Here is a link for it on Banggood.
PCA9685 16-Channel 12-bit PWM Servo Motor Driver I2C


text:
Is my Arduino board defect? No matter what program I upload the pin 13 turns on and off 3 times and that's it
Just trying to find out if my Arduino UNO R1 board is broken or not.
First of all, everything seems normal, Arduino board shows "on" (green) when I plug it on my computer, I also can verify and upload programs to my Arduino board. But, no matter what program I upload the pin 13 turns on and off 3 times and that's it. I'm checkin it by using a LED.
Eg. if I want to use another pin (ex. 7, 8, 12) it doesn't work, or even to write a program for turning on/off 9 times pin 13 doesn't work...
Note: I noticed that pin 8 turns the LED for less than a 1/2 a second.
I already tried to restart board by bridging the reset pin and also by pushing reset directly on the board, I also reinstalled Arduino Genuino Application. I thought to update Atmega8U2 firmware but accordingly to Arduino site I don't need to update since I have firmware rev. 0.01.
It would be also great not to have to buy a new Arduino UNO. Thanks for your help
Edit:
Here is how I'm trying to make pin 12 work
int ledPin = 12;

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

void loop()
{
    digitalWrite(ledPin, HIGH);
    delay(2000);
    digitalWrite(ledPin, LOW);
    delay(2000);
}

Maybe the board is fine, but your programs are bad?

@Majenko that's also an possible. But I'm checking with a really basic tutorial. See my update please

And what do you have wired to pin 12?

The anode of a LED and the cathode to GND

No resistor? Maybe you are suffering from brownouts then.

Tried also with 220 ohms resistor. Yes I'm afraid it's broken

If it's broke you probably only need to replace the ATMega328, which is conveniently in a socket. Just make sure you buy one with the Arduino bootloader already programmed into it.

The best way to check if Arduino is working or not is to install Firmata. Here's the necessary steps:
1) Download Firmata application from the official website.
2) Connect Arduino to the computer
3) Open the Arduino IDE and burn the example Standard Firmata [File - Examples - Firmata - Standard Firmata]
4) Open the application, leaving the Arduino connected.
5) Chose the right serial port and debug every pin =D

So it turns out, that I was uploading my program to the wrong board. Thanks for the help!


text:
Why AnalogRead shows value (395) when its on HIGH State ? why not shows 1023 when its high State
I Took a output from ESP8266 and Connected it with Arduino Nano Analog input A0
i use BLYNK app to on/off D0 pin in ESP8266 , and i connected ESP8266 D0 pin with Arduino Nano A0 analogPin.
when esp8266 D0 in high state , the analogRead value in arduino nano serial monitor it show the value 395.
why not 1023 on high state .

esp8266 has a 3.3 V TTL level. the ATmega analog pin reads 1023 at 5 V. and if you toggle the pin fast then not even 3.3 V will be read.

Did you connect the ground pins together?

@Majenko no i didnt connected the esp8266 ground pin to Arduino nano Ground pin , should i?

Absolutely - otherwise how can the nano know what the 3.3V from the ESP8266 is relative to...?

@Juraj please be specific , it will help me to learn .

datasheets are specific.

There are two problems here - one immediate and one which will be come apparent.
First off, you appear not to have connected the ground pins of the two boards together. This is important. Voltage is not an absolute value, it's a value relative to some other point in the circuit. This is why "voltage" is sometimes called "potential difference". Normally the point in the circuit that voltages are referenced to is termed "ground". Note: there is nothing special about ground, it's just an arbitrary point in the circuit - usually, but not always, the point where the voltage is lowest.  If the ground of the Arduino that it's using to compare incoming voltages against is not the same as the ground that the ESP8266 is using to create its output voltage in relation to, then the Arduino really can't know what the voltage is.
You can think of it as a person standing on the ground. Now I am about 6 feet tall. When I am stood up the top of my head is about 6 feet above the ground. But to someone who is stood on a nearby rise in the ground my head is only maybe 3 feet above the ground. Their ground is not the same as my ground.
The second problem, which will become apparent once you have connected the grounds, is that the Arduino measures voltages between 0 and 5V as values between 0 and 1023. However the ESP8266 doesn't operate at 5V, it operates at 3.3V. The highest voltage it can ever put out is 3.3V. The Arduino can never read that as 1023 because it's not 5V.  Instead it will read somewhere around 675. That is, 3.3V is two thirds of 5V, and 675 is two thirds of 1023.

yes now i got it ., thanks a lot . you are genuis.


text:
Is it possible to use the same power source for the arduino and a high current
I've need to control some leds which draw 300mA with an arduino (actually an atmega) and after some searching I think the following is the circuit I need, but I'm not really sure if the power source for the LEDs can be the same as for the arduino.
R1 = 1k

Yes, it can, as long as it can provide the needed current. And be sure to not let the LED current through the Arduino. Connect the led circuit directly to your power supply

If the power supply has sufficient power and voltage stability, you can use it to power the LED and Arduino. However, the circuit is not entirely correct on the LED side, a current limiting resistor should be used in series with the LED. I would also recommend using a more powerful bipolar transistor or field effect transistor.

Thank you, yes, the leds have a resistor connected I just didn't draw it, didn't realize it could be confusing for someone seeing it.
Thanks for the tip on the transtor, what would be the problem with this one?

This transistor will dissipate about 0.2 W of power and may be slightly warm.

can you use a npn transistor high side like that from the MCU? IT would seem to be a voltage follower, 0.6v below Vcc. Much better to switch on the low side...


text:
read first line from sd card and save the position for again reading from sd card
I am reading sd card .txt file, I want to read the first line then how to save the position of the pointer for the next line read?

You mean like using a variable to save the number of the current line? What have you tried so far? Please show the code, that you already have

You should not need to save the position, the file knows where you last read from. You'd only need to manually save such information if you close the file and re-open it again, which unless you have a good reason is actually a very wasteful operation.
If you really do need to you can use the .position() and .seek() functions:
Save the location:
uint32_t pos = myFile.position();

Recall the location:
myFile.seek(pos);

Documentation:

https://www.arduino.cc/en/Reference/FilePosition
https://www.arduino.cc/en/Reference/FileSeek

File myFile = SD.open("test.txt", O_RDWR);
if (myFile) {

  while (myFile.available()) {
    int i = 0;
    while (i < myFile.size()) {
      inputString =  myFile.readStringUntil('\n');
      //Serial.print(inputString);
      if (myFile.readStringUntil('\n')) {

I have set a size for the loop, every time it returns "I want it to read a new line" but it skips, what could be the reason?
To help with this question, I wanted to show the process I did on the same question. Thank you, I will ask the question elsewhere.
I am sending from the serial port when the end of the line is not read twice, during each reading. I'm sending line by line

Please ask questions as new questions rather than in an answer on another different question. After deleting this, when you create your new question, please be as specific and clear as possible (and maybe explain why you're doing two readStringUntils in a row).

evet dediğinizi anladım ve kaldırdım. Çok teşekkür ederim. işe yarıyor. cevabımı bir yere yazmak gerekirse bana bildiriniz ben oraya cevap olarak eklemek isterim.

Answering your own questions is perfectly fine :)


text:
How to connect ESP8266 12e directly to Arduino Uno (without shields)
I have an ESP8266 12E module and I'm trying to connect it to arduino, without any shields or whatsoever. I've looked everywhere but all I can find is about ESP-01 or with a NodeMCU. I'd like to do the bridge manually, but I don't know which pins I should ground and which pins I should power.
This is my current setup:

And the following sketch:
#include <SoftwareSerial.h>

//RX pin 2, TX pin 3
SoftwareSerial esp8266(2, 3);

#define DEBUG true

void setup() {
  Serial.begin(9600);
  esp8266.begin(115200);
  sendData("AT\r\n", 2000, DEBUG);
  delay(1000);
  Serial.println("Firmware version:");
  delay(3000);
  sendData("AT+GMR\r\n", 2000, DEBUG);
  Serial.println("** End **");
}

void loop() {}

String sendData(String command, const int timeout, boolean debug) {
  String response = "";
  esp8266.print(command);
  long int time = millis();
  while ( (time + timeout) > millis())
  {
    while (esp8266.available())
    {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }
  if (debug)
  {
    Serial.print(response);
  }
  return response;
}

When run, I get the following output:
Firmware version:
** End **

On the module, the led flashes when I power it up, but after that it remains off. I've already tested the voltage regulator with ReadAnalogVoltage, and the output was 3.33v, so it is working.

For future reference, here's a link of my final (working) pinout

And just a heads up: if using Arduino Mega, not all pins can be used as Software Serial, see this post for more details. Currently I'm using pins 10 and 11 and it's working fine.

Make sure to specify as SoftwareSerial's Rx pin, the pin# connected to the ESP's Tx pin. They have to be crossed. (I just fumbled that myself, a couple of hours ago ):
It is the ESP's Rx pin that needs the voltage divider.
Also pullup the ESP's reset pin.
Update:
ESP-01 and ESP-12 modules use the same ESP8266 chip. The differences are in the number of pins brought out from the chip and made available on the board. Other differences include the firmware interpreters installed on them before shipment: "NodeMCU" is one. ESP-01 is usually shipped with the AT+ command interpreter unless it specified otherwise; I would expect the same for the others. Bottom line is they are connected pretty much alike. Interacting with them serially from an Arduino (or other device) then depends on the installed firmware, including whether you've installed your own. So far, I've used all of mine as WiFi modules using the AT+ interpreter they came with.

How can I pullup the reset pin? Also do I need to pullup it just for
  initial setup (changing baud rate and such) or should it be pulled up
  at all times?

I use a 10K-Ohm resistor to +3.3v as a pullup. You need it pulled up anytime you are not trying to force a hardware reset; grounding it resets the chip. I have never used a reset button on my ESPs. I just leave them pulled up. If you want one, it should short the reset pin to ground.
Update 2 (wiring):
You've powered the ESP with 3v but your pullups are taken to the Arduino's 3.3v supply. Most chips have a slim tolerance for signal levels above their supply voltage. I'd suggest driving the entire ESP from your 3v battery - power & both pullups.
I don't know the ESP-12E's pinouts to check them; I'm sure you have, and you might want to label the diagram so someone else can look over it too.
Then there's whatever "chicken dance" is needed on the reset and the GPIO line that needs to get toggled to start an upload. I don't know that sequence, but I think you need a grounding buttons on on each one to be able to sequence them.

I think I fumbled that too initially. How can I pullup the reset pin? Also do I need to pullup it just for initial setup (changing baud rate and such) or should it be pulled up at all times?

I've edited my question with my current setup based on what you and Len said, yet it still doesn't work.

Your comment pointed me in the right direction. After connecting all the pullups to the power supply, I had to ground/pulldown GPIO15 pin, and now it works! I'll attach a picture of my wiring as soon as I can. Thanks!

Oh boy, lot of things can be the problem here.
First of all: a voltage divider using 10k-10k has an output of 2.5V when the source is 5V. The ESPs run on 3.3V, so this effectively could mean the commands are completely scrambled when they arrive at the ESP.
The other way around and you're putting 3.3V comms into a 5V device. This isn't a problem per say, but it could definitely lead to problems. I suggest you use a bi-directional logic level converter which will transform a 5V command to the 3.3V ESP level, and back.
Your wiring between the Arduino and the ESP seems al right, but make sure TX~RX and RX~TX are connected, not TX~TX and RX~RX, but as I said above: use a bi-directional logic level converter.

From your code, I understand that you're setting the baud rate of the software serial pins as 115200. Software serial doesn't support speeds this high. You could set the baud rate of ESP8266 down to 9600 by using a USB to TTL converter and the AT command interface. Then you should try repeating this process using a baud rate of 9600 for the software serial. Or if you happen to have an Arduino Mega which comes with 4 serial ports, you can use the hardware serial pins which supports high speeds.


text:
Sleep and Wake Arduino according to LDR interrupt
I have to sleep the system in the night and have to wake the system in day time. I am using LDR to get input. LDR input is connected to interrupt pin 0 of Arduino Uno.
Here is my code.
#include <avr/sleep.h>
int led =13;
int triggerPin = 2;

void wakeUpNow()
{

}

void setup()
{
pinMode(triggerPin, INPUT);
pinMode(led, OUTPUT);
attachInterrupt(0, sleepNow, LOW);
}

void loop()
{
digitalWrite(led, HIGH);;
delay(1000);
digitalWrite(led, LOW);
}

void sleepNow()
{
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
attachInterrupt(0,wakeUpNow, RISING);
sleep_mode();
sleep_disable();
detachInterrupt(0);
}

Cannot we attach two function in a interrupt?
Edited
The following code works perfectly. I want to replace the conditional check with interrupt.
#include <avr/sleep.h>
int led =13;
int wakePin = 2;

void wakeUpNow()
{
delay(100);
}

void setup()
{
pinMode(wakePin, INPUT);
pinMode(led, OUTPUT);
//attachInterrupt(0, sleepNow, LOW);
}

void loop()
{
digitalWrite(led, HIGH);;
delay(1000);
digitalWrite(led, LOW);

if(digitalRead(wakePin)==LOW)
  sleepNow();

}

void sleepNow()
{
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
attachInterrupt(0,wakeUpNow, RISING); function
sleep_mode();
sleep_disable();
detachInterrupt(0);
}

I want to replace `
if(digitalRead(wakePin)==LOW)
  sleepNow()

with`
attachInterrupt(0, sleepNow, LOW);

Please let me know how I can do that.
Thank you.

Looks to me like you're attaching an interrupt and then immediately detaching it. Could you explain why?

After attach the interrupt, it goes to sleep. When it wake up from sleep, it detach from the interrupt.

I want to replace the conditional check with interrupt.

Why? If it is awake it might just as well be testing the pin as doing anything else.
If you make it an interrupt, in the ISR interrupts will be off. Then if you go to sleep it will never wake.
So, your current design is the correct one, except:
attachInterrupt(0,wakeUpNow, RISING); function

What is function doing there?

The function is not necessary. The normal interrupt automatically wakes up the system.  Is that so?

But we have to add the interrupt to wake up the system when LDR gives output high. Isn't it? Otherwise how will the system wake up?

Yes, you wake when the LDR goes high. But why do you want to have an interrupt when it goes LOW? It is already awake.


text:
Whether my board analog pins shorted? I see same input on all
I am puzzled. I just connected 3.3 V input to the Analog pin A5 of the Arduino UNO. On the script, I am reading all the input pins. Surprizingly, all the pins are giving voltage as that of A5 pin. This made me think whether all of them shorted?
code:
int a0_analogPin = A0;
float a0_val = 0;
int a1_analogPin = A1;
float a1_val = 0;
int a2_analogPin = A2;
float a2_val = 0;
int a3_analogPin = A3;
float a3_val = 0;
int a4_analogPin = A4;
float a4_val = 0;
int a5_analogPin = A5;
float a5_val = 0;

void setup() {
  Serial.begin(9600);           //  setup serial
  pinMode(a0_analogPin,INPUT);
  pinMode(a1_analogPin,INPUT);
  pinMode(a2_analogPin,INPUT);
  pinMode(a3_analogPin,INPUT);
  pinMode(a4_analogPin,INPUT);
  pinMode(a5_analogPin,INPUT);
  Serial.println("A0_val,A1_val,A2_val,A3_val,A4_val,A5_val");
}

void loop() {
  a0_val = analogRead(a0_analogPin)*5.0/1023.0;  // read the input pin
  Serial.print(a0_val);          // debug value
  Serial.print(",");
  a1_val = analogRead(a1_analogPin)*5.0/1023.0;  // read the input pin
  Serial.print(a1_val);
  Serial.print(",");
  a2_val = analogRead(a2_analogPin)*5.0/1023.0;  // read the input pin
  Serial.print(a2_val);
  Serial.print(",");
  a3_val = analogRead(a3_analogPin)*5.0/1023.0;  // read the input pin
  Serial.print(a3_val);
  Serial.print(",");
  a4_val = analogRead(a4_analogPin)*5.0/1023.0;  // read the input pin
  Serial.print(a4_val);
  Serial.print(",");
  a5_val = analogRead(a5_analogPin)*5.0/1023.0;  // read the input pin
  Serial.println(a5_val);
}

Board:

Serial Monitor:

you set all analog pins as digital inputs

@jsotola, analogRead configures the pin for ADC. Mainland, unconnected pins act like an antenna

@Juraj The problem is solved after I connected remaining to the ground. Thanks

Most of your analog pins are not connected to anything. In electrical engineering, that's called "floating". It means they have no reference to anything and thus their value can be anything.
Basically their value is determined by static electricity. Moving your hands near the pins or moving them away may be enough to change the value you read.
It could be that your "oscilloscope view" actually shows that nicely. One pin gets the voltage immediately (value 6) and through static electricity, the other pins slowly take that value as well (value 1, value 2, ...). Probably the steepest curve of those is closest to the pin that is high and the most shallow curve is furthest away. Your observations may vary depending on humidity and temperature, since that makes static electricity spread faster or slower.
Solution: don't let your pins float. Connect them to a defined value, e.g. ground if you want them to have a predictable value.

You are seeing crosstalk between the analog input channels. In the
datasheet of the microcontroller you can see the analog
input circuitry. See the capacitor labeled “CS/H”? This is
the “sample and hold” capacitor. Its job is to hold the voltage being
read while the ADC performs the conversion. When you measure channel A5,
you are charging this capacitor to 3.3 V. Then, when you switch to
a floating input, the capacitor has no path to discharge, and you end
up measuring the same voltage.
Actually, you do not measure exactly the same voltage. The reason is
that each input pin has a parasitic capacitance. When you switch from A5
to A0, the charge in CS/H splits between this capacitor and
the stray capacitance of the pin A0. Then, you switch to A1 and the
remaining charge is split between CS/H and the stray
capacitance of A1, and so on. Eventually, when you come back to A5, you
charge again CS/H to the full 3.3 V and the cycle starts
again. The net effect is that you are progressively moving charges
between the successive pins. This is why the curves look like
exponential relaxations, where each successive pin charges more slowly
than the preceding one.
The solution, as already written in other answers, is to avoid leaving
the pin floating. The datasheet recommends making sure the connected
source has an impedance no larger than 10 kΩ.


text:
serially parse integer after serially read
I want to write below code but I don't know where I doing wrong, so please help me solve this issue.
Serially read some text like number then I want to serially parse integer value into some variable and then my next task is if I wrote as text then serially read string and should save in some other variable...
char c;
String s;
long num1=0;
long num2=0;
void setup()
{
  Serial.begin(9600);
  Serial.println("Let's start: ");
}
void loop()
{
  if(Serial.available()>0)
  {
    delay(5);
    c = Serial.read();
    s += c;
  }
  if(s.length()>0)
  {
    if(s=="n")
    {
        if(num1==0)
        {
        Serial.println("write number: "); //serially print
        num1=Serial.parseInt(); // not serially print
        if(num1>0)
        Serial.print(num1);
        }
        if(num1>0)
        {
        Serial.println("write second number: ");
        num2=Serial.parseInt();
        if(num2>0)
        Serial.print(num2);
        }
    }
    s="";
  }
}

And what's your problem? The sketch works fine : You send n12 33 and the sketch detects two numbers 12 and 33.

Once num1 != 0 it never goes back to 0 so you'll see "write number" only once after reset

There is serially print as "Let's Start".. done.
After gives input "n", Print as "write number".
But after not read any integer value(parseInt).

There's no dialog. After entering only an "n"  your logic is broken: The "n" is removed from s and your code works as programmed.