text:
Controlling a Stepper Motor - sending to specific positions on a 'buttonPushCounter ==' cue, forwards and backwards
I am working on a project using an Arduino control a Stepper Motor. The motor drives a lead screw which moves coloured filters to specific positions along a linear track - forwards and backwards.
The movements are triggered by another device that counts its revolutions (using a sensor. The Arduino reads the inputs and activates the motor on specific revs ie. at 10 move 70mm forwards, at 30 move 70mm backwards.
I can control the Stepper to execute precise moves repeatedly one after another, independently of the counter. I can link the Arduino to the counter and switch on/off an LED at specified counts. But when I try to run the motors from the counter, it's triggered but only moves in tiny discontinuous steps, and only goes one way. Here is that Sketch below. Any help very welcome. Thanks.

// this constant won't change:
const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 7;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include <AccelStepper.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void forwardstep1() {
  myMotor->onestep(FORWARD, DOUBLE);
}
void backwardstep1() {
  myMotor->onestep(BACKWARD, DOUBLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1);

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz
  TWBR = ((F_CPU / 500000l) - 16) / 2; // Change the i2c clock to 400KHz
  Astepper1.setAcceleration(6000.0);
  Astepper1.setMaxSpeed(600);
  Astepper1.setSpeed(600);    // rpm
  //  while (switchIsOff) {
  //turn servo one direction -
  //tell servo this is 0
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(buttonPushCounter);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;

  if (buttonPushCounter == 10) {
    digitalWrite(ledPin, HIGH);
    Astepper1.moveTo(600);
    Astepper1.setSpeed(600);
    Astepper1.run();
  }

  if (buttonPushCounter == 30) {
    digitalWrite(ledPin, LOW);
    Astepper1.moveTo(200);
    Astepper1.setSpeed(600);
    Astepper1.run();
  }

  }
}

I think the problem is that Astepper.run() doesn't wait for the motor to reach it's target position. It is supposed to be called very frequently and will do a step, when it's the right time to, and returns when it is not. In your code it moves exactly until the counter is incremented the next time, because then you don't call the run method anymore. I'm currently not sure. Will write an answer, when I have time to check the source code

Thanks. Your description of the fault makes sense to me. As you point out blocking would be a problem as I need the counter to continue to be registering while the movement is being executed. I've revised the script as you suggest - inside the loop but outside the if statement - have I done as you meant? But the same problem occurs - the motor advances in single steps.

// this constant won't change:
const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 7;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include <AccelStepper.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void forwardstep1() {
  myMotor->onestep(FORWARD, DOUBLE);
}
void backwardstep1() {
  myMotor->onestep(BACKWARD, DOUBLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1);

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz
  TWBR = ((F_CPU / 500000l) - 16) / 2; // Change the i2c clock to 400KHz
  Astepper1.setAcceleration(6000.0);
  Astepper1.setMaxSpeed(600);
  Astepper1.setSpeed(600);    // rpm
  //  while (switchIsOff) {
  //turn servo one direction -
  //tell servo this is 0
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(buttonPushCounter);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // save the current state as the last state, for next time through the loop
    lastButtonState = buttonState;

    if (buttonPushCounter == 10 ) {
      digitalWrite(ledPin, HIGH);
      Astepper1.moveTo(20000);
      Astepper1.setAcceleration(6000.0);
      Astepper1.setSpeed(600);
      //Astepper1.setSpeed(600);
      Astepper1.run();
    }
    Astepper1.run();//this command moved out of an 'if' statement, but still within the 'loop'

    if (buttonPushCounter == 30) {
      digitalWrite(ledPin, LOW);
      Astepper1.moveTo(200);
      Astepper1.setSpeed(600);
    }
    Astepper1.run();//this command moved out of an 'if' statement, but still within the 'loop'

  }

There are several run-like methods in the AccelStepper library.
The one you are using, run(), is intended to be called at EVERY pass through loop(), and it will only cause a step if one is necessary, based on the internal state of the library (i.e., current position, target position, acceleration profile, etc.) It is safe to call so often -- it will determine itself if there is any motion needed.
You could move the run() call to a place inside loop(), but outside of any if statements.
Alternatively, there is a runToPosition() function, which is blocking -- it will stop all execution of your code until the stepper is at the target position. This would be fine for your current code as posted, but if you wish to monitor the revolution counter also, then this would not be the best option to take.


text:
How to add numbers to a position when controlling a seven-segment display
I'm recently having a hard time with my Arduino project. I'm trying to control a seven-segment display (it has a microcontroller on it) with an encoder, and I'm trying so that everytime I rotate the encoder it adds 5 to the number on the display. What am I doing wrong here???
P.S: there are some parts that are for controlling relays, they are not related to the issue. I removed them on this thread on purpose.
Code (without any attempts to change the added amount to the display):
#include <RotaryEncoder.h>
#include <TM1637Display.h>

// Module connection pins (Digital Pins)
#define CLK 10
#define DIO 11

// Setup a RoraryEncoder for pins A2 and A3:
RotaryEncoder encoder(A2, A3);

// The amount of time (in milliseconds) between tests
#define TEST_DELAY   1000

TM1637Display display(CLK, DIO);

void setup()
{
    Serial.begin(57600);
    Serial.println("SimplePollRotator example for the RotaryEncoder
    library.");
}

// The Interrupt Service Routine for Pin Change Interrupt 1
// This routine will only be called on any signal change on A2 and A3:
//exactly where we need to check.
ISR(PCINT1_vect) {
    encoder.tick(); // just call tick() to check the state.
}

// Read the current position of the encoder and print out when changed.
void loop()
{
    static int pos = 0;
    int newPos = encoder.getPosition();
    if(newPos > -1)
    {
        if (pos != newPos) {
            Serial.print(newPos);
            Serial.println();
            pos = newPos + 4;
            display.setBrightness(0x0f);
            // All segments on
            // Show decimal numbers with/without leading zeros
            display.showNumberDec(newPos, true); // Expect: 1234
            delay(100);
        }
    } // if
} // loop ()
// The End

You stated what you want it to do, but what does it actually do instead?

It instead just skips by one and not by 5 (the code which I published right here is without the attempt to do this

I'd mutliply the pos by five. So display.showNumberDec(pos*5, true). Then you need only this single like instead of the whole if statement (all 10 lines).

In your code, you call:
newPos = encoder.getPosition();

which grabs the absolute position of the encoder. When you rotate this one step, the value of newPos goes up (or down) by one.
Then, you make pos = newPos + 4, which simply adds 4 to the value that is going up or down by one step at a time.
newPos: 1    pos: 5
newPos: 2    pos: 6
newPos: 3    pos: 7
newPos: 4    pos: 8
newPos: 5    pos: 9

Instead, it sounds like you wish the display to always read 5 times the encoder position. If so, then you should write pos = newPos*5.
newPos: 1    pos: 5
newPos: 2    pos: 10
newPos: 3    pos: 15
newPos: 4    pos: 20
newPos: 5    pos: 25

Then, when you write to the display, you do so as:
display.showNumberDec(newPos, true); // Expect: 1234

But newPos is not the newly calculated value. Instead, call
display.showNumberDec(pos, true); // Expect: 1234

I think I tried that and to no avail, trying again now.
EDIT: Nope, still counts one at a time.

Well, you also need to write the correct value to the display: display.showNumberDec(newPos, true); tries to write newPos, but newPos is the encoder position. pos is the calculated display value. I will update my answer.

Thanks! It woroks like a charm now.

This is a classic debugging problem. You think you wrote your code to do one thing and what you wrote actually does something else. You need to add print statements that display the values you are using and then think through each line of your code, writing down the values of your variables at each step and pretending you're a computer. Look at the code that's written, and calculate the results of each line, not what you expect to happen. It is made much harder on microcontrollers where you don't have a debugger to work with.

Good eye Jose, catching the fact that the OP is displaying the encoder position rather than the calculated value. (Voted)

source: Stack Exchange

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

sort: votes


text:
Sending data from Arduino Mega to nodeMCU using serial (Multiple sensor data) & upload to firebase
Im working in a project where i have to deal with multiple sensor data.

BME 280
WindSpeed Sensor
Water level Sensor x 10
Soil moisture x 5
Soil pH sensor x 2

i have found this code for both arduino uno and nodemcu esp8266
//Arduino code
#include <SoftwareSerial.h>
SoftwareSerial s(5,6);

void setup() {
s.begin(9600);
}

void loop() {
int data=50;
if(s.available()>0)
{
 s.write(data);
}
}

//for nodeMCU
#include <SoftwareSerial.h>
SoftwareSerial s(D6,D5);
int data;
void setup() {
s.begin(9600);
Serial.begin(9600);
}

void loop() {
  s.write("s");
  if (s.available()>0)
  {
    data=s.read();
    Serial.println(data);
  }
}

In this code here send 1 value from arduino uno to nodeMCU...
but if i want to send 10 values(float temperature,humidity,pressure,waterlevel,windSpeed,windDirection) from mega to nodeMCU using serial, how to do that using serail.

As i know nodemcu still not  work as a slave device . Maybe this support will be available in the future but if you test it and it work . This how to do it
Let's assume you have tow dat to send cast them to string , concatenated characters of string_data1+string_data2 then send theme via uart communication to the nodemcu .
Now in the nodemcu take the string and decoding  [split] string to string 1 and string 2 and cast theme again to any var type you want.
If this method seems so hard to you or your level in coding is still under development use some library exist that can do the work for you i recommend. The easytransfer library by madsci1016 in github enter link description here.

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


text:
`LOW` being defined as `0` and `HIGH` being defined as `1` - is this a part of external specification?
Arduino.h defines LOW as 0x0 and HIGH as 0x1. Does the Arduino API intend to expose that fact? Does it guarantee that this will always be that way?
In other words, what is the intended purpose of these manifest constants: LOW and HIGH?

Is this purely cosmetic mnemonics added as an alternative for 0/1 and false/true, for those who like LOW/HIGH better?
Or is this an attempt to abstract/isolate the user's source code from the actual representation of LOW and HIGH (e.g. in case the representation changes in the future)?

The underlying reason for this question is to figure out whether code like
digitalWrite(some_pin, true);
digitalWrite(some_other_pin, !digitalRead(some_other_pin));

is a good programming practice. (If LOW and HIGH are there to abstract the user's code form their actual values then code like that is definitely a bad programming practice.)

Couldn't it be both?

@jose can u c: It could. But the truly critical part here is whether the answer to the second point is "yes".

Looking at the precursor to Arduino framework, WConstants.h seems to have a commented out 0xFF as a potential definition of HIGH, so point 2 may be the case...

The underlying reason for this question is to figure out whether code like
digitalWrite(some_pin, true);
digitalWrite(some_other_pin, !digitalRead(some_other_pin));

is a good programming practice. (If LOW and HIGH are there to abstract the user's code form their actual values then code like that is definitely a bad programming practice.)

Strictly speaking, no, that is not good programming practice.
digitalRead() returns an int. digitalWrite() expects an int.  Using ! converts the int into a bool and then it's promoted back to an int again.
In fact, the "next gen" Arduino core API changes HIGH and LOW from a simple int to an enum - and that struggles with casting through bool like that:
typedef enum {
  LOW     = 0,
  HIGH    = 1,
  CHANGE  = 2,
  FALLING = 3,
  RISING  = 4,
} PinStatus;

You can see the problems that causes here.


text:
Is it possible that function will get a parameter that can be int OR char?
I'm trying to create a function that enters a key/value into a JSON file.
But, since value can be an int or char, I don't want to create 2 functions for each type.
Is there a way ?
void setValue(char *key, char* value){
        StaticJsonDocument<512> tempJDOC;
        tempJDOC[key]=value;
}

EDIT1
#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

class myJSON
{
private:
bool _useSerial=false;
char _filename[30];

public:
char *ver="myJSON_v1.1";
myJSON(char *filename, bool useserial=false);

bool file_exists();
bool file_remove();
bool format ();
bool FS_ok();

void saveJSON2file(JsonDocument& _doc);
void readJSON_file(JsonDocument& _doc);

void printJSON(JsonDocument& _doc);
void PrettyprintJSON(JsonDocument& _doc);

const char *getValue (char *key);

template <class T>
void setValue(const char *key, T value);
//void setValue(const char *key, char *value);

};
#endif

EDIT2
#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

#define LOG_LENGTH 4
#define DOC_SIZE 512

template <class T> // . <---- line added
class myJSON
{
private:
bool _useSerial=false;
char _filename[30];

public:
char *ver="myJSON_v1.1";
myJSON(char *filename, bool useserial=false);

bool file_exists();
bool file_remove();
bool format ();
bool FS_ok();

void saveJSON2file(JsonDocument& _doc);
void readJSON_file(JsonDocument& _doc);

void printJSON(JsonDocument& _doc);
void PrettyprintJSON(JsonDocument& _doc);

const char *getValue (const char *key);
void removeValue(const char *key);
// void setValue(const char *key, char *value); <--- comment out
void updateArray(char* array_key, int val);
void printFile();
void setValue(const char *key, T value); <---- Added

};
#endif

and in .cpp file :
void myJSON::setValue(const char *key, T value){
        StaticJsonDocument<512> tempJDOC;
        myJSON::readJSON_file(tempJDOC);
        tempJDOC[key]=value;
        myJSON::saveJSON2file(tempJDOC);
        myJSON::PrettyprintJSON(tempJDOC);
}

how will the code that calls the function decide if it's setting a number or a string?

Um... The title and the text of your question refers to char parameter. The code seems to suggest that you are actually talking about char * parameter. So, what is it? char or char *? These are two very different things. You have to edit your question and clarify that.

@AnT - you are right, but it is commented out at this point since as juraj and edgar suggested to use template - so I don't need to use int nor char

If you needed to pass either int or char you wouldn't need to do anything at all. You don't need any "templates". Just one int version of the function by itself would cover all cases, including char, since in C and C++ char is just a small integer type. So, again, why are you asking this question? What is the problem with char that triggered it? Again, the code you provided implies that you need char * (or, better, const char *). Not char, but const char *. You need to reflect it in your question, since currently neither the question not the accepted answer make sense.

And when you use template, you are using int or const char *, albeit you are doing it implicitly. The compiler does it for you. But again, it is a matter of int and const char *, not a matter of int and char as you stated in your question. char is completely irrelevant here.

my intention using this function is to be able to set and int or char values into a JSON that saves at the end to file. What @Juraj and Edgar suggested, to use templates, solved that.

"Solved" what problem? What is the original problem? In your question you are talking about writing two functions - for int and char - and call this a problem you want to solve. But why didn't you just simply use one function - int version - for both types? No templates necessary. Why did you decide that there is a "problem" here in the first place?

In C++ you can create a template function. (The ArduinoJson [] operator is a template too.)
#include <ArduinoJson.h>

StaticJsonDocument<512> tempJDOC;

template <typename T>
void setValue(const char *key, T value){
  tempJDOC[key] = value;
}

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

  setValue("a", 5);
  setValue("b", "xyz");

  serializeJson(tempJDOC, Serial);
}

void loop() {
}

the compiler will create function based on this template for every different type you use as second parameter in your sketch

When trying to take such function and put it inside a library ( using template as noted here ), i get an error. how can it be done?

by "put it inside a library", you mean using it as class's method?

a method that uses template inside a class

add the code of the class to the Question. is it a class with separate .h and .cpp files? do you have the template<> part of function declaration in .h too?

pasted .h file inside my Q

why did you use ? it should be template <typename T>

I try to follow example 2 in : https://www.programiz.com/cpp-programming/templates

see EDIT2 in my Q

you want a class with a template function, not a template class https://stackoverflow.com/questions/972152/how-to-create-a-template-function-within-a-class-c

Yes I know... this is the closest I could find

The short answer is “no, it's not possible”. You will have to use two
different functions. These two functions can share the same name, using
function overloading. You can even have the compiler
write these functions for you, based on a template you provide, as shown
in Juraj's answer. These language features help provide the illusion of
there being a single function. But it's just an illusion, albeit a
useful one that helps with program readability. At the fundamental
level, you still have two different functions.

Edgar - thank you for explaining and usefull link. But I do not understand how Juraj's answer ( using template ) creates/ duplicates the function for other types

@Guy.D: Do a search for “C++ templates”. In short, every time you call setValue() with a new value type, the compiler creates a new version of the setValue() function suitable for that specific type.

I have in my answer: "the compiler will create function based on this template for every different type you use as second parameter in your sketch"

@EdgarBonet I use you link to try to implement this function inside a lib I make ( called myJSON, as you can see in edit 1 and edit 2 ). I'll appreciate your help once more


text:
the code and the actual output didn't match
i want to make the stuff, which the output is written from the analogread, but when the A3 == HIGH, the output pin 9 is used, but when the A3 == LOW, the output pin 10 is used, and when i simulate it on proteus, it seems not the same as i mean, what's wrong with the code, please need your help.
  int hasil
  int reado;
  int z;
  int baca;
  bool en = false;
  void setup() {
  // put your setup code here, to run once:

  TCCR1A = 0b00100010;
  TCCR1B = 0b00011001;
  TCCR0A = 0; TCCR0B = 0;
  ICR1 = 100000;//disable millis, delay and mciroseconds function
  //disable millis, delay and mciroseconds function

   // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(A2, INPUT); pinMode(A3, INPUT);
  pinMode(9,OUTPUT); pinMode(10,OUTPUT);
  }

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

 hasil = analogRead(A2);
 baca = digitalRead(A3);
 for (z=0; z<=hasil; z++)
 reado = map (hasil, 0, 255, 0, ICR1);
 if (hasil > 30 && baca == HIGH)
 {analogWrite(9,hasil); analogWrite(10,0);}
 else if (hasil >30 && baca == LOW)
 {analogWrite(9,0); analogWrite(10,hasil);}
 else if (hasil<30)
 {analogWrite(9, 0);
 analogWrite(10, 0);}}

analogWrite starts the PWM signal. you don't let it run and start it again and again. so instead of |_|_|_ you get ||||||

so how to do pwm properly sir @Juraj

analogWrite will start PWM signal. and then call analogWrite again only if you want to change it or stop it

Re “bool en = false;”: Yes, we did figure out that your variable names are not in English, no need to write it explicitly.

You wrote:

when i simulate it on proteus, it seems not the same as i mean

The attached picture is not very clear, but it seems to me that it's
doing exactly what you asked for: a PWM output that switches between two
different output pins. The program should work as expected, with only a
few caveats. Let me comment it in some detail:
ICR1 = 100000;

Here you are setting ICR1 to 34464 (i.e. 100000 modulo
216). This is likely not what you mean...
Serial.begin(115200);

There is no point in initializing the serial interface if you are not
going to use it.
for (z = 0; z <= hasil; z++)
    reado = map(hasil, 0, 255, 0, ICR1);

There is no point in calculating many times the exact same value.
Actually, there is no point in calculating it even a single time, since
you are not using the result anywhere in your program.
analogWrite(9, hasil);

Here you are setting the duty cycle to some number between 31 and 1023.
Given that the top value of the timer is 34464, the actual duty cycle
will always be less than 3%. This is the reason why it looks like a
series of narrow spikes on the virtual scope.
But maybe what you really meant is
reado = map(hasil, 0, 1023, 0, ICR1); // note: 1023, not 255
analogWrite(9, reado);

I would not recommend using analogWrite() with a non-standard top
counter value. There is a special case handled in analogWrite() where,
if the argument happens to be 255, you get instead a
digitalWrite(pin, HIGH). This is most likely not what you want. Now
that you started controlling the timer with raw IO access, you should
continue this way.
else if (hasil < 30)

Did you consider what the program should do if hasil happens to be
exactly 30? None of the if/else cases would then match. You probably
meant
else if (hasil <= 30)

but, as suggested by user11249082's answer, a plain else is the best
way to ensure you did cover all possible cases.

very brief explanation sir, but still don't know how to make the output the same as analog input, would you like to teach me how to do it?

@johncaren: Fix the issues I showed you, then try again.

The problem as i can see exist in the if else statements . You use multiple else if statements but in the end you must end it with else statement .
Use the “if/else if” if you need to choose either one or none of a series of options. You could write the above program using separate if statements such as show below but the if/else if approach is cleaner and better indicates that the program should choose either one or none of the options
Here how you do it
If (){}....
Else if (){}.....
Else if(){} ......
Else{}
here this can help you enter link description here

thnaks sir, i'll try it


text:
Cannot make LCD & Gyro work together
I'm new to this so there are some poor methods in my code when I try to introduce the LCD into the loop. My issue is that the LCD delay and the servo delay are interfering with each other. How can I isolate them? I like the 50ms response for the servo. But I would like maybe a 200ms refresh for the LCD. But in their current state they are giving a very odd response if I have them both in the loop. The servo is spinning slower as though it's adding both delays. If I disable the LCD it all goes back to normal. Any ideas? Could someone please show me the correct method so I can expand in the future? Thanks!!!!
I've got this so far:
#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

//SERVO
#include <Servo.h>
Servo microservo1;
int servo_pin = 8;

//MAPPED VALUES
int16_t AcXmapped, AcYmapped, AcZmapped;

//LCD
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
//initializes the library

void setup(){

  //SERVO SETUP
  microservo1.attach ( servo_pin );

  //WIRE SETUP
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);
  Serial.println("Transmission Line Initializing");
  delay(350);
  //print("3"); print("2"); print("1");
  Serial.println("3");
  delay(1000);
  Serial.println("2");
  delay(1000);
  Serial.println("1");
  delay(1000);

  //LCD SETUP
  lcd.begin(16,2); //setup LCD number of columns and rows
  digitalWrite(9,1); //can either go 0 --> 1 or LOW --> HIGH || turns LCD on or off ||
  analogWrite(6,70); //contrast setting for the text on the LCD
}

void loop(){

  //WIRE LOOP
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print(" | AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  //Serial.print(" | Tmp =  "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);

  //MAPPING the values from e.g. AcX to AcXmapped so they're better values for servo control.
  //set the AcX inside the map to negative if you want to invert the rotation of the servo.
  AcXmapped = map (AcX, -17000, 17000, 0, 180); //ROLL
  AcYmapped = map (AcY, -17000, 17000, 0, 180); //PITCH
  AcZmapped = map (AcZ, -17000, 17000, 0, 180); //YAW

  //SERVO LOOP
  microservo1.write(AcYmapped);
  //50 ms response between movements
  delay(50);

  //LCD LOOP
  lcd.setCursor(0,0); //set the cursor to (0,0)
  lcd.print(AcYmapped);
  delay(50);

  //EXTRA LCD
  lcd.noAutoscroll(); //turns off autoscroll
  lcd.clear(); //clears the screen for the next loop

}

First upload the msg errors you've get .
Second the lcd can't display values in realtime because when the gyroscope move the arduino blocking the lcd and reading the data from gyroscope because you using no scheduling coding.
I recommend you to use millis  instead of delays and use  multitasking code like freertos .

I fixed the error message BUT (bracket issue) my code is still giving me trouble. My delays are combining between the servo and the LCD. Do you know how I can isolate them so that I can give them both their own delay?

Use millis() if you think realtime data is necessary  . I noticed that you use lcd.noautoscroll() function under the extra lcd comment which is not necessary because the lcd by default doesn't scroll the characters. So try to delete that function . Now first try to delete all the delay and run your code then watch how the system behaves . Actually the servo take it's own time when it moves . During the movement of servo the arduino blocks every thing until the servo reach the desire angle then execute the rest in the loop .

the servo in this question is a hobby servo .... it is non-blocking because there is no position feedback ..... the code simply changes the PWM signal that is being sent to the servo ... the servo does the motion to the desired angle automatically

Don't use delay() at all. You need to refactor your code to record the value of millis() at the beginning of a time interval and then wait until the new value of millis() is greater by the desired interval. Do a google search on "Arduino blink without delay" for articles that discuss this coding technique. It's a fundamental of programming for a single-threaded microcontroller like the Arduino, and something you must learn to do if you're going to write anything of any complexity for the platform.


text:
No ttyACM0 with Pro Micro on Ubuntu 18.04
I am trying to determine the dev path of a USB keyboard running an Arduino Pro Micro on my Ubuntu 18.04 system. The files /dev/ttyACM0 and /dev/ttyUSB0 do not exist.
When I run dmesg I get:
[  410.770931] usb 3-3: new full-speed USB device number 3 using xhci_hcd
[  410.962180] usb 3-3: New USB device found, idVendor=feed, idProduct=3060, bcdDevice= 0.01
[  410.962184] usb 3-3: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[  410.962187] usb 3-3: Product: Dactyl-Manuform (5x6)
[  410.962189] usb 3-3: Manufacturer: tshort
[  410.962191] usb 3-3: SerialNumber: 0
[  411.006440] input: tshort Dactyl-Manuform (5x6) as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.0/0003:FEED:3060.0008/input/input27
[  411.063192] hid-generic 0003:FEED:3060.0008: input,hidraw0: USB HID v1.11 Keyboard [tshort Dactyl-Manuform (5x6)] on usb-0000:11:00.3-3/input0
[  411.089097] input: tshort Dactyl-Manuform (5x6) Mouse as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.1/0003:FEED:3060.0009/input/input28
[  411.147172] input: tshort Dactyl-Manuform (5x6) System Control as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.1/0003:FEED:3060.0009/input/input29
[  411.147297] input: tshort Dactyl-Manuform (5x6) Consumer Control as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.1/0003:FEED:3060.0009/input/input30
[  411.147395] hid-generic 0003:FEED:3060.0009: input,hidraw1: USB HID v1.11 Mouse [tshort Dactyl-Manuform (5x6)] on usb-0000:11:00.3-3/input1

Dactyl-Manuform is the keyboard so it seems to recognize the device. The command lsusb returns several usb devices. The entry with no title is the keyboard (based on doing watch lsusb):
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 003: ID feed:3060
Bus 003 Device 002: ID 045e:02d1 Microsoft Corp. XBOX One Controller for Windows
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 002: ID 1e7d:2c2e ROCCAT
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

I have installed arduino and arduino-core from the official repos.
However, I still cannot get a ttyACM0 or ttyUSB0 to appear, and in the Arduino IDE the "Serial Port" option is greyed out (even when using sudo).
What can I check for to either 1) get the ttyACM0 file to exist for my Arduino device or 2) find some other dev port to use as the serial port?

What makes you think it should have a CDC/ACM endpoint at all?

A Pro Micro will only give a /dev/ttyACMx device node if the firmware installed on it creates a CDC/ACM interface.  That device obviously is running custom firmware which only provides the interfaces that the manufacturer wants to provide - in this case keyboard and mouse interfaces.
To use it as an Arduino you will first have to install the Arduino bootloader. That will then remove the existing manufacturer firmware, and you will have to write your own to make it act as a keyboard again.


text:
Implementing sending from N and recieving from N with FreeRtos and RF24 radio module
I'm trying to make my first chip send data through a nrf24 radio pipe and the other listen to it. After the first data is received it should switch to transmit mode and itself transmit new data. The main goal of all of this is to implement the raft protocol with at least 3 chips participating. So the requirements would be to have each chip listening all the time and to have it stop listening at random intervals to send a broadcast message to all other chips. Basically the communication is never between just two chips but always one to many. I've come across tutorials such as http://forum.arduino.cc/index.php?topic=421081 but it always comes down to a stable Master vs Slaves state while my situation is more dynamic.
This is my current task. The listener works perfectly until the first received message when it opens a writing pipe. It then does not write and does not go back to listening.
void test_Task(void *pvParameters){

    printf("some init\n");
    bool hastoSend = false;

    radio.openReadingPipe(1, address);
    while(1){

        radio.startListening();
        if (radio.available()) {
            radio.read(&rx_data, sizeof(rx_data));

                if (rx_data[1] == 101){
                    printf("Received message: %d\n", rx_data[1]);
                    hastoSend = true;
                    printf("%d\n",rx_data[0]);
                    //int someint = *((int*)pvParameters);

                    // turn on led1
                    write_byte_pcf(led1);
                    vTaskDelay(pdMS_TO_TICKS(200));
                    write_byte_pcf(0xff);
                }

        }else{
                if (hastoSend){

                    printf("I need to send a message!\n");
                    printf("sending a message\n");
                    radio.openWritingPipe(address2);
                    radio.stopListening();
                    transmit_nrf24();
                    radio.printDetails();
                    hastoSend = false;
                    radio.openReadingPipe(1, address);

                }
        }

    }

}

This is my radio setup:
static inline void setup_nrf() {

    uart_set_baud(0, 115200);
    gpio_enable(SCL, GPIO_OUTPUT);
    gpio_enable(CS_NRF, GPIO_OUTPUT);

    // radio configuration
    radio.begin();
    radio.setChannel(channel);
    radio.setAutoAck(false);

}

For testing purposes the messages being transmitted come from my other device which is just a manual transmitter. What would solve my problem is a way to completely reset the radio when the first message is received so that the pipes do not bother each other and the device could then be re-initialised as a transmitter.
Cheers!

what is chip?

Solved it by simply repeating
gpio_enable(SCL, GPIO_OUTPUT);
gpio_enable(CS_NRF, GPIO_OUTPUT);

// radio configuration
radio.begin();
radio.setChannel(channel);
radio.setAutoAck(false);

before opening a new writing pipe.


text:
Questions about HMC5883L library
I'm studying the structures of libraries currently. I want to learn how good programmers write code, what are the strategies they follow, the art the programmer followed to develop the library. And how important the library should be written in the well arranged form.
But as I'm go back and forth into the library over and over, I really need to understand, the way the programmer followed, and the reasons behind the applied strategy.
The example I'm studying now is the HMC5883L and how the programmer used the Wire library to manage the developing the library. This should be quite easy for experienced programmers, but I'm really studying the concepts, strategies .. etc.
As I'm going over and over I have different questions, so to start this discussion I want to begin with this question about the programmer writing two very similar functions that pretty much do the same thing.
// Read byte to register
uint8_t HMC5883L::fastRegister8(uint8_t reg)
{
    uint8_t value;
    Wire.beginTransmission(HMC5883L_ADDRESS);
    #if ARDUINO >= 100
        Wire.write(reg);
    #else
        Wire.send(reg);
    #endif
    Wire.endTransmission();

    Wire.requestFrom(HMC5883L_ADDRESS, 1);
    #if ARDUINO >= 100
        value = Wire.read();
    #else
        value = Wire.receive();
    #endif
    Wire.endTransmission();

    return value;
}

// Read byte from register
uint8_t HMC5883L::readRegister8(uint8_t reg)
{
    uint8_t value;
    Wire.beginTransmission(HMC5883L_ADDRESS);
    #if ARDUINO >= 100
        Wire.write(reg);
    #else
        Wire.send(reg);
    #endif
    Wire.endTransmission();

    Wire.beginTransmission(HMC5883L_ADDRESS);
    Wire.requestFrom(HMC5883L_ADDRESS, 1);
    while(!Wire.available()) {};
    #if ARDUINO >= 100
        value = Wire.read();
    #else
        value = Wire.receive();
    #endif
    Wire.endTransmission();

    return value;
}

Update:
Actually, the programmer used the 1st version only in the HMC5883L.begin(); function, but why?
if ((fastRegister8(HMC5883L_REG_IDENT_A) != 0x48)
|| (fastRegister8(HMC5883L_REG_IDENT_B) != 0x34)
|| (fastRegister8(HMC5883L_REG_IDENT_C) != 0x33))
{
return false;
}

Everything else in the library used the 2nd version.
So, basically the two functions are to read a specified register in the HMC5883L, my questions:

what is the difference? I know that there's an extra care has been put into the second function, but why ?
Is it so important ?
Are there situations that require any version of the functions ?

There has never been a "fast" way to do i2c, it is a myth. There are many wrong ways to do i2c.

Yes, I'm still learning how i2c is actually working, and to deal with i2c chips.

TBH the second version of the function is trash. The first version is (almost) the right way to do it.  There's stuff in the second version that really shouldn't be there. There is absolutely no reason why the creator of the library created that second function.

It "waits" for data to be available, when that data will be available the moment requestFrom() completes - so is completely redundant
It makes a spurious beginTransmission() call right before the requestFrom() call. beginTransmission() is only for writing, not for reading. It's pointless there.

However:

Both functions do an endTransmission() after the receiveFrom(), which makes no sense - the endTransmission() goes to balance a beginTransmission() only - not a receiveFrom().  receiveFrom() is a completely self-contained function that needs no other handling.

This library is probably not a good one to study for learning how to use the Wire library. It contains code that indicates the author themselves didn't have a proper grasp of the workings of the library.

Thank you so much dude ! I mean you ARE the man seriously :) I'm really happy that my points of question are considerable and important. I would try to develop my library too, it's for me about grasping more and more skills, information and how to learn the art of programming. I need to forget about my old codes and libraries :)

But if I got some more questions, should I get back here. Or remove the choose the answer until I finish discussion on the topic?

If you have new questions, then ask new questions. Keep it "atomic" :)

all HMC5883L libraries for Arduino have it like this :-) (including Adafruit)

They all copied off each other then :)  I have a DTWI one for chipKIT that doesn't do it that way - but then DTWI doesn't work the same as Wire...

@Juraj Not all of them. This one has 19 stars and is very nice: https://github.com/sleemanj/HMC5883L_Simple

@Jot Thanks for the link :)

I really discovered just now how to read from a specific register from the HMC5883L, I thought I can read the 1st register and the automatic pointer of the chip would take me to the next one without ending the Wire transmission and starting a new one to read that register, but it turns out it actually that way, I have to do two completely separate wire transmission. One for specifying the register to be read and the second one for reading that register.

Correct. During initialization it is no problem to read or write a single byte. When x,y,z data is required while running, then it might be good to read those 6 bytes together.

There is no "fast" way to do i2c. If you already use the "fast" functions in your code, then you can make it a inline call to readRegister8.
The function below reads a byte from the HMC5883L.
When the HMC5883L is not connected, the Wire.read() returns -1. That will be converted to a return value of 0xFF.
// Read byte from register
uint8_t HMC5883L::readRegister8(uint8_t reg)
{
    uint8_t value;
    Wire.beginTransmission(HMC5883L_ADDRESS);
    Wire.write(reg);
    Wire.endTransmission();    // add parameter 'false' for repeated start

    Wire.requestFrom(HMC5883L_ADDRESS, 1);
    value = Wire.read();

    return value;
}

But doesn't it need Wire.endTransmission(); after value = Wire.read();?

No, never, only when writing data. See: https://www.arduino.cc/en/Reference/WireEndTransmission It is one of the bugs in the code that Majenko mentioned in his answer.

OK, I'm moving around the i2c area, done some work with the Wire library and tested some lines about reading each register. Next, I should do a similar robust i2c code that is working with similar management of data in the ISR and locking each mode until it's ready.

Yep, you're right, I should put false between the write / read operations. Found this one the link: **If true, endTransmission() sends a stop message after transmission, releasing the I2C bus.
If false, endTransmission() sends a restart message after transmission**


text:
Arduino Port randomly changes whenever I punch correct RFID tag
I was working on an Electronic Door Lock/Unlock system using Arduino Uno and RFID Reader/Tags on Ubuntu 18.04.02 lts.
Now the problem is that whenever I punch-in the correct RFID tag to the RFID reader, the Serial Monitor stops working and I notice that the "Port" value under (tools>Port) has also changed or even got un-selected.
Like, before my Port = /dev/ttyACM0
then whenever I punch in the correct tag, Port value either becomes None or gets changed to (= /dev/ttyACM1)
Also, after every 2nd or 3rd upload, I get the error message as /dev/ttyACM0: Permission Denied
My code is as follows:
#include <Servo.h>
#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 10
#define RST_PIN 9
#define ledPin1 A0
#define ledPin2 A1
#define Buzz A2
Servo servo;
int pos = 0;
MFRC522 rc522(SS_PIN, RST_PIN);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  SPI.begin();
  rc522.PCD_Init();     // Initialize card reader
  pinMode(A0, OUTPUT);
  pinMode(A1, OUTPUT);
  pinMode(A2, OUTPUT);
  servo.attach(3);
  servo.write(0);
  Serial.println("Scan the Card:");
}

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

  // check if any card is present and also scan only one card if multiple are present
  if(!rc522.PICC_IsNewCardPresent() || !rc522.PICC_ReadCardSerial())  return;

  // check if the type of the card is what we need and not any other card.
  MFRC522::PICC_Type type = rc522.PICC_GetType(rc522.uid.sak);
  if(type!= MFRC522::PICC_TYPE_MIFARE_MINI &&
     type!= MFRC522::PICC_TYPE_MIFARE_1K &&
     type!= MFRC522::PICC_TYPE_MIFARE_4K) return;
  String strID = "";
  for(byte i=0; i<4; i++) strID += (rc522.uid.uidByte[i] < 0x10 ? "0" : "") + String(rc522.uid.uidByte[i], HEX) + (i != 3 ? ":" : "");

  // put ID in capitals
  strID.toUpperCase();
  Serial.print("Card: ");
  Serial.println(strID);

  // Do the verification
  if(strID.indexOf("92:AA:CD:73") >=0){
    Serial.println("Access Granted");
    digitalWrite(A0, HIGH);
    tone(Buzz, 3000, 500);
    for (pos = 0; pos <= 60; pos += 1) {  // goes from 0 degrees to 60 degrees
    // in steps of 1 degree
    servo.write(pos);                // tell servo to go to position in variable 'pos'
    delay(10);                       // waits 10ms for the servo to reach the position
  }
  delay(500);
  for (pos = 60; pos >= 0; pos -= 1) {  // goes from 60 degrees to 0 degrees
    servo.write(pos);                   // tell servo to go to position in variable 'pos'
    delay(10);                          // waits 10ms for the servo to reach the position
  }
    digitalWrite(A0, LOW);
    delay(500);
  }
  else{
    Serial.println("Access Denied");
    digitalWrite(A1, HIGH);
    tone(Buzz, 300, 200);
    delay(250);
    tone(Buzz, 300, 200);
    delay(250);
    tone(Buzz, 300, 200);
    digitalWrite(A1, LOW);
    delay(400);
  }
}

Please Help!
Thanks in Advance.

Sounds like your code is crashing.

Same code was working in Windows, but showing peculiar output in ubuntu.
Also, can you help me out with why every second time I need to grant permission to ttyACM0/ttyACM1?

on Windows you didn't notice the reset, because the port didn't change?

Comment out all the code related to what happens when you tap the right tag. Then add it back in a few lines at a time until it fails.


text:
Encoder coupled with motor shaft.Encoder is giving larger redings than expected
I am a rookie and i dont have much experience on arduino. please help me.
I intend to build a robot that will drive on a straight path even on nonuniform surfaces like the ones we see in agricultural fields(It is just a prototype, so i want to run it on normal offroad surfaces).The robot has 4 motors, one for each wheel. I plan to use encoder feedback method to drive straight.
Right now, I have coupled a slotted disc to the shaft of a dc motor and i am trying to get the counts from the encoder and display the count after a certain interval(5 seconds) on serial monitor. The count that i get is way off the mark. The disc is having 30 slots. With just 2 to 3 rotations I am getting a count of around 180.
I am using arduino R3.
Encoder output:- Pin2 (external interrupt)
motor Pins :- 8,9
I am attaching the code below.
const int motorPin1  = 8;  // Pin 14 of L293
const int motorPin2  = 9;  // Pin 10 of L293
const int encoder_pin = 2;
volatile unsigned int count = 0;
 int time1 = 0;
 int time2 = 0;
void setup() {
  // put your setup code here, to run once:
  pinMode(motorPin1, OUTPUT);
    pinMode(motorPin2, OUTPUT);
    pinMode(encoder_pin,INPUT);
    digitalWrite(encoder_pin,HIGH);
    attachInterrupt(0,encoder,RISING);
    Serial.begin(9600);
     digitalWrite(motorPin1,HIGH);
    digitalWrite(motorPin2,LOW);
    time1 = millis();
}

void loop() {
  // put your main code here, to run repeatedly:
    time2 = millis();
    if(abs((time2 - time1) > 5000))
    {
    digitalWrite(motorPin1,LOW);
    digitalWrite(motorPin2,LOW);
    Serial.println(count);
    }
}

 void encoder()
 {
  count++;

 }

the end of code
The disc that i have mounted on the shaft doesn't rotate in vertical plane exactly. But i do get the blinks on the encoder when i rotate the shaft with my hand.Can that misalignment be the reason.

I guess this is a kind of debouncing problem, caused by noise on the interrupt pin. The behaviour might also get worsened by the disalignment you mentioned. You could verify this by manually rotating the shaft, even though you "get the blinks" I doubt they are accurate in count.
If that is the case there are two things you could do:

add a capacity or a RC filter to the interrupt pin to smoothen out voltage peaks if there are some. This will decrease the chance that the interrupt gets triggered accidentially (and will not solve the problem), but as a low pass it also limits the maximum count rate you are able to detect.
implement debouncing in software. This is usually done by ignoring the input signal for a specific amount of time ("deadtime") after an interrupt has occured. As you are expecting a periodic signal and debouncing behaviour might be different at different speed it could be a good idea to capture the time span between two "blinks" and make the deadtime dependend on this calculated speed.

Something else: the way you check for the timestamp is little incorrect. You should instead do something like this:
void setup() {
  unsigned long starttime=millis();
}

void loop() {
  if (millis()-starttime > 5000) {
    starttime=millis();
    // put code here to run every 5000 ms
  }
}

Usually a rotary encoder has at least 2 sensors.
Incremental rotary encoders usually only have 2 sensors. Absolute or positional encoders have more, and let you figure out the absolute orientation of your sensor by reading a bit pattern.
To read an incremental encoder you write your code to only pay attention to alternating changes in the sensors. That gives you automatic debouncing of the contacts. I suggest you search for Arduino code for decoding rotary encoders.


text:
VirtualWire `vw_get_message`: docs and examples on the PJRC site
I'm looking at he following page, that describes functions from VirtualWire library and provides some examples.
https://www.pjrc.com/teensy/td_libs_VirtualWire.html
Some basic questions I have after reading it:

The description of vw_get_message function states.

Read the last received message. This should be called only when a message is known to be received with any of the 3 functions above.

"3 functions above" refers to vw_have_message, vw_wait_rx and vw_wait_rx_max functions.
However, in the example on that very same page vw_get_message function is called from receiver's loop() without making any attempts to call any of those 3 functions first.
Why? Is it legal to use vw_get_message by itself? And how does it work in this case, i.e. what is the semantics of the return value?
The function is explicitly described as non-blocking, apparently implying that if this usage is legal, there's no way to tell "corrupted message" situation from "no message" situation.
Does the library preserve the granularity/separation of messages? I.e if the TX side sends 1-byte messages, does it guarantee that each call to vw_get_message on RX side will return 1-byte messages? It seems to be implied by the description of the protocol, but I'd like to ask just in case.
If the answer to the second question is "yes", then does this API preserve zero-length messages? Or are they discarded immediately?

http://www.airspayce.com/mikem/arduino/VirtualWire/

The example with only vw_get_message is the common usage of the VirtualWire library. It returns true if something was received and the checksum was okay.
Yes, each message is seperated from the other messages. Each message gets extra bits (intro bits) and extra bytes (checksum and length).
I don't know, I have never tested that. Looking at the source code, there is no problem with zero length messages.

The VirtualWire library is outdated, although it is still used with Arduino boards with little memory (Arduino Uno, Nano, Leonardo, Pro Mini, and so on).
The RadioHead library (www.airspayce.com/mikem/arduino/RadioHead) has included the VirtualWire protocol with the RH_ASK mode. The examples for the RH_ASK mode shows that the usage is almost the same. The RadioHead library should be used when there is more memory (Arduino MKR, Zero, Due, and so on).

That makes sense, thank you. BTW, someone mentioned in the comments (now deleted), that this usage will probably lead to vw_get_message reading the same message (and returning true) again and again from every call, until a new message is received to replace the previous one.  Do you know if this is the case?

No, that is not the case. The received message is used just once. If you look at the source code, a flag vw_rx_done is used for that. The flag is set true when data has been received, and the vw_get_message sets it to false to indicate that the new data has been read.


text:
About UART one transmitter multiple receivers
I have vector nav vn100 IMU that sends data serially rs232...I want to drive 4 servo motors using atmega32 upon roll angel from vector nav vn100..atmega32 can only drive 2 servos using hardware fast pwm mode 14...so I should to use two atmega32...so I should receive the vn100 message to the two atmega32...my question is ..does UART rs323 support one transmitter multiple receivers?

If you do not need the control lines, and the communication is only one
way, then yes, you can connect the TX (transmit) of the IMU to the RX
(receive) of both microcontrollers. On the other hand, connecting one RX
to multiple TX is likely to burn something.
Note however that the ATmega MCUs do not support RS-232 communication.
If you want to go this way, you will then have to attach an RS-232
transceiver to each MCU. If the distances are short (say, a few
centimeters), I would recommend using “serial TTL” instead.

Thank you very much...I am so thankful for your help...


text:
Is there any limitation with Arduino Nano serial communication distance?
I am trying to build Project which communicate multiple Arduino Nanos. I wanted to understand if Arudino Nano is capable of doing that, while doing research I came across post where it says communication with nano can be done up to 2-3 meter, where as my goal is up to 30 meter.
Project - I am trying intercom system, I have 4 Ring button at main gate, when user press any one of those 4 the Arduino will understand it and send to one of the 4 Arduino sitting at other place. Each Arduino will read that message if its for them they will perform activity if not they will skip it.
My problem is I am in selection mode and want know if Arduino Nano can handle that, communication is not that complex. It will be just sending 2/3 value max during communication. As I saw post of distance limitation, I just want get inputs from community. If you have any similar examples of serial communication between multiple Arduino Nano please let me know, I found several but it might save my time if I find something more similar.

why do you need MCUs for a door bell?

@Juraj Its intercom i am trying to build which will connect 5 apartment with 3 different doors. Using MCU i am trying to control 3 camera situated at each door and then allowing user to open that door from selected room.

I agree with Bob Croft, Nick Gammon has a very good description of how to do what you need. Here is a link to his RS485 site. http://www.gammon.com.au/forum/?id=11428

For that sort of difference you are better using RS-485 instead of UART.  UART is really only designed for short-distance communication.
Converting UART to RS-232 will give an improvement, but switching to RS-485 instead will give you the ability to create a multi-drop bus for connecting more than two Arduinos together over a long distance.

UART uses 5V logic level signalling (on the normal Arduinos - 3.3V on most 32-bit boards). It has a "weak drive" and is highly susceptible to induced noise over longer distances.
RS-232 uses ±10V "Non Return to Zero" signalling. This gives far greater immunity to noise and a stronger drive for greater distances.
RS-485 (and the associated peer-to-peer RS-422) use differential signalling. This gives the greatest immunity to noise over the longest distances.

In summary:

RS-232 can be used if you only want to connect two devices together in a low noise environment.
RS-422 can be used to connect two devices together in a high noise (industrial) environment.
RS-485 can be used to connect lots of devices together in a high noise environment.

For more information on how they work there are some good Wikipedia pages:

RS-232
RS-422
RS-485

For interfacing any of these to an Arduino you will need extra hardware ("Driver Chips"). For example:

RS-232: MAX232
RS-422: MAX1184
RS-485: MAX485

There is also "CAN", which is a more modern replacement for RS-485 and is used in many industrial and automotive environments. As this is a newer technology than RS-485 there are fewer resources available and "initial cost to entry" can be higher.

Do you have any example which i can refer for this. I did found youtube video but it doesn't have much details.

There are millions online. Just Google Arduino rs485 or Arduino max485.

Roughly speaking, for a given protocol and medium (cable) the data rate and the distance are inversely related, that is, a connection with half the data rate can work across twice the distance. You will eventually hit the hard limit when the total capacitance of the cable will become too much for the driver.
RS-232 standard provides this table of maximum cable lengths for standard shielded cables:
Data rate (bps) Distance (m)
2400            60
4800            30
9600            15
19200           7.6
38400           3.7
56000           2.6

So, 30 meters can be easily achieved even with RS-232, if you don't mind the 4800 bps baudrate. Even longer distances (or higher baudrates) can be achieved by running RS-232 over a twisted pair, e.g. a UTP 5 cable: these cables have lower capacitance and can run at 9600 bps over 100 m or more.
There are other protocols suitable for long-distance communication. There are Arduino shields for CAN, RS-485 and even Ethernet.

It's worth noting that RS-232 is not the same as the TX/RX pins. The protocol is the same, but electrically it's not. UART is 5V logic levels and weak drive, whereas RS-232 is ±10V NRZ signalling and stronger drive. Whether you go for RS-232, CAN, or RS-485 you will be needing extra hardware "driver chips" to make it work.

@Majenko Obviously. I believe the 2-3 meters limit mentioned in the question refers to the built-in UART driver. The same remarks apply to it: using lower baudrate and lower-capacitance cable can make it work over a longer distance (though 30 meters is most likely unachievable).

Hi please have a look at Nick Gammon's website as he does an Arduino libary for RS485 using cheap driver modules. In particular the non blocking example may well fit your needs.  The library also works for ESP8266 and ESP32 modules under the Arduino IDE.


text:
Can't connect to my ESP32 board via serial
I'm completely new to electronics work.
Today I've received the ESP32 board that I ordered. (It's a WROOM-32.) I followed the instructions here. I connected the board to my computer via USB and I successfully installed the CP210x drivers and got a new serial port COM3, but when I tried to connect to the board with that serial port, I got nothing. I'm on Windows 7.
I tried with Tera Term, and it just shows an empty screen.
I tried type COM3 in the shell, but got an empty string.
I tried doing esptool.exe --chip esp32 -p com3 erase_flash, but I get "Failed to connect to ESP32: Timed out waiting for packet header".
I tried playing with the two buttons on the WROOM32 board, but that didn't help.
Any idea what I'm doing wrong? I'm a complete newbie so it's likely that I'm forgetting something basic.

What do you think you would expect to see on the serial of a blank chip?

@Majenko Okay, so let's say it's supposed to be blank. The esptool is supposed to run without errors when flashing it, right?

Only if it's set to reset the board into flashing mode. Install the Arduino IDE. Install the ESP32 core. Select the right board. Load an example. Program it. Then, and only then, should you go on to advanced topics like programming from the command line.

@Majenko Okay, I did everything you said. Installed Arduino IDE with the ESP32 core. Loaded the AnalogReadSerial. Pressed upload. It failed. Looks like the ESP32 core is using esptool internally, cause the error from Arduino IDO is the exact same one I got in my question: Failed to connect to ESP32: Timed out waiting for packet header

the tutorial linked in question is about Lua

@Juraj Is that really the reason for this failure though?

I don't know why you followed that tutorial. Do you have a Doit ESP32 devkit board with Lua? Do you want to use Lua?

@Juraj I didn't realize that the Doit ESP32 and the WROOM-32 are distinct things. I have this: https://www.ebay.com/itm/Espressif-ESP32-WLAN-Dev-Kit-Board-Development-Bluetooth-Wifi-v1-WROOM32-NodeMCU/253059783728?ssPageName=STRK%3AMEBIDX%3AIT&_trksid=p2057872.m2749.l2649

If you have a better tutorial to send me, I'll be happy to try that

WROOM-32 is the module mounted to the developement board https://www.mouser.sk/images/espressifsystems/lrg/ESP32-WROOM-32_new_SPL.jpg (a tutorial will not help you with the COM port problem)

The issue is that the Serial port on the ESP32-WROOM setup is not like like on the Arduino. It seems that the initialisation will 'miss' the USB enumeration after reboot.
To fix this add a delay in your setup() function of 10 to 15-seconds before initialising the serial.
For example:
void setup() {
  delay(10000);
  Serial.begin(115200);

  Serial.println("Setting up Access Point...");
  .
  .
  .

This works for me, but I hope there is a more elegant solution out there.


text:
Software serial and port expanders
On my ESP32 project I've run out of pins and have incorporated using a MCP23017 port expander.  I need to run multiple slow serial connections (9600 baud) thru the port expander.  Are there any software serial libraries available that would work over a port expander?

No. Even 9600 baud would be beyond the capabilities of bit-banging through a port expander. Reconsider your topology. What are you trying to achieve that needs you to use multiple UARTs like that?

I have several DHT22's that I want to interface with.  One option is to use a mux on the tx/rx pins such as a 74HC4052.

using a one-way serial connection might half your pins, if you weren't aware that was possible...


text:
Working with Wire core library
I'm studying the Wire library code driver utility/twi.h to learn how twi buffering and ISR management work.
What I did actually, is that I copied the header/source files from the Arduino path F:\Program Files\Arduino\hardware\arduino\avr\libraries\Wire\src\utility and put them in the Arduino custom libraries and changed the .c to .cpp and it worked.
I actually ran through different i2c libraries for avr and this code library is one of the best IMHO.
My test code is to initialize the HMC5883L, and read back those configuration setting from the first SFRs of the HMC5883L.
I'm using Serial.prints inside/outside the ISR to debug my coding. It is working pretty much OK. I'm not sure if this could cause some problems.
But, because I don't have a complete understanding of how twi works, I'm trying to understand things now as displaying the content that is going in the ISR.
I think the initialize is working ok, but the read procedure may not as it should be.
Here's my code, for application code in the Arduino IDE, and the code in the library.
Arduino IDE code:
#include "twi.h"
////////////////////////////////////////////////////////////////////////////
// HMC5883L
#define HMC5883L                    0x1E
#define CONFIG_REG_A                0x00  //Read/Write
#define CONFIG_REG_B                0x01  //Read/Write
#define MODE_REGISTER               0x02  //Read/Write
#define DATA_OUTPUT_X_MSB_REGISTER  0x03  //Read
#define DATA_OUTPUT_X_LSB_REGISTER  0x04  //Read
#define DATA_OUTPUT_Z_MSB_REGISTER  0x05  //Read
#define DATA_OUTPUT_Z_LSB_REGISTER  0x06  //Read
#define DATA_OUTPUT_Y_MSB_REGISTER  0x07  //Read
#define DATA_OUTPUT_Y_LSB_REGISTER  0x08  //Read
#define STATUS_REGISTER             0x09  //Read
#define IDENTIFICATION_REGISTER_A   0x10  //Read
#define IDENTIFICATION_REGISTER_B   0x11  //Read
#define IDENTIFICATION_REGISTER_C   0x12  //Read
#define DECLINATION_ANGLE 3.46

void hmc5883l_init(void);
void init_read(void);
void hmc5883l_print_serial(void);

void setup() {
  Serial.begin(9600);
  twi_init();
  hmc5883l_init();
  init_read();
}

void loop() {
  hmc5883l_print_serial();
}

void hmc5883l_init(void){
  uint8_t err,HMC5883L_ini[] = {CONFIG_REG_A,0x78,0x20,0x00};//
    err = twi_writeTo(HMC5883L,HMC5883L_ini,4,1,1);
    if(err != 0){Serial.print("error of init is");Serial.println(err);}
    Serial.println();
}

void init_read(void){
    uint8_t err,len,dat[3];
    err = twi_writeTo(HMC5883L,0x00,1,0,1);
    if(err != 0){Serial.print("error of init is");Serial.println(err);}
    Serial.println();

    len = twi_readFrom(HMC5883L,dat,3,1);
    Serial.print("length of read op:              ");
    Serial.println(len);
    Serial.println();

    Serial.print("config settings:                ");
    Serial.print(dat[0],HEX);Serial.print("\t");
    Serial.print(dat[1],HEX);Serial.print("\t");
    Serial.println(dat[2],HEX);
}

void hmc5883l_print_serial(void){
  int16_t x,z,y;
  uint8_t data[6],len,err, dst_reg[] = {0x03};
  float heading,heading_in_degrees,declination_angle_YANBU;

  err = twi_writeTo(HMC5883L,dst_reg,1,0,1);
  if(err != 0){Serial.print("error of init is");Serial.println(err);}
  Serial.println();

  len = twi_readFrom(HMC5883L,data,6,1);
  Serial.print("len is: ");Serial.println(len);
  x = data[0] << 8 | data[1];
  z = data[2] << 8 | data[3];
  y = data[4] << 8 | data[5];

  heading = atan2(y,x);
  declination_angle_YANBU = ((3.0 + (52.0 / 60.0)) / (180 / M_PI));  // in yanbu city it's
  heading += declination_angle_YANBU;

  if (heading < 0){heading += 2 * PI;}
  if (heading > 2 * PI){heading -= 2 * PI;}

  heading_in_degrees = heading * 180 / M_PI;
  Serial.println(heading_in_degrees);

  //Serial.print("x-axis\t");Serial.print("z-axis\t");Serial.println("y-axis");
  Serial.print(x);Serial.print("\t");
  Serial.print(z);Serial.print("\t");
  Serial.println(y);
}

And this is the core library:
In this part, I've put Serial.prints inside the ISR cases to display what's going from the start of the tx/rx buffers. Also, I've cut the slave half of the code because it's not necessary in this problem, as I'm only dealing with HMC5883L as a slave and I'm the master.
#include <math.h>
#include <stdlib.h>
#include <inttypes.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <compat/twi.h>
#include "Arduino.h" // for digitalWrite

#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif

#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

#include "pins_arduino.h"
#include "twi.h"

static volatile uint8_t twi_state;
static volatile uint8_t twi_slarw;
static volatile uint8_t twi_sendStop;           // should the transaction end with a stop
static volatile uint8_t twi_inRepStart;         // in the middle of a repeated start

static void (*twi_onSlaveTransmit)(void);
static void (*twi_onSlaveReceive)(uint8_t*, int);

static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t twi_masterBufferIndex;
static volatile uint8_t twi_masterBufferLength;

static uint8_t twi_txBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t twi_txBufferIndex;
static volatile uint8_t twi_txBufferLength;

static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t twi_rxBufferIndex;

static volatile uint8_t twi_error;

void twi_init(void)
{
  // initialize state
  twi_state = TWI_READY;
  twi_sendStop = true;      // default value
  twi_inRepStart = false;

  // activate internal pullups for twi.
  digitalWrite(SDA, 1);
  digitalWrite(SCL, 1);

  // initialize twi prescaler and bit rate
  cbi(TWSR, TWPS0);
  cbi(TWSR, TWPS1);
  TWBR = ((F_CPU / TWI_FREQ) - 16) / 2;

  // enable twi module, acks, and twi interrupt
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);
}

void twi_disable(void)
{
  // disable twi module, acks, and twi interrupt
  TWCR &= ~(_BV(TWEN) | _BV(TWIE) | _BV(TWEA));

  // deactivate internal pullups for twi.
  digitalWrite(SDA, 0);
  digitalWrite(SCL, 0);
}

uint8_t twi_readFrom(uint8_t address, uint8_t* data, uint8_t length, uint8_t sendStop)
{
  uint8_t i;

  // ensure data will fit into buffer
  if(TWI_BUFFER_LENGTH < length){
    return 0;
  }

  // wait until twi is ready, become master receiver
  while(TWI_READY != twi_state){
    continue;
  }
  twi_state = TWI_MRX;
  twi_sendStop = sendStop;
  // reset error state (0xFF.. no error occured)
  twi_error = 0xFF;

  // initialize buffer iteration vars
  twi_masterBufferIndex = 0;
  twi_masterBufferLength = length-1;  // This is not intuitive, read on...

  twi_slarw = TW_READ;
  twi_slarw |= address << 1;

  if (true == twi_inRepStart) {
    twi_inRepStart = false;         // remember, we're dealing with an ASYNC ISR
    do {
      TWDR = twi_slarw;
    } while(TWCR & _BV(TWWC));
    TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE);  // enable INTs, but not START
  }
  else
    // send start condition
    TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);

  // wait for read operation to complete
  while(TWI_MRX == twi_state){
    continue;
  }

  if (twi_masterBufferIndex < length)
    length = twi_masterBufferIndex;

  // copy twi buffer to data
  for(i = 0; i < length; ++i){
    data[i] = twi_masterBuffer[i];
  }

  return length;
}

uint8_t twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait, uint8_t sendStop)
{
  uint8_t i;

  // ensure data will fit into buffer
  if(TWI_BUFFER_LENGTH < length){
    return 1;
  }

  // wait until twi is ready, become master transmitter
  while(TWI_READY != twi_state){
    continue;
  }
  twi_state = TWI_MTX;
  twi_sendStop = sendStop;
  // reset error state (0xFF.. no error occured)
  twi_error = 0xFF;

  // initialize buffer iteration vars
  twi_masterBufferIndex = 0;
  twi_masterBufferLength = length;

  // copy data to twi buffer
  for(i = 0; i < length; ++i){
    twi_masterBuffer[i] = data[i];
  }

  // build sla+w, slave device address + w bit
  twi_slarw = TW_WRITE;
  twi_slarw |= address << 1;

  // if we're in a repeated start, then we've already sent the START
  // in the ISR. Don't do it again.
  //
  if (true == twi_inRepStart) {
    // if we're in the repeated start state, then we've already sent the start,
    // (@@@ we hope), and the TWI statemachine is just waiting for the address byte.
    // We need to remove ourselves from the repeated start state before we enable interrupts,
    // since the ISR is ASYNC, and we could get confused if we hit the ISR before cleaning
    // up. Also, don't enable the START interrupt. There may be one pending from the
    // repeated start that we sent outselves, and that would really confuse things.
    twi_inRepStart = false;         // remember, we're dealing with an ASYNC ISR
    do {
      TWDR = twi_slarw;
    } while(TWCR & _BV(TWWC));
    TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE);  // enable INTs, but not START
  }
  else
    // send start condition
    TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE) | _BV(TWSTA); // enable INTs

  // wait for write operation to complete
  while(wait && (TWI_MTX == twi_state)){
    continue;
  }

  if (twi_error == 0xFF)
    return 0;   // success
  else if (twi_error == TW_MT_SLA_NACK)
    return 2;   // error: address send, nack received
  else if (twi_error == TW_MT_DATA_NACK)
    return 3;   // error: data send, nack received
  else
    return 4;   // other twi error
}

void twi_reply(uint8_t ack)
{
  if(ack){
    TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA);
  }else{
      TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT);
  }
}

void twi_stop(void)
{
  // send stop condition
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO);

  while(TWCR & _BV(TWSTO)){
    continue;
  }

  // update twi state
  twi_state = TWI_READY;
}

/*
 * Function twi_releaseBus
 * Desc     releases bus control
 * Input    none
 * Output   none
 */
void twi_releaseBus(void)
{
  // release bus
  TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT);

  // update twi state
  twi_state = TWI_READY;
}

ISR(TWI_vect)
{
  switch(TW_STATUS){
    // All Master
    case TW_START:     // sent start condition
    case TW_REP_START: // sent repeated start condition
      // copy device address and r/w bit to output register and ack
      TWDR = twi_slarw;
      Serial.print("mt add sent is:                 0x");
      Serial.println(twi_slarw, HEX);
      twi_reply(1);
      break;

    // Master Transmitter
    case TW_MT_SLA_ACK:  // slave receiver acked address
    case TW_MT_DATA_ACK: // slave receiver acked data
      // if there is data to send, send it, otherwise stop
      if(twi_masterBufferIndex < twi_masterBufferLength){
        // copy data to output register and ack
        Serial.print("mt byte transmitted no:         ");
        Serial.println(twi_masterBufferIndex);
        Serial.print("content of tx byte:             0x");
        Serial.println(twi_masterBuffer[twi_masterBufferIndex], HEX);
        TWDR = twi_masterBuffer[twi_masterBufferIndex++];
        twi_reply(1);
      }else{
    if (twi_sendStop){
        Serial.println("mt stop");
        twi_stop();
    }

    else {
      Serial.println("mt repst");
      twi_inRepStart = true;    // we're gonna send the START
      TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;
      twi_state = TWI_READY;
    }
      }
      break;
    case TW_MT_SLA_NACK:  // address sent, nack received
    Serial.println("mt add sent nack");
      twi_error = TW_MT_SLA_NACK;
      twi_stop();
      break;
    case TW_MT_DATA_NACK: // data sent, nack received
      twi_error = TW_MT_DATA_NACK;
      twi_stop();
      break;
    case TW_MT_ARB_LOST: // lost bus arbitration
      twi_error = TW_MT_ARB_LOST;
      twi_releaseBus();
      break;

    // Master Receiver
    case TW_MR_DATA_ACK: // data received, ack sent
      // put byte into buffer
        Serial.print("mr byte received no:            ");
        Serial.println(twi_masterBufferIndex);
        Serial.print("content of rx byte:             0x");
        Serial.println(twi_masterBuffer[twi_masterBufferIndex], HEX);
      twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
    case TW_MR_SLA_ACK:  // address sent, ack received
      // ack if more bytes are expected, otherwise nack
      if(twi_masterBufferIndex < twi_masterBufferLength){
        twi_reply(1);
      }else{
        twi_reply(0);
      }
      break;
    case TW_MR_DATA_NACK: // data received, nack sent
      // put final byte into buffer
        Serial.print("mr last received byte:          ");
        Serial.println(twi_masterBufferIndex);
        Serial.print("content of last rx byte:        0x");
        Serial.println(twi_masterBuffer[twi_masterBufferIndex], HEX);
      twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
    if (twi_sendStop)
          twi_stop();
    else {
      twi_inRepStart = true;
      TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;
      twi_state = TWI_READY;
    }
    break;
    case TW_MR_SLA_NACK:
      twi_stop();
      break;
}

The problem now is:
I get these readings on the Arduino serial monitor.
Note: I've wrote my notes on each section.
// initialization
// I think this process is done just fine, the exact bytes are sent
// but each time I open the serial monitor I get like garbage at the first
// of the window, like this flipped question mark I get it most the time
// Is there something like flush function to clear things?
⸮mt add sent is:                 0x3C
mt byte transmitted no:         0
content of tx byte:             0x0
mt byte transmitted no:         1
content of tx byte:             0x78
mt byte transmitted no:         2
content of tx byte:             0x20
mt byte transmitted no:         3
content of tx byte:             0x0
mt stop

// writing target register which is 0x00, but I get 0xA3 ??!
m
mt byte transmitted no:         0
content of tx byte:             0xA3
mt stop

// Here requesting the 6 bytes data, I send read of HMC5883L which is 0x3D
// but 1st byte should be 0x78 then 2nd should be 0x20, 3rd 0x00
// but the result is different ! it's like they are shifted somehow

// At the end I'm trying to read back the passed array to the function, but
// I get 0s!!
mt add sent is:                 0x3D
mr byte received no:            0
content of rx byte:             0xA3
mr byte received no:            1
content of rx byte:             0x78
mr last received byte:          2
content of last rx byte:        0x20
length of read op:              3

config settings:                0   0   0

That is not the core library, those lower level functions are part of the Wire library.

Aaah, OK, I then didn't differentiate between core/lower functions. OK, so what could be like core library? Is Arduino.h and other related libraries that are within Arduino folder in installation folder, are the core libraries for Arduino ?

There is no "core" library. There are a number of Wire libraries (official and other compatible libraries) for different processors. It just happens that the Wire library for the avr microcontrollers has two layers.

Yes, thanks for the clarification. Absolutely, I think one library can't cover all the mcu families, it can focus on one particular family or group of microcontrollers.

The second parameter to twi_writeTo should be a pointer to a buffer. You have now
twi_writeTo(HMC5883L,0x00,1,0,1);

which sends a byte read at address 0x00.
change it to
uint8_t b = 0x00;
twi_writeTo(HMC5883L,&b,1,0,1);

(C arrays are a pointer to first item)

Yeah, I did that. It's ok. But the problem is reading the config registers. I can read data registers automatically, but I can't read the configuration registers automatically! I have to do it one by one.

that is a very different question. the original was about the twi (sub)library. the new is about the specific device. the automatic register increment is to speed up the common use case. with configuration you don't need to hurry

Yeah, sorry, it's actually connected to a device, but maybe the principle is common on i2c devices. Is the problem I'm trying to understand is this feature of communicating with i2c devices. I think there are two types of communication with i2c devices; at least to the HMC5883L. I think if I want to deal with reading configuration registers then I have to do it one by one, if reading data registers, then I can do it automatically.

it is device specific, not a feature of I2C

Ah, OK, it's clear that I really don't have that much of information :) Thanks dude for the help, I really appreciate it. First I posted all this lengthy post, and I really don't know what I'm trying to get because there are so much related problems I have to be aware of. I'm thinking of deleting the thread ! What you think ? Do you agree ? and then I arrange my self again and consider on one more beneficial thread. Any recommendations?

You mean the last update to the post?


text:
Why UDP does not work after analogRead() on esp8266-12N module?
Consider my loop() in Arduino be:
void loop(){
  for(int i = 0; i<100; i++){
   Value[i] = analogRead(A0);
   delayMicroseconds(62);
  }
   //delay(2) //when I use this line esp8266 works properly
   Udp.beginPacket(IP, Port);
   Udp.write(Value, 100);
   Udp.endPacket();
}

after analogRead() UDP can't send packets and crash occur after a moment. But when I use delay(2) line in the above code it works properly. I want to record samples of microphone with 16000 sample rate and I use 62 microseconds for this. Thus in my application it is not possible for delay 2 milliseconds. How can I fix this without delay?

hard use of A0 disturbs WiFi signal measuring done by SDK with the same ADC. use external ADC for continues measurement with esp8266

Thank you for replying.

+1 for the excellent answer Juraj. I did not know that hard use of the ADC would cause issues with the WiFi signal :)


text:
Passing variables for a PID in an interrupt
I'm needing to pass variables from my timerIsr() function to my loop() function. I have little experience with the Arduino language, I'm mostly familiar with Python so this has been quite difficult for me.
Essentially I'm creating a PID controller to maintain RPM of a fan motor if friction is applied to it. I'm implementing the PID control in the loop() function but I need the rotation variable information from my timerIsr() function. I've tried to return the variable info but it doesn't match up to the actual fan speed. I think it has something to do with difference delay/timer times operating at different instances but I'm unsure.
Here's what I have so far
#include "TimerOne.h"
#include <PID_v1.h>

int counter=0;

const int IN1 = 11;
const int IN2 = 10;
volatile float pot=0;
const int POT = 0;
const int ENA = 6;

double Setpoint, Input, Output;
double Kp=2, Ki=5, Kd=1;

PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);

void docount()  // counts from the speed sensor
{
  counter++;  // increase +1 the counter value
}

void timerIsr()
{
  Timer1.detachInterrupt();  //stop the timer
  Serial.print("Motor Speed: ");
  int rotation = (counter / 30);  // divide by number of holes in Disc
  Serial.print(rotation,DEC);
  Serial.println(" Rotation per second");
  counter=0;  //  reset counter to zero
  Timer1.attachInterrupt( timerIsr );  //enable the timer
  Serial.print("pot = ");
  Serial.print(pot);
  Serial.print("\n");

  //return rotation;
}

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

  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);

  Timer1.initialize(1000000); // set timer for 1sec
  attachInterrupt(0, docount, FALLING);  // increase counter when speed sensor pin goes High
  Timer1.attachInterrupt( timerIsr ); // enable the timer

  myPID.SetMode(AUTOMATIC);
}

void loop()
{
  //Input = timerIsr();
  pot=analogRead(POT)/4.01569;
  //Setpoint = sp;

  //Serial.print(Input);

  analogWrite(ENA, pot);
  digitalWrite(10, HIGH);  // set rotation of motor to Clockwise
  digitalWrite(11, LOW);

  delay (250);
}

As you can see I've commented some stuff out that's related to the PID library. Right now I'm just trying to pass the rotation variable to the loop() function.
Is it possible to update global variables at different times so any function can access them?

Short answer: Yes, it is possible to update global variables from interrupt routines, but it comes also with problems.
Long answer:
First you have to understand, how interrupts work. You are using a timer interrupt and an external (pin) interrupt. The compiled program lies in the flash of the chip. At the start there are some special addresses for the different interrupts. If the hardware then registers a condition for an interrupt, it will stop the execution of the main code (the code, that was executed, when the interrupt condition occured), saving the current state and jumping to the corresponding address, where it get's send to the ISR (interrupt service routine), that you defined (in your case the function docount()). After the execution of this program the microcontroller will return to the execution of the main code (by restoring the previously saved state and jumping there). An ISR can only have a return type of void (no return value), because when it returns, there is no special code to receive and use this value. The interrupt may occur at different times every time.
Instead it is common to write global variables in the ISR. For this you have to consider some points:

Global variables, that may be changed during an ISR, has to be declared (additionally to the type) as volatile. This means, that the compiler cannot optimize this variable (for example to a local variable) and has to consider, that it may change anytime, so that he cannot use a cached value.
The usage of the variable in the main code has to be atomic or secured against changing of the variable. If you use a variable in a calculation, it may take many cycles for it (especially if you have a big datatype or some expensive calculations as with float). If the interrupt occures in this time, the value might be changed in the middle of calculation, making the result a bunch of garbage. If the calculation only takes 1 statement cycle, is cannot be interrupted and is called atomic. Since this is rarely possible, you can enclose the corresponding code into securing code. For the Arduino platform, you can use the noInterrupts() and interrupts() functions, to turn off all interrupts, do the calculation and turning the interrupts on again. Be sure do turn the interrupts off only for a short time, so that you don't miss interrupts. Often this is only used to copy the variables value into a local variable (local working copy), which then can safely used for calculations, while the global variable may still change.

Besides that, you also have to think about, what code you write into an ISR. An ISR cannot be interrupted by another interrupt. So functions, that depend on interrupts to work, will not behave like intended. The delay() function for example will simply block all code execution, since the return of the millis() function will not change (it depends on the timer0 interrupt). In your Timer1 ISR, you use Serial.print(). This function can be used, but only until the Serial libraries buffer is filled. The actual communication will take place, after the ISR returns, because it also depends on interrupts. When you try to send more, than fits in the buffer (64 bytes), you will loose data. Currently you should be below that, but you should have this in mind, when coding.

I don't think, that you really need a timer interrupt for calculating and outputting the data every second. Here I would use a non-blocking coding style in the loop() function, like you can see in the BlinkWithoutDelay example, that comes with the Arduino IDE. This is better than using delay(), which is just busy waiting. You save a timestamp with the millis() function and check the time difference. That saves Timer1 for other purposes and also refactors your main code for being extendable and non-blocking, if you want to add more functions.

As I read from this example from the PID library, you need to call myPID.Compute() once in a while to do the PID calculations with the new values. Since these only change every second, you should call this function directly after the calculation of Input.

All in all you need something like this (I didn't include all the code, just the important part, so that you should be able to understand the principle):
unsigned long timestamp;
#define INTERVAL 1000

void loop(){
    if(millis() - timestamp >= INTERVAL){
        timestamp += INTERVAL;
        noInterrupts();
        int counter_copy = counter;
        interrupts();
        // Do the calculations with counter_copy and same the result to `Input`
        // You can put the code from your timerisr here (without the Timer1 code)
        myPID.Compute();
    }
}

Your pot code then should also be enclosed in such an if statement, to prevent, that the PWM get's restarted again and again very fast. If a reaction time of 1s is ok for you, you can put this code in the if statement above. If you want faster reaction times, you can add a second if statement like this to the loop() function (including it's own global timestamp variable and interval value).
The digitalWrite() calls for the direction can be put into the setup, since they don't ever change in your code.

You mean if (millis() - timestamp >= INTERVAL).

Oh, yes, you are right. I corrected that. Thank you.

So what you're saying is I can pretty much condense all of my interrupts down to this loop by just using timestamps? I'm trying to digest all of this information and apply it, sorry.

No, not all. You still have the external interrupt, which you attach with attachInterrupt() and the docount() function. This makes sense, because you don't want to miss any of the pulses. I left that out from my code, since it is exactly the same, as in your code. I ditched only the Timer1 interrupt. I think the accuracy of the 1s interval is not that important, that you really need an own hardware timer for it. If you use non-blocking code the loop() run very fast, so that should be sufficient.


text:
Is new.cpp programmed improperly? Arduino 1.8.9
I'm having trouble with my code and I'm not sure if it's a memory allocation issue. So I look at the new, delete to see if it throws errors, and finding the source code I find outrageously simple codes. So simple, I think it can't be right.
#include <stdlib.h>

void *operator new(size_t size) {
  return malloc(size);
}

void *operator new[](size_t size) {
  return malloc(size);
}

void operator delete(void * ptr) {
  free(ptr);
}

void operator delete[](void * ptr) {
  free(ptr);
}

Does this mean if I call customClass *ptr = new customClass[10]; it allocates only 10 bytes instead of sizeof(customClass)*10?

when you do new customClass[10] that doesn't mean size_t size = 10

@JaromandaX Yeah... I realized that after I posted the question...

http://www.cplusplus.com/reference/new/operator%20new[]/:

in C++, new[] is an operator with a very specific behavior: An
  expression with the new operator on an array type, first calls
  function operator new (i.e., this function) with the size of its array
  type specifier as first argument (plus any array overhead storage to
  keep track of the size, if any), and if this is successful, it then
  automatically initializes or constructs every object in the array (if
  needed). Finally, the expression evaluates as a pointer to the
  appropriate type pointing to the first element of the array.


text:
is PIN To PIN matching mcu against Atmega328P-AU available?
I want to upgrade my product which is based on Atmega328p-AU, having the problem of programming memory. I don't want to change the PCB of the product. Is PIN To PIN matching MCU against Atmega328P-AU available?

Too little RAM, or too little Flash memory?

The only other AVR chip with more program memory in the 32/TQFP form factor is the ATMEGA4808 at 48 kB.
Unfortunately, the pinout is not the same compared to the ATMEGA328P-AU:
ATMEGAx8P family datasheet
ATMEGAx08 family datasheet


text:
Arduino - "expected primary-expression before '.' token" Error
#include "Ultrasonic.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  // put your setup code here, to run once:
  lcd.begin();
  Serial.begin(9600);
}
Ultrasonic ultrasonic(11, 12); //Ultrasonic ultrasonic(Trig,Echo);
void loop()
{
  int a = (Ultrasonic.Ranging(CM));
  if (a >= 15 && a < 20)
  { Serial.println("guvenli");
    lcd.print("guvenli");
    delay(500);
    lcd.clear();
    tone(3, 2000, 100);
    delay(500);
    noTone(3);
  }
  if (a >= 10 && a < 15) {
    Serial.println("guvenli dikkat");
    lcd.print("guvenli dikkat");
    delay(500);
    lcd.clear();
    tone(3, 2000, 50);
    delay(250);
    noTone(3);
  }
  if (a < 5)
  {
    Serial.println("vurdun");
    lcd.print("vurdun");
    delay(500);
    lcd.clear();**uıhhf
    tone(3, 2000, 50);
    delay(50);
    noTone(3);
  }
}

In this code i'm getting an error like this:
   C:\Users\*\AppData\Local\Temp\arduino_modified_sketch_113625\sketch_apr29a.ino: In function 'void loop()':

sketch_apr29a:19:22: error: expected primary-expression before '.' token

   int a = (Ultrasonic.Ranging(CM));

                      ^

exit status 1
expected primary-expression before '.' token

Please show as a full working example of your code, that shows the problem. This cannot be your full code. Also please provide a link to the library, that you use for Ultrasonic.

http://pasted.co/172df900

I guess you used the following libraries: LiquidCrystal-I2C and Ultrasonic-HC-SR04

And please copy your full code into the question, so that it does not rely on a link, that may become invalid over time. I did that for you now.

If I remove the **uıhhf in line 40 (which does seem like a typo), your sketch compiles fine for me. I don't receive the shown error. I'm using Arduino IDE 1.8.5 and Arduino Uno as target board.

this is all of code

now im getting this code: "Arduino:1.8.8 (Windows 8.1), Kart:"Arduino/Genuino Uno"
C:\Users\ETKullanici\Desktop\sketch_apr29a\sketch_apr29a.ino: In function 'void loop()':
sketch_apr29a:16:21: error: 'class Ultrasonic' has no member named 'Ranging'
int a=(ultrasonic.Ranging(CM));
                 ^

exit status 1
'class Ultrasonic' has no member named 'Ranging'
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences."

Then maybe you have a different ultrasonic library, than I linked above. Please provide a link to the library, that you really use.

i think it's not about library issue, you have `error: expected primary-expression before '.' token
int a = (Ultrasonic.Ranging(CM));but you are using a variableUltrasonic ultrasonic(11, 12);` Please check your code again!!.

@chrisl: You replaced the original code that generated the “expected primary-expression” error with modified code that no longer has that error. Why did you do that? Now the question makes no sense anymore.

@AnT I just copied the code from the pasted link, that the OP provided. You may vote to revoke my edit of the question

@chrisl: I understand. It means that the edit was made by the author of the code. Yet, it does not change the fact that the code no longer matches the error message, defeating the purpose of this entire question.

Ultrasonic is a class name. Why are you trying to use it before a . in an expression?
Judging by the declaration, you need ultrasonic. That is your object name. ultrasonic, not Ultrasonic.

Comparing the provided code with the error text, I would bet that one or the other is a typo, notice the case of 'ultrasonic' in the code does not match the corresponding line in the error.

@Kelly S. French: Well, if you look through the editing history, you'll see that the code in the original post did match the error text. Meanwhile, the pastebin version linked by the author in the comments is slightly different - the Ultrasonic error is already fixed. Later the code here was replaced with pastebin version. So the question became inconsistent with itself.

Good point, I had not considered looking through the edit history. My misgivings were more around my surprise at the error text given that a problem with strict case-matching wouldn't typically be related to a missing 'primary expression' as usually there needs to be a named identifier before the '.' and to expect an expression there would make me wonder if the cause were elsewhere, for instance the snippet ' **uıhhf in line 40 ' mentioned by chrisl, which definitely look like a syntax error but I can't see how it would generate that error either. Did the OP not include the whole error log?