text:
error: expected unqualified-id before '.' token
I am working on a library to display custom text on a TFT screen and I came up with this error while making an example:
EsploraHelloWorld:31: error: expected unqualified-id before '.' token
   TFTCharPlus.drawChar(chars[5, 0], chars[5, 1], chars[5, 2], chars[5, 3], chars[5, 3], 120, 0, 255, 255, 255, 4, EsploraTFT);
               ^

Heres my code:
#include <Esplora.h>
#include <SPI.h>
#include <TFT.h>
#include <TFTCharPlus.h>

// A table for all of the characters
const char chars[6][5] = {
  {0xf8, 0x20, 0xf8, 0x1f, 0x15},
  {0xf8, 0x08, 0x08, 0x1f, 0x01},
  {0x70, 0x88, 0x70, 0x00, 0x00},
  {0xc0, 0x20, 0xc6, 0x29, 0xc6},
  {0xf0, 0x40, 0x80, 0x5f, 0x01},
  {0xf0, 0x90, 0x60, 0x00, 0x3d}
};

TFTCharPlus TFTCharPlus();

void setup() {
  // initialize the screen
  EsploraTFT.begin();

  // make the background black
  EsploraTFT.background(0,0,0);

  // print the characters
  TFTCharPlus.drawChar(chars[0, 0], chars[0, 1], chars[0, 2], chars[0, 3], chars[0, 3], 0, 0, 255, 255, 255, 4, EsploraTFT);
  TFTCharPlus.drawChar(chars[1, 0], chars[1, 1], chars[1, 2], chars[1, 3], chars[1, 3], 24, 0, 255, 255, 255, 4, EsploraTFT);
  TFTCharPlus.drawChar(chars[2, 0], chars[2, 1], chars[2, 2], chars[2, 3], chars[2, 3], 48, 0, 255, 255, 255, 4, EsploraTFT);
  TFTCharPlus.drawChar(chars[3, 0], chars[3, 1], chars[3, 2], chars[3, 3], chars[3, 3], 72, 0, 255, 255, 255, 4, EsploraTFT);
  TFTCharPlus.drawChar(chars[4, 0], chars[4, 1], chars[4, 2], chars[4, 3], chars[4, 3], 96, 0, 255, 255, 255, 4, EsploraTFT);
  TFTCharPlus.drawChar(chars[5, 0], chars[5, 1], chars[5, 2], chars[5, 3], chars[5, 3], 120, 0, 255, 255, 255, 4, EsploraTFT);
}

void loop() {
  // not necessary
}

And for reference, here is the drawChar() function:
void TFTCharPlus::drawChar(byte data1, byte data2, byte data3, byte data4, byte data5, uint8_t xpos, uint8_t ypos, uint8_t colR, uint8_t colG, uint8_t colB, uint8_t size, TFT tft) {
  tft.stroke(colR, colG, colB);
  tft.fill(colR, colG, colB);
  byte data[5] = {data1, data2, data3, data4, data5};
  for (uint8_t x = 0; x < 5; x++) {
    for (uint8_t y = 0; y < 8; y++) {
      if (bitRead(data[x], 7 - y)) {
        tft.rect(x*size+xpos, y*size+ypos, size, size);
      }
    }
  }
}

How can I fix the error?
BTW: The error is not in the library, everything is done correctly
EDIT: I realized that the error occurs on all six drawChar() lines, and After fixing a small error, I also got this:
request for member 'drawChar' in 'TFTCharPlus', which is of non-class type 'TFTCharPlus()'

what does line 30 and 31 say?

What I presume TFTCharPlus is a class, and class can not call the function. You have to define an object of the class and that will call the function.

It appears that you are calling the "description" of the library method (function).  What is necessary is to use the "description" to create a "working copy" of the library method.  Then call the "working copy".
In the above statement, the "description" is the Class, "to create" means to instantiate and "working copy" is referred to as the Object.
In the Arduino Serial Port Example, you will find the following line:
SoftwareSerial mySerial(10, 11); // RX, TX

Here, the Class "SoftwareSerial" is used to instantiate the Object "mySerial".  Later in the code calls are made to the "write" method with in that object:
mySerial.write(Serial.read());

In this line:
TFTCharPlus TFTCharPlus();

you've given your TFT object the same name as its class, making that name ambiguous. If you change the name of the object to, e.g.:
TFTCharPlus TFTobject();

as well as changing all of your references to it (TFTobject.drawChar(...)), it should fix the issue.


text:
Writing Libraries that use libraries that are being used in the sketch
I know the title is a little obtuse, let me try to explain:
I am trying to create a library of simple functions for use with my TFT Panel.
The Panel has an include file (#include "SSD1306Wire.h")
I have a sketch and I have the above #include file referenced in the sketch
I also want to use my library tftHelper.h but that library needs to reference SSD1306Wire.h as well to get the helper functions to work.
Is there a way to reference SSD1306Wire.h one time and be able to use the reference in the functions in my helper library?
I guess, more importantly, what is the proper way to handle a situation like this?

The proper way to handle this is to have an #include guard in the header file to prevent the content from being included more than once.
In your header file filename.h you would add something like this:
#ifndef _FILENAME_H_
#define _FILENAME_H_

// Your header code here

#endif /* _FILENAME_H_ */

The #ifndef block will prevent the code from being included more than once. Best practice is to always put include guards in header files.

A library has no way of knowing what is in your sketch. The two things are completely separate and there is no way to bridge that gap.
You can't include library A into the sketch and expect library B to know about it. Library B has to explicitly have library A included in it for library B to even have a clue what library A is.
There are two important parts to including a library. Not only does it tell the translation unit that you include it in what the library has in it, but it also tells the IDE that you want to use that library and to compile the source code for it.
You see, a library usually contains two distinct things - a header file (or a number of header files) and source code files.  The header file describes the library - what classes it has, any exported functions or variables, etc.  The source code implements the library.  When you include a library it just inserts that definition of the library (the header file) into your source code at the point of the #include. Just like a copy-and-paste.
The IDE does a little extra magic and associates that header file with a directory which has other files in it. It then finds the source code files in that location and compiles them.
Every file that gets compiled gets compiled separately. This is called a translation unit (TU) and each one is completely separate from all the others. None can know what any other file has in it, unless you explicitly tell that file to find something from somewhere else (though you don't tell it where, only that it "exists somewhere else"). And that is what the header files do - they tell the translation units what things are available elsewhere.
So if TU A needs resource F it needs to be told. If TU B needs resource F it also needs to be told.
And because of the IDE's extra magic your main sketch has to also be told about every library in use - whether that library is directly used by the sketch or not - so that it knows to go and find and compile the source code for that library.

source: Stack Exchange

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

sort: votes


text:
Make system with ultrasonic sensor and servo
I want to create a system where the servo will make the ultrasonic sensor move and detect the area in front of it. I have made the program but when run the ultrasonic sensor can not detect as usual.
Does anyone have another program or why my program is not running as planned?
This is the source code :
#include <Servo.h>

const int trigPin = 10;
const int echoPin = 9;
int lampu = 13 ;

// membuat nama objek servo untuk pengontrolan servo
Servo myservo;
// variable untuk menyimpan posisi servo
int pos = 0;
long duration, inches, cm;
void setup() {
  Serial.begin(9600);
  pinMode(lampu, OUTPUT);
  myservo.attach(7);
}

void loop() {
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  inches = microsecondsKeInchi(duration);
  cm = microsecondsKeCenti(duration);
  Serial.print(inches);
  Serial.print(" in, ");
  Serial.print(cm);
  Serial.print(" cm");
  Serial.println();

  lampuNyala() ;
  servo();
  delay(10);
}

// start dari 0 derajar sampai 180 derajat
long microsecondsKeInchi(long microseconds)
{
  return microseconds / 74 / 2;
}

long microsecondsKeCenti(long microseconds)
{
  return microseconds / 29 / 2;
}

void servo(){
  for(pos = 0; pos < 180; pos += 1)
  {
    // pada posisi 1 derajat
    // memberitahu servo untuk pergi ke posisi  'pos'
    myservo.write(pos);
    // tunggu 15ms untuk pencapaian  posisi servo
    delay(30);
  }
  // start dari 180 derajat ke 0 derajat
  for(pos = 180; pos>=1; pos-=1)
  {
    // memberitahu servo untuk pergi ke posisi  'pos'
    myservo.write(pos);
    // tunggu 15ms untuk pencapaian  posisi servo
    delay(30);
  }
}

void lampuNyala(){
  if(cm > 0 && cm <=30){
    digitalWrite(lampu,HIGH) ;
  }
  else{
    digitalWrite(lampu,LOW) ;
  }
}

Comments in English would be helpful

Look at your code sequence. An ultrasonic measurement is only taken, when you use pulseIn(). At the end of the loop() function you call your servo() function. In it you tell the Arduino to first go from 0° to 180° and then back to 0°. AFTER THAT (!) the function exits and the loop() function continues. This means, that nothing else happens during the servo motion. The measurement only takes place between the motions, meaning about every 10s.
To solve this problem you need to make the servo code non-blocking. It is mostly a bad thing to use delay(), since you cannot do anything else during waiting. Think about how you are backing a pizza. You are not sitting in front of the oven the whole time, until the pizza is ready. Instead you are looking at your clock regularily and check, if it is time to take the pizza out of the oven.
You can do the same thing on an Arduino with the millis() function. It will return the milliseconds since the last reset/powerup of the Arduino. This has to be used as a clock. To do something after a specific time you first save the current time in a timestamp:
unsigned long timestamp=0;
...
timestamp = millis();

Then in the loop() function you are regularly (on every loop iteration) checking, if the difference between the timestamp and the current time is above your set interval:
if(millis() - timestamp > 30){
    // do something here, like moving a servo
    timestamp = millis(); //update timestamp for next event
}

The Arduino will not do the things simultaneously, but will switch between the different code parts so fast, that it will seem simultaneous. Also refer to the BlinkWithoutDelay example of the Arduino library.
Note: The current delay between two consecutive servo values is ok. If you want to go way faster with the servo, you have to watch out, that the rest of the code in loop() doesn't take to long. If this happens and you cannot make the other code parts non-blocking too, you can also do the servo part in an interrupt routine from a timer.

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


text:
Arduino Mega Hall sensor interrupt for a speedometer
I am having difficulty setting up an interrupt to count how many times the magnet passes so that I can count something like every 100 ms the actual speed.
I have a little code put together from the Internet:
const byte LED_pin =13;
const unsigned long wheel_circumference = 431800UL * 2UL * 31416UL; // = 94,248,000
unsigned long Speed = 0;
unsigned long PrevSpeed = 0;
volatile byte hall_rising = 0; // interrupt flag
volatile unsigned long irqMicros;
unsigned long startMicros;
unsigned long elapsedMicros;
unsigned long ledFlashStartMillis;
const unsigned long ledFlashWaitMillis = 10;
unsigned long displayStartMillis;
const unsigned long displayWaitMillis = 100;

void wheel_IRQ()
{
  irqMicros = micros();
  hall_rising = 1;
}

void setup()
{
  pinMode( 2, INPUT_PULLUP ); // pin # is tied to the interrupt
  pinMode( LED_pin, OUTPUT );
  Serial.begin( 9600 ); // can this be faster? faster would be better
  delay( 1000 );

  attachInterrupt( 0, wheel_IRQ, RISING ); // pin 2 looks for LOW to HIGH change
}

void loop()
{
  if ( hall_rising == 1 )
  {
    elapsedMicros = irqMicros - startMicros;
    startMicros = irqMicros;
    hall_rising = 2;
  }
  else if  ( hall_rising == 2 )
  {
    if ( millis() - ledFlashStartMillis >= ledFlashWaitMillis )
    {
      hall_rising = 0;
    }
  }

  // print speed 1000/Wait (10) times per second
  if ( millis() - displayStartMillis >= displayWaitMillis )
  {
    Speed = wheel_circumference * 0.0009 / elapsedMicros;

    displayStartMillis += displayWaitMillis;
    if ( Speed != PrevSpeed )
    {
      Serial.print(Speed); // this shows mm/sec with no remainder
      Serial.println(" kmh");
    }
    PrevSpeed = Speed;
  }
}

But when I use this code in U8glib to display the value on a GLCD . Values are totally wrong. Can someone help me?

What hall effect sensor are you using? Do the values come out correct when used with the serial monitor? Could you post what values you are getting with the hall effect sensor that are totally wrong, with the values of should be, how are sure they are wrong or right??

count how many times the magnet passes. In your entire code, you never count the number of times the interrupt is fired. You're code assumes that the loop function is called at least as many times as the interrupt is fired. If the loop function takes longer, by e.g. using the GLCD library, multiple interrupts could have fired, leading to elapsedMicros being a multiple of the value you expect. Leading to your code thinking the motor is running at half, or one-third, etc. the speed.

so this code is obtained from elsewhere. I think the code counts the time between two magnets passes hence my 0*0009 coefficint to convert everything to kmh. when i put the code the output is 1/2 km h instead of 40 km h like in serial output. I still want to sample this way so that the speed output will be constant and will not slow down with the speed. How can i improve the code to handle the wheel circumference in meters? how can i show when the bike is not running? Is there any way to make this simpler?

You either need to change your code to count the number of revolutions in the interrupt.  Then divide that value in your main loop by the elapsed time to get the angular velocity.  This may or may not work, as the number of revolutions may be small or even zero when you do the calculations.  Thus contributing to errors.
Or, change your code to record the elapsed time between rising edges in the interrupt.  Then find the inverse of this value.  This may be better as you could even miss an event in your main loop and still calculate the speed.  Careful not to take the inverse of zero.
To calculate speed you need to find the rotational speed of the wheel, and, consequently, how fast you are bicycling.  Use this equation:

...where omega is the revolutions per time as calculated by the 1st method above or reported by the interrupt routine in the 2nd method above.  Do not forget that the interrupt routine is probably using milliseconds and not seconds.
Also, do not forget to clear out the last value reported by the interrupt.  No matter which of the above 2 approaches you take.
Also consider special cases.  For instance, when you stop bicycling the interrupt will never fire.  In your main loop you may have a second counter which, when exceeded, indicates that your speed is zero.

The code is already in micros to get a good resolution. Actually its for a motorcycle. Can you explain the 0kmh thing?

I did not say in the answer, but, from what you said, I think the U8glib display library is taking too much time to execute and the code to calculate speed, not being robust, is failing.  I think you need to change the code from counting revolutions to counting the time between revolutions.  As for 0kmh, you need a second way of timing to indicate there has not been a revolution for a long time.  Perhaps more than a dozen seconds.  When this occurs, replace the last displayed speed with zero.

So i should use an interrupt that says time = x microseconds every impulse?

That is the approach I would use. Remember to convert from ms to hours.

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


text:
Arduino Dim RGB LED
I have an RGB led and I (just) would like to dim is brightness programmatically.
I searched Google thoroughly without any interesting code.
Some of them present only "how to" fade from on to another color.
If I change PWM value from 0 to 255, I can easily change color, but, my need is to change the brightness value from potentiometer (through read from analog pin).

To control the brightness of an LED with a POT read the pot position using the ADC, convert the range of values from 0 - 1024 to 0 - 255 then write that to the PWM controlling the LED.
This segment of code came from this discussion:
void loop()
{
  knobvalue = analogRead(potpin);
  knobvalue = map(knobvalue, 0, 1023, 0, 255);
  analogWrite(11, knobvalue);
}

This is just for 1 LED.  If you have 3 LEDs connected to 3 Arduino PWM pins, you will have to write the same value to all 3 pins.
If this is 1 RGB LED and you are controlling each of the 3 LEDs with 3 Arduino PWM pins, this will (for most RGB LEDs) cause the RGB LED to always appear White as you are varying all colors by the same amount.
If you are trying to vary the brightness of an RGB LED that is set to an arbitrary color...  this is more difficult:
Using 3 variables ranging from 0 to 255 pick your color.  Before writing these to the 3 PWMs which control the RGB LED, multiply each by the value read from the ADC connected to the POT.  Now divide each by the maximum possible ADC value.  Take care you do not exceed the range of your variables!  Write these new values to the 3 PWMs which control the RGB LEDs.

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


text:
Arduino IRremote stops working
I'm using a standard 38kHz receiver with Arduino-IRremote library and it works fine for a while but then it stops working. The loop function is running time after time as expected but at some point the library decode function starts returning false until I reset the board.
This example code works for me with any arduino nano or bare atmega328p at 8Mhz but for both of them it freezes after some receptions.
The code is the library example itself:
#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

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

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
  delay(100);
}

Some times this happens fast and other times it is after 20 or more receptions.
I only added a led blink later to test if the board is frozen or is only the infrared that stops receiving and it was the second case.

HI, are you the same user who posted the issue on Github

@RSM Yes I am. I don't know if it's a bug or what. First I tested on Nano with RGB leds driven with PWM and thought the problem was with that so I isolated the IR part on a bareduino that only receives from IR and writes to soft serial and sometimes it freezes too. When I reset the bareduino it works again.

I ran the code on an UNO and a pro micro with a continuous spool of IR data pointer at it for 15 minutes? so I don't know whats up the code on yours

I never saw it failing when connected to computer so I thougth had something to do with serial output so I removed all the serial prints but still the same result.

When running 'standalone' the nano is connected to a cell phone charger via USB and later when added the bareduino it is powered by the nano vcc.

I take it you have the latest version of the Library too?

I don't think the VCC is going to be a problem.

I got the latest version before noticing it was not stable. Did small edits myself (defines and so, no code changes) to be able to use it. If you think the problem might be that i'll try to change it this week to the stable tagged release. Now it is embedded on a device and it is not so easy to update.

If you have the library within the last three months it should be the latest. What definitions did you change, maybe put those in the question or link a file, possibly not the problem as it shouldn't cause it to freeze.

My current version of the library is this one https://mega.nz/#!6cwVVKpI!U3uWmixxSzxI5iRXUIXbOknbpRrv6JNWJFbleoWnXoo. I think I copied a change to support arduino pro micro/leonardo (tested but not much), dealt with half-done defines/ifdefs per brand and renamed it because of conflict with RobotIRemote.

Try adding a capacitor to the power rail of you bareduino. It might just be that the processor hangs, and there is nothing wrong with the code. Try toggling a led inside the loop to see whether the code is still running.

@Gerben There is a capacitor on the nano input. I think the processor does not hangs. Currently with nano+bare the nano does not hang at all. I am sure of that. RGB leds keep changing. I'll add a led to bareduino to make sure it is not hanged.

I was having similar problem (but not the same )
And it was due to software serial pins which keep on filling the buffers of MCU.
Some times it happen that pwm pins keep on receiving data e.g. GPS also keep filling the buffer and due to that arduino freeze .
To solve this problem I open new dummy software serial port.( select any pins which is free ) and do listen to your software serial pins when you want to read it otherwise make dummy listen.

This seems completely irrelevant to me. The question does not mention software serial.

Arduino tutorials I've seen don't mention it but the datasheets from the ir receptors manufacturers advice to stabilize vcc with a resistor and a capacitor.

It seems without that the receptor fail to correctly report the received wave so the library may decode it wrong. In my case the problem started to happen when I added RGB leds controlled by PWM on the same (stabilized) power supply.

In short: The IRremote Library has bugs that lead to unresponsiveness of the board.
There were some updates and now IRremote.h library 3.01 runs about a day with a FastLED.h WS1211 led stripe connected to it.
My approach to make it run reliable more than 24h with the latest library you could connect a digital pin to the reset pin on the Arduino.
Then use EVERY_N_HOURS to occasionally pull that pin low.
The Software reset via timer (watchdog timer library) every 2 seconds f.e. worked occasionally but not reliable.
That should even make every 2USD board clone run as reliable as it could/hardware allows it.
Have fun :)


text:
Strange problem. Arduino stops working after few hours. Opinions please
I am trying to setup an automated relay for my aquarium. The Arduino should switch off the pump every 3 hours for 20 minutes, and feed at particular times during the day. The code works fine for the first two on/off cycles. However after that the system stops responding.
I have tried many ways to solve the issue, I am led to believe that the issue could be a memory leak, which I have tried to fix that with watchdog timer reset, I have also tried resetting the Arduino but it doesn't work after the first reset.
I am still not sure what the problem could be, so any information would be appreciated.
I have included the code that I have stitched together using references from the web and a schematic of my circuit along with a picture of a tiny RTC module.
Schematic:

Tiny RTC:

My code is below, any advice would be appreciated.
#include "Wire.h"
 #define DS1307_ADDRESS 0x68
 #define RELAY_PIN 2
 #define Feed_PIN 4
 #define led13 13

 void setup() {
   Wire.begin();
   Serial.begin(9600);
   pinMode(RELAY_PIN, OUTPUT);
   pinMode(Feed_PIN, OUTPUT);
   pinMode(led13, OUTPUT);
 }

 void loop() {
   printDate();
   // digitalWrite(led13, HIGH);
   //delay(500);
   //delay(500);
   //digitalWrite(led13, LOW);
   // byte zero = 0x00;
   ///Wire.write(zero);
 }

 byte bcdToDec(byte val)  {
   // Convert binary coded decimal to normal decimal numbers
   return ( (val / 16 * 10) + (val % 16) );
 }

 void printDate() {
   // Reset the register pointer
   Wire.beginTransmission(DS1307_ADDRESS);
   byte zero = 0x00;
   Wire.write(zero);
   Wire.endTransmission();
   Wire.requestFrom(DS1307_ADDRESS, 7);
   int second = bcdToDec(Wire.read());
   int minute = bcdToDec(Wire.read());
   int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
   int weekDay = bcdToDec(Wire.read()); //0-6 -> sun-sat
   int monthDay = bcdToDec(Wire.read());
   int month = bcdToDec(Wire.read());
   int year = bcdToDec(Wire.read());
   //print the date EG   3/1/11 23:59:59
   Serial.print(month);
   Serial.print("/");
   Serial.print(monthDay);
   Serial.print("/");
   Serial.print(year);
   Serial.print(" ");
   Serial.print(hour);
   Serial.print(":");
   Serial.print(minute);
   Serial.print(":");
   Serial.println(second);
   if ( (hour ==  9 && (minute >= 00 && minute <= 20)) ||
        (hour == 12 && (minute >= 20 && minute <= 40)) ||
        (hour == 15 && (minute >= 40 && minute <= 59)) ||
        (hour == 18 && (minute >= 00 && minute <= 20)) ||
        (hour == 20 && (minute >= 20 && minute <= 40)) ||
        (hour == 22 && (minute >= 40 && minute <= 59)) ||
        (hour ==  1 && (minute >= 00 && minute <= 20)) ||
        (hour ==  3 && (minute >= 20 && minute <= 40)) ||
        (hour ==  5 && (minute >= 40 && minute <= 59)))
   {
     Serial.print(month);
     Serial.print("/");
     Serial.print(monthDay);
     Serial.print("/");
     Serial.print(year);
     Serial.print(" ");
     Serial.print(hour);
     Serial.print(":");
     Serial.print(minute);
     Serial.print(":");
     Serial.println(second);
     Serial.print(':');
     Serial.print(':');
     Serial.println(", pump off!");

     digitalWrite(RELAY_PIN, HIGH);
   } else {
     digitalWrite(RELAY_PIN, LOW);
   }

   if ((hour ==  2 && minute == 43 && second >= 52) ||
       (hour == 10 && minute == 00 && second >= 52) ||
       (hour == 13 && minute == 00 && second >= 52) ||
       (hour == 16 && minute == 00 && second >= 52))
   {
     digitalWrite(Feed_PIN, HIGH);
     Serial.println("feeding fish.....");
   } else {
     digitalWrite(Feed_PIN, LOW);
   }
 }

Important information: what time does it stop at and what is the last serial print? Add the info to your question rather than the comments.

When do you intend to "digitalWrite(Feed_PIN, LOW);"?

the last serial print is nothing. as the serial monitor stops scrolling too.

im not writing digital LOW because after the minute is over the if condition is not met

the time its stops is approximately after an hour

@user16314: Mikael has given you a very big hint. Think, man. Think.

@user16314: Telling us it stopped after an hour doesn't answer my question in the first comment. "What time does it stop at." Anyway listen to the hint!

ok here's the new code,

Ive not been able to figure the exact time it all fails , cause it fails randomly at different times, however ive implemented the Feed_PIN LOW. il try and note the exact time again. thank you

Cross post of Strange Unknown problem. Arduino stops working after few hours. Opinions please - trying to get help from two places, huh?

How do you know the system has stopped responding? Serial monitor? If you put back your LED pin13 blink does it freeze? I'm asking about exact times because that may point us to your if clauses.

@transistor I would suggest every one looks at the forum post Nick Gammon linked to as it has info the OP has posted related to some serial info.

http://forum.arduino.cc/index.php?topic=369822.0 here's a link to the arduino forum post

MIght avoid reading the RTC while the motor is running.

power input problem, try to solve the problem with power bank. another solution 555 Watchdog Timer

Perhaps you could expand your answer to explain what a 555 Watchdog Timer is, and why you think it would solve the problem in this case?

Your code seems fine, I cannot give a comment yet due to me not being a high enough ranked member, so i will try to phrase this as annswer instead.
Your arduino might be the problem, but I don't think it is likely as the clock is known to be troublesome, but as "transistor" suggested you should let it run on the serial for some time so that you can see if time is reported correctly.
I time is not working then I would like to direct your attention to this thread on the arduino forum, as this is apperently a very poor module. Several people have clocks that doesn't function properbly and there is many post adressing troubleshooting, but since this is supposed to be answer I have taken the top issues and put in below.
https://forum.arduino.cc/index.php?topic=177297.0
primarely they problems come from:
an unrechargeable Cr2032 battery is shipped, instead of a rechargeable li2032, this cause the charging Circuit on the board to act up.
Fix : replace to li2032 or remove charging circuitry - se link
ungrounded crystal - may or may not be a real issue
Fix: ground the crystal
Bad crystal:
Fix: replace crystal
Error in design - Resistor nr. 7 in place
Fix: remove resistor

Here's what the exact timings are :start time
::, pump off!
1/13/16 5:50:49
1/13/16 5:50:49
::, pump off!
1/13/16 5:50:49
1/13/16 5:50:49
::, pump off!
1/13/16 5:50:49
1/13/16 5:50:49
::, pump off!
1/13/16 5:50:50
end time
1/13/16 15:42:55
1/13/16 15:42:55
::, pump off!
1/13/16 15:42:55
1/13/16 15:42:55
::, pump off!
1/1/0 0:0:80
1/1/0 0:0:80
1/1/0 0:0:80
1/1/0 0:0:80
1/1/0 0:0:80
1/1/0 0:0:80                               after it starts spaziing 0:0:80 is the outpu

I know a very rough brute force idea, but I'm afraid you won't like it.
Here, how it goes: Use additional relay for powering arduino: While arduino is turned on, let the power be connected to NC contact and after each cycle, just turn this output to HIGH. How it works, you ask? Well, after a cycle, you will with logic 1 (HIGH) state cause to "unplug" the arduino power, which will lead to loosing power supply. However, the relay has a spring, that in case of loosing power, it goes back to NC, in which case, your arduino will be reset and working for another cycle.
That should 100% work, but as I said before: It's a horrible brute force idea :)

Perhaps you can try while (Wire.available() != 7); before calling Wire.read() 7 times in succession. Also remove leading zeros in the integer literals of 0 in your IF conditions. And make bcdToDec return an int instead of a byte, in the unlikely case of any overflow issues.

I had something same with my  Arduino UNO weather station until I switch to the PSU with lead battery. The most common thing is the power supply.
Try to use more powerful and use the ferrites on the PSU wires.


text:
Avrdude verification error after months of successful use
I have a 2560 that I've been working with for a while (over a year for sure), programming it with an avrisp mk2. No issue this whole time, then suddenly, a couple of days ago it starts failing with
avrdude: verification error, first mismatch at byte 0x0002
         0x01 != 0x95
avrdude: verification error; content mismatch

And very obviously not flashing (there's logic that blinks the LED on boot, and the LED isn't blinking anymore).
The first time this happened, the board appeared completely dead - the programmer wouldn't recognize it, and refused to flash it. After a few days and magic it started recognizing it again, and going through the motions of flashing my firmware, but the verification error persists. The location of the error hasn't changed, nor has the two values (0x01 vs 0x95).
Any ideas what this could be?

I have seen this myself. It turned out that coms were a little distorted. If you have access to one, use an oscilloscope to view the waveforms of the 4 ISP pins.

Similar to: https://arduino.stackexchange.com/q/44965/19409 https://arduino.stackexchange.com/q/30946/19409 https://arduino.stackexchange.com/q/52798/19409

@sa_leinad why would the coms get distorted after such a long time? i'll scope it tonight when i can.

Track corrosion, static damage, dry joint just to name a few.

Still don't know why, but now have a fix. Re-running the 'Burn bootloader' command from Arduino allowed me to then burn my firmware. Not sure if the issue is with fuses somehow being changed, or what, but this seems to have fixed the issue.
One more fun fact - I tried the same thing on a brand new Mega - same effect. First trying to burn my firmware resulted in a verification error (at a slightly different address), then burned bootloader and re-burned my firmware successfully. Wondering if an update to boards.txt or avrdude came through and changed something.

Had the same problem. Did the same thing: burn bootloader then burn my sketch. It worked.


text:
Trying to make a heart rate analyser with Arduino that will calculate the BPM of a person
I am trying to make a heart rate analyzer device using an Arduino board that will calculate the BPM of a person by using raw sensor signals greater or equal to the threshold value to calculate pulses/heartbeat in 10 seconds and then multiply the number of pulses by 6.
The circuit is fairly simple: it has a led that is going to flash on the finger of the person. In-front of the finger there is going to be a photoresistor that is going to read changing values of light falling on it. The values will be varying because of the blood flowing through the finger. When there is going to be a  pulse/heart-beat the amount of light falling on the photoresistor will increase, hence the reading of the photoresistor will also increase.
If the raw values read by the sensor are equal to or greater than the threshold value the code will increment the number of pulses by 1. To calculate the heartbeat rate we will have to count the number of pulses/heart-beats for 10 seconds and then multiply the count by 6.
In short the code that I will use will convert raw analog sensor data into BPM (Beats Per Minute) so that a user can get a standard measurement of his pulse rate.
I took the code that I am going to use from a website. Here is a link to page so that you can also have a look at the code.
I had some problem in the code and was wondering if anyone could help me with it. The full code is given below:
int sensorValue = 0;
int sensorValue = 0;
// variable to store the value coming from the sensor
int count=0;
unsigned long time1=0; // store the initial time
unsigned long time2; // store the current time

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(sensorPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  if(count==0) {
    time1=millis();
  }
  time2=millis();
  sensorValue = analogRead(sensorPin);
  if(sensorValue>156) {
    increment();
  }
  if(time2>=time1+10000) {
    counter();
  }
}

void increment() {
  count++;
  while(sensorValue>156) {
    Serial.print("Sensor value is greater than .75V\n");
  }
}

void counter() {
  count=count*6;
  Serial.print("Heartbeat rate is ");
  Serial.print(count);
  Serial.print(" per min\n");
  time1=0;
  time2=0;
  count=0;
}

Part of the code I'm not able to understand. This is located at the very top of void loop():
[note: i pretty much understand how increment and counter functions work but i am not able to understand how the program is able to take input for 10 seconds.basically how the counter function runs for 10 seconds]
 if(count==0) {
    time1=millis();
  }
  time2=millis();
  sensorValue = analogRead(sensorPin);
  if(sensorValue>156) {
    increment();
  }
  if(time2>=time1+10000) {
    counter();

Although I know that this part of the code that I am not able to understand counts the pulses for 10 seconds by taking raw sensor values and checking if these values are above or equal to the threshold value, I am not able to understand how it is working.
I would be highly obliged if anyone could help me with this problem of mine.

What that block does is fundamentally linked with the counter and increment functions. Replace those function calls with the function contents and what they do will become obvious.

Note: Most photo resistors are very slow to respond to changes in light.  I would be very surprised if you could even see significant fluctuations if the input changed as fast as 90 cycles per minute.

@Majenko  u misunderstood me. I am aware of what counter and increment functions do. im interested in knowing how the program is able to run for 10 seconds and and increment the value of the integer count, when the photoresistor detects raw input greater or equal to the threshold value.

@Majenko here are the lines of code in specific that i want to understand:

Is the problem that the code is not working as expected?  It it working correctly and you want it to do something different?

You must know this method has an error of up to 6, which is nearly 10%. Do you know that you can be much more accurate if you count the length of time 12 heartbeats takes instead of counting the heartbeats in 10 seconds? Once you have an exact period, 1/period is an exact frequency, without the error that came from multiplying to up-scale the per-interval frequency to a per-minute frequency.

// Record the start time into time1
if(count==0) {
  time1=millis();
}

// Set time2 to the current time
time2=millis();

// Read the sensor
sensorValue = analogRead(sensorPin);

// If the sensor value is high enough, increment the beat counter
if(sensorValue>156) {
  increment();
}

// If the current time is greater than, or equal to, the start time
// plus 10,000 milliseconds (10 seconds), show the heart rate
if(time2>=time1+10000) {
 counter();
}

int sensorValue = 0;
// variable to store the value coming from the sensor
int count=0;
unsigned long time1=0; // store the initial time
unsigned long time2; // store the current time

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(A1, INPUT);
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  if(count==0) {
    time1=millis();
  }
  time2=millis();
  sensorValue = analogRead(A1);
  if(sensorValue>800) {
    increment();
  }
  if(time2>=time1+10000) {
    counter();
  }
}

void increment() {
  count++;
  while(sensorValue>800) {
    Serial.print("Sensor value is greater than .75V\n");
  }
}

void counter() {
  count=count*6;
  Serial.print("Heartbeat rate is ");
  Serial.print(count);
  Serial.print(" per min\n");
  time1=0;
  time2=0;
  count=0;
}

try the above code


text:
ESP8266 using EEPROM to store a value of 100,000
I'm using Wemos mini in my project. I wish to store a Boolean value in cell #0, which changes every boot.
Since writing to EEPROM is limited to roughly 100,000 cycles - I want to store in cell #1 the amount of writing cycles done so far, so when reaching 100,000 , value will be stored in cell#2 and writing cycles will be stored in cell#3 and so on.
Reading and writing using #include <EEPROM.h> is done as needed, but since each cell can store a byte, it can only reach 255.
My question is how to store a value of 10^6 (except of convert it to a*2^0 + b*2^1 + c*2^2 + d*2^3....).
Guy
EDIT1
Part or relevant code:
void setup() {
        Serial.begin(9600);
        Serial.println("BEGIN:");
        if (HARD_REBOOT) {
                EEPROM.begin(1024);
        }
        if (HARD_REBOOT) {
                EEPROM.write(0,100000);
                EEPROM.commit();
                delay(50);
                Serial.print("value in flash: ");
                Serial.println(EEPROM.read(0));
        }
}

and its output:
Ȥl⸮⸮BGS[⸮<b8ɗ⸮BEGIN:
22:40:58.732 -> value in flash: 160

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

to save any variable to EEPROM use EEPROM.put(), to read it use EEPROM.get(). example
EEPROM.put(EEPROM_COUNT_ADDR, count);
EEPROM.get(EEPROM_COUNT_ADDR, count);
On esp8266 EEPROM is emulated in flash and there the whole page wears out. The EEPROM library of esp8266 does what can be done to protect the flash pages used for EEPROM emulation.

But still can use ‘put’ and ‘get’?

yes. the esp8266 EEPROM library has put() and get() too.

substitute write in put, was OK, but when using get yielded :
error: no matching function for call to 'EEPROMClass::get(int)'                  Serial.println(EEPROM.get(0));

EEPROM.get(EEPROM_COUNT_ADDR, count); ! Use second parameter for a variable to be filled.

@Guy.D, does it work?

The esp doesn't have an eeprom, but emulates it in its flash. Therefore 100.000 cylces will not apply, it's more like 10.000 cycles for flash.
The easiest way to prepare a datatype to be stored as bytes is to use union like follows:
union Converter{
  uint32_t ui32;
  byte eeprom_bytes[4];
}convert;

void convert_for_eeprom (uint32_t your_number) {
  convert.ui32=your_number;
  // convert.eeprom_bytes contains the 4-byte represenstation of your number, write those to eeprom
}

uint32_t convert_from_eeprom () {
  // read four bytes from eeprom and assign those to convert.eeprom_bytes
  return convert.ui32;
}

Note that this isn't a type conversion and the value of convert.eeprom_bytes are not meant to be processed, as they are simply interpreted as if they were a four-byte array, indeed those bytes contain "dumb" values. This way you can "convert" any datatype for byte-wise storage and read-back respectively.
Another option to convert a 32 bit integer to 4 bytes is by using bit-wise operations:
uint32_t your_number=100000;
byte b1=your_number;
byte b2=your_number>>8;
byte b3=your_number>>16;
byte b4=your_number>>24;

But this only makes sense for integers and I suggest taking a look at union.

EEPROM.put() can write any type. that is the easiest  way


text:
Obtain retained MQTT message
I’m using ESP8266 with Arduino code. Each device posts a ‘state’ and an ‘avail’ messages for a specific topic.
I wish to be able to read those retained messages and not only right after connecting and subscribe to MQTT broker.
EDIT 1  - Clarifications

I'm using Raspberry Pi Zero W as a MQTT Broker ( Local ).
When device boots, it changes its state from offline to online, but a different process checks periodically if state is offline or online for current device and others on the network.
it is not same as when subscribing to a retained topic, that you get the state at that specific time.
Storing chage of state in a variable, is one way to do it, but is there a different way ?

Sorry, question edited.

@jsotola - I'm subscribed for specific topic, but how I actively ( on demand -  inside an if statement ), verify that my retained state is online or offline ?

@Guy.D, when you say: "it is not same as when subscribing to a retained topic, that you get the state at that specific time." what do you mean?  If the publisher and the broker were on line all the time and the subscriber just came on line, the retained Node-RED message (topic and payload) would be  the last message sent from the publisher.

Once a message has passed through an MQTT broker there is not a way to retrieve it from the broker.
Consider instead deciding upon the action at the time the message is received by the subscriber.  If this decision needs to be made at a later time consider storing the state in the of the payload of the message on the subscriber.
Also consider running Node-RED.  If the platform running the MQTT broker can support Node-RED (such as a Raspberry Pi), it turns out to be convenient to run both on the same computer.  Node-RED contains nodes (graphical programming blocks) which can subscribe to and publish to MQTT topics.  By connecting other nodes to these, the topic and payload can be manipulated.  Of interest is an option within the Output MQTT node.  Here you can select Retain True.  This page explains how this option works:

Once you have sent a retained message to a topic, all subscribers will
  receive that message when they subscribe.
To clear a previously retained topic from the broker, send a blank
  message to that topic with the retain flag set.

This is the only way I had in mind ( storing state change in a specific variable ), but I was hoping there is a better way.

Please edit your question: 1) Add your comment in which you make it clear why you want to retrieve old MQTT topics.  2) Tell us what you are running your MQTT broker on.  3) What you will do with the on-line / off-line information.  As there are additional tools that work well with MQTT that may apply to your situation.

thank you. edited

@Guy.D, I need to go off line for a while.  If you do edit your question to make it better - I am going to assume you are using a normal personal computer for the MQTT broker.  That platform likely will support Node-RED a graphical programming language designed to process MQTT topics which uses a web page interface.  It will take some time to get used to - so we need to make a decision, based on your edited question, if it is worth the effort to install and learn.

thank you, did you see Q was edited with information asked?

Yes, it will be an effort, but I think installing and learning Node-RED will solve your problems.  And perhaps you can process your MQTT message payloads partly on Node-RED simplifying the code on your MQTT Arduino clients.

By the way- updating status to offline ( generated by lastwill) won’t update the specified variable


text:
How to recreate this basic ALPS switch board in Arduino?
I want to recreate this existing ALPS switch board (the board on the left) in Arduino, so I can control the switches (and 3 memory + 1 menu buttons) from my laptop. The ALPS switch board connects to a controller board (PSM) with relays, microprocessor, and DC motors connected to it.

The idea is to use Arduino to completely replace the ALPS switch board, while still preserving the controller board connection and current wiring and connector (16 pins + 2 empty pins).
Is there a way I can just connect the 16-pin connector directly to header pins on a certain Arduino variant? And program the individual pins, to replicate the manual switch input + 4 buttons?

See pin diagram attached (seen from the other end of the wiring, on the controller board side), where I get a little bit confused about terminal #C4 - #C7.
If easily possible, I want to use the controller board power, not the Arduino power.
I’m also not sure about what the 2000 Ohm resistor on the left side does exactly.
Edit 1:
Hopefully the new picture above clears things up a bit. The switch board connects to a PSM (Power Seat Module), which controls the DC motors of an early 2000s car power seat (don't think the OEM matters here). I want to control the PSM with my Arduino (so I don't have to use the ALPS board anymore). In other words, I have to replicate all the functionality from the ALPS board with my Arduino.
Edit 2: A picture of underside of Alps board:

Edit 3:
The P/N for the switch board is: ALPS ANJ971038D RH DR. And for the PSM (which includes the relays): ALPS ANV971018A. There is no public documentation that I found for any of the 2 boards. The pinout diagram above is from the dealership, but I'm not allowed to post further details about it.
Here are the results of what I measured myself using my multimeter. When the switch board is powered from the PSM I measured 4,5V on the + and - of the 4 memory buttons in neutral position. By pressing a memory butting the voltage drops to 0V. The + and - on the white switches measured 11,90V in neutral position. According to the pinout diagram the voltage is supposed to drop to 0V, but this didn't happen when I moved the switch while measuring. I also measured a resistance of 1490 Ohm between pin 2 and 5 of a white switch (so the neutral position), while the switch board was being powered! No resistance when the board is disconnected from the PSM.
I also measured pin #C4 and #C6/7 right from the connector, and I got 0,99V. #C5 and #C6-7 gave me 2,95V. Pin #C4 and #C5 are connected to the resistor (R1).
The switches are all momentary switches.
2 pictures of sketches/measurement results:

I think there's not enough information given for anyone to say (unless they happen to have that same board, and can read your mind to discover what you want to do).   Please edit your question to include the part number and model number the board is out of.    Please edit your question to indicate which switch connects to which pin, which switches are momentary or latching, and draw a picture of before and after  – ie, where the switch board is now, with what it connects to, and where you want it after whatever the conversion is.

Yes you could do that, if you could find the matching half of the connector.  You then run the leads off to your Arduino and write a program to do what you want.  How you do it is anyone's guess, but you could do it.

Before we can answer this question we will need a little more information from you. I can see that this board is for an electronic seat adjustment system. Do you want to replace the board in the picture with an Arduino or do you want to keep it and have the board control an Arduino? Also, what car is this board from?

@Matt I just edited. Is it more clear for you now?

@jwpat7 I just added more details. I think the pin diagram is clear enough on what pin connects to what switch, right? Which switch is doing what is printed on the switch board. All of the switches are in neutral mode as you can see on the picture. If you manually move the switch left or right or up or down, a signal will be send to the PSM and the motors to change the seat position. Let me know if you need further clarification.

That's much better. You probably wont find an off the shelf Arduino variant which would directly accept the plug but you can use an Arduino Uno with the Proto shield and wire up your own headers.  Please could you upload a picture of the underside of the ALPS switchboard and I'll try and figure out what that resistor is for.

@Matt Okay sounds good! Someone also told me I should use 8 relays (8 actions in total with the manual switches). I don't know why he said that or why I need it, if I can just directly program the pins from Arduino? (Still leaves open the question about the meaning of #C4 - #C7) Underside pic: https://imgur.com/a/CKSDZ

I was assuming you'd make some sort of graphical user interface on the software side which will replace the switches which will program the pins, so i'm not sure why they said that. That picture looks good, I'll get right on figuring out what the resistor does. Would it be possible for you to trace the wires to figure out which pins are connected on both ends? I'm not 100% sure but i think the #C4 and #C5 pins are used for diagnostics (The ECU uses them to check whether the board is connected and will bring up a fault code if not). I have a few people i can ask

Please could you get a picture of the board with the switches (Switches up pointing up like this picture at the top of this page) as top down as possible, i'm having a hard time seeing all the traces as some of them are hidden by the switches

CocoaNut, since the cable wiring at the Alps board end has a different pinout than the relay board end, you still should say which switch connects to which pin, and which switches are momentary or latching.  Also include all the documentation links and part numbers you have available, such as for the Alps board, the relay board, the PSM.  This will save time for people who are trying to help, by allowing them to find stuff on the web.   For example, there apparently is some document that you got the relay board pinout diagram from; what's the doc's name, and where is it found?

@Matt Yes, I indeed want to make a GUI! But after talking to an Arduino webshop guy, he also recommended me to use relays, based on the fact the switches are supplied with Ubat. So I measured 11,90V on 4 of the 6 switch pins when in neutral position. According to the pin diagram the voltage is supposed to drop to 0V as long as the switch is operated. When I operated the switch the voltage didn't change at all though on my multimeter.
I'll update my question later to reflect this information.

@Matt When I have my multimeter set to 2000 Ohm, it’ll either give me 1979 Ohm or 001 between C4/C5 and the resistor! So looks like you’re right :-)!
I also measured 0,99V and 2,95V on the C4-C7 circuits. Here’s a picture from a better angle: https://imgur.com/a/8bpZo (my Stack reputation doesn’t allow me to add it to the question).

Relays are good but as they are a mechanical device they have a higher rate of failure than a solid state device. I have personally used these MOSFETS in many projects and would highly recommend them http://www.ebay.co.uk/itm/10PCS-IRLB3034-IRLB3034PBF-HEXFET-Power-MOSFET-TO-220-NEW-/191736129878?hash=item2ca45d2956:g:n7cAAOSwI-BWQvbo     Here's the data sheet  http://www.infineon.com/dgdl/irlb3034pbf.pdf?fileId=5546d462533600a40153566027b22585

Have you been able to trace the wires between the plugs, as soon as you send me that information i will be able to start designing you a control board. Also, which Arduino would you like to use? I'd recommend an Arduino nano as they can be very easily integrated in to a custom circuit board.

@Matt Interesting, didn't know that! Thanks! I've been busy collecting answers, I hope to be able to update my post soon. I ordered some Arduino gear yesterday already. I have an Arduino Uno R3, Relay Shield v3.0 (4 relays, couldn't find one (in stock) with 8 relays), RedBear BLE Shield and an ARDX starter kit, so I have some extra components, wiring, breadboard, etc. The Arduino Nano looks good for a later stage in the project I think! (Same for MOSFETS, as it looks like it needs to be custom made, not an off the shelf shield)

http://i.imgur.com/GNR6K13.jpg   This is a picture of my most recent project's control board with the nano in the middle. Hopefully we'll be able to make something like this for your use-case or even get a custom PCB made but they can be expensive. If you don't mind me asking, what is your background? Have you got much electronics or programming experience?

@Matt Super cool! Looks exciting! Sorry it took me so long, but  I just added the extra information! (Still figuring out how to answer the "momentary or latching" question from yesterday.) Is this good enough for you? I have done some iOS projects and UI/UX design projects. So not a lot of electronics or Arduino programming experience. Do you have a website or a way to chat outside of this comments section ;)? I'm seeing a warning now to "avoid extended discussions in comments" ;-)

@jwpat7 Just added the details. Thanks for pushing ;-)!

CocoaNut, great, +1.  Note, the pinout voltages in diagram might be what you should see with cables attached both ends and under power, vs only one end hooked up. @Matt, you can flag the moderator to move the discussion to Arduino.stackexchange chat, if you want, which will key the discussion to the question.  Or just click on StackExchange, at top left corner of this page, then click 'chat' in the CURRENT COMMUNITY section, and open a chat.


text:
CRC test fail on MS5803-14BA pressure sensor - what can I do?
Problem:
I bought two MS5803-14BA sensors and I soldered them myself to a SOIC-8 PCB to be able to use them. Only one sensor is used in my circuit. To access it, I use an Arduino Pro Mini 8MHz/3.3V with a library that has a CRC check for the sensor. When assembled to the circuit, one of the sensors pass the test, however the other fails. I'm using I2C to access the sensor.
I would like both sensors to pass the test so I could compare readings from two assembled circuits, but I really don't know how to do it. I have a three questions:

Where this problem can be originating from?
What kind of limitations I have for not passing the CRC test? Does it mean that the collected data can not be trusted?
If I use the raw readings D1 and D2 from a sensor that have failed the CRC test and pos-compensate them in the computer, will I have trustful results?
How to solve it?

Schematic:

simulate this circuit – Schematic created using CircuitLab

The resistors R1 and R2 are pull-up resistors.
The capacitor C1 is recommended by the sensor's datasheet.
Sensor's PS pin is connected to Vcc in order to select I2C mode for communication. The other option was SDI.
Sensor's CLS pin is connected to ground to select the address 0x77 to the sensor. Case it is connected to Vcc, the address is set to 0x76.

Documentation

Sensor's Data Sheet
Library used

Are both devices on the same address and you manually swap them, or are they on different addresses and both connected to the same bus all the time?

They are on the same address and I manually swap them. I was doing this to see how close their readings are and after I saw bigger differences than expected, I started to research and end up finding the CRC test.

It sounds to me like either one is dead (damaged during soldering maybe?) or there is a problem with the carrier board for that one, or it's not soldered quite right (did you reflow it or hand solder it?)

I thought about this also. It is a STM soldering and I hand solder it. I used a multimeter to check continuity between the solder and the pins and didn't notice anything unusual. I'm using a breadboard, can this interfere? My SOIC board are from adafruit, they are quite good quality.

Breadboard can sometimes cause issues with its parasitic capacitance and poor connections, yes. However I'd expect spurious results from both modules if that were the case.

Agreed. I first have them assembled in different circuits, but than to prevent different capacitances, reatances and component failures, I decided to just swap them in the same circuit. I'm thinking about buying more sensors to test but each of them is 20$, not cheap at all. Apparently, it can only be the solder, although a visual inspection and continuity checks leads to no failure. Also, the sensor is recognized by the arduino board and give reasonable readings. I just don't understand why it is struggling to pass the CRC test

Welcome to StackExchange.  Be sure to take the Tour:  https://diy.stackexchange.com/Tour

Where this problem can be originating from?
As per page 7 and page 14 of the data sheet, there are 16 bytes of PROM in the unit which contain calibration information determined and written at the factory. This calibration information includes coefficients that must be used by whatever's reading the sensor to adjust for manufacturing variations. The data also include a CRC check code to let you confirm you've read the PROM correctly.
So there are three possibilities here:

The CRC as written to PROM is wrong.
There was an error while transferring the data from PROM to your MCU.
The software is doing the CRC calculation incorrectly.

The source code suggests that the most likely reason for this sort of failure is faulty wiring between the MCU and the sensor.
What kind of limitations I have for not passing the CRC test? Does it mean that the collected data can not be trusted?
Potentially, yes. To determine how bad things really are and what might be going wrong you need to do a bit more experimentation.
When you call the initializeMS_5803() function you pass it a boolean parameter determining whether it's running in verbose mode. Set this to true so it prints out the coefficients 0 through 7 to the serial port during initialization. Restart your Arduino several times, ideally under different conditions of temperature, power, physical wire configuration (if any), etc., and see if the values ever change. If they are ever different from a previous run, you have either cabling corrupting the data transfer or a defective sensor. You may be able to look at which bits change, if any change consistently, to get some insight into how "random" the problem really is. (Could it be that only a certain bit pattern is being transmitted unreliably?)
If all values always read the same, compare them to the values read from your good sensor. If they're quite similar, and you're generally getting similar readings under similar conditions from both sensors, I would suspect possibility 1 or 3 above, and reckon that you're likely to be getting reasonably reliable data from the sensor. If the values are vastly different this doesn't necessarily mean that the sensor will be unreliable; I have no idea how much these coefficients vary from unit to unit.
If I use the raw readings D1 and D2 from a sensor that have failed the CRC test and pos-compensate them in the computer, will I have trustful results?
Again, that depends on whether or not it looks as if you're getting corruption on the data link. As above, if you ever read different PROM data from run to run on startup, the sensor is much less likely to be producing trustworthy data.
You could also try comparing the raw readings from both sensors under conditions as close to identical as you can make them. I don't know how close in calibration the two sensors are, but if they are close, the raw data should look similar and that would be a sign of reliability.
How to solve it?
First, determine if you are getting the same or different PROM values across multiple startups. If they're always the same, send your good and bad values to the author of the driver and ask him if he thinks his CRC algorithm might have an error in it. (Or check it yourself against the application note mentioned in the data sheet, if you feel up to it.)
If the CRC algorithm in the software you're using is correct, given that you appear to reading successfully from another sensor, I'd send the sensor giving the CRC error back to the manufacturer, along with the coefficients you had read, with a query as to whether they have got the CRC wrong or you're reading the data wrong.
If you're getting different PROM values, that's either a faulty sensor or a wiring problem. You may be able to help isolate this with the usual tricks: slow down the transfer speed (with Wire.setClock()) to see if that reduces data corruption, re-wire the circuit with different (and preferably shorter) wires and other parts, make sure you've got caps in the appropriate places to filter noise, put a scope or a logic analyzer on the SCK and SDA lines to see if you can see any dodgy-looking waveforms, and so on. If anything looks strange, you can always use your working unit for comparison. If all that still looks good, it may well be a faulty sensor.

Thank you for this very elaborated answer. You got all the points I had doubts.


text:
Interfacing TRRS headphone to Arduino Uno
I have been working in a Arduino project lately which requires human voice input to Arduino with some processing Arduino need to perform specific task. Simple sampling of incoming signal and calculating average amplitude from it nothing complex.
My problem is I have tried using electret microphone to receive human voice input but failed since the Elec Mic is not sensitive to detect the voice even though i hooked up with LM386 amplifier circuit. So that option is out of the picture. Then i intend to use Android mobile headphones (TRRS) to receive the human voice which will provide great sensitivity for our voice.
Starting through simple internet searches i bought a product 3.5mm breakout module from Ebay. But am unsure of how to connect them to Arduino. Different sources in internet giving different information i couldn't figure out how to connect the headphone to arduino and read it's Mic output from headphone.
Seeing the pin out of TRRS headphones

i can't understand how could i possibly power my headphones with only GND pin available. I tried several wiring connections given in the internet to read the Mic output of my headphones through Analog pin A0 of Arduino but no luck so far. So my question is
1) How do i power the TRRS headphone using Arduino?

2) How can i read the MIC output of my headphone using Arduino? Is it even possible?
3) I have read somewhere the audio out from headphones will be of FSK modulated is it true?
Any help will be much appreciated. Please do provide if you have any links that might answer my questions.
Thanks in advance.

No.... Just that: no.

You were seriously ripped off with that breakout. That's about 10p worth of components they sold you for about £4.

You "power" the left and right channels of the headphones the same way you "power" a pair of speakers: send an audio-frequency signal of sufficient amplitude to them. This is, for example, what a headphone amplifier or the audio amplifier in your stereo system does.

Welcome to Arduino SE.  You can take the tour at https://arduino.stackexchange.com/Tour

@Majenko That's a real shame and i regret for buying it.

@Curt J. Sampson Thanks for that :) but i need to receive signal from Mic part of my headphone to my Arduino pin and how do i do it? Should i connect a 10k resistor in series with "Sleeve" pin and pull it high to 5v rail like the way we use the electret microphones in a circuit?    That's the part am having trouble with exactly.

You use whatever technique is appropriate for the microphone connected to the sleeve pin, which is the same technique you'd use for that mic. when connected via something other than TRRS. I think you really want to ask a new question describing the mic. you're using (as opposed to the cable between the mic. and Arduino) and asking how to hook that up.

@CurtJ.Sampson Identifying  the Microphone can be a problem. Am using my old Samsung mobile headphone for feeding the voice input to my project. I am not sure Mic used can be identified in it. Thoughts please?

Seems the question then might be, "given a typical headset/mic of the sort used on PCs and mobile phones with a TRRS jack, how can I use the mic as input to an Ardunio to do _______?"

@Curt J Sampson Yeah that makes more sense will post a new question as you suggested

TRRS relates to the style of the jack plug used: Tip Ring Ring Sleeve. You still need to amplify the signal with a microphone preamp the same as your electret (in fact it will be an electret in there anyway).
And then the Arduino cannot process human speech. You may be able to use a voice recognition module to get it to respond to specific commands, but the Arduino by itself has no hope of even thinking about it.

Check PID library for signal processing possibilities

@mico How on earth can the PID library process audio?

I meant to tell some basic signal processing library, first I found was PID. It did not do what I wanted on closer look. Supposedly there is some low pass filtering, noise reduction and or echo controls available? Or are they all circuits on this scale? Not libraries?

@mico The Arduino lacks the resources to do much in the way of audio processing. The quantity of data and speed of processing required is too much. You can do low-pass filtering (averaging) on small sample sets (a few hundreds of samples - fractions of a second), and just about run an integer FFT on a similarly tiny sample set. Anything like voice recognition is impossible without dedicated hardware.

I missed the need for recognizing voice. Signal sampling can maybe detect sound level in general, quite much not more, so it is not good fit.

@Majenko I described it incorrectly, i didn't want to do complex signal processesing with the input signal. To be more clear my project is intended for fun purpose only so nothing critical. Am looking to sample the input signal from MIC and then want to determine the average amplitude of the samples no big deal ( I believe). But am stuck at getting the input from the headphone mic to the Arduino, to cut my question short what exactly i need to connect to the "Sleeve" part of my this TRRS module to get the output? Any suggestions please

@FrankDonald You need a microphone preamp then. With that you need a 50% Vcc DC offset imposed on the signal for the ADC to read it properly.  You can build your own, there's plenty of schematics on google. Or you can probably buy one.

@Majenko Now that can be a start. I will look for preamp circuits and build one for my headphones. But again the question stands how to connect it to the sleeve pin and my headphones will be powered? thoughts? Edited the question with image explaining my problem, kindly take a look

You don't power it at all. The microphone forms part of a circuit and that circuit is powered.

@Majenko Seems like i got some idea about that. Let me try it out and see check if it works

It sounds to me as if your project is really more about what you do with the audio once you're sampling it into the Arduino and this whole "how do I get a usable signal out of a microphone" thing is not your main interest. In that case, I suggest just going with something like this MEMS microphone breakout board which includes the microphone and all the circuitry necessary to get a proper signal to an analog input on the Arduino.

Looks like pretty thing to use for my project will consider buying it. But before that let me try again with my headphones with all suggestions. Am trying to make it look like more of DIY setup so hoping my headphone setup should work


text:
Problem with programming digispark ATtiny85 board with Arduino IDE
I have bought a Digispark ATtiny85 board to learn about that microcontroller. So I tried using internal register names in the code rather than using Arduino in built functions. I can get the board to work when comes just input and output operations. For example the below code works and I can get the on board LED to turn ON and OFF
#include<avr/io.h>
void setup()
{
  DDRB |=(1 << PB1);  //set PB1 as output
}
void loop() {
 PORTB |= (1 << PB1);    // Turning ON LED connected to PB1
 delay(1000);            //Using Arduino IDE inbuilt delay function to generate delay of 1 second
 PORTB &= ~(1 << PB1);   //Turning the LED off
 delay(1000);

}
I have tried using Timer0 of ATtiny85 module to generate time delay of one second. But unfortunately I couldn't get it to work.
#include<avr/io.h>
#define F_CPU 16500000UL
#include<util/delay.h>

void timer_config()
{
 DDRB =0b00000010; // set PB1 as output
 GTCCR|= (1<<TSM);      ///Halt the timer for configuration
 TCCR0A=0x00;             //Normal mode
 TCCR0B=0x00;
 TCCR0B |= (1<<CS00)|(1<<CS02);   //prescaling with 1024
 TCNT0=0;
 GTCCR&=~(1<<TSM); //Start the timer
}

void tmdel()
{
 int i=0;
 while(i<=6)
 {
  while((TIFR & (1 << TOV0) )==0);        //Waiting for 0-255 and flag to raise
  TIFR|=(1<<TOV0);      //Clear the flag
  i=i++;                          //increment by one
 }
}

int main()
{
 timer_config();
 while(1)
 {
  PORTB|=(1<<PB1);     //PortB1 high
  tmdel();                         //Delay of 1 second
  PORTB&=~(1<<PB1);     //PORTB1 low
  tmdel();
 }
}

I have used the overflow flag to identify TCNT0 register status. I have uploaded the above code but the LED isn't responding as anticipated.
When searching the internet I have got few suggestions that this might be because Arduino IDE uses timer registers for delay function. When user attempts to access timer registers it might not work as intended.
But am not sure about the validity of above opinion. Can anyone help me with it? Since am learning this controller, practicing core programming is quite important. If I cannot program ATtiny85 using Arduino IDE this way, can someone suggest a way or alternate hardware setup to program ATtiny85 and access its registers without a problem.

Since the Arduino ecosystem is open-sourced, you could look into their sources to find out about timer usage. -- However, as the Arduino IDE comes with a complete GCC for AVR, you can use any editor or IDE you like and write software without using the Arduino IDE / library.

Your code (the second one) does not use any Arduino functions, and thus the IDE is not relevant. It would help to indent your code in the usual way, to make it more readable.

Without going through your code line-by-line, I would say your issue is the registers you have used. The IDE is not relevant to your problem. Or possibly your use of i=i++ as I mentioned in my reply.

 i=i++;                          //increment by one

The result of the above statement is not defined. That is, it is not necessarily "i + 1".
See:

http://en.wikipedia.org/wiki/Sequence_point
http://c-faq.com/expr/seqpoints.html

Instead use:
i++;

Or:
i = i + 1;

A note about "undefined behavior":
http://en.wikipedia.org/wiki/Undefined_behavior

When an instance of undefined behavior occurs, so far as the language specification is concerned anything could happen, maybe nothing at all.

i = ++i; then? q-;

Very amusing. No.


text:
How to edit this IR sensor code to COINSLOT sensor
The project is Like a secured PiggyBank but it will count the coins inside it.
Im using a coin sensor at default it has 5v, then goes to zer if inserted with a coin.
I have 2 codes The one was form my old project then second one was a coinslot code got in youtube.
Im hoping someone can guide me where to deelte some codes, then add it at one lsit of code.
Behavior of the project
-Start > Display Total : Amount > if I will unlock the solenoid it will display Welcome "NAME" .
Hope you can get my Idea. Some of code inside of the solenoid was not perfect sorry for that I just get it from scrath without proper knowledge.
This is code for FINGERPRINT TO SOLENOID LOCK
#include <Adafruit_Fingerprint.h>    //Libraries needed
#include <SoftwareSerial.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

#define I2C_ADDR 0x27          //LCD i2c stuff
#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7

int in2 = 4;

int But1=8;  // In order to add a push button I got the 5v from the pin 8 instead of "5v" arduino pin
int But2=9;

String Names[] = { "RAVEN", "Surtr", "Tech",}; //Those are the names affected to the fingertemplates IDs
                                                 //The first on which is Names[0] : Yassine has the ID 1 in the fingerprint sensor

SoftwareSerial mySerial(2, 3);                  //Fingerprint sensor wiring RX 3, TX 2
LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin); //LCD declaring

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);                    //Fingerprint sensor declaring

void setup()
{
  pinMode(in2, OUTPUT);
  digitalWrite(in2, HIGH);
  pinMode(But1, OUTPUT);    //Push button stuff, I made the pin 8 permanent LOW level
  digitalWrite(But1,LOW);
  pinMode(But2,INPUT_PULLUP);     //And I read the button state on pin 9

  Serial.begin(9600);               //Serial begin incase you need to see something on the serial monitor
  finger.begin(57600);              //Sensor baude rate
  lcd.begin (16,2);
  lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.home();
  finger.getTemplateCount();        //Counts the number of templates stored in the sensor flash memory
  delay(2000);
  introScreen();
}

void loop()
{
  int result = getFingerprintIDez();  //This function keeps looping and waiting for a fingerprint to be put on the sensor
  //delay(50);
  bool Button1=digitalRead(But2);  //Reading the state of the pushbutton
  if(Button1==LOW or result >= 0){
    //If the button is pressed it opens the doorlock as the button is meant to be inside
    OpenDoor();
    introScreen();
  }
}

void introScreen()
{
    lcd.clear();
    lcd.print("Place finger");
}

//Main function taken from the "fingerprint" example and modified
//Only the modifications are commented
int getFingerprintIDez() {
  uint8_t p = finger.getImage();        //Image scanning
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.image2Tz();               //Converting
  if (p != FINGERPRINT_OK)  return -1;

  lcd.clear();                     //And here we write a message or take an action for the denied template
  p = finger.fingerFastSearch();     //Looking for matches in the internal memory
  if (p != FINGERPRINT_OK){          //if the searching fails it means that the template isn't registered
    lcd.print("Access denied");
    delay(2000);
    introScreen();
    return -1;
  }
            //If we found a match we proceed in the function

  lcd.print("Welcome");                  //Printing a message for the recognized template
  lcd.setCursor(2,1);
  lcd.print(Names[finger.fingerID-1]); //Then print the name we gave it and the -1 is to remove the shift as the ID starts from "1" but the array from "0"
  return finger.fingerID;
}

/*The two following functions depends on your locking system
 *mine has a DC motor that should turn in both ways for opening and closing
 *that's why I'm using H bridge, you could have a solenoid with a transistor
 *then you'll need only opening sequence but controlling the transistor
 *as the closing is spring loaded...
 */

void OpenDoor(){
  digitalWrite(in2, LOW); // turn on motor
  delay(5000);
  digitalWrite(in2, HIGH); // turn off motor
}

This code is for COINSLOT
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
#include <EEPROM.h>
#define coinSlot 6

LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7); // 0x27 is the I2C bus address for an unmodified module

int coinCount = 0;
int coinSlotSignal;
int requiredCoins = 1;
boolean coinInserted = false;

void setup() {
  Serial.begin(9600);
 pinMode(coinSlot, INPUT_PULLUP);

 lcd.setBacklightPin(3,POSITIVE);
 lcd.setBacklight(LOW); // You can turn the backlight off by setting it to LOW instead of HIGH
 lcd.begin(16, 2);
lcd.write(EEPROM.read(5));
}

void loop() {
  while(!coinInserted){
  coinSlotSignal = digitalRead(coinSlot);
  if(coinSlotSignal < 1) {
    coinCount += 1;
    coinInserted = true;
EEPROM.write(0,coinCount);
Serial.println(EEPROM.read(0));

lcd.setCursor(0,0);
lcd.print("TOTAL:");
lcd.setCursor(0,1);
lcd.print(coinCount);
}
  }

while(coinInserted) {
  coinSlotSignal = digitalRead(coinSlot);
  if(coinSlotSignal >0) {
    coinInserted = false;

  }
}
if(coinCount >= requiredCoins) {
  delay(1500);
}
}

you cannot have two void setup() ... put codes from both into one ... same with void loop()

please fix the indentation of your code ... it will be much easier to follow the code flow and it will make it more difficult to make mistakes

why does PROJECT BEHAVIOR say nothing about the coinslot? ... is coinslot part of the project or not? ... it also does not say anything about the lock solenoid ....... not a very good description of the project behavior .... a clear, detailed description of the project behavior usually translates into code almost directly

I have 2 separated project codes sir but I got the coinslot code in google, Im hoping that how to sink 2 coses at 1 to run the project

It's unclear what the issue is. If the coin slot device has a logic output based on an internal sensor then hook that output up to the Arduino and process it like any other logic input--what's the specific problem?

I don't know how to sink the 2 project code in to 1 code :(

I read the article sir and try to sink the code but its giving a short of a problem that I cant find why its causing it but try to see the error code it keep on saying that "expected unqualified-id before 'while'


text:
Problem with floating of AnalogRead
For a university Lab course i have to realize a UPS unit with a internal LiPo battery . The unit uses as battery charger a buck converter
I have only a problem with the battery charger (buck converter). Few weeks before i verify the code and it works without problem. Now i can notice that the analog value that i read are floating too much and this represents a problem for the Constant Current (CC) and Constant Voltage (CV) phases of the battery charge process.
I found that this problem happens when plug arduino  after i have started the PC, while it doesn't happen when i plug the USB cable of arduino and then start the PC. It seems to be a problem with the ground of arduino.
the circuit scheme is the following one:

and what i obtain is that:

as you can see i have a strange increase of all the voltage that i read with the analog pin of arduino. The code is correct since before this week it works well, but if necessary i will upload it.
the 10Ohm resistor is placed in the buck converter only to measure the chargin current that i calculate as:
charging_current=(analogRead(A1)-analogRead(A2))*5.00/1023.00
The battery must be charged at constant current equal to 50mA until the battery voltage became equal to 4.10V, after that value the battery must be charged at constant voltage equal to 4.20V until the charging current became smaller than 10/5mA.
Notice that i try also to make more acquisition for each voltage: i made 8 measurement and then i calculate the average value, but the result doesn't change.

Please add information about which measurement are floating and what the actual and expected ranges are.

The measurement that are flosting are the voltsge that i masured on the network, on the battery and on the resistor... So all the vale that i read from analogo PIN of Arduino...the network voltage should be around 6V while the resistor voltage and the battery voltage should grow up while the battery charges... The start from 3.40V and the should reach about 4.20V

I can't make head nor tail of that fritzy thing. Please provide a proper schematic that we can follow.

I try to give you more detail information about the problem and i post a schematic of the battery charger. The other componente are ok so i can focus on the buck converter

I would expect some fluctuation, based one where in the PWM cycle you are doing the measurement. That is, based on whether the mosfet is turned on or not.

there are same fluctuation but sometime they are very smaller, like 40mV other time they are very big, like 100/150mV. On other thing that i note right now while i was testing the circuit, is that if i move the usb cable the voltage read frome the 3 pin (A0,A1 e A2) changes a lot, like 1V....this is due to the fact that the cable that i'm using isn't a cable of good quality?

Do you have an oscilloscope to measure waveforms? Then do this, please. And you might like to use an output of your Aduino to mark the times you read the analog inputs. Trace these, too.

i don't have an oscilloscope....

put caps in parallel with the voltage divider resistors, start around 100u. Also, you can expect a few levels of noise on a built-in ADC no matter what. Use an external ADC for more accurate + precise readings.


text:
Need HELP!! Serial communication has a very "Strange Problem"
I am working on building a serial command receiver. The idea is came from the boot loader. However, I got a very strange problem that I have no idea what could cause it.
As the first screenshot show, the print isn't finished because "===a=" is stuck, like this.

In the code, it should print out and the others.
char* receiveCmd(Stream &_serial, char &cmd_ptr, int &l_ptr) {
  Stream* serial = &_serial;

  if (serial->available() && (uint8_t)serialRead(_serial) == CMD_START) {
    int buf_count = 0; //start at data
    cmd_ptr = serialRead(_serial); //cmd_byte

    char low_byte = serialRead(_serial);
    char high_byte = serialRead(_serial);

    uint16_t length = low_byte; //data_length
    length = length | (high_byte << 8);

    Serial.println("\n\n===a===");
    Serial.println(length);
    Serial.println("===b===");

    l_ptr = (int)length;

    char* _buf = (char*)malloc(length * sizeof(char));

    while (buf_count != length) {
      if (serial->available()) {
        _buf[buf_count] = serial->read();
        buf_count++;
      }
    }

    char checksum = serialRead(_serial); //checksum, don't bother it yett
    char stop_byte = serialRead(_serial);

    if (stop_byte != CMD_EOF) {
      free(_buf);
      return NULL; //error
    }

    return _buf;
  }

  return NULL;
}

Anyway, the problem is fixed when I print out other variables first, then the length var..
char* receiveCmd(Stream &_serial, char &cmd_ptr, int &l_ptr) {
  Stream* serial = &_serial;

  if (serial->available() && (uint8_t)serialRead(_serial) == CMD_START) {
    int buf_count = 0; //start at data
    cmd_ptr = serialRead(_serial); //cmd_byte

    char low_byte = serialRead(_serial);
    char high_byte = serialRead(_serial);

    uint16_t length = low_byte; //data_length
    length = length | (high_byte << 8);

    Serial.println("\n\n===a===");
    Serial.println(low_byte, HEX);
    Serial.println(high_byte, HEX);
    Serial.println(length);
    Serial.println("===b===");

    l_ptr = (int)length;

    char* _buf = (char*)malloc(length * sizeof(char));

    while (buf_count != length) {
      if (serial->available()) {
        _buf[buf_count] = serial->read();
        buf_count++;
      }
    }

    char checksum = serialRead(_serial); //checksum, don't bother it yett
    char stop_byte = serialRead(_serial);

    if (stop_byte != CMD_EOF) {
      free(_buf);
      return NULL; //error
    }

    return _buf;
  }

  return NULL;
}

Other code is exactly the same. Does anyone know what may cause it? I can't print out those thing during production because it is only for debugging. If I remove those print, the code is also stuck(because of the length variable again).
For additional information, the serial signal is generated from other Arduino and AltSerial Library. The structure is like this.
void sendCmd(Stream &_serial, char cmd, char* payload, int length) {
  Stream* serial = &_serial;
  char buf[6 + length]; //start, data_length, data, checksum, stop

  buf[0] = CMD_START; //start_byte
  buf[1] = cmd; //cmd_byte
  buf[2] = length & 0xff; //data_length - low byte
  buf[3] = (length >> 8) & 0xff; //data_length - high byte
  buf[4 + length] = (char)calcCRC(payload); //checksum
  buf[5 + length] = CMD_EOF; //stop_byte

  for (int i = 0; i < length; i++) //load buf
    buf[4 + i] = payload[i];

  for (int i = 0; i < sizeof(buf); i++)
    serial->print(buf[i]);
}

I have used Serial.print(altSerial.read(), HEX) to check whether the byte is received correctly. They are all correct. That's why it is confusing me.QAQ
===== UPDATED INFORMATION =====
I have narrowed the problem. It seems like the below code is the main cause regard the issue. But no solution for this still.
uint16_t length = low_byte; //data_length
length = length | (high_byte << 8);

Thank you.

please, no pictures of text ... add the actual text

@jsotola Do you mean the code? Ok, I will change it.

Are you sure _buf is actually being allocated? You should always check if malloc() returns NULL before using the memory you think you've allocated.

@Majenko Thank you so much! It seems like the cause of the problem, but how do I check the buffer has been allocated?

if (_buf == NULL) { // do something to alert the user and abort the operation }

@Majenko It is not allocated because of the lack of memory?  I think that I have enough memory for that.

It's always worth checking. You may think you have enough, but you may not, since other things besides you use the memory.

Also, what is the function serialRead()?

@Majenko
char serialRead(Stream &_serial) {
Stream* serial = &_serial;
delay(1);
return (uint8_t)serial->read();
}

And what baud rate are you working at?

You should only ever read from serial if .available() has told you that there is actually a byte there to read, or if you check that you actually read a byte after reading (it will return -1 if there was nothing to read). You check if there is at least one byte available, then proceed to read loads of bytes that may, or may not, be there. You're entirely beholden to timing quirks to get it right, and that is bad. You should always wait for a byte to actually be there before attempting to read it.

Here is an example of how to handle reading of packets in a non-blocking manner.

@Majenko I did, there is a loop function to repeatedly check there is any available byte to read. Only after that, function receiveCmd will be called. The baud rate is 115200.

Yes, but you only check once for a single byte at the start of readCommand, and then proceed to read multiple bytes. How do you know those bytes have arrived? You don't.

https://majenko.co.uk/blog/reading-serial-arduino

what for is the pointer alias Stream* serial if you have a reference?

Why it does not work? You already got the answer in comments:

You are reading more bytes from the serial stream than what you know
are available. Then, your length variable can contain garbage, which
makes malloc() fail even if you have plenty of available memory.

You write into the memory buffer even if the allocation failed, which
makes your program corrupt its memory. From this point, anything can
happen.

You may notice that the behavior of your program depends on the timing.
Adding more instructions, or delays, may make it work. This is simply
because you give your peer more time to send its data packet. Of course,
relying on the timings is not a good approach: you instead have to make
sure you never read() more than what is actually available().
Here is an (untested) attempt to do this correctly and in a non-blocking
fashion. It is based on a finite state machine. What is original
about this state machine is that it is implemented as a switch/case
where every single case falls through:
/*
 * Packet format:
 *   CMD_START cmd_byte length_L length_H [payload] checksum CMD_EOF
 */
char *receiveCmd(Stream &serial, char &cmd_ref, int &l_ref) {

    // The current state is defined by what parts of the packet
    // we have already received.
    static enum {
        GOT_NONE, GOT_START, GOT_HEADER, GOT_PAYLOAD
    } state = GOT_NONE;

    // Variables only valid in the states GOT_HEADER and GOT_PAYLOAD.
    static char cmd_byte;
    static uint16_t length;
    static char *buffer;
    static size_t buffer_pos;

    switch (state) {
        case GOT_NONE:
            if (serial.available() < 1 || serial.read() != CMD_START)
                break;
            state = GOT_START;
            // fallthrough
        case GOT_START:
            if (serial.available() < 3)
                break;
            cmd_byte = serial.read();
            length = serial.read();
            length |= (uint16_t) serial.read() << 8;
            buffer = (char *) malloc(length);
            if (!buffer) {
                Serial.print(F("ERROR: Failed to allocate "));
                Serial.print(length);
                Serial.println(F(" bytes."));
                state = GOT_NONE;
                break;
            }
            buffer_pos = 0;
            state = GOT_HEADER;
            // fallthrough
        case GOT_HEADER:
            while (buffer_pos < length && serial.available())
                buffer[buffer_pos++] = serial.read();
            if (buffer_pos < length)
                break;
            state = GOT_PAYLOAD;
            // fallthrough
        case GOT_PAYLOAD:
            if (serial.available() < 2)
                break;
            serial.read();  // consume checksum
            if (serial.read() != CMD_EOF) {
                Serial.println(F("ERROR: Expected CMD_EOF."));
                free(buffer);
                state = GOT_NONE;
                break;
            }
            cmd_ref = cmd_byte;
            l_ref = length;
            state = GOT_NONE;
            return buffer;
    }
    return NULL;
}

You can think of this switch/case as a set of actions to perform
sequentially in order to process the whole packet. However, if the
function gets stuck for lack of incoming data, it just bails out. On the
next call, the switch puts it back where it left.

Thank you very much. I have found the problem. It is just not enough memory. therefore, it fails. However, I will take your suggestion for the 'receiveCmd' function.


text:
avrdude : stk500_get sync<> attempt 10 of 10 not in sync : resp=0x20 how do i get pass this error for ardunio uno board
When I first started with a bare minimum code. The compiler compiles the code, but when I try to upload, this is the error message I get:
 AVRDUDE: STK500_GETSYNC<> ATTEMPT 10 OF 10 NOT IN SYNC :RESP=0X20

How do I fix this?

Search for: attempt 10 of 10 not in sync, in the search box on this page. This question is asked frequently.

See my lengthy post about Have I bricked my Arduino Uno?.
Also the popular question Some dude named avr won't let me upload my program, aka “avrdude: stk500_getsync(): not in sync: resp=0x00”.

There are multiple reasons why you are getting this error.

Bootloader is either missing or corrupted. This is fairly unlikely.
Wire connected to pin 0 (RX)
Wrong COM port is chosen within the arduino IDE.
Drivers are not installed. You can update it within the Device Manager if you are using Windows.

Here is a link to an article explaining the causes and how to fix them, http://www.instructables.com/id/A-solution-to-avrdude-stk500getsync-not-in-syn/


text:
How do I communicate with a sensor via an Arduino's RX/TX ports?
I have a sensor that communicates via serial communication. CTi Sensors TILT-05. It transmits an ASCII string with data separated by commas. I want to be able to read the incoming ASCII data in the Arduino IDE's Serial Monitor in real time (the device is an accelerometer).
I am struggling to convey this in the code. Currently, I have the sensor's RX connected to an Arduino Uno's TX port (digital 1) and sensor TX-> Arduino RX (digital 0). The sensor is powered and grounded via the Arduino.
I have searched for serial communication methods but can't find any that seem to work. How can I receive and interpret the incoming data from the sensor?

You don't mention the sensor brand or a datasheet so this will be a very general answer to the problem.
Firstly, how you have the sensor connected now should just spool info into the Serial monitor of the Arduino IDE without any code on the Arduino.
What are the data speed and the exact way the Serial comes out from the sensor?
If you want to interpret the data as it is coming through you should use Software Serial as you can't relay info to the PC with an Arduino's RX TX lines connected to something else.
What you can do is below(Untested):
#include <SoftwareSerial.h>

SoftwareSerial mySer(3, 4); //RX TX

//these are char areay because its from Serial
char accel[3] = {'0'};
uint8_t place = 0;

// array to print in sync with the accelerometer values array
const char* SerialText[3] = {
   "\nX Axis: ",
   "\nY Axis: ",
   "\nZ Axis: ",
};

char inData = '0';
char separator = ','; // separator you described

void setup(){
//set to the normal baud, mines for the example
     Serial.begin(9600);

     mySer.begin(9600);

}//~ end setup

void loop(){

    if(mySer.available()){

     inData = mySer.read(); // get the value at the instance of the serial data being there

        if(inData != separator){
          accel[place] = inData;
          Serial.print(SerialText[place]); // print the current values identifier
          Serial.print(accel[place]); // print value
          place++; // increment for the next time
     }
   }

if(place >= 3) place = 0;
}//~ end loop

The above gives this output at the moment, with an input of $CSACC,-0156.4,-0226.3,+0981.2*49
X Axis: $
Y Axis: C
Z Axis: S
X Axis: A
Y Axis: C
Z Axis: C
X Axis:
Y Axis: -
Z Axis:
X Axis: 0
Y Axis: 1
Z Axis: 5
X Axis: 6
Y Axis: .
Z Axis: 4
X Axis:
Y Axis: -
Z Axis:
X Axis: 0
Y Axis: 2
Z Axis: 2
X Axis: 6
Y Axis: .
Z Axis: 3
X Axis: +
Y Axis: 0
Z Axis: 9
X Axis: 8
Y Axis: 1
Z Axis: .
X Axis: 2
Y Axis: *
Z Axis: 4
X Axis: 9
Y Axis:
Z Axis:
X Axis:

The code doesn't filter this the way it should but is a stepping stone. I will update it to do it properly when I have a chance.

There are other ways, but I will add some info later if needed or after clarification from the OP.

Hi there, thank you so much for trying to help. For clarification, this is the sensor I'm trying to use: http://ctisensors.com/wp-content/uploads/2016/03/TILT-05-Datasheet-01b.pdf. It transmits an ASCII string at a baud rate of 115200. I've tried your code but have encountered a few errors, primarily: error: array must be initialized with a brace-enclosed initializer
char accel[3] = 0;

@FYoung        thanks for the sensor info, i will amend my answer to that and also to fix the error of the code.

As a side note, as the device uses NMEA 0183, here is a link to way to split it nicely

With RSM's help I've managed to get the sensor reading into the serial monitor semi-reliably. I have yet to solder the headers onto the sensor yet and am just doing prototyping (basically just me pushing a wire against the sensor output hole) which is unreliable. I believe once I get some headers soldered on the output will be much more reliable. For those searching, this code worked for me.
Digital pins 3/4 function as your RX/TX pins respectively. Connect the TX of your sensor to the RX (3) of the Arduino and likewise for the TX. I used a baud rate of 115200 but you can change it to whatever works in the code. This is simply a simplification of RSM's code in his previous answer and all credit/kudos goes to him.
#include <SoftwareSerial.h>

SoftwareSerial mySer(3, 4);

char inData = '0';

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

void loop(){
    if(mySer.available()){
     inData = mySer.read();
     Serial.print(inData);
  }
}


text:
Porting ATMega8 AVR based program to Intel Curie Processor
I'm currently trying to port a program called 'ArduinoUSBLinker' to work on my Arduino 101 (which has an Intel Curie CPU instead of the standard ATMega CPU).
The program is used to flash ESCs without the need of additional hardware.
Arduino USB Linker
Unfortunately the code is mainly based on the ATMega's built in AVR timers,
which uses several different predefined variables such as TCCR0,TCCR1,TCTN2…
These are not available (or are they?) in the Curie Module. Since the Arduino 101 has timer functionality, I was wondering if there is a way to translate those into the Curie Timer library.

Those variables are the addresses of physical registers on the AVR that manipulate its timer/counters. Most other processors will have equivalent, but not likely identical, hardware. You'll need to port functionality, not the code.
You'll need to reverse-engineer (worst-case) the code you're trying to port (assuming you aren't intimately familiar with it, e.g., you designed it), develop a spec for it (at least in your head), and write to that spec for the Curie.
If the overall job is not (too heavily) processor-specific, you may be able to write it to be portable by writing the job-specific code in, e.g., in C, and call well-defined functions (in C or assembler) for the CPU-specific ones, that could easily be replicated on another processor.