text:
Cannot find solution to "variable out of scope"
First C program. Spent a lot of time looking for a solution. KeyPad produces 'char' instead on 'int'.  Plus I want to display 'End', thus I wrote the 'main' to to support 'char' and thus had to adapt a 'char' to 'int' conversion work around, line 89  Certainly there are other errors.
extern "C"
// Microwave ccp

  #include <Arduino.h>
  #include <stdlib.h>
  #include <string.h>
  #include <inttypes.h>
  #include <Keypad.h>
  #include "TM1637.h"
  #include <TimerOne.h>
class TimingISR
{
public:
    TimingISR();
    bool Enable_interrupts, Disable_interrupts;

  char lead_char, unit_sec, tens_sec, num_min;
  int int_unit_sec, int_tens_sec, int_num_min;
  int Count_Seconds, Remainder, brightness = 4, PowerLevel;   //BRIGHT_TYPICAL = 4, BRIGHT_DARKEST = 0, BRIGHTEST = 7
  bool Colon, PointFlag, Points_enable;
  char data_char;
};

// these are all Clobal Variables
  int pin_Clk = 2; //  or 3 for IC2
  int pin_DIO = 3; //  or 2 for IC2
  int PIN_RELAY = 4;  // controls power on/off to 'cook'
  int PIN_Beeper = 5; // PWM beeps when finished

  int  pos, Remainder, num;
    // Timer variables
  char tempchar;

  // Read Key Pad, continuously
const byte ROWS = 4; // Four rows
const byte COLS = 3; // Three columns
char lastkey;
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'#','0','*'} };// Define the Keymap
byte rowPins[ROWS] = { 9, 8, 7, 6 };  // Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte colPins[COLS] = { 12, 11, 10 };  // Connect keypad COL0, COL1 and COL2 to these Arduino pins.
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );  // Create the Keypad
#define ledpin 13
void setup()
//        Colon = OFF;   PointFlag, Points_enable   ***************************not coded yet
{
  pinMode(ledpin,OUTPUT);
  digitalWrite(ledpin, HIGH);
  Serial.begin(9600);
}
void loop()
{    // run repeatedly

   char key = kpd.getKey();
   // if ((key = NO_KEY) || (lastkey = key)); delay(100); exit(0);    }

 {  if (key)  // Check for a valid key.
      switch (key) {

      case ('0'): case ('1' - '0'): case ('2' - '0'): case ('3'-'0'): case ('4' - '0'):  case ('5' - '0'): case ('6' - '0'): case ('7' - '0'): case ('8' - '0'): case ('9' - '0'): //all key integers
 { if ( Count_Seconds > 0 ) // Cooking in progress, thus SHUT DOWN, any numeric key shuts down the power
  {  lead_char = 'C';
     num_min=    'n';
     tens_sec=   'C';
     unit_sec=   'l';
goto CancelPower;
  } //  Short Delay, then Display “A000”
    else
  {     num_min = tens_sec;  // integers: update the 'time' 'stack' as integers
        tens_sec = unit_sec;
        unit_sec =  (key-'0');  // '0' = 30 base 10 etc
        lastkey = key;
        Colon = ON;
goto DisplayAll;   // accumulate time value  // any old num_min_segment fall off
  } }     //
  break;  //---------------------------------------

      case ('#'-'0'):  // Start Heating
      if (lead_char != 'A')
goto OOPS ;
       else  // convert time parts to Count_Seconds
        (  Count_Seconds = int(unit_sec) + int(tens_sec) * 10 + int(num_min) * 60  );
  {       if  (  Count_Seconds > 0 )
TimingISR(  ) ;
          lead_char = 'c'; //  ’c’ooking
          Colon = ON;
          pinMode(PIN_RELAY, OUTPUT);
          digitalWrite(PIN_RELAY, HIGH);  // turn on the heat
          PowerLevel = 10;
  }
   break;  //---------------------------------------

      case  ('*'-'0'):  // Set Power level or default DEFROST Power level
     //unit_sec_segment = a number as a 'segment' value    // a power level manually inserted
{   if ( lead_char ==  'A'  &&   num_min == '0' &&  tens_sec == '0' )
{    if ( unit_sec =  !('0') )         // &&  unit_sec > '0' && unit_sec <= '9' )
 {      int PowerLevel = aoti(unit_sec);
        lead_char = 'P';    //Display "P=n0", n = percent power via duty cycle
        num_min =   '=';
        tens_sec = unit_sec;  //display 'char' as 10's 'percent' value, move number left one place
        unit_sec =  '0';  // insert a zero
 }   else  // power not manually set
 {      PowerLevel = 2;     // 'defrost' = 20 %
        lead_char = 'd';
        num_min =   'E';
        tens_sec =  'F';
        unit_sec =  '_';
 }
goto DisplayAll;
}
   else
//    if ( lead_char != 'A'  ||  num_min != '0' ||  tens_sec != '0' || unit_sec !=  '0' )
goto OOPS ;
}     //end if, of Case “*"
      break;  //---------------------------------------

   lastkey = key;
delay(100);  //100 millisec
}   // End Of Switch Key
}  //  End of If (Key)
//return

// Beginning of GOTO's--------------------------------------
{
OOPS:
     lead_char = 'o';   //Display "ooPS"
     num_min =   'o';
     tens_sec=   'P';
     unit_sec =  'S';   // then Short Delay, then Display “A000”
CancelPower:
      pinMode(PIN_RELAY,OUTPUT);
      digitalWrite(PIN_RELAY, LOW);  // turn off the heat
goto DisplayAll;  //ready to accumulate 'heating' time input
    delay (3000);     //let it display for 3 Count_Seconds, then clear the display
    lead_char = 'A';        //ready to accumulate 'heating' time input
    num_min =   '0';
    tens_sec =  '0';
    unit_sec =  '0';
    Disable_interrupts;
    int Count_Seconds = 0 ;
DisplayAll:

// DisplayAll:  //Would like to put this into the 7 segment display
 // Address each 7 segent unit, one after the other; left to right
{    for ( pos = 0 ; 3 < 4; pos++);
      if ( pos = 0 )
        char_data = lead_char
      if ( pos = 1 )
        char_data = num_min
      if ( pos = 2 )
        char_data = tens_sec
      if ( pos = 3 )
        char_data = unit_sec

if ( char_data='0') ; num = 1; // the 7 segment display 'h' only allows for integers 0 through 15, i.e. HEX characters
if ( char_data='1') ; num = 2;
if ( char_data='2') ; num = 3;
if ( char_data='3') ; num = 4;
if ( char_data='4') ; num = 5;
if ( char_data='5') ; num = 6;
if ( char_data='6') ; num = 7;
if ( char_data='7') ; num = 8;
if ( char_data='8') ; num = 9;
if ( char_data='9') ; num = 10;
if ( char_data='A') ; num = 11;
if ( char_data='B') ; num = 12;
if ( char_data='C') ; num = 13;
if ( char_data='d') ; num = 14;
if ( char_data='E') ; num = 15;
if ( char_data='F') ; num = 16;
if ( char_data='c') ; num = 17;
if ( char_data='H') ; num = 18;
if ( char_data='h') ; num = 19;
if ( char_data='I') ; num = 20; //left vertical 2 segments
if ( char_data='i') ; num = 21;
if ( char_data='L') ; num = 22;
if ( char_data='l') ; num = 23; /right /vertical 2 segments
if ( char_data='n') ; num = 24;
if ( char_data='O') ; num = 25;
if ( char_data='o') ; num = 26;
if ( char_data='P') ; num = 27;
if ( char_data='r') ; num = 28;
if ( char_data='S') ; num = 29; //same as a five
if ( char_data='U') ; num = 30;
if ( char_data='u') ; num = 31;
if ( char_data=' ') ; num = 32;
if ( char_data='=') ; num = 33;
if ( char_data='-') ; num = 34; //dash / minus
if ( char_data='_') ; num = 35; //under score
if ( char_data='[') ; num = 36; /left /bracket
if ( char_data=']') ; num = 37; //right bracket
// there are other usefull, such as "top score", "middle score... "top minus", "bottom Minus",
// which yoou could assign some other othervise unprintable character as a proxy, e.g  the ampersant to display a "top position minus sign"

}
Disable_Interrupts;
  TM1637DisplayAll(uint8_t num, uint8_t pos);
Enable_Interrupts;
}
return(0)
}
}  //  End of void LOOP()

//--------------------------------------

// ----------------------------------------------------

"Auto Format Canceled: too many right curly braces" says the Arduino IDE. Your code has quite a few problems, and it can't compile as is.

I totally had to stop reading... You should first learn how to write a program before trying to make a complicated program like this. Indentation, parentheses, comments are used to make the program more readable and easier to understand, for both us and you. Then in this program I see a lot of problems: you should not define classes inside the main .ino file, but have a header (.h) file with the declarations of the members and a source (.cpp) file for the implementation. A couple for each class. And... I highly suggest you to use the modular approach (i.e. write a piece of the program, test...

... it, then write another one, test it again, until you added all the features). Writing all the program at once (or worse copying and pasting pieces from other programs) without testing them when you add will lead to this: an unfixable mess of compiling errors and bad behaviors. Divide et impera! For instance: 1) communicate through serial 2) read the keypad and write to serial 3) read from serial and display 4) join the jeypad and display, ... And, please, use 8-bit (uint8_t or byte) variables whenever possible, and make constant values (like pin number) constant; your uC will thank you

You have a pointless class defined, there is no need for a class for that. 2) if ( char_data='u') ; num = 31; will set char_data to 'u' and num to 31. == not = for a logical comparison and skip the first ; in those lines. 3) goto is EVIL. There are a few situations when it's use can be justified. This isn't one. 4) case ('1' - '0'): should probably be case '1': And that's just from a very quick skim through the code.

@frarugi87 - This is a way of learning, yes its riddled with bugs but its a start, you sound quite negative about it.

@CodeGorilla It was not my intent, sorry if I sounded too negative but it was just because comments need to be too short, so I have to sum up ;) anyway what I wanted to point out is that rather than writing everything at once and then struggling to fix it it's much better to divide the problem, make small solutions, test them and fix their bugs, then integrate them in one program and fix the interactions. For this particular project I'd start from scratch again, because it is much longer to fix it than to rewrite it

The first line says extern "C" but you haven't scoped it, I'm really not sure what you are trying to achieve or if it will work.  Personally I would remove that line.
"Microwave ccp" come compilers complain if the filename is not right.  As far as I know it should be either .cc or .cpp, but its proably just a typo in the comment, because I doubt you would get this far if it was wrong.
Pins 2 and 3 for I2C, its normally A4 and A5.
Line 58 The reason your commented out code didn't work is (lastkey = delay) you should have used equivalence (==) rather than assignment (=).
Use function calls rather than goto statements, it isn't the 1970s anymore! :)
int(variable) is not casting it is creating an integer from variable and then its disposed of when it goes out of scope.  (int)variable is casting.
for (pos = 0; 3 < 4; pos++); This will cause you problems, because its an empty loop, does nothing, which means pos doesn't have the value you think it does.

Please don't take any of this the wrong way, I'm not a teacher but I need to explain what has gone wrong with you code and how you can fix it.  It is not personal criticism, I bet my first program was ten times worse.
You seem to have a misunderstanding of "variable scopes".  Put simply a variable can only be 'seen' after the point you declare it and within the immediate curly braces {} and all child braces. e.g.:
int GlobalVariable = 1; // Visible through-out the code
void loop ()
{
    int LoopVariable = 2;
    for (int ForVariable = 0 ForVariable < LoopVariable; ++ForVariable)
    {
       ++GlobalVariable;
    }
    Serial.println (ForVariable);  // ERROR
}
void AFunction()
{
    Serial.println(LoopVariable);//ERROR
}

You immediate error is you have defined the variable unit_sec inside class TimingISR and you are accessing it like a local variable.
Now The way you have defined class TimingISR is like designing a car, its fine on paper but you can't drive it until you build one.  As far as I can see you haven't instantiated an instance of TimingISR.  It sounds complex but you have been doing it for int and char (They aren't classes, but its very similar)
int pin_clk = 2;
TimingISR aTimingISR;

If a value should change define it as const.
const int pin_clk = 2;

If it does change you will get a compilation error rather than suddenly sending the I2C clock signal to the on board LED.
goto is evil.
case ('0'): case ('1' - '0'): case ('2' - '0'): case ('3' - '0'): case ('4' - '0'):  case ('5' - '0'): case ('6' - '0'): case ('7' - '0'): case ('8' - '0'): case ('9' - '0'): //all key integers
        { if (Count_Seconds > 0) // Cooking in progress, thus SHUT DOWN, any numeric key shuts down the power
        {
            lead_char = 'C';
            num_min = 'n';
            tens_sec = 'C';
            unit_sec = 'l';
            goto CancelPower;

CancelPower:
        pinMode(PIN_RELAY, OUTPUT);
        digitalWrite(PIN_RELAY, LOW);  // turn off the heat
        goto DisplayAll;  //ready to accumulate 'heating' time input
        delay(3000);         /// NEVER EXECUTED
        lead_char = 'A';     /// NEVER EXECUTED
        num_min = '0';       /// NEVER EXECUTED
        tens_sec = '0';      /// NEVER EXECUTED
        unit_sec = '0';      /// NEVER EXECUTED
        Disable_interrupts;  /// NEVER EXECUTED
        int Count_Seconds = 0;/// NEVER EXECUTED
    DisplayAll:

        // DisplayAll:  //Would like to put this into the 7 segment display
        // Address each 7 segent unit, one after the other; left to right
// Code cut (but it should be == not =)
        Disable_Interrupts;
        TM1637DisplayAll(uint8_t num, uint8_t pos);
        Enable_Interrupts;

Code isn't being executed because gotos never return to the call, they just carry on from the label.  Try this instead:
// TimingISR& theISR means you can change the values in theISR
// TimingISR  theISR means you copy theISR and all changes are lost when the function exits.
// TimingISR const& theISR means you can't change the values in theISR
void CancelPower (TimingISR& theISR)
{
  pinMode(PIN_RELAY, OUTPUT);
  digitalWrite(PIN_RELAY, LOW);  // turn off the heat
  DisplayAll(theISR);  //ready to accumulate 'heating' time input
  delay(3000);     //let it display for 3 Count_Seconds,
  ClearDisplay();
  theISR.lead_char = 'A';        //ready to accumulate 'heating' time input
  theISR.num_min = '0';
  theISR.tens_sec = '0';
  theISR.unit_sec = '0';
  theISR.Disable_interrupts(); // This should be a function that does something, not a bool
  theISR.Count_Seconds = 0;
}

I'm afraid that's just some of the things you need to change, BUT that's one hell of a program for a first attempts and that's the only reason I raised so many issues.  Try again and post it again, I'd love to  see the differences.


text:
Use MQ2 Sensor with Arduino Uno without breadboard?
I want to make a small and compact gas sensor using the Arduino Uno and MQ2 sensor. However all sites list a breadboard as a requirement.
Now, the MQ2 has A0, D0, GND, VCC, pins and the Uno also has A0, GND, 3.3V and 5V connectors.
So can I use Male to Female Jumper Wires to directly connect these? I am not using anything else like LEDs or speakers.
My code keeps the inbuilt LED ON when smoke level is LOW and blinks when the Level is HIGH. Also will I need any resistor for it?

This is point-to-point wiring, a technique loved by high-end audio amplifier fans:

Usually I don't think at the UNO as "small and compact"; I usually prefer to use a barebone atmega or an arduino pro mini / nano as alternatives (nano has inbuilt usb, pro mini doesn't). But anyway...
The SeeedStudio MQ2 has four pins, but no D0 pin; it has Vcc, GND and A0 and a NC pin (which means do not connect this pin).
So... Yes, The sensor is 5V powered and has an analog out interface, so you should connect the A0 pin to any analog input on the arduino (A0..A7); you are not forced to use A0.
Be careful that the sensor uses 800mW of power (160mA at 5V) in the pre-heating, so you are not advised to use it form a battery source

Yes, you can use male to female jumper wires to directly connect them. Breadboard is not a requirement. Also, you don't need any resistors.

You can connect it exactly like this.
I'm using female-female jumper wires and have soldered pins onto the UNO clone to enable me to do this.

Pins on sensor from left to right A0 - D0 - GND - VCC
You can also find the wiring diagram on-line for a barebones sensor
if you've not got the sensor module.
here MQ2- Sensor Information
You can either use the D0 output pin to turn on an LED in the presence of gas / smoke or you can use the A0 to report a gas / smoke level.
The code in my other reply is for the analogue reporting of the sensor value.
The Digital output is either on or off and the potentiometer on the back of the sensor will adjust the point at which the D0 pin report a High output level, if it's not set right then the D0 pin won't actually output a voltage.

MQ2 flammable gas and smoke sensor detects the concentrations of combustible gas in the air and ouputs its reading as an analog voltage.
The sensor can measure concentrations of flammable gas of 300 to 10,000 ppm.
The sensor can operate at temperatures from -20 to 50°C and consumes less than 150 mA at 5 V.
Connecting five volts across the heating (H) pins keeps the sensor hot enough to function correctly. Connecting five volts at either the A or B pins causes the sensor to emit an analog voltage on the other pins.
A resistive load between the output pins and ground sets the sensitivity of the detector. Please note that the picture in the datasheet for the top configuration is wrong. Both configurations have the same pinout consistent with the bottom configuration.
The resistive load should be calibrated for your particular application using the equations in the datasheet, but a good starting value for the resistor is 20 kΩ.
DataSheet PDF Here
    * Smoke/Gas Sensor Module project
     * tutorial url: http://osoyoo.com/?p=671
     */
    void setup()
    {
        Serial.begin(9600);
    }

    void loop()
    {
        int val;
        val=analogRead(0);
        Serial.println(val,DEC);
        delay(100);

}

source: Stack Exchange

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

sort: votes


text:
Function pointer or abstract class?
I need to implement callback in my C++ library. The "proper" C++ way of doing it would be to create an interface (or pure abstract class) and pass it to interested party. I'm wondering though, would that be optimal?
My analysis:

Function pointer - occupies 2 bytes in memory (+code of function)
Class derived from abstract one - occupies 2 bytes in memory PLUS 2 bytes for VMT (since we have derived method) PLUS size of VMT table (if any) (+code of method).

Is optimizer smart enough to compile abstract class with single method as method pointer? Which solution is more optimal in regard of memory and speed? Is my analysis correct?

You have to choose between size optimization and usability/readability. With a virtual method, you can encapsulate data with the actual code, at the size cost you mentioned. The response will actually depend on how much size you have for your project?

Regarding your optimizer question, it would be better to ask this to GCC people as it is certainly not specific to Arduino.

Sometimes you want your callback to be fed some data that you provide
when you register that callback. Here is a very common callback pattern
in plain C that does that:
// The API:

typedef void (*callback_t)(void *data);
void register_callback(callback_t callback, void* data);

// Usage:

typedef struct {
    // stuff only the user of the API knows about.
} my_data_t;

void my_callback(void *in_data)
{
    my_data_t *data = (my_data_t *) in_data;
    // do something with data->foo, data->bar...
}

// ...somewhere else:
my_data_t my_data = { stuff... };
register_callback(my_callback, (void *)&my_data);

The problem is: it's clumsy. C++ classes allow you to pack together the
code (the callback function) and the data it needs. Thus, if in your use
case you need to pass data to the callback, by all means use a C++
class. It will make your life easier and you are unlikely to even notice
the memory overhead.
However, if you only need to pass a function, with no attached data,
then a plain function pointer would be both easier for the API user and
optimal memory-wise.

The best way is to find out yourself, there are memory 'debug'  functions to show the amount of free memory, so if you do some tests you know for sure what the compiler optimizes.
See e.g. AvailableMemory library.
It might be quite hard to exactly calculate and predict the optimizer. However, is it really needed to optimize? Mostly it is best to not optimize before knowing it is really necessary.

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


text:
Delay in displaying data received from UART when used with PCINT on PIN0
I have been trying to find a solution for UART receive interrupt for my UNO board and I came across a possible solution in : PCInt
I did a small editing in the following portion of the code to make it work for UART.(code works like a loop-back test)
void RXint(void) {
char k;
if(Serial.available()>0)
{
k=Serial.read();
Serial.print(k);
}}
void setup()
{
Serial.begin(9600);
PCattachInterrupt(0, RXint, FALLING);
}
void loop()
{}

The code works pretty well with one big drawback.
The character displayed is having one char delay, what i mean is that for the following input

qwerty

output is

qwert

That means if I enter the 5th char,the output will be 4th one.
When the first input is given, it doesn't show output till the second input is entered.
Can someone help me out with this
(This is only a test code, the interrupt part is to be used in a larger code where the loop() carries out different tasks and interrupt is to be raised when data is received via UART)  .

Forget about interrupts and rename RXint → loop. It should work like a charm. Serial already handles the UART interrupt pretty well. Trying to manage the incoming data in an interrupt is misguided.

@EdgarBonet Actually this is only a testing code. The real code is a long one consisting of other connected devices and in that code I need to add interrupt for UART as the data is to b stored to a RAM. I cant use Serial.event() as it checks only at the ending of loop.

“I need to add interrupt for UART as the data is to be stored to a RAM”. The Serial object already provides an interrupt that does exactly what you want: it stores the incoming data in a RAM buffer. It makes little sense to add a second buffering layer of your own. “I cant use Serial.event() as it checks only at the ending of loop”. Checking at the end of loop() is fine, unless your loop() is too slow. If this is the case, then your real problem is: too many blocking calls. It's not a problem about serial interrupts at all.

Here the working is like, the data is received in a sequence and the received data is stored into an External RAM(from where further processing is done). Of course the loop() is slow as it needs to be reading RTC and pushing data to other devices and I cant miss a character in sequence that I am receiving. Cause of these reasons I am trying to implement interrupt.

Your interrupt is happening at the same time the START bit of the next frame is arriving in the hardware. As a result you don't have that data yet, because it's still to arrive. All you have is what has gone before. You won't get the new character until the frame has finished arriving and the UART RX interrupt fires and the byte gets copied out of the RX FIFO and placed into the Arduino receive buffer.
The way you are doing it is completely wrong. The data is already being captured using an interrupt and placed in a buffer for you to deal with as you see fit at a time that suits you (as long as it is before the buffer overflows).
If you can't read it fast enough using your main loop (or variations thereon) then you need to rethink how you are doing your main loop.

are there no USART interrupts in arduino?

You mean besides the one I already mentioned that the API already uses to receive the incoming bytes...?

I am a little new to this. It would be much helpful if you could show me a way how to do this without an interrupt. I tried Serial.event(), but my main loop() is too long i guess, so its not working as expected.

So make your main loop() shorter. Get rid of delays, while loops, etc. You don't want to write blocking code on an Arduino or you find you can't do much.

As other have emphasized, make sure your loop runs freely, without delays or blocking while loops.  It would be very unusual to have a loop that really takes > 64ms (the input buffer overflow time @ 9600).
However, there is one case where a frequently-used library is blocked for 150ms or more:  SDfat.  If you are logging data, the library may have to wait for the SD card to accept more data.  It is an indeterminate length of time, and it is specific to the individual card.  In this case, you have two choices:

process the RX characters as they arrive, during the RX character interrupt; or
add a yield call to the offending SDFat method.

For the former solution, I have posted modified versions of the most commonly-used Arduino serial port libraries.  They all have a new attachInterrupt method that allows your function to be called for each RX character.  See NeoHWSerial (a modified HardwareSerial), NeoICSerial (a modified AltSoftSerial) and NeoSWSerial (a more-efficient alternative to SoftwareSeriall).


text:
Output 12-25V from Arduino Mega
I am currently building my first Arduino project : a car that you can control from your computer. I have my Arduino Mega that outputs 3.3 or 5V and my stepper that receives 12-25V, how can I make my Arduino digitally write something to that stepper?

https://www.arduino.cc/en/Reference/Stepper

Use an H-bridge motor driver. They can use arduino signals to control higher voltages without damaging the arduino. Check out the  L298N from gearbest. It's cheap but will probably do the trick if you're not using too much current.
It can supply about 1A through each gate at 5-30V.
this video should help explain it. (I haven't watched the video but it seems like it got good feedback).


text:
Taking pictures with a small Arduino
I'm trying to make a time lapse video of a crystal patch in a small space.  I need some way of taking a picture every hour or so within an area no greater than 35mm, the smaller the better.  Something like the Arduino-Leonardo-Beetle would be the ideal dimensions.  What sort of camera and Arduino board do people recommend?  Thanks!

While not entirely impossible, an Arduino is not suited to this, something already explained to you when you asked this on EESE: https://electronics.stackexchange.com/questions/312692/arduino-beetle-and-camera

I'm just looking for a second opinion.  You've told me on two different boards that it isn't entirely impossible, but both times you haven't offered any suggestions on how to go about it in the (admittedly small) realm of what is possible.  I don't intend to sound rude, but if you insist on following me from board to board to comment on how it isn't entirely impossible, would you kindly at least offer some advice on how to perform this operation instead of just saying it wouldn't be your top choice of doing it and downvoting me?

I didn't downvote your original posting, someone else did.  And I already mentioned buffered cameras but that even with that the lack of memory on an Arduino still makes things very challenging.  You are wasting your time and money to pursue this with an Arduino.

Many digital cameras, and even some motorized analog cameras, can be triggered by a wired remote. You can replace the remote by a relay, and have the Arduino drive the relay through some sort of transistor.

Sounds like the issue is space. Can you use a camera like this connected to a RPi? The ribbon cable allows you to place the RPi outside the container (I assume the crystals are in some type of enclosure). With the RPi, you would probably not even need any coding.

Yeah @Johnny, this ought to work!

Check out Arducam. I have used it and the library is maintained.


text:
Splitting a string read from Serial into parts
Is there any method with which I can split a string given by Serial.read() into an array of 3 items: [command, address, message], to write it to EEPROM?
Thanks.

Serial.read() reads a single byte, not a string.

Ah!! , so How can i manage a string like : read 13; ps: 13 is address
or another string like: Write 13 15 where 15 is the message?

The first thing you should do is to collect your serial input into a string.
If your incoming data use a separator, then you can take advantage of the useful function "readStringUntil".
For example, if your separator is comma (,):
while (Serial.available() > 0) {
  var1 = Serial.readStringUntil(','); // writes in the string all the inputs till a comma
  Serial.read();
  var2 = Serial.readStringUntil(',');
  Serial.read();
  var3 = Serial.readStringUntil('\n'); // writes in the string all the inputs till the end of line character
}

At this point you have your data in 3 different variables and you can use the standard eeprom library to store. Don't forget you will need to declare the variables and to initialize the Serial.
A faster way is to save the whole input in string and process it when ready.
Much better it will be if you use interrupts attached on the Serial input, so you can keep free your loop from waiting data. This can't be done with the standard Serial library but you can use this library:
https://github.com/SlashDevin/NeoHWSerial
It works really well, we use it to collect data from GPS receivers at very high speed and it's fast.
N.B. eeprom is limited in the numbers of reads and writes it can support before risk a failure. Even 100,000 reads/writes sounds a big numnber, if you write the data once every second your eeprom will die in just 27 hours, a day of life. Try to write data only when it's strictly necessary and read data as well only when you start the procedure that uses those data, once.

That's the code I used to fix this issue.
#include <EEPROM.h>

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

void loop() {
    while (Serial.available() > 0) {
      String command = Serial.readStringUntil(' '); // writes in the string all the inputs till a comma
      Serial.read();
      String addressStr = Serial.readStringUntil(' ');
      Serial.read();
      String messageStr = Serial.readStringUntil('\n'); // writes in the string all the inputs till the end of line character
      int address = addressStr.toInt();
      int message = messageStr.toInt();
      if (command == "Read"){
        Serial.print("Reading from EEPROM->Address: ");
        Serial.print(address);
        Serial.print("\n");
        Serial.print("Content of ");
        Serial.print(address);
        Serial.print("is: ");
        Serial.println(EEPROM.read(address));
      }else if(command == "Write"){
        Serial.print("Writing to EEPROM in Address: ");
        Serial.print(address);
        Serial.println();
        EEPROM.write(address, message);
      }
  }
}


text:
Undervoltage from solar panels
So i'be been toying with the idea in my head of creating a solar powered weather station with an arduino, two 6V 2W solar panels in parallel, two 5V USB battery packs, and an adafruit module which converts voltages from 3-12V to 5V (to charge my batteries). I'm also working on using some small relays or MOSFETs for the arduino switch between batteries.
The problem: If my solar panel voltage drops below 3V, the adafruit board will supply the batteries with a n unstable voltage below 4.8V. I need some sort of circuit or sensor that is capable of detecting when the voltage  from the solar panels drops below 3.3V and which will open the circuit to protect the batteries from unstable voltages.

You have selected a number of things that don't go well together. It is possible to use relays or mosfets to switch between batteries, and the Arduino could be used to measure a voltage. Or you can make a circuit with a few electronic components (e.g. a comparator). However, no one does it like that. It would be unreliable.
Every solar power charging module can handle darkness as well. Some modules will also create 5V.
This Adafruit module has no 5V output, it only contains the charging part: Adafruit:USB / DC / Solar Lithium Ion/Polymer charger - v2
It is out of stock at the moment, and you need solar cells, battery, a cable, and a DC-DC converter to make 5V.
When it is dark and the battery is empty, I assume the output drops and the Arduino stops working. Adafruit made a tutorial for it that shows the DC-DC converter and also Collin shows a DC-DC converter: Youtube, Collin's Lab: Solar
There are other modules like that. For example the Sparkfun Sunny Buddy.
Take care that the batteries don't get too hot.
It is possible to run some Arduino boards directly from a battery (3.1 to 4.2V). Then you would not need the DC-DC converter.
Buy solar cells that are the best in low light conditions. With enough sunlight, the power is no problem. It is the dark winter days that could be a problem.

So I've looked at many solar panel charge controllers and modules, and I found that pretty much all of them are just variable input D.C.-DC Step down converters, taking inputs from 6V or above. That would mean that the batteries would only charge in direct sunlight. However with the adafruit module I found, the input voltage can be anywhere from 3-12V.                                                              It sounds like I will try a comparator, which I have never used.

The other problem (which is very likely to occur) is that even with 2 solar panels in parallel at 3V there isn't enough current to charge the batteries properly. So i'll just set the comparator to a higher voltage.

In my opinion, you are still going in the wrong direction. If the voltage of a solar cell is low, then there is probably not enough current either. If you want even the smallest energy from the solar panel, try a energy harvester module. The solar charging modules have a chip specifically for that, it is not just a DC-DC converter. Don't connect solar panels parallel, set them in series.

I see what you're saying with the voltage dropping. However, why wouldn't I put them In parallel? It draws less current from each of them and still keeps them above 6V each in good sunlight right?

Maybe you can if they always have the same amount of light, but it doesn't make sense and it has no advantages. In series it is possible to add a bypass diode to each panel. In series the MPPT can be used to the maximum. The solar charging modules use a switching regulator, that means with more voltage and less current as input, they can create a lower voltage with more current.

ok I'll do series panel with some sort of charge controller, thanks!


text:
How to convert an hex string to an array of bytes?
How to convert the char array to Byte array? I tried every method but it doesn't work.
char CardNumber[8] = "B763AB23"; // Length is 8, basically it's in Hex
                                 // B7 63 AB 23

I need to convert it into Byte array to byte CardNumberByte[4];
So basically, it should be like :
CardNumberByte[0] = B7;
CardNumberByte[1] = 63;
CardNumberByte[2] = AB;
CardNumberByte[3] = 23;

I am unable to find any solution for that.

"B763AB23" is actually 9 bytes. You forgot the null terminator. And B7, 63, AB, 23 are not valid hexadecimal integer literals. They should be 0xB7, 0x63, 0xAB, 0x23.

Related: convert String Hex to Hex byte

There are indeed many methods (and they all work if done right).
Is it always a lenght of 8 ? That means it is 32-bit unsigned long number.
The strtoul can convert it to a long. Use '16' for the base. If you need the seperate numbers, you can shift the unsigned long and convert to bytes or use a union.
It is also possible to do with a for statement can convert each character of the input to a value: forum.arduino.cc: convert HEX (ASCII) to a DEC int
[ADDED]
Thank you @goddland_16 for providing a full sketch. I could not stay behind and wrote a sketch with strtoul.
char *CardNumber = "B763AB23";
byte CardNumberByte[4];

void setup()
{
  Serial.begin(9600);
  Serial.println("With strtoul");

  // Use 'nullptr' or 'NULL' for the second parameter.
  unsigned long number = strtoul( CardNumber, nullptr, 16);

  for(int i=3; i>=0; i--)    // start with lowest byte of number
  {
    CardNumberByte[i] = number & 0xFF;  // or: = byte( number);
    number >>= 8;            // get next byte into position
  }

  for(int i=0; i<4; i++)
  {
    Serial.print("0x");
    Serial.println(CardNumberByte[i], HEX);
  }
}

void loop()
{
}

Note that this is limited to 0xFFFFFFFF, or 4 bytes.

Here is a simple solution to your question. I took each character, checked against its hexadecimal character and returned as a combination.
char CardNumber[] = "B763AB23";
byte CardNumberByte[4];

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

void loop() {
  for(char i = 0; i < 4; i++)
{
  byte extract;
  char a = CardNumber[2*i];
  char b = CardNumber[2*i + 1];
  extract = convertCharToHex(a)<<4 | convertCharToHex(b);
  CardNumberByte[i] = extract;
  Serial.println(CardNumberByte[i], HEX);
}

  while(1);
}

char convertCharToHex(char ch)
{
  char returnType;
  switch(ch)
  {
    case '0':
    returnType = 0;
    break;
    case  '1' :
    returnType = 1;
    break;
    case  '2':
    returnType = 2;
    break;
    case  '3':
    returnType = 3;
    break;
    case  '4' :
    returnType = 4;
    break;
    case  '5':
    returnType = 5;
    break;
    case  '6':
    returnType = 6;
    break;
    case  '7':
    returnType = 7;
    break;
    case  '8':
    returnType = 8;
    break;
    case  '9':
    returnType = 9;
    break;
    case  'A':
    returnType = 10;
    break;
    case  'B':
    returnType = 11;
    break;
    case  'C':
    returnType = 12;
    break;
    case  'D':
    returnType = 13;
    break;
    case  'E':
    returnType = 14;
    break;
    case  'F' :
    returnType = 15;
    break;
    default:
    returnType = 0;
    break;
  }
  return returnType;
}

That is very kind of you to provide a working sketch. I hope you don't mind that I have a few positive comments. You give CardNumber a string of 9 bytes (with the zero-terminator it is 9 bytes) and CardNumber has only 8 bytes. The switch-case statement is long, when there is an error in there, it can be overlooked. Therefor a short calculation would be preferred.

yes, no problem. I only provided a simple working copy, not necessarily compact. Yours is a good one though.

A char array is a byte arrray. No difference whatsoever
What you are attempting to do is a conversion of hex string to byte. For that you have to determine if you are scanning left to right or right to left.
After that convert a char in the string to a half byte.
From there you shift the half byte left and or it with the next half byte until the whole string has been exhausted.

This is a great explanation. Now we just need to see you do it in code. Then, I'll upvote it.

Keep in mind you need to make sure to also convert from ASCII chars to hex/binary. A 0 in ASCII is a decimal 48 or hex 30, so you must subtract 48 from it to be a true hex zero. You must do this for all the ASCII chars, taking care to also account for the fact that you might see the ASCII "hex" chars in lower or uppercase A through F, and lowercase must be handled differently from uppercase since they are different decimal values.


text:
What is importance of the reflow profile?
I was reading the MPU6050 datasheet to understand all the type of errors that affect the accelerometer, after finding information on the Reflow Profile i look up on wikipedia the Reflow Soldering Definition
As a noob i can't understand the importance, initially i though it was correlated with the temperature effect on the accelerometer bias, but i was wrong.
Why is important?
How do you read this values?(or when you use this data)

This is not an Arduino question, it's an electronics assembly process question which would belong not here, but on electronics.stackexchange.com however it has already been asked and answered multiple times there.  Realistically most Arduino enthusiasts would buy this chip already on a board.  If you want to deal with the bare part for non-critical prototypes, skilled use of a hot air wand usually produces an acceptable outcome. If you are going for automated assembly, you would discuss this with your assembly provider; actually programming a reflow oven is far beyond the scope of things here.

Sorry for that,my mistake, i read now this link the idea to post this question here was to give the possibility to find information on this section about to the relevance or not to understand this concept related to Arduino. Before posting here i searched on electronics.stackexchange.com but i didn't find a suitable question, now i am studying this for example  Thanks for the suggestion :)

The reflow profile is of no interest to the end user - only to the manufacturer building a PCB. You don't need to know or understand it unless you are becoming a PCB manufacturer.

You use solder to attach components to a PCB. Reflowing is a specific soldering technique, manufacturers of components will specify which heating/cooling pattern will match the component(s). This having said, it's probably irrelevant to you, but atleast you now know why :)

@ChrisStratton Majenko  Paul Yep my question was offtopic, sorry for that. The story is the following: i went to a Fablab in Rome, with no previous experience, they suggest me  for a deep understanding on how Arduino works with an accelerometer to read all the datasheet, i was studiyng the "Sensitivity Scale Factor Variation Over Temperature" and arrived to the reflow profile, i made a mistake :) Thanks for your time, and sorry again :)

Reflow soldering is an assembly process for printed circuit boards (PCBs) in which surface-mount parts are placed on a PCB prepared with solder paste.  The solder is melted by heating in a temperature-controlled oven, which then electrically connects component leads to pads on the PCB.  ICs can be damaged by high temperatures/rapid changes in temperatures, so the thermal profile defines the acceptable limits on the temperature of the reflow to avoid damaging the component.


text:
Arduino uno and 1602A I2C not working
I'm a newbie in engineering.
I bought this with arduino learning kit.
It's simply not working.
There are several possible problems:

The display is not working due to a hardware problem. It could need to be repaired or soldered better.
The library that I chose could be buggy (software problem)

How can I check this? Thanks!
PS Build-in led is blinking as expected.
Here is the code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup()
{
  lcd.init();
  lcd.begin(8,2);

  pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
  digitalWrite(LED_BUILTIN, HIGH);
  lcd.setCursor(0, 0);
  lcd.print("TEST");
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  lcd.setCursor(0, 0);
  lcd.print("   ");
  delay(1000);
}

Do you have pull up resistors from sda and scl to your vdd?

Did you run scanner program first to verify the address of the I2C? you'll find the software at the bottom of this page https://arduino-info.wikispaces.com/LCD-Blue-I2C

Scanner is definitely best approach, but if 0x27 address is wrong, try 0x35 as a quick test. Unless you have soldered jumpers, these are the two most likely addresses. Your wiring looks correct.

Try with this address 0x3F or 0x27
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // or 0x27
void setup() {
lcd.begin(16, 2);
}
void loop()
{
  digitalWrite(LED_BUILTIN, HIGH);
  lcd.setCursor(0, 0);
  lcd.print("TEST");
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  lcd.setCursor(0, 0);
  lcd.print("   ");
  delay(1000);
}

Scaner helped me to find this address. https://arduino-info.wikispaces.com/LCD-Blue-I2C


text:
How to identify Adafruit Feather 32u4 via mac id/UUID/etc
I'm working with a couple Feather 32u4 devices and I've had success so far in setting them up as transmitters and receivers as well as hooking up one of them to a Featherwing Ethernet and talking over MQTT. My problem is that I'm trying to find out how I can implement some sort of identification system among them so that I can send packets to a specific radio. The approach I'd like to avoid is that of writing different versions of the code with different IDs hardcoded in each and uploading them to a radio (so ideally I'm wondering if there's a way to access an inherent mac ID/UUID of each radio). Each radio did come with what appears to be a mac ID printed on a piece of paper but I don't know how to access that directly from the device.
Thanks!

It doesn't sound like any of the components in your system have hardware unique ID's.  The ATmega does not, and if your radio does is unknowable without it being specifically identified, but most likely not given the included piece of paper.

There are multiple boards partially named "Feather 32U4". You need to edit your question to specify which one and post a link that provides more information on it.

I'm quite sure the reason they print a mac address on a sticker and put it in the package is that they have no way of storing the address in the the feather wing, or at least don't bother to do so if there is a place to store it.
It's up to you to get that address to your Ethernet.begin() call.
FYI, I have been trying to use EEPROM to store the mac address, but the bootloader appears to blow away EEPROM with every reboot.  If I figure that one out I'll update.


text:
Connect Arduino to an external microSD card reader
I have a camera with a microSd card reader that is the only output type.
I want to read the microSd when the camera makes a photo.
How can I read it with an Arduino?
Duplicating the reader connections and join it to my Arduino microSd reader?
Or I can try to connect to the circuit (its very very small)?
Do you think I can put an ESP8266 to the camera?
Thanks for all!!!

Have a look into "Processing" and the camera libraries for it.

Or do you want to achieve something like: http://www.instructables.com/id/How-to-use-OV7670-Camera-Module-with-Arduino/

I'm voting to close this question as off-topic because it's unclear what the goal is and/or the current goal is beyond the capabilities of an Arduino

You cannot
SD cards cannot be shared between masters in operation, and it is unsafe to disconnect the card from the camera with an electronic switch when the camera is not expecting that.
Nor is an ordinary Arduino fast enough to passively snoop the data being written to the card by the camera (while a card will let an Arduino write to it quite slowly, any camera would do so far, far faster)
Nor is an ordinary Arduino able to do much of anything meaningful with the image files produced by a typical camera in real time.
Nor can an ESP8266 while running Arduino-based software; it apparently does have some high-speed I/O capabilities but that would require low-level rather than Arduino-port-based programming.
For all practical purposes, you'd need to power off the camera, remove the card, and place it in the Arduino reader.

I guess no is an answer as well :) I highly agree that it doesn't really make sense nor seems practically possible. A lot of camera's can be directly interfaced with an PC, that would be a better option.

For what it's worth, I personally believe that the question is not on topic for the Arduino site because the fundamental problem is that SD cards are not designed to be shared, and already voted accordingly to close it.  But since we seem to be very slow about closing such questions went ahead and posted a comprehensive explanation as to why it's not achievable with an Arduino or Arduino-based technology.

True, but wel it's a question on Arduino. If it was possible, it would be on topic? But I agree it's not really answerable in any further way than you just did.

the camera is in other circuit and I need to extract the images/videos

As already explained, it doesn't really matter what you need, SD cards simply cannot be shared.  You will have to find another way to share data, or power down both devices and move the card between them.


text:
Powering a DC motor with an external battery
I'm working on a project where i need to control a 6 volt motor with an Arduino. The motor that I'm using requires 6 volts so I'm using a 9 volt with a voltage divider to get those 6 volts. My problem is that when I use the external power, the motor keeps spinning and ignores the input from the Arduino. If I use a 5 V battery and draw the 5 V from the Arduino, it works fine. I made sure that the voltage divider sends out 6 volts and the current code should have the motor not spinning. Here is the circuit: Motor Schematic.
What could I do to make the motor take the input from the Arduino?
Note: The schematic isn't like my actual circuit. In reality I have 6 V power supply instead of a 9 V and a voltage divider. I also am using a motor that requires 6 volts, while the one in the schematic requires 5 V.

The circuit appears to have 1KΩ in series with 2KΩ for the voltage divider, and it shows a 9V battery supplying power.  Is that how things actually are, or do you have some other resistor and some other power supply?   Also,  Please edit your question to include the motor part number and/or specifications, such as its rated current and its KV number

Neither a 9v transistor radio battery nor a voltage divider are suitable for powering a motor.

Im not using a 9v battery in the actual circuit, its just all that was available on circuits.io

Still, the voltage divider is a bad idea.

Your schematic is bad - the motor is connected betveen base and power, emitor is connected to ground.That keeps the transistor open, and B-E voltage is like 0.7V, rest is for the motor to rotate.
More over the transistor is open, so if you send pulses from pin 3, they are shortcuted to ground thru the transistor, not affecting the motor at all.
Switch the wires to Base and to Colector (lines 48 and 49) and it should work better.
(Still I would not use divider 9->6 volts, losing a lot of power constantly, I would rather change the PWM little down (and have it relatively fast, 1kHz or more) and the motor should be OK, if effective voltage ther would be under 6V - so the PWM under like 66% HIGH. Also shortcutting pin3 to ground with resistor is not optimal, the resistor should be between pin3 and Base.)

Switching the base and collector worked great! Thanks so much for the help

Good :) So can you mark it as solution?

In power application like motor driver you can not use voltage divider for step down the voltage because resistor drop the voltage when current flowing from the resistor increase. You can used voltage regulator or buck converter. The motor will work fine. Even you can use 9V battery and control the speed of dc motor using PWM. you use the following schematic both will work fine. The 2n2222 is the general purpose npn transistor which is used for power amplification. The arduino board can not provide large current at output pins to drive motors directly having a current rating more than 250mA.
In above schematic the LM2596 buck converter is used which current rating is about 3A. and you can adjust the desired output voltage.

The second option which shows in schematic is to use 6V battery.


text:
Drawing specific RGB on touch screen
I have the Arduino MEGA and an adafruit touch screen 2.8 inches.
My goal is to draw a pixel given a specific RGB
I am using the ILI9341, GFX, and TFT.h libraries to draw and control the touch screen. I noticed the drawPixel function given, in which it takes in three parameters and draws the pixel:
tft.drawPixel(4,4,ILI9341_BLUE);

But, I am trying to draw a pixel with specific a RGB. So instead, the function would ideally need 5 parameters instead of 3, x, y, and then R, G, and B:
tft.idealDrawPixel(5,6,89,234,76);

I tried putting in a number as the third parameter and not ILI9341_COLOR, and the screen just prints blue:
tft.drawPixel(45,67,255);

Is there a function that allows me to draw RGB pixels specifically? Thanks for any help!

As noted in the second paragraph on Adafruit's Graphics Library webpage,

First thing to note is that color is 16-bit, and that includes Red, Green and Blue in a 16-bit variable. The way the color is packed in is the top 5 bits are red, the middle 6 bits are green and the bottom 5 bits are blue.

If you want to specify 8-bit color components, you could write an intermediary routine to translate from that form to the 565 form.  For example:
#define rgbDrawPixel(x,y,r,g,b) drawPixel(x,y,(((r)&0b11111000)<<8)|(((g)&0b11111100)<<3)|(((b)&0b11111000)>>3))

Note, this assumes the TFT library you're using has the same specs as Adafruit's.  That might or might not be; I don't know how to account for a 255 color number showing up as blue rather than white.


text:
LEDs interfering with analog sound detection
My project is a sound reactive LED display on an Arduino Nano. There are 112 WS2811s in series connected to 5v, Gnd and D5 via 220ohm resistor.
I have a Keyes style sound detection module that has an analog output. It is connected to 5v and Gnd as well, and to A0.
The code reads the analog signal and then maps it to the brightness of the LEDs, in theory causing the LEDs to pulse.
Unfortunately what's happening is the brighter the LEDs, the higher the readings on the analog pin from the sound module.
Power is 5v 3A connected directly to Gnd and 5V with a 1000mF cap across + & - on the barrel adapter. I did this to allow the LEDs to draw the full 3A from the AC/DC converter (and to avoid having to power this via USB)
My suspicion is that as the LEDs get brighter the voltage to the sound module fluctuates which is throwing off the readings. Is there some merit to this hypothesis or is there another possible explanation?
Short of running two separate power lines (one to the Arduino and the other exclusively to the LEDs) are there any other ways I can regulate the voltage to the sound module regardless of the draw by the LEDs?

Your suspicion sounds very likely.  Temporarily running the Arduino and sound module off another source, with only a common signal ground shared with the LED supply, could be a way to test if that is related to the problem.

adding a schematic and your code would probably help the people trying to help you to give you better help.

Is not the Arduino Uno's barrel adapter connected to the Arduino Uno's linear 5 volt regulator.  That regulator likely needs more than a 0 volt drop across it's input and output.  Does your sound card sit on top of the Arduino leaching power from the Arduino board.  Consider what the sound card would see if it is leaching power after the Arduino Uno's 5 volt regulator.  This is where a schematic of your setup is needed.  Because all we can do otherwise is guess as I have just done above.

It's a Nano, not an Uno, so I've wired up my own adaptor as I mention in the OP.


text:
Serial.Write(buf,Len) how to read Serial sended array of byte
hello i'm trying to send array of byte with Serial.Write(buf,Len) but don't know hot to read this code with receiver.
SENDER code:
byte buf[4]={1,2,3,4};
void setup(){
Serial.begin(250000);
}

void loop(){
Serial.write(buf,4);
}

RECEIVER code (WRONG)
byte buf[4];

void setup() {
  Serial.begin(250000); // how suggest

}

void loop() {
  int i = 0;

  if (Serial.available()) {
    Serial.readBytes(buf,4);
    Serial.print(buf[0]);
    Serial.print(buf[1]);
    Serial.print(buf[2]);
    Serial.print(buf[3]);
  }
}

How to receive this ??

if (Serial.available()) only ensures that you have at least 1 byte inside the serial buffer, not 4. Read https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

You have two issues:
Firstly the transmitter is set to 250000 baud (a non-standard rate) while the receiver is set to 9600 baud. Both need to be set to the same rate.
Secondly the transmitter is constantly sending data and the receiver is constantly reading it, there is no way to ensure the two are synchronized. So your receive buffer could well end up being the end of one set of data and then the start of the next e.g. 3,4,1,2. If all you are sending is the same loop over and over this doesn't matter but for real world data it's an issue. If you have a value which you know will never be in your data (e.g. 0 or 0xff) then you can use that as a start of data marker, if not then things get a little more tricky.


text:
I have problem in sketch compiling error message is 'printNormalModeMessage' is not declared so what I can do
/* a,rduino door look project */
#include <SPI.h>
#include <MFRC522.h>
#include <LiquidCrystal.h>
#include <Servo.h>

#define RST_PIN  9
#define SS_PIN 10

byte readCard[4];
char* myTags[100] = {};
int tagsCount = 0;
String tagID = "";
boolean successRead = false;
boolean correctTag = false;
int proximitySensor;
boolean doorOpened = false;

//Creat instance
MFRC522 mfrc522(SS_PIN, RST_PIN);
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
//Parameters : (rs, enable, d4, d5, d6, d7)
Servo myServo;

void setup() {
  //Initiating
  SPI.begin();
  mfrc522.PCD_Init();
  lcd.begin(16,2);
  myServo.attach(8);

  myServo.write(10);

  lcd.print("-No Master Tag!-");
  lcd.setCursor(0,1);
  lcd.print("   SCAN NOW");

  while (!successRead) {
    successRead = getID();
    if (successRead == true) {
      myTags[tagsCount] = strdup(tagID.c_str());
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("-Master  Tag Set!-");
      tagsCount++;
    }
  }
  successRead = false;
  printNormalModeMessage();
}
void loop() {
  int proximitySensor = analogRead(A0);
  // if door closed
  if (proximitySensor > 200) {
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
      return;
    }
    if ( ! mfrc522.PICC_ReadCardSerial()) {
      return;
    }
    tagID = "";
    for ( unit8_t i = 0; i < 4; i++) {
      readCard[i]  = mfrc522.uid.uidByte[i];
      tagID.concat(String(mfrc522.uid.uidByte[i],HEX));
    }
    tagID.toUpperCase();
    mfrc522.PICC_HaltA();

    correctTag = false;
    if (tagID == myTags[0]) {
      lcd.clear();
      lcd.print("Program mode:");
      lcd.setCursor (1,0);
      lcd.print("Add/ Remove Tag");
      while (!successRead) {
        successRead = getID();
        if (successRead == true) {
          for (int i = 0; i < 100; i++) {
            if (tagID == myTags[i]) {
              myTags[i] = "";
              lcd.clear();
              lcd.setCursor(0,0);
              lcd.print("   Tag Removed!");
              printNormalModwMessage();
              tagsCount++;
              return:
            }
          }
        myTags[tagsCount] = strdup(tagID.c_str());
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(" Tag Added!");
        printNormalModeMessage();
        return;
        }
      }
    }
    successRead = false;
    for (int i = 0; i < 100; i++) {
      if (tagID == myTags[i] ) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print( "Access Granted!");
        myServo.write(170);
        printNormalModeMessage();
        correctTag = true;
      }
    }
    if (correctTag == false) {
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print(" Access Denide!");
      printNormalModeMessags();
    }
  }
  else {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print(" Door opeded!");
    while (!doorOpened) {
      proximitySensor = analogRead(A0);
      if (proximitySensor > 200)  {
        doorOpened = true ;
      }
    }
    doorOpened = false;
    delay(500);
    myServo.write(10);
    printNormalModeMessage();
  }
}
uint8_t getID() {
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return 0;
  }
  if ( ! mfrc522.PICC_ReadCardSerial()) {
     return 0;
  }
  tagID = "";
  for ( unit_8 i = 0; i < 4; i++) {
    readCard[i] = mfrc522.uid.uidByte[i];
    tagID.concat(String(mfrc522.uid.uidByte[i],HEX));
  }
  tagID.toUpperCase();
  mfrc522.PICC_HaltA();
  return 1;
}
void printNoramalModeMessage() {
  delay(1500);
  lcd.clear();
  lcd.print("-Access Control-");
  lcd.setCorsor(0,1);
  lcd.print( " Scan Your Tag!");
}

Arduino: 1.8.2 (Windows 7), Board: "Arduino/Genuino Uno"

C:\Program Files\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files\Arduino\hardware -tools C:\Program Files\Arduino\tools-builder -tools C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files\Arduino\libraries -libraries D:\arduino\libraries -fqbn=arduino:avr:uno -ide-version=10802 -build-path C:\Users\pc\AppData\Local\Temp\arduino_build_303473 -warnings=none -build-cache C:\Users\pc\AppData\Local\Temp\arduino_cache_499902 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files\Arduino\hardware\tools\avr -verbose D:\Arduino\dooropened.ino\dooropened.ino.ino
C:\Program Files\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files\Arduino\hardware -tools C:\Program Files\Arduino\tools-builder -tools C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files\Arduino\libraries -libraries D:\arduino\libraries -fqbn=arduino:avr:uno -ide-version=10802 -build-path C:\Users\pc\AppData\Local\Temp\arduino_build_303473 -warnings=none -build-cache C:\Users\pc\AppData\Local\Temp\arduino_cache_499902 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files\Arduino\hardware\tools\avr -verbose D:\Arduino\dooropened.ino\dooropened.ino.ino
Using board 'uno' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
Detecting libraries used...
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src\SPI.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\rfid-master\src\MFRC522.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\rfid-master\src\MFRC522Debug.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\rfid-master\src\MFRC522Extended.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\rfid-master\src\MFRC522Hack.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\LiquidCrystal\src\LiquidCrystal.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\Servo\src\avr\Servo.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\Servo\src\nrf52\Servo.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\Servo\src\sam\Servo.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\Servo\src\samd\Servo.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\Servo\src\stm32f4\Servo.cpp" -o "nul"
Generating function prototypes...
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp" -o "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\preproc\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp" -o "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp.o"
D:\Arduino\dooropened.ino\dooropened.ino.ino: In function 'void setup()':

dooropened.ino:49: error: 'printNormalModeMessage' was not declared in this scope

   printNormalModeMessage();

                          ^

D:\Arduino\dooropened.ino\dooropened.ino.ino: In function 'void loop()':

dooropened.ino:62: error: 'unit8_t' was not declared in this scope

     for ( unit8_t i = 0; i < 4; i++) {

           ^

dooropened.ino:62: error: 'i' was not declared in this scope

     for ( unit8_t i = 0; i < 4; i++) {

                          ^

dooropened.ino:84: error: 'printNormalModwMessage' was not declared in this scope

               printNormalModwMessage();

                                      ^

dooropened.ino:86: error: expected primary-expression before ':' token

               return:

                     ^

dooropened.ino:86: error: expected ';' before ':' token

dooropened.ino:86: error: expected primary-expression before ':' token

dooropened.ino:93: error: 'printNormalModeMessage' was not declared in this scope

         printNormalModeMessage();

                                ^

dooropened.ino:105: error: 'printNormalModeMessage' was not declared in this scope

         printNormalModeMessage();

                                ^

dooropened.ino:113: error: 'printNormalModeMessags' was not declared in this scope

       printNormalModeMessags();

                              ^

dooropened.ino:129: error: 'printNormalModeMessage' was not declared in this scope

     printNormalModeMessage();

                            ^

D:\Arduino\dooropened.ino\dooropened.ino.ino: In function 'uint8_t getID()':

dooropened.ino:140: error: 'unit_8' was not declared in this scope

   for ( unit_8 i = 0; i < 4; i++) {

         ^

dooropened.ino:140: error: 'i' was not declared in this scope

   for ( unit_8 i = 0; i < 4; i++) {

                       ^

D:\Arduino\dooropened.ino\dooropened.ino.ino: In function 'void printNoramalModeMessage()':

dooropened.ino:152: error: 'class LiquidCrystal' has no member named 'setCorsor'

   lcd.setCorsor(0,1);

       ^

Using library SPI at version 1.0 in folder: C:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI
Using library rfid-master at version 1.3.6 in folder: C:\Program Files\Arduino\libraries\rfid-master
Using library LiquidCrystal at version 1.0.5 in folder: C:\Program Files\Arduino\libraries\LiquidCrystal
Using library Servo at version 1.1.2 in folder: C:\Program Files\Arduino\libraries\Servo
exit status 1
'printNormalModeMessage' was not declared in this scope

You had typos in the title and you have an awful lot of typos in your code.

void printNoramalModeMessage() {
  delay(1500);
  lcd.clear();
  lcd.print("-Access Control-");
  lcd.setCorsor(0,1);
  lcd.print( " Scan Your Tag!");
}

You can't spell "Normal".

See :
dooropened.ino:49: error: 'printNormalModeMessage' was not declared in this scope

printNormalModeMessage();
You didn't implement this function.
(please align your code correctly to make it readable)

(it seems now the code is formatted, the function can be seen easier), See Majenko's answer


text:
How to pass variables to custom callback functions
I want to use the Ticker library of the ESP8266 Arduino core to (asynchronously) delay the switch of a pin to a desired state like below. I am not sure about the "here is" function definitions and I am having a hard time to find some documentation. Please have a look at what I tried so far:
#include <Ticker.h>

Ticker change_pin;

...

    uint8_t desired_state = 1;
    ...
    change_pin.attach_ms(100, [](uint8_t state_to_change_to){
        if( digitalRead(PIN) != state_to_change_to ) {
            digitalWrite(PIN, state_to_change_to);
        }
        else {
            change_pin.detach();
        }
    }, desired_state);

But the compiler's yelling:
espIKEA:145: error: no matching function for call to 'Ticker::attach_ms(int, toogle_light(uint8_t)::__lambda0, uint8_t&)'

   }, des_state);

               ^

...

C:\Users\USER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\Ticker/Ticker.h:45:7: note:   candidate expects 2 arguments, 3 provided

C:\Users\USER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\Ticker/Ticker.h:62:7: note: template<class TArg> void Ticker::attach_ms(uint32_t, void (*)(TArg), TArg)

  void attach_ms(uint32_t milliseconds, void (*callback)(TArg), TArg arg)

       ^

C:\Users\USER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\Ticker/Ticker.h:62:7: note:   template argument deduction/substitution failed:

C:\Users\USER\Documents\Arduino\Scratch\pintest\pintest.ino:145:15: note:   mismatched types 'void (*)(TArg)' and 'toogle_light(u8)::__lambda0'

   }, des_state);

               ^

So, I am having too few knowledge to understand what to do about it. I really would like to avoid having a separate function for the callback body.
PS: Important source file can be found here: Ticker.h

The function you are trying to call is a template function:
template<typename TArg>
void attach_ms(uint32_t milliseconds, void (*callback)(TArg), TArg arg)
{
    ....
}

So, you need to tell it what type of parameter you are passing:
change_pin.attach_ms<uint8_t>(100, [](uint8_t state_to_change_to) {
//                     ^- tell the compiler about the parameter
    ....
}, desired_state);

To pass more than one parameter: Since the library only allows one parameter, I would create a struct and pass a pointer to it.
struct callback_parameter {
    int i;
    char *p;
};

Then create one of these structs and pass the address of it. You just have to make sure the struct is valid the entire time the timer is running. So either use new, static, or make it global.
callback_parameter param; // global variable

...

change_pin.attach_ms<callback_parameter *>(100, [](callback_parameter * state_to_change_to) {
    ....
}, &param);

compiles now. thank you! what about passing multiple parameters? <uint8_t, char*> ?

@milkpirate I've updated the answer.

It looks like you are trying to do a lambda function and that's a bit too modern for the Arduino compiler.
So you have:
change_pin.attach_ms(100, ????, desired_state);

Its just the ???? we need to sort, which you have:
void DoStuff (state_to_change_to)
{
    if( digitalRead(PIN) != state_to_change_to )
    {
        digitalWrite(PIN, state_to_change_to);
    }
    else
    {
        change_pin.detach();
    }
}

Now you can't just define your own function signature, it has to be either callback_t or callback_with_arg_t.  So to make your "DoSTuff" function comply with callback_with_arg_t you have to define it as:
void DoStuff (void* argument);

Which means inside you function you will have to do this:
void DoStuff (void* argument)
{
    if (argument != NULL)
    {
       const uint8_t state_to_change_to = *argument;
       if( digitalRead(PIN) != state_to_change_to )
       .... As above.

Does that make sense?
The library defines the signature of the function that acts as the call back, it has to otherwise it wouldn't be able to provide all the parameters.  void* gets around any pretence at type safe behaviour and is fine as long as you are careful to control what can get passed through those parameters.
Always remember if you are working asynchronously there is no guarantee that data will still exist when you process it, if its dynamic memory it could have been freed/deleted or variables can go out of scope.

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


text:
analogWrite mosfet problem
i have a custom atmega328p board which have connected to pin 9 the gate of a MOSFET.
If i run a simple sketch like:
void setup() {

}
void loop() {
  analogWrite(9,70);
}

The motor connected to the mosfet works just fine, from 70pwm to 255pwm.
On the other sketch i'm receiving serial data from an android app via bluetooth. Ive 2 Servo motors and a DC motor connected to the mosfet.
The 2 servos works like expected, the DC motor doesn't spin unless i use a 255pwm.
void loop() {
  if(Serial.available() > 0){
      state = Serial.read();
  }
  if (state == 'S') {
      servoONE.write(90);
      servoTWO.write(90);
      analogWrite(MOSFET,MOSFET_LOW);
  }
  else if (state == 'F') {
      analogWrite(9,70);
      servoONE.write(90);
      servoTWO.write(90);
  }
  else if (state == 'L') {
      servoONE.write(MAX_SERVO);
      servoTWO.write(MIN_SERVO);
  }
  else if (state == 'R') {
      servoONE.write(MIN_SERVO);
      servoTWO.write(MAX_SERVO);
  }
  else if (state == 'Q') {
      analogWrite(MOSFET,MOSFET_HIGH);
      servoONE.write(MAX_SERVO);
      servoTWO.write(MIN_SERVO);
  }
  else if (state == 'E') {
      analogWrite(MOSFET,MOSFET_HIGH);
      servoONE.write(MIN_SERVO);
      servoTWO.write(MAX_SERVO);
  }
}

Do you know why the same motor works on the first sketch with any pwm above 70 and on the second sketch it only works at 255?

You have a timer conflict.
Pin 9 is OC1A which is the Output Compare Channel A pin of Timer 1. However the Servo.h library also uses timer 1.
So you can't use servos and still use pins 9 (OC1A) and 10 (OC1B) as PWM.
However, you can still use pins 3, 5, 6 and 11 as PWM since they are on other timers.

Ok, thanks for the quick answer, i see the pin 11 is the MOSI pin and im using an ISP programmer to program my board. Will i be able to program my board if i use pin 11 as PWM ?

Of course. So long as what you have connected to it doesn't interfere with the ICSP signal - and the gate of a MOSFET shouldn't.

Tested right now using pin 3 instead of pin 9, it works!!!  You saved me a lot of troubles :D


text:
Specify F_CPU in arduino to use 8MHz clock
I am using a custom made AVR board with Atmege-328p on it and it doesn't have a 16MHz crystal on it. I would like to use the internal 8MHz as clock. I have set the appropriate Fuses but now I am unable to tell the programs that F_CPU is 8000000UL. One way of doing it is to add another variant to the boards. I would like to if there is another way to set F_CPU ?

No, the boards.txt file is where it is defined and the only place it is (or can be) defined. Making a new board variant is the proper way of adding a new board with new settings.

Maybe there is already a board in "boards.txt" that is compatible with your board. The bootloader doesn't know if the 8MHz is from a crystal or from the internal oscillator, that means you can even use a bootloader for a 8MHz crystal, and you only have to change the fuse for the internal oscillator. During programming (for example burn the bootloader) with a programmer the ATmega328p requires a clock. Therefor you have to be careful not to set the external crystal (when there is no crystal), because then the programmer doesn't work.


text:
Arduino Due unable to access library
I am unable to run code on Arduino Due that I earlier ran on an Arduino Uno. The error indicates it is unable to recognize the library. Could this library access problem be due to difference of the micro-controllers of the 2 boards?

Quite possibly. The modern library format contains a list of board types it runs on (in library.properties). If the Due (SAM) isn't listed then it won't be included in the list of libraries.
For instance the SD library has:
name=SD
version=1.1.1
author=Arduino, SparkFun
maintainer=Arduino <info@arduino.cc>
sentence=Enables reading and writing on SD cards.
paragraph=Once an SD memory card is connected to the SPI interface of the Arduino or Genuino board you can create files and read/write on them. You can also move through directories on the SD card.
category=Data Storage
url=http://www.arduino.cc/en/Reference/SD
architectures=*

However the AVR specific SPI library has:
name=SPI
version=1.0
author=Arduino
maintainer=Arduino <info@arduino.cc>
sentence=Enables the communication with devices that use the Serial Peripheral Interface (SPI) Bus.
paragraph=SPI is a synchronous serial data protocol used by microcontrollers for communicating with one or more peripheral devices quickly over short distances. It uses three lines common to all devices (MISO, MOSI and SCK) and one specific for each device.
category=Communication
url=http://www.arduino.cc/en/Reference/SPI
architectures=avr

Note the last line of each - architectures=... - that defines what the library can work with. If your (unspecified) library doesn't have * or include sam in that parameter then there is no way that library will work with the Due.

Yes, Due wasn't listed earlier. I installed Due from the Boards Manager. It is able to run other programs . Currently it is not able to access a DFT library which I had earlier ran on Arduino Uno.

I am not talking about board support. I am talking about whether the library can ever support the Due. If it's a modern layout with library.properties and it's not designed to run on the Due then the IDE won't even see that it exists - no matter what you do.

"the IDE won't even see that it exists". This is incorrect. The Arduino IDE will still attempt to compile for the library even though the architectures value in library.properties doesn't match the architecture of the selected board. If compilation can proceed past preprocessing then the Arduino IDE will display a helpful warning: "WARNING: library FooBar claims to run on (avr) architecture(s) and may be incompatible with your current board which runs on (avr) architecture(s)." The examples of the library will also appear under File > Examples > INCOMPATIBLE.

Now libraries such as SPI that are bundled with hardware packages are only seen by the IDE when a board of that hardware package is selected but this has nothing to do with the architectures value in library.properties, it is solely controlled by the folder the library is located in.


text:
Powering leds from arduino with adapter
Sorry for having (again) a beginners question, but I was wondering something.
If I would want to drive like 20-30 LEDs from an Arduino (Uno), and I want to use an external adapter (12V, 1A), going into the Arduino, in what way I should drive the LEDs?
Problems I see:

I cannot connect too many LEDs per pin (max 20mA per pin)
I cannot connect too many LEDs per 'group' (I have to find out which pins are connected to what groups)
I cannot connect too many LEDS in total because of the max. 200 mA per VCC/GND (there are 2 or 3 GNDs, so that should be ok)
Using a relay/transistor etc, but how do I get the power? (there are also only 2 VCCs for 200 mA max)

So my basic question: how can I use the 1A from my adapter?

How precisely do you want to control the LEDs?

Have you considered using a driver that works with 12V?

I just read about a darlington IC (ULN8023) ... so probably that's the best way to do ... but I haven't found yet how to connect the 12V 1A adapter (I mean it will go into the Arduino), but how to connect / get that power to the LED ' chains' ?

Using relay module if you don't want to controle every single led could be a good aproach like this one - http://arduinobasics.blogspot.com.br/2014/09/relay-module.html

@AndrewPaes Well I don't need to control them one by one, but I want to have quite some possibilities, so a relay is a bit annoying to use in this case. I would need many.

drive each control group with an n-chan mosfet disconnecting the ground; cheaper than relays and silent. be prepared to use resistors to balance R,G, and B LED's "brightness"

@Majenko ... I'm thinking about a ULN8023 ... can I use the VIn to power the LEDs (and having 12V, 1A, or a bit less) ?

@IgnacioVazquez-Abrams I just found out about the  ULN8023 (can I use the VIn to power the LEDs (and having 12V, 1A, or a bit less) ?

I don't mean what hardware you think you want to use - I mean what do you want the LEDs to do?

@Majenko ... I want for Christmas to make some wooden small '2D'  cardboard tree, put LEDs in it, and making the LEDs go around, or flash on/off in groups, maybe add some Christmas tune along

Do you want individual control of each and every LED? Or will having, say, 6 groups of LEDs that all react together be sufficient?

@Majenko ... initially I had the plan to control every LED, but I don't want it to become a too complicated project (I would have to use 74HC595 probably), so I stick with like 6 groups or so.

@Downvoter: Please say what can be improved (this also applies to all my other answers you downvoted).

The simplest thing you can do is group the LEDs together into chains that almost add up to the voltage of the power supply.
If you have LEDs with a 2V forward voltage (typical red LEDs) you could have up to say 5 per chain.
Each chain, since it only has 20mA or so maximum, can be driven with a simple small transistor.

simulate this circuit – Schematic created using CircuitLab
Connect the 12V to either VIN or the barrel jack, and also drive the LED chain through a suitable resistor (R=V/I = (12 - (Num LEDs * Forward Voltage)) / 0.02). You can have as many chains as your supply can provide current for.

That sounds good ... would it be useful to use the ULN8023 (instead of the transistors)?

(and where does the maximum of 20mA per chain comes from? I would say 20 mA (per LED) * 5 LEDs = 100 mA)

Being darlingtons you get a larger voltage drop than just a transistor. You may not get it quite as bright. Other than that, it could be a convenient way of reducing component count (a chip instead of transistors)

Components in series have the same current but sum the voltages. Components in parallel have the same voltage but sum the current. The LEDs are in series, so they share the same current - 20mA, but sum their voltage - 2V each is 10V, leaving 2V for the transistor and the resistor.

Oh off course (now I feel really stupid).


text:
Cannot find COM port for Arduino after replacing Atmega328p
I had mistakenly burnt my ATmega328p that was there on the Arduino UNO R3 board. So I bought a new ATmega328p-pu with Arduino UNO bootloader installed and a sample blinking LED program pre-flashed.
However when I replaced it and plugged in to the PC using the provided Arduino programmer cable, I could not find the COM port in the device manager in Windows and neither in the Arduino IDE.
I should also mention that when I put the new Atmega328p-pu into the Arduino UNO board, the LED at 13 or L did start blinking. So I am inclined to think that both the bootloader and the sample program are there. But I cannot find the required COM port.
How do I fix this?

you should see the com port on the computer even without a chip. try rebooting.

Maybe the ATMega328P-PU isn't the only chip you blew up...?

@dandavis I could see the COM port in the device manager as a hidden device but it wasn't "active".

I agree with @Majenko.  Think of all the connections on the board, and the current path it would take to fry the CPU.  It must have gone through other components on the way.  Might be time to try another board to eliminate the possibility of it being a bad cable or a computer software problem.  .

Alright I might have fried the some other component on the board. I'll try something else. Thank you all for your replies.

My very first Arduino board had a bad UART on it. I can't believe how close I came to giving up before requesting a replacement board. I was just so sure I had messed something up.

Putting the ATmega into the socket backwards could potentially short out the board, and either prevent the USB chip from working or cause the PC to shutdown that USB port.

Then check wheather the problem is with your computer or the arduino.if it is with your arduino, consider replacing it. Check the arduino internal circuit for any burns

Generally the IDE will detect one it can use, so you shouldn't need to use the Device Manager.
When you select the board type, so far, so good.
Then when you ask it to pick the port, it will present a list of ports that it has discovered that are registered in the Device Manager.
One thing you will notice is that if you have a Genuine Uno, for instance, it will list that next to the port name.
But if you are using a board (of any type) that have the CH340-type port it will show just the COM9 or whatever it finds.
If it doesn't find any ports (My laptop always detects the COM1 port on the back that I never use so in my case if that is all it finds then it is not finding any USB ports)  then jump ahead to the arrow below.
So by trying each one you will find a port that works with your board.  Or not.
I am sure you have already seen the errors it throws when you use a port that won't work for you.
----->  If you have tried all the ports listed and none works, then you are left with only a couple of possibilities:  Either the cable is bad, or the board is not responding.
Ultimately, it doesn't matter what it says in Device Manager if the IDE won't use it.
So if you can find another board and see if the cable works that would eliminate the cable as being a problem.
But if it simply will not respond then look above in the comments at what @Majenko said.
Good luck.

Just a heads-up, this answer has been flagged as low quality. You might want to do something about it and expand upon your answer, before it gets deleted. It is rather terse, as it stands, tbh.

Thank you, @Greenonline.  I was tired and at the end of my work day when I posted that.  I agree that if I was reviewing it I would at the very least have said that it looks more like a comment.  I really appreciate the heads-up.  I hope this is better.  I know for sure that it works like this because I have had a bad cable that made me doubt brand-new Nanos.  I put three of them in the ? box before I decided to change cables and Amazing Grace they all worked.  TNX again.  Have a great day!

I met her once. She wasn't that amazing...

Heh, heh!     ;-)  That's pretty funny.


text:
How to store u-blox coordinates (lat, lng) values in doubles? [TinyGps++]
I use a u-blox gps with my arduino. I can successfully write out the value of a coordinate (lat, lng) like this: Serial.println (gps.location.lat(), 8); but when I try to store the value with all the decimals it returns 8.00 instead of the correct coordinate + all of the 8 decimals.
This is my code:
#include "TinyGPS++.h"
#include <SoftwareSerial.h>
SoftwareSerial gpsconnection (4,3);
TinyGPSPlus gps;

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

void loop()
{
 while (gpsconnection.available())
 {
   gps.encode(gpsconnection.read());
 }

 //this works and returns 8 decimals
 Serial.println (gps.location.lat(), 8);
 Serial.println (gps.location.lng(), 8);

 //but if i try to store it like this:
 double latcord = (gps.location.lat(), 8);
 double lngcord = (gps.location.lng(), 8);

 //it returns 8.00 on both the "latcord" and "lngcord" which is the wrong coordinate and also it doesnt return 8 decimals
 Serial.println (latcord);
 Serial.println (lngcord);

 //if i try to convert the value to a string and then back to a double like this:
 double lat = gps.location.lat();
 String msgLat =  String(lat, 8);

 double thelat = atof(msgLat.c_str());

 //with this i get the correct first two numbers out but only 2 decimals after, not 8 decimals as it should be.
 Serial.println (thelat);

}

Note, accuracy of floats and doubles is the same on Arduino: 25 bits max, or about 7.53 decimals

You forgot the , 8 from your println that specifies that it should print 8 decimal places. Instead you seem to have added it to the end of an assignment which makes absolutely no sense whatsoever.
double latcord = gps.location.lat();
double lngcord = gps.location.lng();

Serial.println(latcord, 8);
Serial.println(lngcord, 8);

ah ok so i cant store the value (with the 8 dec) straight to a double, i have to give the dec afterwards. got it! thanks

Floats and doubles don't have a fixed number of decimal places, that's not how they work.