text:
Integer looping in EEPROM Read
I am reading data from a 24LC1025 over I2C with an Arduino and then outputing that data to my PC through the Serial interface. The EEPROM chip is seperated into two pages and at address 65535 [0x0FFFF] it switches over to the second page sending [0x10000 through 0x1FFFF] I had it working by reading each address with a random read:
#include <Wire.h>

byte i2c_eeprom_read_byte( int deviceaddress, unsigned long eeaddress ) {
    byte rdata = 0xFF;
    Wire.beginTransmission(deviceaddress);
    Wire.write((eeaddress >> 8)); // MSB
    Wire.write((eeaddress & 0xFF)); // LSB
    Wire.endTransmission();
    Wire.requestFrom(deviceaddress,1);
    if (Wire.available()) rdata = Wire.read();
    return rdata;
}

void setup() {
  Wire.begin(); // initialise the connection
  Serial.begin(9600);
  delay(100); //add a small delay
  Serial.println("Arduino Group Delay Read Program");

  for (unsigned long i = 0; i < 128000; i++){
    Serial.print(i);
    Serial.print(",");
    byte a = i2c_eeprom_read_byte(0x50, i);
    Serial.println(a, BIN);
  }
}

void loop() {
  //
}

To reduce overhead and speed up the process I am now using the code below:
#include <Wire.h>

byte bytes[32];

void i2c_eeprom_read_buffer( int deviceaddress, unsigned long eeaddress, byte *buffer, int length ) {
    Wire.beginTransmission(deviceaddress);
    Wire.write((eeaddress >> 8)); // MSB
    Wire.write((eeaddress & 0xFF)); // LSB
    Wire.endTransmission();
    Wire.requestFrom(deviceaddress,length);
    int c = 0;
    for ( c = 0; c < length; c++ )
        if (Wire.available()) buffer[c] = Wire.read();
}

void setup() {
  Wire.setClock(400000); // 400kHz
  Wire.begin(); // initialise the connection
  Serial.begin(250000);
  delay(100); //add a small delay
  Serial.println("Arduino Group Delay Read Program");

  for (unsigned int i = 0; i < 128000;){
    i2c_eeprom_read_buffer(0x50, i, (byte *)bytes, 32);
    for (int j = 0; j < 32; j++){
      Serial.print(i);
      Serial.print(",");
      Serial.println(bytes[j], BIN);
      i++;
    }
  }
}

void loop() {
  //
}

Unfortunately, the program now loops at the page boundary back to the start of the address range. Here is a sample of the output:
65500,1110100
65501,1101000
65502,1101001
65503,1110011
65504,100000
65505,1101001
65506,1110011
65507,100000
65508,1100100
65509,1100001
65510,1110100
65511,1100001
65512,100000
65513,1100110
65514,1110010
65515,1101111
65516,1101101
65517,100000
65518,1110100
65519,1101000
65520,1100101
65521,100000
65522,1100101
65523,1100101
65524,1110000
65525,1110010
65526,1101111
65527,1101101
65528,0
65529,11111111
65530,11111111
65531,11111111
65532,11111111
65533,11111111
65534,11111111
65535,11111111
0,0
1,0
2,1
3,110000
4,111000
5,111001
6,110110
7,110001
8,111001
9,1000001
10,101110
11,1011000
12,110001
13,110001
14,1010110
15,1011001
16,110001
17,110111
18,110100
19,110001
20,1110100
21,1101000
22,1101001
23,1110011
24,100000
25,1101001
26,1110011
27,100000
28,1100100
29,1100001
30,1110100
31,1100001
32,100000
33,1100110
34,1110010
35,1101111
36,1101101
37,100000
38,1110100
39,1101000
40,1100101
41,100000
42,1100101
43,1100101
44,1110000
45,1110010
46,1101111
47,1101101
48,0
49,111001
50,100010
51,11010010
52,110101
53,1001000
54,11101011
55,11000000
56,110101
57,11101011
58,1011100
59,10010100
60,110101
61,100000
62,10100011
63,1110110
64,10110100
65,10110001
66,1111010
67,11100000
68,10110110
69,101100
70,11010110

I could see how an error in the code could cause the second page to display the first page's values, but there is nothing in the code that should cause the counter itself to loop. Any idea what could be causing this?
Edit:
For anyone who is working a similar issue, here is the code that I ended up with once I solved this issue and then dealt with the page boundary problem (line 4):
#include <Wire.h>

byte i2c_eeprom_read_byte( int deviceaddress, unsigned long eeaddress ) {
  byte rdata = 0xFF;
   if( eeaddress > 65535 ){
    deviceaddress = deviceaddress | B00000100;
    eeaddress = eeaddress & 0xFFFF;
    }
  Wire.beginTransmission(deviceaddress);
  Wire.write((eeaddress >> 8));   // MSB
  Wire.write((eeaddress & 0xFF)); // LSB
  Wire.endTransmission();
  Wire.requestFrom(deviceaddress,1);
  if (Wire.available()) rdata = Wire.read();
  return rdata;
}

void setup() {
  Wire.setClock(400000);
  Wire.begin(); // initialise the connection
  Serial.begin(115200);
  delay(100); //add a small delay
  Serial.println("Arduino Group Delay Read Program");

  for (unsigned long i = 0; i < 128000; i++){
    Serial.print(i);
    Serial.print(",");
    byte a = i2c_eeprom_read_byte(0x50, i);
    Serial.println(a, BIN);
  }
}

void loop() {
}

Note that this last code will work with the i2c_eeprom_read_buffer function as well as long as you add the if statement starting at line 4.

for (unsigned int i = 0; i < 128000;){

An unsigned int can only count from 0 to 65536 on an 8-bit system...  You need that to be an unsigned long, or better, a uint32_t (better because it's guaranteed to be an unsigned 32-bit value on any platform regardless of how wide its registers are).


text:
I can't control my DC motors speed with analogWrite()
I have Arduino Uno and I attached it to 2 DC motors with L298N bridge.
I want to control the speed of the motors so they don't move at maximum speed.
I use analogWrite() but it does nothing,and the motors move at maximum speed
Here is my code:
//motor A
int enA = 9;
int in1 = 8;
int in2 = 7;

//motor B
int enB = 3;
int in3 = 5;
int in4 = 4;

void setup() {
  Serial.begin(9600);
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}

void loop() {

  analogWrite(enA, 0);

  analogWrite(enB, 0);

  digitalWrite (in1, HIGH);
  digitalWrite (in3, HIGH);
  digitalWrite (in2, LOW);
  digitalWrite (in4, LOW);

  delay(50);
}

Do you know that analogWrite(enA, 0); stops it? Or what exactly is the problem?

With using analogWrite Do make sure you use the pwn pins of arduino to control the motors.

yes i know that analogWrite(enA,0) stops the motor and that is what i want but it dosen't work and the motors are alwayes at maximum speed

Please add a schematic of photo of your wiring setup. As you have described it thus far, your code should halt the motor, so perhaps the wiring is not correct.

@josecanuc i did my wire base on video on youtube with my same electronics and it runs perfect with his device

@MukharJain i am sure that i am using them and i tried all the pins ,however the problem still the same

If the youtube video project runs perfect and yours doesn't, this is why we are asking to see what you have done, because of the possibility that you made a mistake in re-creating this project.

I did find solutions for the problem. It turned out that the bridge does not work as it should be and the pins of en(A,B) is replaced with the in pins ..now I can control the speed but can't reverse the direction of the motors

This was really frustrating to figure out, so thanks for your answer here! I had a similar bad module, and looks like just connecting my pwm pin to IN1 was all that was needed for speed control in a single direction. I just disconnected the enable jumper/pin and in2 pin, and measured a good pwm output. Seems like the enable pin does nothing on my module!

analogWrite() can take values between 0 and 255 as its second parameter. Where 255 will give you the maximum motor speed and 0 will give you the lowest (motor will not run).
For example, below code will give you almost the half of max speed.
analogWrite(enA, 128);
analogWrite(enB, 128);

i know what it does but it does not work the way it should and the motors are allwayes at maximum speed even if i put it to (0) and i am sure of the pins

I'm looking at one of the L298N bridges on Amazon. What are those two jumpers on pins ENA and ENB? Try taking those off, because I wonder if they're pegging you at full "on".

@LegitimateWorkUser these are the speed control pins(voltage) if you take them off the motor will not run at all

source: Stack Exchange

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

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

sort: votes


text:
LDC paired with Arduino locks up and freezes. Out of SPRAM?
I am making an alarm clock using a 4x20 lcd display, rtc, and Arduino Pro Mini 3.3v. I have implemented a menu system for setting the time/date that blinks the text on the lcd display to indicate that I have it selected, but the blinking randomly stops and the Arduino stops printing to the serial after about ten seconds.
After much head scratching and Googling I came to the conclusion that all my lcd.print() lines were using up all my ram. I tried to create PROGMEM variables to use in the print commands, but I couldn't get it to work so I ended up just adding the F() macro to every print statement (there's a lot). This now prints everything as expected, but the Arduino still freezes up after the same amount of time. Am I using F() wrong or is the problem something else like power???
Visual Studio code says I am using 643/2048 bytes of data/ram and 14960/30720 bytes of flash when I upload the code. (that is with the F() macro implemented)
--------------EDIT----------------
So I've created a small test sketch to use with the same circut, and now I'm really confused. I've been running it for about an hour now and it is still not freezing. The script blinks a full screen of number signs every 200ms. The backlight is on and everything is still powered the same way. This, in theory, rules out both running out of ram and not providing enough power. Any other ideas?
#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <RTClibExtended.h>

LiquidCrystal_I2C lcd(0x27,20,4);
RTC_DS3231 clock;

void setup() {
    Serial.begin (9600);
    lcd.init();
    clock.begin();
    clock.adjust (DateTime (__DATE__, __TIME__));
    lcd.backlight();
}

bool on = true;

void loop() {
    lcd.setCursor (0, 0);

    if (on) {
        for (int i = 0; i < 4; i++) {
            lcd.setCursor (0, i);
            for (int j = 0; j < 20; j++) {
                lcd.print ("#");
            }
        }
    }
    else {
        for (int i = 0; i < 4; i++) {
            lcd.setCursor (0, i);
            for (int j = 0; j < 20; j++) {
                lcd.print (" ");
            }
        }
    }

    on = !on;
    delay (200);
}

add your code to the Question.

A lcd display requires 5v and your Arduino is a 3.3v pro mini board. How did you connect that? Are there long wires to the rtc and the display?

Along with what Jot said, and my own WAG, it sounds like you're trying to pull too much power, potentially overheating the power regulator.  Once you add some code, we can see if that's an alternate possibility.

I have the Arduino powered by the usb from my computer and the rtc and lcd are connected to the vcc pin on the Arduino. I am using the lcd without the backlight, so does it still need 5v? Also, I tried using a 9v battery to power the circuit (connected the Arduino to the battery through the raw pin and connected the lcd and rtc directly into the battery instead of the vcc pin from the Arduino), and the lcd still freezes. Would it be helpful if I posted the circuit diagram? My code is over 1000 lines long, so I'm not sure what the best way to share it with you would be.

create a small test sketch to test if the problem is power or overheating

@Juraj I posted one

Any other ideas? - there is a problem in your longer code which isn't in the smaller code. Hard to say what that is without seeing the longer code.

I found the problem! it was specific to my code and didn't turn out to have anything to do with ram or power. The problem was I hadn't detached the interrupt from the rtc when I woke it up with a button. It would freeze seemingly randomly because the rtc would fire an interrupt signal when the next minute ticked, while the arduino was awake. I guess it causes problems when you try to interrupt arduino's sleep and it's not actually sleeping. All I had to do was detach both interrupts when the button is clicked. Thank you all for your help :)

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


text:
U-blox GPS module (and TinyGPS library): altitude data getting stuck at strange values
We have built a HAB (high-altitude balloon) tracker based on an Arduino and a U-blox GPS module, but we have a sporadic issue where the altitude data gets stuck at odd (usually low) values. The altitude data of two flights are shown below, showing the issue. All other data (lat, long, time etc) is correct, it's just altitude we have the issue with. We would expect a linear increase in altitude, then a quick drop once it bursts. The squares on the graph mark the data points, so it's not just a case of us missing the data. Sometimes it gets stuck at the current value, and sometimes it just gets stuck at a nonsense value.
For example, in both cases the value is initially stuck at about 270m, which is correct for our launch site. However, it then gets stuck at other nonsense values for a long time (less than 500m) before it starts correctly reporting the altitude. In the 2018 chart you can see that the value drops to 0 for a while.
We have searched online and asked on some forums where people often use the U-blox GPS module, but it doesn't seem to be an issue others have come across. Also, the flights shown here were done on 2 different sets of hardware (Arduino and GPS module), with the 2019 flight using brand new components, so we don't think it's a hardware issue. It's not a transmission issue, as one data set is what was recorded by receivers and uploaded to HABHub, and the other is what was stored on the SD card and recovered after the flight. The same code was used for both, so that is our current suspect. The code had been used in previous years without problem, with only minor modifications between years.
The whole code is pasted below, I have highlighted the main loop with ####### as this is where the reading of the GPS occurs. Some notes on the code:

This is the code I've inherited, so I can't necessarily say why things have been done in a certain way.
The TinyGPS library looks like it hasn't been updated since this was written (2014ish I think).
I am considering re-writing the code from scratch, but I want to make sure I understand the cause of this issue if possible so I can avoid it in the future.

The current hardware is an Elegoo Mega2560 R3 and a u-blox NEO-6M GPS module.
Are we doing something wrong with reading/storing/processing the altitude data?
Edit to add more information and observations:
The code takes time, lat, long, altitude from the GPS module, along with the packet counter, callsign and checksum and assembles them into a string, which is transmitted via radio and stored on the SD card. The string has the following format:
$$Callsign,PacketNumber,HHMMSS,lat,long,alt*Checksum
Here's an example packet:
$$XXXXXXXX,1377,121226,51.545547,-1.296546,23*DE62
These packets are generated every 11-12s and stored and transmitted.
During the periods of incorrect data, the packets appear fine: counter and time increasing, lat and long giving sensible values, just with a nonsense altitude (in this example, 23m). In the 2018 flight, the altitude is stuck at 267m (the altitude of the launch site) for about 40minutes, even though we have seen it ascend into the clouds. The value then drops to 23m and stays there for over an hour, before briefly jumping to 117m for a couple of minutes before jumping to 15,669m, and from then on reports sensible data (until the drop to 0 during the descent).
What I have just noticed while inspecting the logs is that every time the altitude value jumps to a new nonsense value (either from a sensible value or a nonsense one), the packet that reports the new altitude value is corrupted in some manner! This is true even in the data logged on the SD card, so it is not something that has been introduced by transmitting it, but an issue with generating the string.
Below are 3 adjacent packets received, showing a jump between 2 (nonsense) altitude values:
$$XXXXXXXX,1377,121226,51.545547,-1.296546,23*DE62
$$XXXXXXXX,1379,121226,5.216667,-0.583333,117*CDB2
$$XXXXXXXX,1381,121248,51.547260,-1.293762,117*80C5
Note that the packet counter has increased correctly (by 2, but it's "supposed" to do that, it's not an error), but the timestamp is identical in the first and second packets, and the timestamp of the 3rd is 22s later (they should be every 11s). Also, the second packet (the one with the new altitude), reports a nonsense lat and/or long value. Packets then continue to be sensible (except for the altitude), until at some point it starts reporting correct altitude. Looking though both logs, I can see that this happens every time we get a new nonsense altitude.
Any suggestion as to what is messing up acquiring the altitude data and/or assembling the string? I notice that altitude is handled differently in the code compared to lat/long/time, but I am not aware of the reason for this.

//434.25MHz USB RTTY 50 Baud 500Hz shift ASCII-7 no parity 2 stop bits

#include <TinyGPS.h>
#include <SD.h>
#include <string.h>
#include <util/crc16.h>
#include <Arduino.h>

#define TempAPin A8
#define TempBPin A12
#define PresAPin A10
#define PresBPin A13
#define BatteryVoltagePin A7
#define GreenLED 11
#define RedLED 13
#define RADIOPIN 10
#define RADIOEN 9
int RADIOHIGH = 110;
int RADIOLOW = 100;

int sentance_id = 0;

char UKHAS[80];
char logString[100];
char datastring[80];
char slat[10];
char slon[10];
File myFile; //SD card setup

unsigned int TempA = 0;
unsigned int TempB = 0;
unsigned int PresA = 0;
unsigned int PresB = 0;
unsigned int BatteryVoltage = 0;

long lat, lon, alt;
unsigned long date, oldtime, time, fix_age, vel, bearing;
unsigned char dop, sats;
int year;
byte month, day, hour, minute, second, hundredths;

byte gps_set_sucess = 0 ;

TinyGPS gps;

void setup()
{
  delay(1000);
  Serial.begin(9600);
  //Serial2.begin(9600); //Bluetooth
  analogReference(DEFAULT);

  pinMode(RedLED, OUTPUT);
  pinMode(GreenLED, OUTPUT);
  digitalWrite(RedLED, HIGH);// Switch both on until GPS module is configured
  digitalWrite(GreenLED, HIGH);
  Serial.println("PROGRAM START");
  SetupGPS();
  digitalWrite(GreenLED, LOW);
  delay(1000);

  //SD setup
  //pinMode(10, OUTPUT); //Required for SPI CS to work
  //if (!SD.begin(10)) {
    pinMode(53, OUTPUT); //Required for SPI CS to work
  if (!SD.begin(53)) {
    Serial.println("Card failed, or not present");
    return;
  }
  Serial.println("SD card initialization done.");
  delay(1000);
  //radio setup
   pinMode(RADIOPIN,OUTPUT);
   pinMode(RADIOEN,OUTPUT);
   setPwmFrequency(RADIOPIN, 1);
   digitalWrite(RADIOEN,HIGH);
   Serial.println("FREE RAM:");
   Serial.println(freeRam() );
}

void SetupGPS(void)
{
   // START OUR SERIAL DEBUG PORT
  Serial.println("Initialising GPS....");
  //
  // THE FOLLOWING COMMAND SWITCHES MODULE TO 4800 BAUD
  // THEN SWITCHES THE SOFTWARE SERIAL TO 4,800 BAUD
  //
  Serial3.begin(9600);
  Serial3.print("$PUBX,41,1,0007,0003,4800,0*13\r\n");
  delay(2000);
  Serial3.begin(4800);
  //Serial3.flush();

  //  THIS COMMAND SETS FLIGHT MODE AND CONFIRMS IT
  Serial.println("Setting uBlox nav mode: ");
  uint8_t setNav[] = {
    0xB5, 0x62, 0x06, 0x24, 0x24, 0x00, 0xFF, 0xFF, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 0x05, 0x00, 0xFA, 0x00, 0xFA, 0x00, 0x64, 0x00, 0x2C, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0xDC                        };
  while(!gps_set_sucess)
  {
    sendUBX(setNav, sizeof(setNav)/sizeof(uint8_t));
    gps_set_sucess=getUBX_ACK(setNav);
  }
  gps_set_sucess=0;
}

unsigned int charsToInt(unsigned char loByte, unsigned char hiByte)
{
  unsigned int temp = 0;
  temp = loByte + (hiByte<<8);
  return temp;
}

unsigned char lo(unsigned int input)
{
  unsigned char temp = 0;
  temp = (unsigned char)(input & 0xFF);
  return temp;
}

unsigned char hi(unsigned int input)
{
  unsigned char temp = 0;
  temp = (unsigned char)((input>>8) & 0xFF);
  return temp;
}

###################################################################################
void loop()
{
  unsigned char b = 0;
  long int counter = 10000;
  int x = 0;
  int mem;
  while(1)
  {
    counter--;
    x = counter % 10000;
    if (x == 1)
    {
      Serial.println(counter);
    }

    if (counter==0)
    {

      counter = 100000;
      digitalWrite(GreenLED, LOW);
      digitalWrite(RedLED, HIGH);
      readSensors();
      sprintf(logString, "NOGPS,%i,%lu,0,0,0,%i,%i,%i,%i", sentance_id++, time, TempA, TempB, PresA, PresB);
      Serial.println(logString);
      writeSD();

     sprintf(UKHAS,  "&&XXXXXXXX,%i,NOGPS", sentance_id);

      Serial.println(UKHAS);

      writeRADIO();

    }
    if(Serial3.available() & 0)
    {

       b=Serial3.read();

       if (gps.encode(b))
       {
        Serial.println("TEST");
         counter = 1000000;
         digitalWrite(GreenLED, HIGH);
         digitalWrite(RedLED, LOW);
         //Serial.println("Got valid GPS data");
         // read values from the gps.
         gps.get_position(&lat, &lon, &fix_age);
         gps.get_datetime(&date, &time, &fix_age);
         alt = gps.altitude();
         Serial.print("alt=");
           Serial.println(alt);
         vel = gps.speed();
         bearing = gps.course();
         gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &fix_age);
         readSensors();
         //if (time > (oldtime + 1000))
         //{
           // print the details to BT and SD every 10 seconds
           oldtime = time;
           // comaptible comms protocol: http://ukhas.org.uk/communication:protocol
       sentance_id++; //count number of packets
           char timeS[10] = {time/100};
           char hour[10];

           alt = alt / 100; //convert from cm to m
           //if (alt > 50000){ //if nonsense altitude
          //   alt = -1;
          // }
           double dlat = double(lat);
          //char slat[10];
           dtostrf(dlat/1000000, 8, 6, slat);
           if (lon > 0){ //if west of meridian
             lon = lon * -1;
           }
           double dlon = double(lon);
           //char slon[10];
           dtostrf(dlon/1000000, 8, 6, slon);
           sprintf(UKHAS, "$$XXXXXXXX,%i,%06lu,%s,%s,%lu", sentance_id, time/100, slat, slon, alt);
           //sprintf(UKHAS, "$$XXXXXXXX,%i,%lu:%lu:%lu,%s,%s,%lu", sentance_id, hour, minute, second, slat, slon, alt);
           //change time format
             sprintf(logString, "LOG,%i,%lu,%s,%s,%lu,%i,%i,%i,%i", sentance_id++, time, slat, slon, alt, TempA, TempB, PresA, PresB);
           Serial.println(logString); //debug
           //Serial2.println(logString); //Bluetooth
           Serial.println(UKHAS); //debug
           //50 buad 500Hz
           writeSD();
           writeRADIO();
         //}
       }
    }//if GPS available
  }//while(1)
}//loop
###########################################################################
void writeRADIO()
{
 //digitalWrite(RADIOEN,HIGH);
 //delay(10);
 //Serial.println(UKHAS);

 snprintf(datastring,80,UKHAS); // Puts the text in the datastring

 unsigned int CHECKSUM = gps_CRC16_checksum(datastring); // Calculates the checksum for this datastring

 char checksum_str[8];

 sprintf(checksum_str, "*%04X\n", CHECKSUM);

 strcat(datastring,checksum_str);
Serial.println(datastring);
 rtty_txstring (datastring);

Serial.println("MS");
 //digitalWrite(RADIOEN,LOW);
}

void writeSD() //write sensor log to file on SD card
{
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
  myFile = SD.open("log.txt", FILE_WRITE);
  // if the file opened okay, write to it:

  if (myFile) {
    Serial.print("Writing to SD card");
    //write full telemetry packet
     myFile.println(logString);

    //close the file:
    myFile.close();
    Serial.println("done.");
  }
   else {
     //if the file didn't open, print an error:
    Serial.println("error opening SD card file");
  }
}

void readSensors()
{
  TempA = analogRead(TempAPin);
  TempB = analogRead(TempBPin);
  PresA = analogRead(PresAPin);
  PresB = analogRead(PresBPin);
  BatteryVoltage = analogRead(BatteryVoltagePin);
}

void rtty_txstring (char * string)
{

/* Simple function to sent a char at a time to
 ** rtty_txbyte function.
 ** NB Each char is one byte (8 Bits)
 */

char c;

c = *string++;

while ( c != '\0')
 {
 rtty_txbyte (c);
 c = *string++;
 }
}
void rtty_txbyte (char c)
{
 /* Simple function to sent each bit of a char to
 ** rtty_txbit function.
 ** NB The bits are sent Least Significant Bit first
 **
 ** All chars should be preceded with a 0 and
 ** proceed with a 1. 0 = Start bit; 1 = Stop bit
 **
 */

int i;

rtty_txbit (0); // Start bit

// Send bits for for char LSB first

for (i=0;i<7;i++) // Change this here 7 or 8 for ASCII-7 / ASCII-8
 {
 if (c & 1) rtty_txbit(1);

else rtty_txbit(0);

c = c >> 1;

}
rtty_txbit (1); // Stop bit
rtty_txbit (1); // Stop bit
}

void rtty_txbit (int bit)
{
 if (bit)
 {
 // high
 analogWrite(RADIOPIN,115);
 }
 else
 {
 // low
 analogWrite(RADIOPIN,100);
 }

// delayMicroseconds(3370); // 300 baud
 delayMicroseconds(10000); // For 50 Baud uncomment this and the line below.
 delayMicroseconds(10150); // You can't do 20150 it just doesn't work as the
 // largest value that will produce an accurate delay is 16383
 // See : http://arduino.cc/en/Reference/DelayMicroseconds

}

uint16_t gps_CRC16_checksum (char *string)
{
 size_t i;
 uint16_t crc;
 uint8_t c;

crc = 0xFFFF;

// Calculate checksum ignoring the first two $s
 for (i = 2; i < strlen(string); i++)
 {
 c = string[i];
 crc = _crc_xmodem_update (crc, c);
 }

return crc;
}

void setPwmFrequency(int pin, int divisor) {
 byte mode;
 if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
 switch(divisor) {
 case 1:
 mode = 0x01;
 break;
 case 8:
 mode = 0x02;
 break;
 case 64:
 mode = 0x03;
 break;
 case 256:
 mode = 0x04;
 break;
 case 1024:
 mode = 0x05;
 break;
 default:
 return;
 }
 if(pin == 5) {
 TCCR3B = TCCR3B & 0b11111000 | mode;
 }
 else {
 TCCR2B = TCCR2B & 0b11111000 | mode;
 }
 }
 else if(pin == 3 || pin == 11) {
 switch(divisor) {
 case 1:
 mode = 0x01;
 break;
 case 8:
 mode = 0x02;
 break;
 case 32:
 mode = 0x03;
 break;
 case 64:
 mode = 0x04;
 break;
 case 128:
 mode = 0x05;
 break;
 case 256:
 mode = 0x06;
 break;
 case 1024:
 mode = 0x7;
 break;
 default:
 return;
 }
  TCCR3B = TCCR3B & 0b11111000 | mode;
 }
}

// Send a byte array of UBX protocol to the GPS
void sendUBX(uint8_t *MSG, uint8_t len) {
  for(int i=0; i<len; i++) {
    Serial3.write(MSG[i]);
    Serial.print(MSG[i], HEX);
  }
  Serial3.println();
}

// Calculate expected UBX ACK packet and parse UBX response from GPS
boolean getUBX_ACK(uint8_t *MSG) {
  uint8_t b;
  uint8_t ackByteID = 0;
  uint8_t ackPacket[10];
  unsigned long startTime = millis();
  Serial.print(" * Reading ACK response: ");

  // Construct the expected ACK packet
  ackPacket[0] = 0xB5;  // header
  ackPacket[1] = 0x62;  // header
  ackPacket[2] = 0x05;  // class
  ackPacket[3] = 0x01;  // id
  ackPacket[4] = 0x02;  // length
  ackPacket[5] = 0x00;
  ackPacket[6] = MSG[2];    // ACK class
  ackPacket[7] = MSG[3];    // ACK id
  ackPacket[8] = 0;     // CK_A
  ackPacket[9] = 0;     // CK_B

  // Calculate the checksums
  for (uint8_t i=2; i<8; i++) {
    ackPacket[8] = ackPacket[8] + ackPacket[i];
    ackPacket[9] = ackPacket[9] + ackPacket[8];
  }

  while (1) {

    // Test for success
    if (ackByteID > 9) {
      // All packets in order!
      Serial.println(" (SUCCESS!)");
      return true;
    }

    // Timeout if no valid response in 3 seconds
    if (millis() - startTime > 3000) {
      Serial.println(" (FAILED!)");
      return false;
    }

    // Make sure data is available to read
    if (Serial3.available()) {
      b = Serial3.read();

      // Check that bytes arrive in sequence as per expected ACK packet
      if (b == ackPacket[ackByteID]) {
        ackByteID++;
        Serial.print(b, HEX);
      }
      else {
        ackByteID = 0;  // Reset and look again, invalid order
      }

    }
  }
}

int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

referring to the graphs ... what are the sample index numbers, sample values and milli() values on either side of the anomalies

@jsotola the data is extracted from the logs, which doesn't save the millis() value. What do you mean by "either side of the anomalies"? The anomalies are the long stretches of data close to ground level (<500m), so I'm not sure what to say for values "either side" of them.

i am thinking that the long vertical lines are the transitions between valid data and invalid data (anomalies is not the correct term) ... i was trying to ask for infornation about the one or two data points before the vertical lines, and one or two points after the vertical lines

You're correct, the vertical lines are where it switches between realistic and nonsense data (and vice-versa). The smaller vertical lines (such as on the descent in the 2019 graph at around 39,000s) look like the altitude value is just "sticking" for a while (for example it stays at 29,732m for about 90s, before updating the value to 25,653m). Data packets are generated approximately every 11-12s. I will update the question describing what we're seeing in the packets, as there is something odd happening during these "stuck" values.

Is this a real U-blox GPS module? There are a lot of fake ones around.. Altitude measured by GPS is generally not very accurate. Have you thought about measuring altitude with an altimeter (air pressure sensor)?

@StarCat hmm, you may be right, it does look like the module we are using is counterfeit (based on the label anyway, I will check the GPTXT data when I get a chance). We bought 2 modules at the same time, and the other one appears to be genuine (I'm just checking where we bought them from). I guess it's hard say whether this is the cause, but with the added observation it still looks like there is a coding issue perhaps? The lack of accuracy is fine, even it it's out by 100s of m. However there is a pressure sensor on the tracker, so I will add a "backup" altitude estimation from that.

I've tried the module that appears to be genuine, but still get the same behaviour. Also, even if the modules are counterfeit (and some were purchased several years apart, and from different companies), it seems relatively unlikely that they would fail in exactly the same way, so it still seems like it is a coding problem of some kind to me.


text:
changing bitrate of audio recording and taking samples from audio in arduino
I am looking to make a baby cry detection module that is a part of a bigger project i.e. IOT based baby monitoring system. Using AI, i have a dataset (of baby crying and not crying) to train model using binary classification through logistic regression. The problem is that the dataset has a 10kbps sample rate. and arduino records audio on 192kbps probably. so i need the arduino recorded audio to be 10kbps. secondly i need 100 weights or samples from the arduino recorded audio. so lets say the audio is of 5 seconds, so i need a sample after every 50ms so that the total samples would be 100. the main problem is i don't know how to take samples from an audio being recorded or a prerecorded audio using arduino. The 100 samples would then be multiplied by the 100 samples from the trained model and then added and then sigmoid function will be used so that at the end we can know whether the baby is crying or not. All the deployment of the model will be done in arduino. Any help regarding taking the samples or bitrate, would be much appreciated. Thanks in advance! :)

“kbps” means kilobits per second. That is a unit of bit rate, not of sample rate. If you want help for controlling the sampling rate of the Arduino, tell us what sampling rate you need, and what model of Arduino you are using.

What arduino are you using that can sample at 192ksps?

With what exactly do you need help? Do you already have a code, that samples the audio and sends it to the rest of your setup? Or are you starting from zero in this part?

@EdgarBonet what i need at the end is 10kbps arduino recording quality or to convert any kbps into 10kbps. i am using arduino mega and node mcu. finally will be working on either one. thanks

@Majenko i have heard that arduino recording quality is 192kbps, i have not tested it yet. thanks

Where did you hear such nonsense?

@chrisl at the end of the day, i need 100 samples from the recorded audio on the arduino. it can be real time which means arduino just records the 100 sample values and not the audio, or it can be post processing which means that first arduino records the audio and then extracts 100 samples from that audio. either ways i need 100 samples. so that then the 100 samples can be done some calculations on, to finally deploy the model on arduino to check whether baby is crying or not. thanks

@Majenko kindly guide, I am fairly new to arduino and this is my Final Year Project at the university. thanks

Well, firstly the Arduino (as in most basic 8 bit Arduino branded boards, the most common type) really do not do audio. Maybe very low quality, brief, scratch sounds, but not proper audio. Secondly the absolute maximum sampling rate of a single ADC channel  is 9615Hz.

Thirdly most Arduinos have such a minuscule amount of memory there's no way you'll ever get multi-second sampling to fit into it.

@Majenko i am confused in Hz and kbps. secondly i know arduino don't have much memory thats why i will be using a memory card reader along with it. i have seen tutorials on how to record audio with arduino on memory card. Moreover, i was thinking what if i directly attach a microphone on A0, and get the analogRead out of it after every 50ms. that will make 100 samples but i doubt that'll work. thanks

1Hz is one sample per second. 1000Hz is 1kHz and 1000 samples per second is 1ksps. One sample consists of a number of bits depending on the resolution. The bps is the bits per second, or the number of bits per sample multiplied by the number of samples per second.

What are you actually trying to achieve? Don't tell us what you think you want to do, but tell us what you want to achieve as the end result.

If you take 1 sample every 50ms that is a sampling rate of 20sps. According to Nyquist-Shannon theorem that means you'd have a maximum detectable frequency of 10Hz. I fail to see how that would be of any use unless you're a blue whale.

@Majenko thanks for the valuable information. i am actually trying to train a model for baby crying detection. and then deploying that model on arduino. since many machine learning algorithms require heavy processing power for deployment, but logistic regression method is very lightweight to deploy. in this method we take 100 samples from recorded audio on arduino, and 100 weights from the trained model from dataset. then we multiply these two and then add them. and then apply sigmoid function. then give a threshold of 0.5. the result will be a numerical value and will tell whether baby crying

@Majenko yes that will be 20SPS and we will have 100 samples for a 5 second audio

@Majenko, Baby whale doo doo doo doo doo, baby whale doo... there, now it's stuck in your your head.  Thanks for that.

First of all, I am pretty sure your idea of using discrete ADC samples
as predictors for your model is hopelessly naive. As explained by
Majenko, you cannot expect anything meaningful from a sound recording
taken at 20 samples per second. You may have more luck using
spectral intensities as predictors. I suggest you start by doing some
time–frequency analysis on your training data, just to get some ideas on
what predictors may be worth trying. In any case, I strongly suggest you
train and test your model on your computer, before committing any
code to the Arduino.
That being said, sampling a signal at 20 Hz is quite easy: wait for
50 ms (or 50,000 µs for better accuracy), take one sample,
repeat. The only caveat is that you have to use millis() or micros()
rather than delay() or delayMicroseconds(), otherwise the sampling
period will be longer than expected because of the time needed to
execute the code.
Applying the sigmoid function just to compare the result to 0.5 makes
little sense. You know the sigmoid is larger than 0.5 only when its
argument is positive, so you can trivially save yourself expensive
floating point operations.
Here is a tentative implementation of (my understanding of) the idea you
suggest:
const uint8_t mic_pin = A0;
const size_t sample_count = 100;
const uint32_t sample_period = 50000;  // 50,000 us = 50 ms
const int weights[sample_count] = { 12, -42, 23 /* etc... */};

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

void loop() {
    // Record the samples.
    int samples[sample_count];
    uint32_t last_sample = micros();
    for (size_t i = 0; i < sample_count; i++) {
        while (micros() - last_sample < sample_period) { /* wait */ }
        samples[i] = analogRead(mic_pin);
        last_sample += sample_period;
    }

    // Compute the weighted sum.
    long sum = 0;
    for (size_t i = 0; i < sample_count; i++) {
        sum += (long) samples[i] * weights[i];
    }

    // Predict.
    if (sum >= 0) {
        Serial.println("The baby is crying!");
    }
}

surely i am looking into more methods of machine learning, the big downside of the rest of the models is that they cannot be deployed on arduino. And yes i have looked into spectrograms, they are much more valuable. thanks alot for the information and the code you provided :)


text:
Fail to burn bootloader into standalone atmega2560
I am making a project where I use standalone atmega2560. I used arduino mega schematic to put all necessary components so atmega2560 would be working. I tried to burn bootloader into it using arduino mega as ISP, but failed. I get this error:
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega2560 -cstk500v1 -PCOM4 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xD9:m -Ulfuse:w:0xFF:m

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
         AVR Part                      : ATmega2560
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
           flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

I use schematic which I attached.
At first I uploaded arduinoISP example code to my arduino mega and then used it to program several arduino megas to be sure that it is working and then I connected cables to arduino mega ISCP connector which is master and then put them into my PCB board X3 connector which also has SPI connected to it. After trying to burn bootloader I got an error above.
Things I already did:
Made sure that all VCC pins are connected. And AVCC is connected to VCC
Made sure that all GND pins have ground and my PCB has same GND level as arduino mega (programmer)
Made sure that I connected SPI correctly.
Made sure that arduino as ISP is working.
Made sure that VCC level is high (it is about 4.7 V)
I also tried to put external voltage, but it also did not help.
I tried putting capacitor between Reset and GND pins on arduino mega (programmer)
What could go wrong? After all my struggles I came to the conclusion that it is probaby hardware problem, but I cannot find it.
Also I read that atmega2560 by default use 8 MHZ internal clock, can it be a problem?

What exactly is the RESET signal of your target connected to on the "programmer" Arduino?  What pin?

RESET in my arduino mega(programmer) is connected to digital pin 10. I also tried connecting it to digital pin 53 which is slave select, while doing so I change the code. Both methods did not work. In my board RESET is inverted atmega2560 RESET

You know there is widely used ISP header pinout and you are using something completely different?

I use ISP header you just mentioned except RESET pin. I use RESET pin from programmer side as digital pin 10 as mentioned in arduino ISP firmware and website.

Pauliusr, I saw that in your above comment.  Do you understand the significance of what @KIIV has pointed out?  Can you confirm that you know that you're using a non-standard pinout and that you're not miswiring because you think that you have used a standard pinout?

I understand. I can assure that I use standard pinout, because with the same pinout I managed to burn bootloader into another arduino mega

I have not tried standing on my head yet, but every which way I've looked at your ISP header in your schematic, trying to imagine how the footprint could be mated to a symbol in such a way as to make the pins land where the should, has failed to make this look like a normal pinout.  So, I'll have to take your word for it that you've done it with your PCB.  If you're saying you've managed to use arduinoisp.ino on an Arduino Mega to successfully program another Arduino Mega, I'm not too surprised.

Oh sorry. I see what you mean... Yeah I am not using standard header. That is a good point and I should use a standard one, but I am aware of my pinout and I am sure that I connect MISO to MISO, MOSI to MOSI and so on.


text:
Input Capture Mode PPM signal
Greetings to all members of the Forum. I would like to express my deepest gratitude, with respect to the title of this post.
The last week I am trying to capture and decode a PPM Signal from an RC transmitter. Although I have seen many different approaches and codes online, using methods like Input Capture Mode and Pin Change Interrupts I would like to seek some help on my approach.
Most of the codes I have found online present glitches and instabilities while trying to read the time between the rising pulses.
I have tried to read and understand how to set up the Input Capture registers on the Atmega 32u4 chip, aka Arduino Pro Micro / Lepnardo, but I cannot find a proper way of defining the registers as well as the ISR (_vec) function.
In the next few lines I will try to explain the code I have written so far, but I will need some help with respect to the initialization of registers.
Please bare with me, as any help will be much appreciated. Without further ado, let me introduce you to the following lines.

#define STICK_CENTER 1500
#define STICK_HALFWAY 500
#define THRESHOLD 15

#define MIN_PULSE_WIDTH (STICK_CENTER - STICK_HALFWAY - 15)
#define MAX_PULSE_WIDTH (STICK_CENTER + STICK_HALFWAY + 15)

#define RC_CHANNELS_COUNT 8

#define PPM_CAPTURE_PIN 4
#define NEWFRAME_PULSE_WIDTH 2000
#define TIMER_COUNT_DIVIDER 2

void rc_setup_ppm() {
  setupPins();
  initTimer();
}

void setupPins(void) {
  // Set up the Input Capture pin
  pinMode(PPM_CAPTURE_PIN, INPUT);
  digitalWrite(PPM_CAPTURE_PIN, 1); // enable the pullup
}

void initTimer(void) {
  cli();

  TIFR = (1 << ICF1); //Clear any Interrupt flags
  PRR |= (0 << PRTIM1); //Enable Timer1
  TCCR1A = 0; //Clear TCCR1A
  TCCR1B = 0; //Clear TCCR1B
  TCCR1C = 0; //Clear TCCR1C
  TCCR1B = (1 << ICNC1) | (1 << ICES1) | (1 << WGM13) | (1 << WGM12) | (0 << CS12) | (1 << CS11) | (0 << CS10);
  TIMSK1 |= (1 << ICIE1); //Enable input capture
  TIFR1 = (1 << ICF1); //Clear interrupt flag

 sei();
}

uint16_t adjust(uint16_t diff, uint8_t chan) {

  return diff / TIMER_COUNT_DIVIDER;
}

ISR(TIMER1_CAPT_vect) {
  union twoBytes {
    uint16_t word;
    uint8_t  byte[2];
  } timeValue;

  uint16_t now, diff;
  static uint16_t last = 0;
  static uint8_t chan = 0;

  timeValue.byte[0] = ICR1L;    // grab captured timer value (low byte)
  timeValue.byte[1] = ICR1H;    // grab captured timer value (high byte)

  now = timeValue.word;
  diff = now - last;
  last = now;

  //all numbers are microseconds multiplied by TIMER_COUNT_DIVIDER (as prescaler is set to 1/8 of 16 MHz)
  if (diff > (NEWFRAME_PULSE_WIDTH * TIMER_COUNT_DIVIDER)) {
    chan = 0;  // new data frame detected, start again
  }
  else {
    if (diff > (MIN_PULSE_WIDTH * TIMER_COUNT_DIVIDER - THRESHOLD)
        && diff < (MAX_PULSE_WIDTH * TIMER_COUNT_DIVIDER + THRESHOLD)
        && chan < RC_CHANNELS_COUNT)
    {
      rc_values[chan] = adjust(diff, chan); //store detected value
    }
    chan++; //no value detected within expected range, move to next channel
  }
}

Given the above I would like to help setting the initialization routine of the registers. Some information about my signal:
PPM includes 8 different channels as a summed signal. In total 9 pulses while each one, has a time duration from 998 - 2012 microsecs.
The time frame of each pulse is easy to be changed though the transmitter settings. Also the total period of the frame can be changed. By the first I mean the HIGH time of each pulse, and by the second I mean the total frame period after the 8 channels have been scanned. Given these, the time periods are 26.5 mills and 350 microsecs.
Enough with these. Going back to the actual code you will see the cli(); and sei(); functions. Do I really have to set these during that part of the code?
Also do I need to reset or delete any active flags? Should I include any flags (e.g. Overflow flag after the counter has reached its peack value)
At this point I would also like to mention that I am using a prescaler of 1/8, which results to a tick period of apx. 0.5 microsecs.
Also, I am capturing only the rising part of the pulses. And I am using an Input canceler, but given the datasheet specifications I have seen that the cancel frame is 4 periods long. Is there any possible way to use a low latency filtering scheme?
Please take some time to read this post, as I am confident enough that any responses will help others too clarify these topics.
I know that I have included many different aspects and I feel sorry for this.
Many thanks,
Koutsoukos Theodosios

I feel like you're about to pull a rabbit out of a hat or challenge us to a duel or something.  In all seriousness, you'll probably have better luck if you cut this down.

Sorry for the contents of my post. I would like to seek advices only to the Initialization of the input capture mode. Only the registers and how to  use these.

I could probably write something about how to setup input capture.  But in your question you mention that you're trying to do this with 8 different signals.  The 32u4 only has 2 input capture pins.  That would seem to be something of a problem for you, if I understand correctly.

Dear timemage, thank you for your reply. It was something I wrote wrong, so please forgive me. I meant that the ppm signal contains 8 different signals, (9 pulses in total).

If "after the 8 channels have been scanned" means after "after 8 pulses..." you can edit your question  to say that.  Clarifications to questions asked here normally supposed to edited into the question.

Many thanks once again, I have change it and included what really happens.

Do I really have to set these during that part of the code?

No, you don't. I would, however, change the order of the last
initializations:

Update TIFR1 right before TIMSK1 in order to avoid an interrupt to
be triggered immediately.

Set TCCR1B last in order for the timer to start only when it has
been fully configured.

Also do I need to reset or delete any active flags?

AFAIK the Arduino core does not use the Timer 1 interrupts. You can take
control of all the bits in the registers (e.g. TIMSK1 = (1 << ICIE1);)
instead of only some selected bits. It shouldn't make a difference
though.

Should I include any flags (e.g. Overflow flag after the counter has
reached its peak value)

Do not worry about overflows. The computation diff = now - last is
done modulo 216 and, owing to the rules of modular
arithmetics, gives the correct result even across an overflow.

And I am using an Input canceler, but given the datasheet
specifications I have seen that the cancel frame is 4 periods long.

This creates a delay of “four system clock cycles”, or 0.25 µs. Do
you really care about such a small latency? Please note that, since all
edges suffer the same latency, it doesn't affect the calculated
differences.
Now, if I may, a couple of comments about your code:
  pinMode(PPM_CAPTURE_PIN, INPUT);
  digitalWrite(PPM_CAPTURE_PIN, 1); // enable the pullup

This can be simplified an made more explicit:
  pinMode(PPM_CAPTURE_PIN, INPUT_PULLUP);

Then,
  union twoBytes {
    uint16_t word;
    uint8_t  byte[2];
  } timeValue;
  timeValue.byte[0] = ICR1L;    // grab captured timer value (low byte)
  timeValue.byte[1] = ICR1H;    // grab captured timer value (high byte)
  now = timeValue.word;

This used to be the way to read 16-bit registers a long time ago. Since
many years now, the C compiler knows how to do it, you just have to
issue:
  now = ICR1;

This contains most of what I was writing, so I'm just going to vote this up.

PRR |= (0 << PRTIM1); -> PRR0 &=  ~(1 << PRTIM1);

TCCR1C = 0; does nothing useful.

Dear Edgar, timemage, many thanks for your replies. Especially to the the one from Edger, which included everything I was asking for. Just amazed by the simplicity and the way you did transmit all the information. Cheers!


text:
why does function affect my ISR?
I am currently running this piece of code:
main.ino
#include "speed_profile.h"

void setup() {
  // put your setup code here, to run once:
  output_pin_setup();
  cli();
  timer1_setup();
  sei();
}

void loop()
{
      //int motor_steps = 23400;//-9600; //23400 -  100%
      // Accelration to use.
      //int motor_acceleration = 500;//500;
      // Deceleration to use.
      //int motor_deceleration = 500;//500;
      // Speed to use.
      //int motor_speed = 1000; // 1000
      init_tipper_position();
      compute_speed_profile(23400, 500, 500, 1000);
}

Speed_profile.cpp
#include "speed_profile.h"

volatile speed_profile profile;

ros::NodeHandle_<ArduinoHardware, 1, 2, 125, 125> nh;
//ros::NodeHandle nh;

std_msgs::Int16 status_step_count;
std_msgs::Int16 status_tipper_availability;
ros::Publisher chatter_status("tipper_status", &status_step_count);
ros::Publisher chatter_availabilty("tipper_availability", &status_tipper_availability);

volatile bool global_state = false;
int received_data = 0;

void call_back_control( const std_msgs::Empty & msg)
{
  global_state = true;
  // For HMI
  received_data  = (100 *23400.0)/100.0; // Converts input to motor_steps.
}

ros::Subscriber<std_msgs::Empty> sub_control("tipper_control", &call_back_control );

void output_pin_setup()
{
  pinMode(en_pin, OUTPUT);
  pinMode(dir_pin, OUTPUT);
  pinMode(step_pin, OUTPUT);
  pinMode(slot_sensor_pin,INPUT_PULLUP);
  nh.initNode();
  nh.advertise(chatter_status);
  nh.advertise(chatter_availabilty);
  nh.subscribe(sub_control);
  //nh.subscribe(sub_command);
  profile.current_step_position = 0;
  delay(10);
  nh.getHardware()->setBaud(57600);
}

void init_tipper_position()
{
  //digitalWrite(en_pin, HIGH);
  //delay(1);

  //digitalWrite(dir_pin, LOW);
  //delay(1);

  while(!(PINB & (1 << 2)))
  {
    //PORTB ^= _BV(PB3);
    //delayMicroseconds(100);
  }

  //digitalWrite(en_pin, LOW);

}
void timer1_setup()
{
  // Tells what part of speed ramp we are in.
  profile.run_state = STOP;

  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;  // reset the timer

  // Timer/Counter 1 in mode 4 CTC (Not running).
  TCCR1B = (1 << WGM12);

  // Timer/Counter 1 Output Compare A Match Interrupt enable.
  TIMSK1 = (1 << OCIE1A);
}

void computation_of_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed)
{
  unsigned int steps_to_speed;  // Steps required to achieve the the speed desired
  unsigned int acceleration_step_limit; // If desired speed is not achieved, will this variable contain step_limit to when to stop accelerating.
  // If moving only 1 step.
  if (motor_steps == 1)
  {
    // Move one step
    profile.accel_count = -1;
    // in DECEL state.
    profile.run_state = DECEL;
    // Just a short delay so main() can act on 'running'.
    profile.first_step_delay = 1000;
    OCR1A = 10;
    // Run Timer/Counter 1 with prescaler = 8.
    TCCR1B |= ((0 << CS12) | (1 << CS11) | (0 << CS10));
  }
  else if (motor_steps != 0)
  {
    // Set max speed limit, by calc min_delay to use in timer.
    // min_delay = (alpha / tt)/ w
    profile.min_time_delay = A_T_x100 / motor_speed;

    // Set accelration by calc the first (c0) step delay .
    // first_step_delay = 1/tt * sqrt(2*alpha/accel)
    // first_step_delay = ( tfreq*0.676/100 )*100 * sqrt( (2*alpha*10000000000) / (accel*100) )/10000
    profile.first_step_delay = (T1_FREQ_148 * sqrt(A_SQ / motor_accel)) / 100;

    // Find out after how many steps does the speed hit the max speed limit.
    // steps_to_speed = speed^2 / (2*alpha*accel)
    steps_to_speed = (long)motor_speed * motor_speed / (long)(((long)A_x20000 * motor_accel) / 100);
    // If we hit max speed limit before 0,5 step it will round to 0.
    // But in practice we need to move atleast 1 step to get any speed at all.
    if (steps_to_speed == 0)
    {
      steps_to_speed = 1;
    }

    // Find out after how many steps we must start deceleration.
    // n1 = (n1+n2)decel / (accel + decel)
    acceleration_step_limit = ((long)motor_steps * motor_decel) / (motor_accel + motor_decel);
    // We must accelrate at least 1 step before we can start deceleration.
    if (acceleration_step_limit == 0)
    {
      acceleration_step_limit = 1;
    }

    // Use the limit we hit first to calc decel.
    if (acceleration_step_limit <= steps_to_speed)
    {
      profile.decel_length = -(motor_steps - acceleration_step_limit); //---
    }
    else
    {
      profile.decel_length = -((long)steps_to_speed * motor_accel) / motor_decel; //--
    }
    // We must decelrate at least 1 step to stop.
    if (profile.decel_length == 0)
    {
      profile.decel_length = -1;
    }

    // Find step to start decleration.
    profile.decel_start = motor_steps + profile.decel_length;

    // If the maximum speed is so low that we dont need to go via accelration state.
    if (profile.first_step_delay <= profile.min_time_delay)
    {
      profile.first_step_delay = profile.min_time_delay;
      profile.run_state = RUN;
    }
    else
    {
      profile.run_state = ACCEL;
    }

    // Reset counter.
    profile.accel_count = 0;
    //profile.step_counter = steps_to_speed;
  }
}

void compute_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed)
{
  while (global_state == false)
  {
    //do nothing
    status_step_count.data = ((float)(profile.current_step_position / 23400.0)) * 100.0; //map(profile.current_step_position,0,23400,0,100); // could be expensive -- Nice flowing is only available with float
    status_tipper_availability.data = 1;

    chatter_status.publish( &status_step_count);
    chatter_availabilty.publish(&status_tipper_availability);
    nh.spinOnce();
  }

  digitalWrite(en_pin, HIGH);
  delay(1);

  signed int move_steps;
  //if (motor_steps < 0)
  if(received_data > profile.current_step_position) // Compares whether received percentage (converted to motor_steps) is greater or smaller than current_step_position.
  {
    profile.dir = CCW;
    move_steps =  received_data - profile.current_step_position;
    digitalWrite(dir_pin, HIGH);
  }
  else
  {
    profile.dir = CW;
    move_steps =  profile.current_step_position - received_data;
    digitalWrite(dir_pin, LOW);
  }

  delay(1);
  // received_data = percentage converted to a step number received from tipper_control topic

  computation_of_speed_profile(move_steps, motor_accel, motor_decel, motor_speed); // function should be called with the correct motor_steps value

  OCR1A = 10;
  // Set Timer/Counter to divide clock by 8
  TCCR1B |= ((0 << CS12) | (1 << CS11) | (0 << CS10));

  while (global_state == true)
  {
    status_step_count.data = ((float)(profile.current_step_position / 23400.0)) * 100.0; //map(profile.current_step_position,0,23400,0,100); // could be expensive -- Nice flowing is only available with float
    status_tipper_availability.data = profile.run_state;

    chatter_availabilty.publish(&status_tipper_availability);
    chatter_status.publish( &status_step_count);
    nh.spinOnce();
  }
}

ISR(TIMER1_COMPA_vect)
{
  // Holds next delay period.
  unsigned int new_first_step_delay;

  // Remember the last step delay used when accelrating.
  static int last_accel_delay;

  // Counting steps when moving.
  static unsigned int step_count = 0;

  // Keep track of remainder from new_step-delay calculation to incrase accurancy
  static unsigned int rest = 0;
  OCR1A = profile.first_step_delay;
  switch (profile.run_state)
  {

    case STOP:
      step_count = 0;
      global_state = false;
      rest = 0;
      TCCR1B &= ~((1 << CS12) | (1 << CS11) | (1 << CS10)); // Stop the timer,  No clock source
      break;

    case ACCEL:
      //digitalWrite(step_pin, !digitalRead(step_pin));
      PORTB ^= _BV(PB3);  // Toggles the step_pin
      step_count++;

      if (profile.dir == CCW)
      {
        profile.current_step_position++;
      }
      else
      {
        profile.current_step_position--;
      }

      profile.accel_count++;
      new_first_step_delay = profile.first_step_delay - (((2 * (long)profile.first_step_delay) + rest) / (4 * profile.accel_count + 1));
      rest = ((2 * (long)profile.first_step_delay) + rest) % (4 * profile.accel_count + 1);

      // Chech if we should start decelration.
      if (step_count >= profile.decel_start)
      {
        profile.accel_count = profile.decel_length;
        profile.run_state = DECEL;
      }

      // Chech if we hitted max speed.
      else if (new_first_step_delay <= profile.min_time_delay)
      {
        last_accel_delay = new_first_step_delay;
        new_first_step_delay = profile.min_time_delay;
        rest = 0;
        profile.run_state = RUN;
      }
      break;
    case RUN:
      //digitalWrite(step_pin, !digitalRead(step_pin));
      PORTB ^= _BV(PB3); // Toggles the step_pin
      step_count++;

      if (profile.dir == CCW)
      {
        profile.current_step_position++;
      }
      else
      {
        profile.current_step_position--;
      }
      new_first_step_delay = profile.min_time_delay;
      // Chech if we should start decelration.
      if (step_count >= profile.decel_start)
      {
        profile.accel_count = profile.decel_length;
        // Start decelration with same delay as accel ended with.
        new_first_step_delay = last_accel_delay;
        profile.run_state = DECEL;
      }
      break;
    case DECEL:
      //digitalWrite(step_pin, !digitalRead(step_pin));
      PORTB ^= _BV(PB3); // Toggles the step_pin
      step_count++;
      if (profile.dir == CCW)
      {
         profile.current_step_position++;
      }
      else
      {
        profile.current_step_position--;
      }
      profile.accel_count++;
      new_first_step_delay = profile.first_step_delay - (((2 * (long)profile.first_step_delay) + rest) / (4 * profile.accel_count + 1));
      rest = ((2 * (long)profile.first_step_delay) + rest) % (4 * profile.accel_count + 1);
      // Check if we at last step

      if (profile.accel_count >= 0)
      {
        digitalWrite(en_pin, !digitalRead(en_pin));
        //PORTB &= ~_BV(PB3);
        profile.run_state = STOP;
      }
      break;

  }

  profile.first_step_delay = new_first_step_delay;

}

And the Speed_profile.h
/*
 * Contains the class concerning with calculating the proper speed profile
 * for accelerating and decelerating the stepper motor.
 *
 */

#ifndef speed_profile_h
#define speed_profile_h

#include <Arduino.h>
#include <ros.h>
#include <std_msgs/Int16.h>
#include <std_msgs/Empty.h>

// Timer/Counter 1 running on 3,686MHz / 8 = 460,75kHz (2,17uS). (T1-FREQ 460750)
//#define T1_FREQ 460750
#define T1_FREQ 1382400

//! Number of (full)steps per round on stepper motor in use.
#define FSPR 1600

// Maths constants. To simplify maths when calculating in compute_speed_profile().
#define ALPHA (2*3.14159/FSPR)                    // 2*pi/spr
#define A_T_x100 ((long)(ALPHA*T1_FREQ*100))     // (ALPHA / T1_FREQ)*100
#define T1_FREQ_148 ((int)((T1_FREQ*0.676)/100)) // divided by 100 and scaled by 0.676
#define A_SQ (long)(ALPHA*2*10000000000)         // ALPHA*2*10000000000
#define A_x20000 (int)(ALPHA*20000)              // ALPHA*20000

// Speed ramp states
#define STOP  0
#define ACCEL 1
#define DECEL 2
#define RUN   3

// Pin numbering
#define en_pin 13
#define dir_pin 12
#define step_pin 11
#define slot_sensor_pin 10

// Motor direction
#define CW  0
#define CCW 1

typedef struct
{
  unsigned char run_state : 3; // Determining the state of the speed profile
  unsigned char dir: 1; // Determining the direction the motor has to move - Start being CCW
  unsigned int first_step_delay; // Period time for the next timer_delay, determines the acceleration rate.
  unsigned int decel_start; //  Determines at which step the deceleration should begin.
  signed int decel_length; // Set the deceleration length
  signed int min_time_delay; //minium time required time_delay for achieving the wanted speed.
  signed int accel_count; // counter used when computing step_delay for acceleration/decelleration.
  volatile signed int current_step_position; // contains the current step_position

}speed_profile;

void compute_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed);
void computation_of_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed);
void init_tipper_position();
void timer1_setup(void);
void output_pin_setup(void);
#endif

The problems is with the ISR. The function init_tipper_position seem to be causing a timing problem that makes is impossible the ISR to go through all its states. I changed some parts of the code based on @EdgarBonet 's answer, which seem have helped a bit. The problem here is that the program stalls when the it reaches the state STOP. This is not a issue at all if the prior function is executed..?? why am I having this issue?

What does "the ISR stalls at its last state" mean? Which is the "last state" and how exactly does it "stall"?

@brhans It stalls  by the global state doesn't go further on from the state DECEL to STOP where the clock source for the timer1 is being removed, and thereby disables the occurrence of the ISR.

Could you please edit the question and remove all the duplicate stuff?

Rewrote the post, which now basically include the full code.

Can you please stop making multiple posts of what is basically the same issue? You have another question why is function being skipped? where you are speculating that init_tipper_position is being "skipped" or "ignored". The compiler just doesn't ignore functions in a whim. With thread after thread of yours (some now migrated from EE.SE) it is very hard to keep up with you. As soon as someone starts answering you throw all the same code into a new thread with a new idea about what the problem is.

You should try chatting with Carlton Banks - he seems to have exactly the same issues that you do.

Lamda / CB, Nick's comment about throwing in all the same code each time is worth heeding.  I find the code you've been posting awkward reading because of its formatting and presentation.  More people may look for the problem if it's less painful to read.  Perhaps ask on codereview.stackexchange for some advice on better formatting and presentation.

This isn't the sort of approach you should use in an ISR.  You need to get into the ISR, and get out of it ASAP.  Set a flag, and read the flag in your code to decide what needs to be done.  There should be very little in the way of decisions and branching in an ISR.  Most certainly, there should be zero floating point math in your ISR, especially on a platform that doesn't have a floating point processor (actually, my preference is to avoid floating point math wherever possible in an embedded system, but I might be a bit extreme.
Start from scratch, rebuilding your ISR to do only what needs to be done, and use main to do the rest of it (or "loop" or some such on an Arduino).
Having spent no real time on an Arduino, interrupts just don't seem all that convenient to use to me.  If the Arduino environment doesn't let you use interrupts the right way, you should consider programming the AVR wit AVR compilers.

The ISR could be changed i agree, It is basically an implementation taken from an Atmel application note.  and basically is only one of states performed for each ISR, meaning it might not be that critical. According to the application note  http://www.atmel.com/images/doc8017.pdf

will it spent 200µs in the Accel state and Decel state, and 35 µs in Run state, approx. measured. I've tried moving things outside the ISR and computed it there, but that often result in different values, or using non updated values even if I use volatile variables or static, which is why i choose to do it as such. the implementation can be found on github

you should consider programming the AVR wit AVR compilers - the Arduino IDE uses avr-g++ which is a perfectly fine tool. It also lets you generate your own interrupt routines if you want to.

I'm not very familiar with the details of the Arduino infrastructure either, but I think your fundamental problem is the fact that you are doing GPIO (i.e., digitalRead() and digitalWrite()) both in your ISR and in your main loop().
Since these functions manipulate global hardware and use various "shadow" variables to keep track of their state, it's very unlikely that they are "reentrant". A reentrant function is written without global/static variables (and a few other restrictions), such that one call to it can be interrupted and another call made to it without interfering with the first one.
The Arduino environment was never intended for projects in which issues such as reentrancy should arise; such projects should be using using a "real" RTOS or equivalent. Yes, you can shoehorn such project into the Arduino environment, but only if you already know exactly what you're doing.

The digitalRead and digitalWrite are performed in two different places. When init_tipper_position()  is called, is the ISR not activated yet, meaning the Timer1 has been setup to be in (CTC-mode), and a compare match interrupt is being enabled, but at no value has been given to OCR1A. Its only in the next function where it is being given a value.

There are no “shadow variables” in digitalRead() nor digitalWrite(), and digitalWrite() toggles the pin atomically (i.e. with interrupts disabled), precisely to avoid the kind of reentrancy problems you are afraid of.

What alternatives do i have for instead of using digitalRead and digitalWrite

@Lamda: Direct port access, but that won't help unless your problem is genuinely cause by digitalRead() or digitalWrite().

I have nothing else to go by. Everything works as it should be if I remove the while(digitalRead()..). I completely agrees that it does not make any sense that this should be the cause.  It could maybe a compiler optimisation? as I am currently running low on memory on the board?

@EdgarBonet: OK, I'll concede that point, provisionally. I was able to find the source code for wiring_digital, which does show that the actual port update is done inside a critical section. However, there is a lot of other stuff going on first that is not protected, such as program memory table lookups to determine pin parameters such as port number, bit mask and whether there's an associated PWM function. If there is a possibility of PWM, the timer register is twiddled unconditionally.

... I was not able to drill down into the details well enough to satisfy myself that there were no non-reentrant side-effects from all of this activity. I'll just have to take your word for it.

@EdgarBonet My bug was intermittent. After running some tests for a few hours, you may be correct about digitalRead being okay in an ISR so my previous comment was deleted.

I narrowed the search space to be inside the init_tipper_position

I see nothing wrong with this function, except that it takes some time
to execute, and makes compute_speed_profile() start later. So I am
guessing yours is a timing problem: your code may be sensitive to the
value held by the timer when compute_speed_profile() starts. It is
just a wild guess, as you did not show all your code, and the real
problem may be somewhere we cannot see.
Did you completely initialize Timer 1 before using it? I see no mention
of TCCR1A in the part you showed us. You should be aware that the
Arduino core library initializes this timer to provide 8-bit PWM. It is
likely that you will need to undo that initialization, e.g., at the very
beginning of your program:
TCCR1A = 0;  // undo the initialization done by...
TCCR1B = 0;  // ...the Arduino core library
TCNT1  = 0;  // reset the timer

This is the default state set by the hardware at boot, and the Atmel
application note you are using as a reference may well assume this state
has not been tampered with.
Also, I did not check your algorithm, but since your are stopping and
restarting the timer, it may make sense to also reset it (TCNT1 = 0;).

I am sure i understand why timer1_setup() starts later due to init_tipper_position is timer1_setup() not executed prior to init_tipper_position?

timer1_setup() is responsible for the initialisation of the timer.  But as you i don't touch TCCR1A as it by default is 0.  I stop and restart the timer, by removing the clock source, in the State STOP.
TCCR1B &= ~((1 << CS12) | (1 << CS11) | (1 << CS10));
And global_state becomes false, which makes the code loop in the while(global_state == false) until it becomes true, where it gets a clock source.

Which can be seen in the function compute_speed_profile

@Lamda: Sorry, I meant compute_speed_profile(). I edited the answer accordingly. It is an error not to set TCCR1A.

I might have been to fast to conclude whether it worked or not. I added TCCR1A in the timer1 setup, and the ISR stalls now in the state STOP...

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


text:
amblone error :85: error: 'TCCR3B' was not declared in this scope - no fullscreen vlc support
getting the following error when trying to upload Amblone code to my Arduino One board:
Arduino: 1.6.12 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\pha\Desktop\amblone\amblone.pde: In function 'void setup()':

amblone:85: error: 'TCCR3B' was not declared in this scope

   TCCR3B = TCCR0B & 0b11111000 | 0x2;

   ^

amblone:86: error: 'TCCR4B' was not declared in this scope

   TCCR4B = TCCR0B & 0b11111000 | 0x2;

   ^

exit status 1
'TCCR3B' was not declared in this scope

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe1
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

Code:
void setup()   {
  // initialize the serial communication
  Serial.begin(256000); // opens serial port, sets data rate to 256000 bps

  TCCR0B = TCCR0B & 0b11111000 | 0x2;
  TCCR1B = TCCR0B & 0b11111000 | 0x2;
  TCCR2B = TCCR0B & 0b11111000 | 0x2;
  TCCR3B = TCCR0B & 0b11111000 | 0x2;
  TCCR4B = TCCR0B & 0b11111000 | 0x2;

  State = S_WAIT_FOR_SF;
}

The full code please.

Amblone doesn't work on an Uno. As stated in the requirements list, you require a Mega.

Thanks to @Majenko, I realised I was uploading code to wrong arduino board as mine was Mega not Uno.
I was also not getting colour changes (Amblone) when playing a file on VLC player full screen - downgraded version and it works again now.


text:
GSM shield 2 - Fully erase memory buffer
I would love to get real developers' input regarding the following issue as I've been spinning my head around it for a while now.
What I'd like to do
My program receives SMS containing simple instructions. When a SMS is received, the code will run according to the instruction. In the mean time, other SMS can be received by the modem[1].

I would like my program to ignore any instruction received while it was busy doing something, and therefore I'm looking for a way to delete any SMS received before the arduino finished doing what it was doing.

What I'm having trouble with is the sms.flush() function. This function is available from the GSM.h library, which is bundled with the Arduino IDE by default.

and here comes the first glitch: the flush()function reference page states that it "clears the modem memory of any sent messages once all outgoing characters have been sent". So it seems at first that flush() would only work for outgoing messages...
...but in the mean time, the official sketch for SMS reception (ReceiveSMS) does indeed use flush() to delete received SMS.

So for me, flush() really works both for outgoing and received SMS. Am I right?
What I did
Here is how the program works:

The arduino receives a SMS and is asked to light a LED
It does as instructed
then sends a SMS back saying that the LED is ON.
The DeleteSMS function is triggered

Here is the code:
void DeleteSMS(){
    int MessageQtt = 0;
    Serial.print(F("["));
    do{
        sms.flush();
        MessageQtt++;
    } while (sms.available() > 0);
    Serial.print(MessageQtt);
    Serial.print(F(" message(s)"));
    Serial.println(F(" have been deleted]\n"));
}

This function is therefore called at the end of the Arduino operations. With it, I wanted to force the Arduino to delete not only the first SMS received as well as the one sent back, but also any SMS received in the mean time.
But it doesn't work and I can't really find out why.
My devices

Arduino UNO
GSM Shield 2
local (France) provider SIM card

Thanks all in advance for your input...
(by the way: if someone could tell me where to find the GSM.h file, I could mess with it to see how things work...)

[^1]: From what I've learned, any SMS received while the modem is turned off or the Arduino busy doing something else will be stored in the memory buffer, but I can't really retrieve my source on that one.

Well, for those who might find it easier to take a look at the whole code, I translated it in (broken) english here.

Well, after many trials, here is the thing: the GSM shield actually can suck up a lot of electric current (up to 2A at full whack).
So, for some functions (connecting to the GSM network, deleting SMS), if you MEGA or UNO is only powered through your computer's USB port, chances are that the whole program will get stuck in a loop waiting for the command to execute.
Good news: if you just plug a 12V power cable even in the middle of the freeze, the program will go on.
So, the bottom line: never try to use the shield without a good powering system.


text:
My Arduino got stuck and continuous looping in if condition
I'm using RTC and when the if condition is true the Time gots stuck and the condition keeps looping. Please help
Here is my code:
// CONNECTIONS:
// DS1302 CLK/SCLK --> 5
// DS1302 DAT/IO --> 4
// DS1302 RST/CE --> 2
// DS1302 VCC --> 3.3v - 5v
// DS1302 GND --> GND
#include <Servo.h>
#include <ThreeWire.h>
#include <RtcDS1302.h>

ThreeWire myWire(4,5,2); // IO, SCLK, CE
RtcDS1302<ThreeWire> Rtc(myWire);
int servoPin = 3;
Servo Servo1;
void setup ()
{
    Serial.begin(57600);
    Servo1.attach(servoPin);
//    Serial.print("compiled: ");
//    Serial.print(__DATE__);
    Serial.println(__TIME__);

    Rtc.Begin();

    RtcDateTime compiled = RtcDateTime(__TIME__);
    printDateTime(compiled);
    Serial.println();

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

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

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

void loop ()
{
    RtcDateTime now = Rtc.GetDateTime();

    printDateTime(now);
    Serial.println();
    delay(5000);

//here is my problem>>>>

    if(now.Hour() == 22 && now.Minute() == 40)
    {
      Servo1.write(0);
      delay(1000);
      Servo1.write(90);
      delay(1000);

    }

//////////////////////

    delay(5000);

}

#define countof(a) (sizeof(a) / sizeof(a[0]))

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

Um... What does "Time gots stuck" mean? Your condition is true for a whole minute.

when the condition is true the time interval of rtc gots stuck and the codition above keeps looping

It is loop() function keeps looping. That's what it is for, as the name suggests. What made you believe that "time interval of rtc gots stuck" is not clear to me.

The time is stuck and the condition keeps triggering..

What made you believe that "the time is stuck"??? The condition should keep triggering again, again and again for a whole minute. That's what you wrote in your code.

Im looking in serial monitor and the time got stuck when the condition is reach. And it keeps triggering the servo again and again..

Post the serial monitor output from printDateTime(now); in loop(). Do you see the same time printed continuously?

The ds1302 is not a good rtc, the ds1307 is better, but the ds3231 is the best by far. The ds1302 can freeze and there can be troubles with the crystal. Could you upgrade to a ds3231. The ds3231 has an internal crystal, so there are no problems with bad quality crystals.

AnT It stuck on condition and the servo keeps triggered 5 to 10 times and the time continue after triggering.

Im not using crystal

i think i have a problem in delay seconds

Im not using crystal -- So.... how does the clock "tick" then...?

You do know that a minute lasts for a whole minute, don't you? It's not some instantaneous thing that only happens for an instant. It's a minute long. A lot can happen in a minute.

The delays in your loop() amount for 12 seconds. So it is perfectly expected to see this if triggered ~5 times per minute.

What is being brought to your attention is the following part of your code...
//here is my problem>>>>

if(now.Hour() == 22 && now.Minute() == 40)
{
  Servo1.write(0);
  delay(1000);
  Servo1.write(90);
  delay(1000);
}

In this code you use an "if" statement and ask:
   if the now.Hour is equal 22 AND if the now.Minute is equal 40 then
    write a 0 to your servo then
    delay for 1000
    then write a 90 to your servo
    and wait another 1000
What is being brought to your attention is that until now.Hour changes or
until now.Minute changes your write 0, delay, write 90, delay will continue
on and on and on until now.Hour changes (which will take a while) or now.Minute
changes. Since minutes are 60 seconds long your code will repeat for all of those
60 seconds...
If you were to change your code to include, oh, lets say now.Second() (like this)--
if(now.Hour() == 22 && now.Minute() == 40 && now.Second() == 00)

Then your code will repeat over and over until now.Second changes (which will take 1 second).
By the time your loop gets back to the "if" statement now.Second will no longer be 00 and it will not be "stuck" for you...

As has been brought to my attention, your 5 second delay will be a problem, so you might find that changing it will allow the now.Second "fix" to work.
In the following part of your code change delay(5000)
void loop ()
{
    RtcDateTime now = Rtc.GetDateTime();

    printDateTime(now);
    Serial.println();
    delay(5000);
}

to something like delay(1000) or so.
That way it will only wait 1 second before dropping out of the loop and checking the loop with the newly added now.Second(). This will make the printDateTime(now) happen every second instead of every 5 seconds, but it shouldn't get "stuck".
Hopefully this helps you to better understand how time (and its parts) work.

a state variable would be a much better solution. with the 5 sec delay in loop() the code could miss the exact second

Aiming for the exact equality with the scheduled time is a bad approach, regardless of how short the delay is. The proper condition should look as (current_time >= scheduled_time && event_has_not_been_triggered_yet). I.e. it should be a greater-or-equal comparison, not an equality comparison.

Ah, experience speaks! I like that, a much better solution...

This approach might be further modified with extra tweaks like: if the above condition is true, but too much time has passed since the scheduled time (due to some unfortunate blocking operation in loop()), then just abandon the event. Depends on the specific application. Sounding an alarm to wake people
up on a weekday morning is typically not a "discardable" event. Feeding the cat, if it is already well past its bedtime, probably is.

Thank you Alexander!  I do not know how to use the 'editor' as well as you, I was unable to add the OP's original code as well as you.  Again, thanks!

You can use four spaces to mark it as a code block.


text:
Serial communIcation from OS X app to Arduino Mega
I am new to stack overflow. I have a question regarding using the USB serial communication sending data from an OS X app to the Arduino Mega 2560.
What happens is, when I have the Arduino running with the Serial monitor open, then I run the OS X app to send data, the Arduino does receive the data for a few seconds, then it stops.
This is the simplified Object-C code on the Mac side:
-(IBAction)sendData:(id)sender{
    NSString *toSend=[NSString stringWithFormat:@"echo %f > /dev/tty.usbmodem1a1341" ,vector.x];
    //vector is the continuous data generated by the Mac
    const char *toCSend =[toSend UTF8String];
    //converting to c string
    printf("%s", toCSend);
    popen(toCSend, "r");
}

This is the code on the Arduino side:
// Read Serial input:
void setup() {
  // Open Serial commurial1.beginnications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    // wait for Serial port to connect. Needed for Leonardo only
  }
}

void loop() {
  // Read Serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();
    if (inChar != '\n') {
      inString += (char)inChar;
      Serial.read();
    } else {
      // if you get a newline, print the string,
      // then the string's value as a float:
      Serial.println(inString.toFloat(), 6);
      // clear the string for new input:
      inString = "";
    }//end of if else
  }//end of while (Serial.available() > 0)
}

I am not sure what the problem, could it be the OS X app send out too much data to quickly? Or could it be the Arduino serial buffer is overflowed?
I really don't know much about serial communication so I don't know what I am missing. Any help will be greatly appreciated.

You should close the serial monitor before you run your custom OSX program.  Just as it auto closes when you upload, only one program should (ordinarily) be using the port at a time.  You may want to build simple output monitoring to the screen/stdout into your custom program.

Like Chris said, opening a serial connection will reset the Arduino, so you probably should add some delay in your OBJC code. Secondly you haven't set a baudrate. Try something like this

Actually, the reset or not is configurable with stty on linux/OSX, and may (perhaps?) not occur if the port is already open by someone else.  But it is indeed one of the several concerns - having the serial monitor grab responses before your program can being another.

One problem is here:

  // Read Serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();

    if (inChar != '\n') {
      inString += (char)inChar;
      Serial.read();
    }

Your Serial.available() call guarantees that you have one byte of serial input, but you are attempting to read two of them if the first one is not a newline. This is not valid.
How to process incoming serial data without blocking


text:
Error while trying to drive relay through the state of a digital input pin in Arduino
I'm trying to change the state of a relay according to the state of a digital input in an Arduino with an ethernet shield. It works sometimes and some other times it doesn't work.
My code:
const int led1 = 2;
const int enable1 = 4;
boolean led1_OnOff;

void setup() {
  led1_OnOff = false;
  pinMode(enable1, INPUT);
  digitalWrite(enable1, LOW);
  pinMode(led1, OUTPUT);
}

void loop() {
  if(digitalRead(enable1) == HIGH) {
    if(led1_OnOff == true) {
      led1_OnOff = false;
    } else {
      led1_OnOff = true;
    }
  }

  if(led1_OnOff == true)
    digitalWrite(led1, HIGH);
  else
    digitalWrite(led1, LOW);
}

My schematics:
Relay 5v -> arduino 5v
Relay gnd -> arduino gnd
Relay in -> digital pin 2
Relay com -> 220 AC
Relay NC -> 220 AC
Push button pin 1 -> Arduino 5v
Push button pin 2 -> digital pin 4
Pin 2 is connected to the relay enable pin and pin 4 is connected to a push button and the boolean is used for saving the state.
Can anyone tell me what the problem is, and why the relay doesn't work most of the time?

Your "My Schematics" is a description, not a schematic. Please make a schematic showing how the Arduino drives your relay. Is it directly connected? How much current does your relay's coil draw? An Arduino pin is only meant to supply 20ma with an absolute maximum of 40ma. It may just not have enough drive. You'll also need a diode to across the coil to quench the inductive kickback when you release the coil, to stop it reaching and destroying the Arduino pin.

Thanks for stopping by...I already answered my question so no need to tell you more about my schematic as it is already right and there is nothing wrong about it...have a good day.

I modified my code and added some code for button debounce and added 10k ohm pull down resistor to my hardware and it works like a charm now.
my new code :
const uint8_t led1 = 6;
const uint8_t enable1 = 7;
const uint16_t buttonConfidenceLevel = 500;
boolean led1_OnOff;

uint16_t pressedConfidenceLevel;
uint16_t releasedConfidenceLevel;
boolean pressed;

void setup() {
    led1_OnOff = false;
    pinMode(enable1, INPUT);
    pinMode(led1, OUTPUT);

    pressedConfidenceLevel = 0;
    releasedConfidenceLevel = 0;
    pressed = false;
}

void loop() {
    if(isButtonPressed()) {
        // Button is pressed
        led1_OnOff = !led1_OnOff;

        if(led1_OnOff == true)
          digitalWrite(led1, LOW);
        else
          digitalWrite(led1, HIGH);
    }

}

boolean isButtonPressed() {
    if(digitalRead(enable1) == HIGH) // button is sensed pushed down
    {
        releasedConfidenceLevel = 0;

        if(pressed == false)
        {
            pressedConfidenceLevel++;

            if(pressedConfidenceLevel > buttonConfidenceLevel)
            {
                pressedConfidenceLevel = 0;
                pressed = true;

                // Button is pressed
                return true;
            }
        }
    }
    else // button is sensed released
    {
        pressedConfidenceLevel = 0;

        if(pressed == true)
        {
            releasedConfidenceLevel ++;

            if(releasedConfidenceLevel > buttonConfidenceLevel)
            {
                releasedConfidenceLevel = 0;
                pressed = false;
            }
        }
    }

    return false;
}

Assuming your circuit is correct (and perhaps it is, since you imply that it works some of the time), the first obvious problem is that when you press the button, the code will repeatedly toggle the output, very very fast.  It may seem to you like you're only pressing the button for a moment, but the code will loop many many times.  When you release the button, it's a 50/50 chance whether it leaves the relay on or off.
To solve this, you can wait until the button is released before checking again.
In addition to this, you may have switch bounce.  There are nicer ways of fixing this, but for your stated purpose, waiting 0.1s after a releae before checking the button again is probably sufficient.
....
void loop() {
  if(digitalRead(enable1) == HIGH)
  {
    if(led1_OnOff == true)
    {
      led1_OnOff = false;
      //+digitalWrite(led1, LOW);
    }
    else
    {
      led1_OnOff = true;
      //digitalWrite(led1, HIGH);
    }

    // Wait for the button to be released
    while(digitalRead(enable1) == HIGH)
    {
      // do nothing, just wait
    }
    // Poor-man's debounce
    delay(100);
  }

  if(led1_OnOff == true)
    digitalWrite(led1, HIGH);
  else
    digitalWrite(led1, LOW);
}

that's a little bit steadier but still doesn't work always

Perhaps you have switch bounce.  Code modified to address that.

I tried something else and it works now, but thanks for the help.

First, how you are set a pin as input and write in this pin?

pinMode(enable1, INPUT);
digitalWrite(enable1, LOW);

You dont need compare a boolean with true

if(digitalRead(enable1) == HIGH)

is the same as:
if(digitalRead(enable1))

use a debbounce with a button state flag to change the button state
if( digitalRead(enable1))
       ena_deb++;
       if(ena_deb > 5){
            change_en_state
       }
}else{
    change_en_state = 0
}

if(change_en_state == X)
    change_output_value;

Thanks for your answer...I already figuered out the answer.

And by the way it's ok to define a pin as input and intialize it at start up...and I already know that trick you said about booleans but it's a programing habit.

When you define a pin as input you can not intialize it, is physically Impossible.
The best way for do a debbounce is use a timer for that. count the debbounce in the timer and set a flag, so you only need read a flag