text:
Serial.available is working only for the first time
I am working on RFID. I am sending data through serial monitor and the Serial.available is not identifying the data after the first time, its working perfectly fine only once after reopening the comport.
I have tried all the possible changes I could do in the code. I want that when I run this code, then after entering the data in serial monitor it should show "Scan the mifare card" and after scanning the card it should perform read or write action.
#include <SPI.h>//include the SPI bus library
#include <MFRC522.h>//include the RFID reader library

#define SS_PIN 10  //slave select pin
#define RST_PIN 9 //reset pin
MFRC522 mfrc522(SS_PIN, RST_PIN);        // instatiate a MFRC522 reader object.
MFRC522::MIFARE_Key key;//create a MIFARE_Key struct named 'key', which will hold the card information

void setup()
 {
        Serial.begin(9600);        // Initialize serial communications with the PC
        SPI.begin();               // Init SPI bus
        mfrc522.PCD_Init();
        //while (! Serial); // Wait untilSerial is ready - Leonardo
        //Serial.println("Enter data");
 }

String incomingStr;
byte blockcontent[16];
int count=0;
String arr2[6];
int arr3[6];
int u2=0;
String arr[16];
int arr1[16];
int u=0;
int y;
char action;
//int newc=0;

void loop()
{
 // Serial.println("bahar");
  if (Serial.available())
    {
      doReceive();
      int newc=0;
      while(newc==0)
       {
         if ( ! mfrc522.PICC_IsNewCardPresent())
            {
               if(count==0)
                   {
                       Serial.println("Scan your mifare card %");
                       count++;
                   }
            }
        else
            {
               newc=1;
            }
       }

     if ( ! mfrc522.PICC_ReadCardSerial())
       {
         return;
       }
     if(action=='%')
       {
         doWrite();
       }
     else if(action=='$')
       {
         doRead();
       }
     else if(action=='^')
       {
         for (byte i = 0; i < mfrc522.uid.size; ++i)
           { // read id (in parts)
              Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
              Serial.print(mfrc522.uid.uidByte[i], HEX);
           }
         Serial.print("*");
       }
  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
  Serial.flush();
   }
}

void doReceive()
{
   incomingStr = Serial.readString();
   int sto=incomingStr.indexOf(')');
   action=incomingStr.charAt(sto+1);
   y=sto+2;
   for(int j=0;j<sto;j++)
    {
      if(incomingStr.charAt(j)!= ' ')
       {
         //Serial.print(incomingStr.charAt(j));
         //arr[u]=arr[u].concat(incomingStr.charAt(j));
         arr2[u2]+=incomingStr.charAt(j);
       }
     else
       {
         //Serial.println(arr[u]);
         u2++;
       }
    }
  for(u2=0;u2<6;u2++)
    {
      arr3[u2]=arr2[u2].toInt();
      key.keyByte[u2]=arr3[u2];
      //Serial.println(key.keyByte[u2]);
    }
 }
void doWrite()
{
  int block=1;
  for(int i=0;i<incomingStr.length();i=i+16)
  {
    if(block == 3 || block ==7 || block ==11 || block ==15 || block ==19 || block ==23 || block ==27 || block ==31 || block ==35 || block ==39 || block ==43 || block ==47 || block ==51 || block ==55 || block ==59 || block ==63)
      {
        block=block+1;
      }
    for(int u=0;u<16;u++)
      {
        blockcontent[u]=0;
        //Serial.println(arr1[u]);
      }
    String s1=incomingStr.substring(y+i,y+16+i);
    s1.getBytes((char *) blockcontent, 30);
    writeBlock(block, blockcontent);
    block=block+1;
  }
  Serial.println("Data written successfully*");
}
void doRead()
{
  int block=1;
  for(int i=0;i<4;i++)
    {
      if(block == 3 || block ==7 || block ==11 || block ==15 || block ==19 || block ==23 || block ==27 || block ==31 || block ==35 || block ==39 || block ==43 || block ==47 || block ==51 || block ==55 || block ==59 || block ==63)
        {
          block=block+1;
        }
      byte readbackblock[18];
      readBlock(block, readbackblock);//read the block back
      //Serial.print("Block contains: ");
      for (int j=0 ; j<16 ; j++)//print the block contents
        {
           Serial.write (readbackblock[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
        }

     //Serial.println();
     block=block+1;
    }
  Serial.println("*");
 }

I have tried all the possible changes I could do in the code. First of all, you could make it reabable by proper indenting.

arr2[u2]+=incomingStr.charAt(j); I don't understand this. But I doubt, it's doing want you want

@user55609 please use proper indentation wile programming. It help other to understand your code easily.

add some test point in you code after every module execution, that will help you to get the error.

what string you sent from serial monitor?

First of all try to add these debugging prints here to see if this while loop is becoming infinite:
  while(newc==0)
   {
     if ( ! mfrc522.PICC_IsNewCardPresent())
        {
           if(count==0)
               {
                   Serial.println("Scan your mifare card %");
                   count++;
                   **Serial.println("test0")*
               }

        }
    else
        {
           newc=1;
           **Serial.println ("newc=1")**
        }
   }

arr2 have size 6. Have you made sure that here
...
for(int j=0;j<sto;j++)
{
  if(incomingStr.charAt(j)!= ' ')
   {
     arr2[u2]+=incomingStr.charAt(j);
   }
 else
   {
     u2++;
   }
}
...

you are not writing beyond the bounds of that array?
Moreover, you never explicitly set the initial value of u2 before starting this cycle - whatever was left in global variable u2 from the previous uses will serve as the staring value for this cycle.
Judging by cursory examination of the rest of your code, only the very first call to doReceive will begin this cycle with u2 == 0. After that every time you call doReceive, you will start this cycle with u2 == 6, definitely overflowing the array and destroying the content of adjacent memory locations. The behavior is undefined.
I guess it is a "global variables strike again" kind of situation. Why on Earth is u2 made a global variable???
It is quite possible that you can "fix" your code by simply adding u2 = 0; before the above cycle. But even after that the code will remain in a rather precarious state.


text:
Trying to individually control the servos in my robot using keyboard input
#include<Servo.h>
Servo ser1;
Servo ser2;
Servo ser3;
Servo ser4;
Servo ser5;
int poser = 0;
int val;
int mot;

void setup() {
  Serial.begin(9600);
  ser1.attach(4);
  ser2.attach(5);
  ser3.attach(6);
  ser4.attach(7);
  ser5.attach(8);
}

void loop() {
    Serial.print("Choose the motor");
      mot=Serial.read();
      switch(mot)
      {
        case 1:
        {
            val = Serial.read();
            if (val == 'd')
             {
                poser += 1;
                ser1.write(poser);
               delay(15);
             }
           if (val == 'a')
             {
                poser -= 1;
                ser1.write(poser);
                delay(15);
             }
           break;
         }
       case 2:
         {
           val = Serial.read();
           if (val == 'd')
            {
               poser += 1;
               ser2.write(poser);
               delay(15);
            }
           if (val == 'a')
            {
               poser -= 1;
               ser2.write(poser);
               delay(15);
            }
           break;
         }
      case 3:
         {
           val = Serial.read();
           if (val == 'd')
            {
              poser += 1;
              ser3.write(poser);
              delay(15);
            }
          if (val == 'a')
            {
              poser -= 1;
              ser3.write(poser);
              delay(15);
            }
          break;
         }
       case 4:
         {
            val = Serial.read();
            if (val == 'd')
             {
                poser += 1;
                ser4.write(poser);
                delay(15);
             }
           if (val == 'a')
             {
                poser -= 1;
                ser4.write(poser);
                delay(15);
             }
           break;
         }
       case 5:
         {
           val = Serial.read();
           if (val == 'd')
             {
                poser += 1;
                ser4.write(poser);
                delay(15);
             }
           if (val == 'a')
             {
                poser -= 1;
                ser4.write(poser);
                delay(15);
             }
           break;
          }
      default:
          {
              Serial.print("Type valid number");
              break;
          }
    }
  }

The code just shows "Choose the motor type valid number" repeatedly and the arm contorts as soon as I upload it. Can someone please check the code and tell me what could've gone wrong?

I had edited your code, basically add indentation so now your code is much clear.

The values that you get from read are characters not integers. You will receive the character '1' or '2' not the integers you are currently checking for. As a result, none of the cases will match and you will always end up at the default: block of code.
So, you need to modify your case statement to check for characters. I.e.
switch(mot){
        case '1':       // put your digit in quoted
        {

And so on throughout the program

Oh, since you are controlling more than one servo, you might want to consider using more than one variable to track their current positions. Unless of course you want the movement of the most recently selected motor to move to one position offset from the previously selected motor. If you unsure what I mean, think about the value of poser if I select motor 1; 20 times and advance it. Poser will = 20. Then select motor 2 and advance it 1 time what will the value of poser be???

Yes, i think i understand what you mean. The value of poser will be 21. So to clarify, you're suggesting that i use different variables (eg.: poser1, poser2, poser3 etc.) for different motors right?

Actually I would suggest use an array but for now maintaining variables named like that is a good first step. If this has helped you can you please accept it as the answer (click the grey checkmark next to the answer that has helped you the most)

@aditii, did either of these answers help you? If so, please accept the one that helped you the most as the answer by clicking on the little check mark next to that answer. Accepting an answer is a way of saying "Thanks for the help".

I would suggest you to add these line in your code.
while(!Serial.available()){;} before mot = Serial.read();
This will hold you logic till any input received from Serial.
Same you add before val = Serial.read();.

source: Stack Exchange

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

sort: votes


text:
How to have some code executed at a certain time of day with a DS3231 RTC?
I recently bought a DS3231 RTC, but I cannot seem to figure out how to get it to work. I have tried all different tutorials and example programs but I keep getting 2165.25.165 165:165:165 as the output.
I am using an Arduino Micro, with the RTC connected as follows:

GND > GND
VCC > 5V
SDA > A4
SCL > A5

Project details:
The project uses a 16x2 LCD to display the time of day, and a countdown to the next occurrence of 06:00. Then at 6 it will allow for a button to be pressed to open a servo and do other things. I got temporary test code to work using millis(), but it is only displaying a 12-hour countdown in seconds, and I would like to replace it with a more reliable RTC.

Nostradamus says the problem is with your code, but his crystal ball is a little cloudy at the moment.

Every time I got this 165:165:165 from an RTC, it turned out the RTC wasn't online -- either not powered, or not on the I2C bus for some reason.

Usual questions on wiring of an I2C device: do you use pullup resistors on SDA  and SCL signals? Note that some circuits may already integrate these, but it is hard to say without knowing the exact circuit (you provided the chip name but you probably have some breakout from Adafruit, Sparkfun... with additional components)

BTW if you want some logic to be executed at certain times, it is better to program RTC to generate alarm interrupt and process external interrupt on MCU. This way no constant polling will be needed on MCU.

Sililar to https://arduino.stackexchange.com/questions/30638/how-to-set-alarms-on-the-ds3231-easily

SDA and SDL pins on an Arduino Micro are on pins D2 and D3 as mentioned on the official page:

TWI: 2 (SDA) and 3 (SCL). Support TWI communication using the Wire library.

and shown on this pinout reference:

If you are getting 165:165:165 that indicates usually a problem with your I2C bus. But it might also be a power problem in the RTC.
In any case, check your wiring.
Your processor is simply not properly communicating with the RTC. If the RTC's red light is on then check your wiring and make sure you haven't reversed SDA and SCL.
Also, the DS3231 has and most Arduinos have enough pull-up that you won't need external pull-up resistors in order to communicate directly with the DS3231.
Try plugging it straight into the Arduino - go minimalist and make that work before adding other devices to the I2C bus like a LCD display. Set the clock by code and watch it in the serial monitor.
Once you're sure the RTC is not a problem then you can go from there with the I2C bus. It is certainly possible for other devices on the bus to cause the RTC to be unable to respond correctly. For a short-range I2C bus that includes the DS3231 don't add any external pullups.
The most reliable RTC for Arduino is the DS3231, but if you bought it via the slow boat you might try a voltmeter to verify the battery so it keeps time even when powered down.
And of course, it is only as accurate as you program it to be. When I program my DS3231s, I always add a couple of minutes to the current time to allow for the time to fix forgotten semicolons and such before it gets around to actually programming the device.
One last note: The program will run when you open the serial monitor. So that will be when it sets the time then begins to display it.

I forgot to add that the DS3231 can set alarms that trigger software interrupts.  Look up the data sheets and you'll find out how.  Here is a library that makes it easy to control them:  https://github.com/rodan/ds3231

Your question doesn't match your title so I will go with your title.

How to have some code executed at a certain time of day with a DS3231 RTC?

The typical approach is to set an alarm on the RTC (to the extent that it supports it), and process that interrupt from the RTC on the MCU side.
Alternatively, you can poll the time on the RTC periodically and once the time is up, do your thing.

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


text:
Problem regarding getting split data of JSON - Another issue
In my recent project, I'm working with Arduino and JSON. I've successfully split the JSON data I want. My JSON data length is fixed. So, I used the length() function and I'm getting the length of my data.
Now, my input JSON data is:
{"TPS":"0.40","MAP":"0.95","LOAD":"14"}

Using the length() function, its length is 39.
But when I use an if statement like if(len == 39) and put my logic inside this, I'm not getting the split data. Below is my whole code.
Here, I'm displaying my data on LCD.
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);
String data_TPS_Json = "";
String data_MAP_Json = "";
String data_LOAD_TM_Json = "";
String response = "";
bool begin = false;
int counter = 0;
int len = 0;
char in;
float TPS_Json;
float MAP_Json;
float LOAD_TM_Json;

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

void loop() {
  while(Serial.available() || !begin) {
    in = Serial.read();
    if (in == '{') {
      begin = true;
    }
    if(begin) {
      counter++;
      response += (in);
      len = response.length();
      if(len == 39) {
        if(counter >= 9 && counter <= 12) {
          data_TPS_Json += (in);
        }
        if(counter >= 22 && counter <= 25) {
          data_MAP_Json += (in);
        }
        if(counter >= 36 && counter <= 37) {
          data_LOAD_TM_Json += (in);
        }
      }
    }

    if(in == '}') {
      break;
    }
    delay(1);
  }
  TPS_Json = data_TPS_Json.toFloat();
  MAP_Json = data_MAP_Json.toFloat();
  LOAD_TM_Json = data_LOAD_TM_Json.toFloat();
  lcd.setCursor(0, 0);
  lcd.print(TPS_Json);
  lcd.setCursor(8, 0);
  lcd.print(MAP_Json);
  lcd.setCursor(0, 1);
  lcd.print(LOAD_TM_Json);
}

Finally, I got the solution. Using substring() function, I can able to split my data.
Here, suppose I have two input data with fixed length.
{"TPS":"0.40","MAP":"0.95","LOAD":"14"}

{"LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}

So, using length() function I got the length of both data. So, I can able to differentiate the different data. In my previous code, I use counter and according to counter index I split my data. But somehow it does not work. So, after using substring() function I got the same result even better.
And below is my whole arduino code:
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String data_TPS_Json = "";
String data_MAP_Json = "";
String data_LOAD_TM_Json = "";

String data_LOAD_RI_Json = "";
String data_RPM_Json = "";
String data_INJECTION_TIME_Json = "";

String response = "";
bool begin = false;

char in;
int len = 0;

float TPS_Json;
float MAP_Json;
float LOAD_TM_Json;

float LOAD_RI_Json;
float RPM_Json;
float INJECTION_TIME_Json;

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

void loop()
{
  while(Serial.available() || !begin)
  {
      in = Serial.read();

      if (in == '{')
      {
        begin = true;
      }

      if(begin)
      {
        response += (in);
      }

      if(in == '}')
      {
        break;
      }

      delay(1);
  }

  len = response.length();

  if(len == 39)
  {
    data_TPS_Json = response.substring(8, 12);
    data_MAP_Json = response.substring(21, 25);
    data_LOAD_TM_Json = response.substring(35, 37);

    jsonMapTps();
  }

  if(len == 52)
  {
    data_LOAD_RI_Json = response.substring(9, 13);
    data_RPM_Json = response.substring(22, 26);
    data_INJECTION_TIME_Json = response.substring(46, 50);

    jsonRpmLoad();
  }
}

void jsonMapTps()
{
    TPS_Json = data_TPS_Json.toFloat();
    MAP_Json = data_MAP_Json.toFloat();
    LOAD_TM_Json = data_LOAD_TM_Json.toFloat();

    lcd.setCursor(0, 0);
    lcd.print(TPS_Json);
    lcd.setCursor(8, 0);
    lcd.print(MAP_Json);
    lcd.setCursor(0, 1);
    lcd.print(LOAD_TM_Json);
}

void jsonRpmLoad()
{
    LOAD_RI_Json = data_LOAD_RI_Json.toFloat();
    RPM_Json = data_RPM_Json.toFloat();
    INJECTION_TIME_Json = data_INJECTION_TIME_Json.toFloat();

    lcd.setCursor(0, 0);
    lcd.print(LOAD_RI_Json);
    lcd.setCursor(8, 0);
    lcd.print(RPM_Json);
    lcd.setCursor(0, 1);
    lcd.print(INJECTION_TIME_Json);
}

I don't think your loop handles the situation where the data comes in too slowly. Looking at your while condition:
while(Serial.available() || !begin)

Once you receive the start char, this becomes:
while(Serial.available())

Now, if there is a delay in the serial buffer, the loop exits before you have the entire message.
You should change the loop so it only ends when you have all 39 chars.
void loop() {
    while (39 != response.length()) {  // Keep going until full msg {
        // Check for data in serial buffer
        if (Serial.available()) {
            in = Serial.read();
            .....
        }
        // No data?
        else {
            delay(10);
        }
    }

    TPS_Json = data_TPS_Json.toFloat();
    MAP_Json = data_MAP_Json.toFloat();
    .....
}

Thank you for your efforts. I tried it out. But still not getting data. This looks logically correct, but If data length changed then what? By the way, I got the solution.

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


text:
How to write an integer value to an RFID tag?
I'm working on a project in which two Arduinos are to be used. Each Arduino is connected to an RFID reader. The first RFID reader should write an integer value to the tag detected, whereas the second RFID reader will read the value that was written by Arduino 1.
I'm facing a problem writing an integer value to the tag. I've found many libraries that include functions that write only strings or characters to the tag. But I need to write an integer. Can anyone help me solve this issue?
Following is code that I found and I tried to edit, so that the write and read functions accept (integer values) as the blockContent. However as expected it didn't work because those functions are defined to accept arrays.
/******************************************
   PURPOSE:  Learn to use the MF522-AN RFID card reader
  Created by      Rudy Schlaf for www.makecourse.com
  DATE:   2/2014
*******************************************/

/*
  This sketch uses the MFRC522 Library to use ARDUINO RFID MODULE KIT   13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
  The library file MFRC522.h has a wealth of useful info. Please read it.
  The functions are documented in MFRC522.cpp.

  Based on code Dr.Leong   ( WWW.B2CQSHOP.COM )
  Created by Miguel Balboa (circuitito.com), Jan, 2012.
  Rewritten by Søren Thing Andersen (access.thing.dk), fall of 2013
  (Translation to English, refactored, comments, anti collision, cascade levels.)

           This library has been released into the public domain.
*/

#include <SPI.h>//include the SPI bus library
#include <MFRC522.h>//include the RFID reader library

#define SS_PIN 10  //slave select pin
#define RST_PIN 5  //reset pin

MFRC522 rfid(SS_PIN, RST_PIN);

MFRC522::MIFARE_Key key;
char order = 49;

void setup() {
  Serial.begin(9600);        // Initialize serial communications with   the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card (in case you wonder what PCD means: proximity coupling device)
  Serial.println("Scan a MIFARE Classic card");

  // Prepare the security key for the read and write functions - all six key bytes are set to 0xFF at chip delivery from the factory.
  // Since the cards in the kit are new and the keys were never defined, they are 0xFF
  // if we had a card that was programmed by someone else, we would need to know the key to be able to access it. This key would then need to be stored in 'key' instead.

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;//keyByte is defined in the "MIFARE_Key" 'struct' definition in the .h file of the library
  }

}

int block = 2; //this is the block number we will write into and then read. Do not write into 'sector trailer' block, since this can make the block unusable.

byte blockcontent[16] = {"SubScribe______"};//an array with 16 bytes to be written into one of the 64 card blocks is defined!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//byte blockcontent[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};//all zeros. This can be used to delete a block.
byte readbackblock[18];//This array is used for reading out a block. The MIFARE_Read method requires a buffer that is at least 18 bytes to hold the 16 bytes of a block.

void loop() {
  /*****************************************establishing contact with a tag/card**********************************************************************/
  // Look for new cards (in case you wonder what PICC means: proximity integrated circuit card)
  if ( ! mfrc522.PICC_IsNewCardPresent()) {//if PICC_IsNewCardPresent returns 1, a new card has been found and we continue
    return;//if it did not find a new card is returns a '0' and we return to the start of the loop
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {//if PICC_ReadCardSerial returns 1, the "uid" struct (see MFRC522.h lines 238-45)) contains the ID of the read card.
    return;//if it returns a '0' something went wrong and we return to the start of the loop
  }

  // Among other things, the PICC_ReadCardSerial() method reads the UID and the SAK (Select acknowledge) into the mfrc522.uid struct, which is also instantiated
  // during this process.
  // The UID is needed during the authentication process
  //The Uid struct:
  //typedef struct {
  //byte    size;     // Number of bytes in the UID. 4, 7 or 10.
  //byte    uidByte[10];            //the user ID in 10 bytes.
  //byte    sak;      // The SAK (Select acknowledge) byte returned from the PICC after successful selection.
  //} Uid;

  Serial.println("card selected");

  /*****************************************writing and reading a block on the card**********************************************************************/
  writeBlock(block, blockcontent);//the blockcontent array is written into the card block
  //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));

  //The 'PICC_DumpToSerial' method 'dumps' the entire MIFARE data block into the serial monitor. Very useful while programming a sketch with the RFID reader...
  //Notes:
  //(1) MIFARE cards conceal key A in all trailer blocks, and shows 0x00 instead of 0xFF. This is a secutiry feature. Key B appears to be public by default.
  //(2) The card needs to be on the reader for the entire duration of the dump. If it is removed prematurely, the dump interrupts and an error message will appear.
  //(3) The dump takes longer than the time alloted for interaction per pairing between reader and card, i.e. the readBlock function below will produce a timeout if
  //    the dump is used.

  //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));//uncomment this if you want to see the entire 1k memory with the block written into it.

  readBlock(block, readbackblock);//read the block back
  Serial.print("read block: ");
  for (int j = 0 ; j < 16 ; j++) {
    //print the block contents
    Serial.write (readbackblock[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
  }
  Serial.println("");
}

int writeBlock(int blockNumber, byte arrayAddress[]) {
  //this makes sure that we only write into data blocks. Every 4th block is a trailer block for the access/security info.
  int largestModulo4Number = blockNumber / 4 * 4;
  int trailerBlock = largestModulo4Number + 3; //determine trailer block for the sector
  if (blockNumber > 2 && (blockNumber + 1) % 4 == 0) {
    Serial.print(blockNumber);  //block number is a trailer block (modulo 4); quit and send error code 2
    Serial.println(" is a trailer block:");
    return 2;
  }
  Serial.print(blockNumber);
  Serial.println(" is a data block:");

  /*****************************************authentication of the desired block for access***********************************************************/
  byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
  //byte PCD_Authenticate(byte command, byte blockAddr, MIFARE_Key *key, Uid *uid);
  //this method is used to authenticate a certain block for writing or reading
  //command: See enumerations above -> PICC_CMD_MF_AUTH_KEY_A = 0x60 (=1100000),    // this command performs authentication with Key A
  //blockAddr is the number of the block from 0 to 15.
  //MIFARE_Key *key is a pointer to the MIFARE_Key struct defined above, this struct needs to be defined for each block. New cards have all A/B= FF FF FF FF FF FF
  //Uid *uid is a pointer to the UID struct that contains the user ID of the card.
  if (status != MFRC522::STATUS_OK) {
    Serial.print("PCD_Authenticate() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return 3;//return "3" as error message
  }
  //it appears the authentication needs to be made before every block read/write within a specific sector.
  //If a different sector is being authenticated access to the previous one is lost.

  /*****************************************writing the block***********************************************************/

  status = mfrc522.MIFARE_Write(blockNumber, arrayAddress, 16);//valueBlockA is the block number, MIFARE_Write(block number (0-15), byte array containing 16 values, number of bytes in block (=16))
  //status = mfrc522.MIFARE_Write(9, value1Block, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print("MIFARE_Write() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return 4;//return "4" as error message
  }
  Serial.println("block was written");
}

int readBlock(int blockNumber, byte arrayAddress[]) {
  int largestModulo4Number = blockNumber / 4 * 4;
  int trailerBlock = largestModulo4Number + 3; //determine trailer block for the sector

  /*****************************************authentication of the desired block for access***********************************************************/
  byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
  //byte PCD_Authenticate(byte command, byte blockAddr, MIFARE_Key *key, Uid *uid);
  //this method is used to authenticate a certain block for writing or reading
  //command: See enumerations above -> PICC_CMD_MF_AUTH_KEY_A = 0x60 (=1100000),
  // this command performs authentication with Key A
  //blockAddr is the number of the block from 0 to 15.
  //MIFARE_Key *key is a pointer to the MIFARE_Key struct defined above, this struct needs to be defined for each block. New cards have all A/B= FF FF FF FF FF FF
  //Uid *uid is a pointer to the UID struct that contains the user ID of the card.
  if (status != MFRC522::STATUS_OK) {
    Serial.print("PCD_Authenticate() failed (read): ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return 3;//return "3" as error message
  }
  //it appears the authentication needs to be made before every block read/write within a specific sector.
  //If a different sector is being authenticated access to the previous one is lost.

  /*****************************************reading a block***********************************************************/

  byte buffersize = 18;//we need to define a variable with the read    buffer size, since the MIFARE_Read method below needs a pointer to the variable that contains the size...
  status = mfrc522.MIFARE_Read(blockNumber, arrayAddress, &buffersize);//&buffersize is a pointer to the buffersize variable;     MIFARE_Read requires a pointer instead of just a number
  if (status != MFRC522::STATUS_OK) {
    Serial.print("MIFARE_read() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return 4;//return "4" as error message
  }
  Serial.println("block was read");
}

It would be easier to show you how if you included a link to the library you are using. And a snippet of the code you are trying to get working.

@MikaelPatel I have attached the code I'm trying to edit.

As I have already said in the question, I need the code to be writing and reading integers as block content or if there's a way to represent integers as a string and still be able to increment them

Let's say you have an array and an int.
unsigned char blockcontent[16];
int number = 15;

To save the int at position 0 of blockcontent, you do this:
memcpy(blockcontent, &number, sizeof(int));

If you want it at another position, do blockcontent+offset.
If you want to read the int from blockcontent, do the reverse:
memcpy(&number, blockcontent, sizeof(int));

That's all there is to it.

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


text:
Which Arduino is the most suitable for my project?
I've started to prototype something using an Arduino Mega and Yún Shield.
It's simple. It reads an ADC at 50Hz and sends data to a server through a socket. But because of that combination, I need to use Bridge to send data through the socket. It's very slow.
Should I change the Arduino Mega for a Leonardo or a Due to get better performance?
Here is my code, maybe I did something wrong.
Arduino code:
#include <Bridge.h>
#include <Process.h>
#include <Time.h>
#include <TimeLib.h>
#include <stdlib.h>

boolean interruptFlag = 0;
int HD = A0;
int HG = A1;
int CD = A2;
int CG = A3;
int ECG = A5;
String analogSignals = "";
static char outstr[15];
int count = 0;
float x = 0.0;

void setup() {
  // Bridge startup.
  Bridge.begin();
  // Initialize Bridge values.
  Bridge.put("data", "");
  noInterrupts(); // Stop interrupts.
  TCCR1A = 0; // Set entire TCCR1A register to 0.
  TCCR1B = 0; // Same for TCCR1B.
  TCNT1  = 0; // Initialize counter value to 0.
  // Set compare match register for 50Hz increments.
  OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)
  // Turn on CTC mode.
  TCCR1B |= (1 << WGM12);
  // Set CS12, CS11 and CS10 bits for 64 prescaler.
  TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
  // Enable timer compare interrupt.
  TIMSK1 |= (1 << OCIE1A);
  interrupts(); // Allow interrupts.
  // Launch Python script.
  /*Process p;
  p.begin("python");
  p.addParameter("/root/test/send.py");
  p.run();*/
}

ISR(TIMER1_COMPA_vect) {
  if (!interruptFlag) {
    interruptFlag = 1;
  }
}

void loop() {
  if (interruptFlag) {
    writeAnalogSignals();
    interruptFlag = 0;
  }
}

void writeAnalogSignals() {
  String HDReading = convertToVoltage(analogRead(HD));
  String HGReading = convertToVoltage(analogRead(HG));
  String CDReading = convertToVoltage(analogRead(CD));
  String CGReading = convertToVoltage(analogRead(CG));
  String ECGReading = convertToVoltage(analogRead(ECG));
  if (analogSignals.length() == 0) {
    analogSignals =  String(x, 2) + ";" + HDReading + ";" + HGReading + ";" + CDReading + ";" + CGReading + ";0.0;0.0;" + ECGReading;
  } else {
    analogSignals += "|" + String(x, 2) + ";" + HDReading + ";" + HGReading + ";" + CDReading + ";" + CGReading + ";0.0;0.0;" + ECGReading;
  }
  x += 0.02;
  count += 1;
  if (count >= 50) {
    Bridge.put("data", analogSignals);
    analogSignals = "";
    count = 0;
  }
}
// Convert the analog reading to voltage.
String convertToVoltage(int analogSignal) {
  dtostrf(analogSignal * (5.0 / 1023),8, 6, outstr);
  return outstr;
}

Python code:
import socket
import sys
import getopt
import time

def main(argv):
    try:
        sys.path.insert(0, '/usr/lib/python2.7/bridge/')
        from bridgeclient import BridgeClient as bridgeclient
        # Create a UDP socket.
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        server_address = ('192.168.1.100', 9050)
        bridge = bridgeclient()
        previous = ""

        # Send data
        while 1:
            data = bridge.get("data")
            if data != previous:
                sent = sock.sendto(data, server_address)
                previous = data
            time.sleep(0.5)

    finally:
        sock.close()

I'm not very much into Yùns, but I think that the problem is that time.sleep(0.5) that you put. Try lowering it to e.g. 0.01 to perform a check every 10 milliseconds... If this doesn't work, maybe the problem is the overhead added; to limit this store on the arduino or the Yùn some data (e.g. 50 acquisitions) and then send them all at once.

I've changed the time.sleep(0.01) and I stored 50 acquisitions, but It's slow to get 1 sec of datas.

You'll have to figure out where the bottleneck is. The Arduino sending the data, the yun receiving the data and/or transmitting the data over UDP.

What do you mean by "slow"? How much is "slow" for you? And is it just delayed or you are losing packets?

You shouldn't be sleeping in the python code, you should be doing a blocking wait (or select) on the data, since it is merely proxying readings timed at the source.  Also without sequence numbers in your UDP traffic you can't know if samples have been dropped or misordered.  Just swapping components in the existing software/communication architecture won't meaningfully help, as you are far below the capability of your current ones, but getting rid of the bridge would clean things up substantially - perhaps consider if an ESP8266's ADC input is suitable?

Hi @JonathanAnctil, could you please clarify your question. Are you asking if the other Arduinos are suitable or are you asking us to tell you why your coms are slow?

Hi @se_leinad, I'm asking if other Arduinos are more suitable for what I am trying to do. But I also put the code because I'm not an Arduino expert (I know the base) and maybe I did something wrong. One problem that I'm almost sure about using the Mega + Yùn Shield, is that I need to use the Bridge and that seems pretty slow.

@ChrisStratton yes I read about ESP8266 but my knowledge stops there.

Well, read more.  That, or figuring out how to use an ADC directly on a Linux wifi module is your best bet on getting rid of the bridge.  But you also need to fix the conceptual problems in your design - data sources time things, data conduits shouldn't have program delays as that will only make timing problems worse.

Both Mega 2560 and Due can handle 4 channels of 1,440 samples per second A-to-D and the least significant byte of the system time stamp sent as a continuous stream of vectors through the USB port to Linux.
In the lab I train at, we see almost no variance in time increment between samples or between receiver read operations, indicating that the bottleneck is our deliberate delays between samples.
The Due is running at full resolution too and communicates via the native port. The receiver process is running in normal user process priority, not boosted for real time.
We use C++ for both endpoints, the embedded Arduino code and the receiver, but the C++ on the Arduino side runs just as fast as the same loop in Arduino sketch language. Python low-level reads are generally able to handle this same level of throughput with ease too, so it is not likely that your hardware or speed goals that are the problem.
I can see a few design issues right away.

Don't use libraries for what one can do in just a few low level lines of code.
Don't place numbers in strings. Keep them as numbers.
Send the numbers as messages placed carefully into byte arrays using bitwise operations.
Don't convert raw samples to voltages on the Arduino. That can be done in the receiver or elsewhere on the Linux side.
Most importantly, find the various code examples that people posted on the Arduino blogs when testing USB baud rates (speed).

The lab engineers started with that speed testing code, replicated the throughput published with it, and then added A-to-D conversion and other features one step at a time.
It is recommended that you place the code under version control and then, with each change, test the speed again. That way you'll notice any bottleneck you introduce immediately and can see the exact changes that must have caused it.

The Bridge running in Python in Linux is the biggest problem. Open a terminal (for example with putty) and run top to see the CPU usage. Try to keep it under 50%.
A few parameters at 5 times per second with Bridge.put() is possible, but I don't recommend it, because of the CPU load in Linux. The 50Hz is way too much. Beside that you have also a Python script to send them to a server.
There is about 30 MB of fast RAM storage in /tmp and more storage if you add an SD memory card. You could do a test to write the data to a file, and upload the file every few seconds.
If you really need 50Hz, then I suggest to try the Raspberry Pi (or the ESP8266, as mentioned).
The dtostrf() function does not return a String, but a buffer. You could easily get rid of the Strings, to have more time in the Arduino. A good use ofmillis() is just as accurate as a timer. I think you can do the same without the hardware timer and without the interrupt.
ADDED: Chris Stratton pointed out that the Bridge is not the problem, so I did a small test.
Using 4 values with short names (like: "temp"). Writing them with Bridge.put() every second, and reading them in a webpage via zepto.min.js every second is a CPU load of 6% for python -u bridge.py.
Writing them 50 times per second and reading 1 time per second is a CPU load of 25% for the bridge.
Writing them 50 times per second and reading them 50 times per second does not change a lot, it adds extra load for uhttpd, resulting in a total of about 60 to 70%. That is still okay to run commands from a terminal.
This 'clean' test is different from my previous tests. It is therefore indeed possible to send data through the Bridge at 50 times per second. Sorry for my wrong answer.

The original suggestions here are highly mistaken and would be best ignored - following would just trade the problems of one set of fundamental misunderstandings for those of another, equally mistaken set.

You are right. However, code can be improved. It can be very informative to make changes to the code and see the result for the cpu load. The 50Hz is too much for an Arduino Yún Bridge anyway.

This is where you are fundamentally wrong - the issue is not CPU load at all, and 50 Hz is not too much if done right.  The issue is with the implementation not taking the bridge into account.  Getting rid of the bridge would make things simpler, but it can be done through the bridge by someone who understands communication between systems.  What your proposal does is trade the asker's mistakes for your own, different set of mistakes, which put them no closer to a solution.

Thank you for correcting me. I learned something and I have added it to my answer after "ADDED".
I hope you still agree with the 30Mbyte ram in /tmp and the unnecessary use of the timer, interrrupt and String object.

Hi @Jot, could you provide me the code you did to test it? What did you do different from my implementation?

Should I change the Arduino Mega for a Leonardo or a Due to get better performance?

You didn't quite say what kind of performance gains you had in mind. Looking at your code, it doesn't have any particular needs to justify a fancier Arduino.
With that said, I wanted to highlight one particular aspect of ATmega32u / Leonardo that in my view made it a particularly interesting chip for mixed signal application: its ADC unit features a PGA (1x, 10x, 200x) in differential mode with bipolar readings.
it can be quite handy for some applications.

@JonathanAnctil, @ChrisStratton, I have done some more tests, and the Bridge.put takes an average of 7 milliseconds in the sketch. For 5 values at a rate of 50Hz, that alone takes 1.7 seconds. The Bridge can not keep up with that rate, but the overall cpu load in linux is still under 50%. Therefor the cpu load does not indicate if everything is running okay.
Because I was looking at the cpu load, I took the wrong assumption that it was possible. These tests confirm my previous experiences that the Bridge is too slow.
I have installed extra packages in linux, but I think they will not influence the slow Bridge.put.
With more tests with Bridge.put I learned that Bridge.put takes 4ms, plus 0.3ms per character for the key name and the value text, plus the delay caused by things running at the other side of the Bridge in linux.
The value must be a zero terminated string, it is not possible to send binary data. Suppose turning it into readable hex values, then 20 bytes are needed for the value.
With the key name as a single character, and a value of 20 bytes, it takes 10 ms. However, then the values have to be retrieved (and converted) at the other side of the Bridge. I assume that Python will also slow down the Bridge.put, just like Javascript does.
This is my test sketch.
// Showing the webpage on the other side of the Bridge with zepto.min.js
// and 50 updates per seconds slows down the sketch, because the Bridge.put
// in the sketch will take a lot more time.
// A Bridge.put takes about 7 to 260 ms when the webpage is in a browser
// with 50Hz updates.
// A Bridge.put takes about 7 ms when the webpage is not shown in a browser.
// A itoa takes about 13 us.
//
// When showing the webpage with 50Hz updates:
//     Only the counter : 43 seconds for 1000 counts = 23 Hz
//     With 6 analog inputs and the free ram : 342 seconds for 1000 counts = 3 Hz
// When showing the webpage with once per 5 seconds updates:
//     Only the counter : 20 seconds for 974 counts = 49 Hz
//     With 6 analog inputs and the free ram : 50 seconds for 985 counts = 20 Hz

#include <Bridge.h>

Process yunProcess;

unsigned long previousMillis;

#define NUM_PINS 6
const int pins[NUM_PINS] = { A0, A1, A2, A3, A4, A5, };
const char * names[NUM_PINS] = { "A0", "A1", "A2", "A3", "A4", "A5" };

void setup()
{
//  SerialUSB.begin(115200);
//  while(!SerialUSB);
//  SerialUSB.println("Started");
  Bridge.begin();
//  SerialUSB.println("Bridge is running");
}

void loop()
{
  unsigned long currentMillis = millis();

  // A software timer of 50Hz.
  if(currentMillis - previousMillis >= 20UL)
  {
    previousMillis = currentMillis;

    // The fastest way to turn an integer into text is with itoa.
    // The function itoa takes about 13us.
    // A buffer is used for itoa.
    char buffer[20];

    for(int i=0; i<NUM_PINS; i++)
    {
      int adc = analogRead(pins[i]);
      itoa(adc, buffer, 10);
      Bridge.put(names[i], buffer);
    }

    int freeram = freeRam();
    itoa(freeram, buffer, 10);
    Bridge.put("freeRam", buffer);

    // a counter.
    static int count;
    count++;
    itoa(count, buffer, 10);
//    unsigned long t1 = micros();
    Bridge.put("counter", buffer);
//    unsigned long t2 = micros();
//    SerialUSB.println(t2 - t1);

//    SerialUSB.println(count);
  }
}

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

And my test webpage is:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Test</title>

Show JSON data

Analog Input A0 = ---

Analog Input A1 = ---

Analog Input A2 = ---

Analog Input A3 = ---

Analog Input A4 = ---

Analog Input A5 = ---

freeRam = ---

counter = ---

Great demonstration, thanks a lot. This confirm a lot what I saw about the Bridge!


text:
Location of examples folder in Ubuntu
I'm trying to add some additional example files to the Arduino IDE in Ubuntu 14.04. However, I can't for the life of me find where the examples are stored in my system. I checked the Arduino website, but can't find any information there. Does anyone know where I need to put my additional files?

Usually there is no good reason to know where the folder is. The examples are available in Arduino IDE in Files->Examples menu and it doesn't make much sense to add more sketches to built-in examples in local installation.

After some more searching I found it in /usr/share/arduino/examples.

I found mine in Linux Mint 17.3 under opt/arduino/examples

In Ubuntu I found arduino library on
/home/MYUSERNAME/snap/arduino
where MYUSERNAME is user name

don't install Arduino IDE with snap. it installs some old version


text:
error: expected unqualified-id before 'if' if (send) { but all semicolons are available
I am getting a compilation error: expected unqualified-id before 'if' .  Btu I have check all the semicolons . Please help finding my error.
The rest of the message error reads
C:\Users\jecalderon\Documents\Arduino\Codigo_AS7262_Investigacion_V2\Codigo_AS7262_Investigacion_V2.ino:35:1: error: expected unqualified-id before 'if'
 if (currentMillis - previousMillis >= interval) {
 ^~
C:........\Codigo_AS7262_Investigacion_V2.ino:40:1: error: expected unqualified-id before 'if'
 if (send) {
 ^~

exit status 1

Compilation error: expected unqualified-id before 'if'

#include <Wire.h>
#include "Adafruit_AS726x.h"
//create the object
Adafruit_AS726x ams;
//buffer para leer valores en bruto
uint16_t sensorValues[AS726x_NUM_CHANNELS];
//buffer para  guardar los valores calibrados( no esta siendo utilizado en este codigo)
//float calibratedValues[AS726x_NUM_CHANNELS];
unsigned long previousMillis = 0;
const long interval = 250;
bool send = false;
void setup() {
  Serial.begin(115200);
  while (!Serial) {
    // inicializa el pin digital LED_BUILTIN como un output.
    pinMode(LED_BUILTIN, OUTPUT);

    //inicia y permite la comunicacion con el sensor
    if (!ams.begin()) {
      Serial.println("could not connect to sensor! Please check your wiring.");

    }
  }
}
void loop() {
  //lee la temperatura del sensor
  //uint8_t temp = ams.readTemperature();
  //ams.drvOn(); // descomentar esto si quieres usar el led del sensor para hacer medidas
  ams.startMeasurement();  //begin a measurement
  //permite que el sensor lea la data cuando este disponible
  unsigned long currentMillis = millis();
};
//ams.drvOff(); //descomentar esto si quieres usar el led del sensor para hacer medidas
if (currentMillis - previousMillis >= interval) {
  previousMillis = currentMillis;
  send = true;
}

if (send) {
  //lee los valores!
  ams.readRawValues(sensorValues);
  //ams.readCalibratedValues(calibratedValues);

  //Serial.print("{");
  //Serial.print("Temp: ");
  //Serial.print(temp);
  //Serial.print(",");
  //Serial.print(" Violet: ");
  Serial.print(sensorValues[AS726x_VIOLET]);
  Serial.print(",");
  //Serial.print(" Blue: ");
  Serial.print(sensorValues[AS726x_BLUE]);
  Serial.print(",");
  //Serial.print(" Green: ");
  Serial.print(sensorValues[AS726x_GREEN]);
  Serial.print(",");
  //Serial.print(" Yellow: ");
  Serial.print(sensorValues[AS726x_YELLOW]);
  Serial.print(",");
  //Serial.print(" Orange: ");
  Serial.print(sensorValues[AS726x_ORANGE]);
  Serial.print(",");
  //Serial.print(" Red: ");
  Serial.print(sensorValues[AS726x_RED]);
  //Serial.print("}");

  Serial.println();

  send = false;
}

If your original issue is solved, please mark the answer. Do not change this question into something else, instead post a new question. You can link back to this question to provide some background. However, each question shall be self-contained.

Thank you or breaking my troubleshooting process. Publishing Updates have always been very effective to reach solutions to very difficult subjects.  I suggest you not to edit or remove any edit that specifically calls to be an UPDATE.  Now, I had to issue credit to an answer that although close to  a solution, had not  accomplished to  satisfy the objective.  This is bad enough added to the fact that you had down voted my original post that where active   receiving  feedbacks from community contributions.

Disclaimer: I did not vote down or edited your question. However, I feel with the one who did. -- You might want to take the [tour] (again) and read some of the [help] pages. This site is not a forum, and it might not support your process of troubleshooting. This is a Q&A site, with specific questions and answers, if there are some. If your issue is not solved, do not mark an answer and clarify why it does not answer the specific issue. But if your process leads to another issue, please post that in a new question. Otherwise you render all work done to the former useless.

Your update is not lost. You can see it if you follow the "edited" link. You can use that to post a new question. Please learn about this site before blaming.

I consider to watch closely people down voting on threads but offering no significant contribution to the post.  I have been around for 10 years and find this down voting activity motivated for the wrong reasons. I pointing  to the number of negative credits when compared to positive votes.  Hope my feedback is taken  well by the moderators and administrators.

The reasoning on closures and down-votes are already well formulated. If a question is closed, there is a lot of help in the frame above the question. The "down" button has a helpful popup. What should someone voting to close or down contribute more? The questioner is supposed to follow the rules, and many voters I see additionally leave a comment telling why. Please don't be paranoid, you are not stalked. If you have just above 100 reputation points after 10 years, it's not the fault of others.

Check your braces.  Use Control-T to autoformat your code and the error will become apparent.
This is your entire loop function.  Everything after this is is outside of the function.
void loop() {
  //lee la temperatura del sensor
  //uint8_t temp = ams.readTemperature();
  //ams.drvOn(); // descomentar esto si quieres usar el led del sensor para hacer medidas
  ams.startMeasurement();  //begin a measurement
  //permite que el sensor lea la data cuando este disponible
  unsigned long currentMillis = millis();
};

Thankyou for the contribution.

Did it solve your problem?


text:
I am using Arduino stepper motor and pir sensor
my project about automated system I am using stepper motor to open and close the gate but my point is I want my code be like when the gate opened it stays 5 seconds then check the sensor if there is a motion the gate should not close and stay open when there is no motion the gate should close and if the gate is closing and there is a motion , motion should interrupt closing the gate and reopening the gate I am using Arduino uno
the code is :

#include <RH_ASK.h>//include radioHead ASK library
#include <SPI.h> // include dependant SPI libray
#include <Stepper.h> // Include the Arduino Stepper.h library:
// Define number of steps per rotation:

RH_ASK rf_driver; // create ASK object
int ledon = 13;
int ledoff = 5;
int sensor = 3;

const int stepsPerRevolution = 2048;// Define number of steps per rotation:

// Wiring:
// Pin 8 to IN1 on the ULN2003 driver
// Pin 9 to IN2 on the ULN2003 driver
// Pin 10 to IN3 on the ULN2003 driver
// Pin 11 to IN4 on the ULN2003 driver
// Create stepper object called 'myStepper', note the pin order:
Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

void setup() {

  rf_driver.init(); //initialize ASK object

  // Begin Serial communication at a baud rate of 9600:
  Serial.begin(9600);

  // Set the speed to 5 rpm:
  myStepper.setSpeed(5);
  pinMode(ledon, OUTPUT);
  pinMode(ledoff, OUTPUT);

}

void loop() {

  //set buffer to size of expected message
  //uint8_t buf[8];
  // uint8_t buflen =sizeof(buf);

  //check if recevied packet is correct size
  //  if (rf_driver.recv(buf,&buflen))
  //{
  // int i;
  // message received with valid checksum
  // Serial.print("id: ");
  // Serial.println((char*)buf);
  // String userid =(char*)buf;
  // Serial.println(userid);

  // }

  //delay(5000);

  // uint8_t buf2[8];
  // uint8_t buflen2 = sizeof(buf2);

  // if (rf_driver.recv(buf,&buflen))

  // {

  //  int i;
  // message received with valid checksum
  // Serial.print("password: ");
  // Serial.println((char*)buf);
  // String password = (char*)buf;
  //  Serial.println(password);

  // }
  // delay(5000);

  String pass = "1234";
  String id = "A00036757";

  if (pass == "1234" ) {
    Serial.print("car exists");
    digitalWrite(ledon, HIGH);
    delay(300);
    myStepper.step(stepsPerRevolution / 3); //clockwise -OPEN GATE
    delay(10000);

    //if(digitalRead(sensor) == HIGH){
    delay(500);
  }

  if (digitalRead(sensor) == LOW) {

    digitalWrite(ledon, LOW);
    delay(300);

    digitalWrite(ledoff, HIGH);
    delay(300);
    myStepper.step(-stepsPerRevolution / 3); // CLOSE AFTER 5s COUNTERCLOCKWISE -  close gate
    digitalWrite(ledoff, LOW);
  }
  else {
    Serial.print("NO CAR");
  }

And what is your question?

Motion sensor's operation depends on the sensor's setting. See motion sensor setting. Please post your sensor's setting


text:
Run function when triggered
I'm trying to create a motion/fall sensing device. I have a sensor that continuously checks if motion and fall is detected in void loop(). If both motion and fall are detected, then I'd like to send an image to my computer. My image capture function is camCapture(). The problem is that once the motion and fall detected, it continuously calls camCapture() and repeatedly sends images to the computer given that camCapture() is called in void loop(). I'd like to only send a single image when it is triggered, and a single image every time it is triggered thereafter.
For example, if the motion and fall is triggered, then send an image once. If it detects motion and fall again after it has already gone back to LOW, then send an image again once.
I can't use setup() since I can only run a function once, and it defeats the purpose of what I'm trying to do. My void loop() code is below.
void loop()
{
  // Read data from accelerometer
  mma.read();
  sensors_event_t event;
  mma.getEvent(&event);

  // Store magnitude of all axis
  magnitude = calculateMagnitude(event.acceleration.x, event.acceleration.y, event.acceleration.z);

  // Motion is detected! 20 seconds will be given to detect a fall from the accelerometer
  if(digitalRead(pirSensor) == HIGH)
  {
    num_timeAtPIR = millis(); // Time that PIR sensor was activated with respect to the system time
    bool_waitForAccel = 1; // Set flag to true to wait for accelerometer
    Serial.println("Motion detected!");
    digitalWrite(buzzer, LOW);
    //delay(1000);

  }
  else if(magnitude > sensitivity)
  {
    num_timeAtAccel = millis();
    Serial.println("Fall detected!");
    Serial.print("Magnitude is: ");
    Serial.println(magnitude);
    bool_waitForPIR = 1; // Waiting for PIR
    Serial.println();

    digitalWrite(buzzer, HIGH);
    delay(4000);

  }
  else // No motion is detected
  {
    Serial.println("No motion detected! :(");
    bool_waitForPIR = 0;
    bool_waitForAccel = 0;
    Firebase.setInt(firebaseData, pirPath, 0);
    Firebase.setInt(firebaseData, accelPath, 0);
    digitalWrite(buzzer, LOW);
  }

  // Motion then Fall are detected. Alarm is activated and picture is captured and save onto server.
  if(bool_waitForAccel == 1 && (magnitude > sensitivity))
  {

    Serial.println("Motion and Fall detected!");
    Serial.print("Magnitude is: ");
    Serial.println(magnitude);
    bool_waitForAccel = 0; // No longer waiting for accelerometer
    Serial.println();

    digitalWrite(buzzer, HIGH);
    delay(4000);

    camCapture(); // Take picture!

  }

  // Fall then motion are detected. Alarm is activated and picture/video is captured to save onto website.
  else if(bool_waitForPIR == 1 && (magnitude > sensitivity))
  {
    Serial.println("Fall detected");
    Serial.print("Magnitude is: ");
    Serial.println(magnitude);
    Serial.println();

    bool_waitForPIR = 0; // No longer waiting for PIR

    digitalWrite(buzzer, HIGH);

    delay(4000);

    camCapture(); // Take picture!

  }

  // 20 second timer to check if a Fall is detected after Motion is detected.
  if(millis() > (num_timeAtPIR + period))
  {
    bool_waitForAccel = 0; // Set flag to false
  }
  else if(millis() > (num_timeAtAccel + period)) // 20 second timer to check if Motion is detected after a fall is detected
  {
    bool_waitForPIR = 0;
  }

}

UPDATE 1: Posting the rest of the code.
// Program header files
#include <Wire.h>
#include <WiFi.h>
#include <WebServer.h>
#include <ArduCAM.h>
#include <SPI.h>
#include "FS.h"
#include "FirebaseESP32.h"
#include "memorysaver.h"
#include <Adafruit_MMA8451.h>
#include <Adafruit_Sensor.h>

//Time and Date NTP Server Header
#include <NTPClient.h>
#include <WiFiUdp.h>

//Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

//Variables to save date and time
String formattedDate = "";
String dayStamp = "";
String timeStamp = "";

String logPath = "/Log";
String tempPath = "/Log/Temperature";
String pirPath = "/Log/PIR_Sensor";
String accelPath = "/Log/Accelerometer";
String pirDatePath = "/Log/pir_Date";
String pirTimePath = "/Log/pir_Time";
String accelDatePath = "/Log/accel_Date";
String accelTimePath = "/Log/accel_Time";

// Database/Wi-Fi configuration
#define FIREBASE_HOST "host"
#define FIREBASE_AUTH "auth"
#define AP_SSID "apssid"
#define AP_PASSWORD "password"

#define WIFI_SSID "ssid"
#define WIFI_PASSWORD "passsword"

// Variables to keep track of previous and current time to create a delay
unsigned long currentTime = 0;
unsigned long prevTime = 0;

unsigned long bool_waitForAccel = 0; // Used to flag the accelerometer
unsigned long bool_waitForPIR = 0; // Used to flag the PIR
unsigned long num_timeAtPIR = 0; // Used to keep track of the time the PIR sensor detected motion
unsigned long num_timeAtAccel = 0; // Used to keep track of the time the accelerometer detected a fall
unsigned long period = 20000; // Amount of time given to check after motion is detected

int statusLED = 26; // Choose the pin for status LED
int buzzer = 12; // Choose the pin for Piezzo Buzzer. Connected from MOSFET gate.
int tempSensor = 2; // Choose pin for Temperature Sensor
int pirSensor = 27; // Choose pin for controller PIR Sensor

int PIR_Power = 25; // Controls Power gate for PIR Sensor
int ArduCAM_Power = 32; // Controls Power gate for ArduCAM

const int CS = 5; // GPIO5 as Slave Select for ArduCAM

int wifiType = 0; // 0: Station    1: AP (Access Point)

// Set up requests to send captured image to external server
bool onlineMode = true;
String start_request = "";
String boundary = "_cam_";
String end_request = "\n--" + boundary + "--\n";

// Set buffer size for camera data
static const size_t bufferSize = 2048;
static uint8_t buffer[bufferSize] = {0xFF};
byte buf[256];
static int iPic = 0;
static int kPic = 0;
uint8_t temp = 0, temp_last = 0;
uint32_t len = 0;
bool is_header = false;

// Threshhold for declaring a fall on the accelerometer
float sensitivity = 11.0;

float magnitude = 0.0; // Stores the calculated magnitude

// Accelerometer, Semaphore, and Firebase instances
Adafruit_MMA8451 mma = Adafruit_MMA8451();
FirebaseData firebaseData;

#if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
ArduCAM myCAM(OV2640, CS);
#endif

WiFiClient client;

void start_capture()
{
  myCAM.clear_fifo_flag();
  myCAM.start_capture();
}

void camCapture()
{
  digitalWrite(ArduCAM_Power, HIGH);

  // Flush the FIFO
  myCAM.flush_fifo();
  // Clear capture done flag
  myCAM.clear_fifo_flag();
  // Start capture
  myCAM.start_capture();

  Serial.println("Start capture!");
  while(!myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK));

  len = myCAM.read_fifo_length();
  Serial.print("The FIFO length is: ");
  Serial.println(len);

  if(len >= MAX_FIFO_SIZE) // 8M
  {
    Serial.println("Over size!");
  }
  if(len == 0) // 0KB
  {
    Serial.println("Size is 0KB");
    return;
  }

  long full_length;
  if(client.connect("xx.xx.xx.xx", 80) || onlineMode)
  {
    if(onlineMode)
    {
      while(client.available())
      {
        String line = client.readStringUntil('\r');
      }
    }

  start_request = start_request +
  "\n--" + boundary + "\n" +
  "Content-Disposition: form-data; name=\"data\"; filename=\"CAM.jpg\"\n" +
  "Content-Transfer-Encoding: binary\n\n";

  full_length = start_request.length() + len + end_request.length();
  client.println("POST /uploads.php HTTP/1.1");
  client.println("Host: xx.xx.xx.x");
  client.println("Content-Type: multipart/form-data; boundary =" + boundary);
  client.print("Content-Length: "); client.println(full_length);
  client.println();
  client.print(start_request);

  iPic = 0;

  static uint8_t buffer[bufferSize] = {0xFF};

  while (len--)
  {
    temp_last = temp;
    temp =  SPI.transfer(0x00);
    //Read JPEG data from FIFO
    if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
    {
      buf[iPic++] = temp;  //save the last  0XD9
      //Write the remain bytes in the buffer
      myCAM.CS_HIGH();
      client.write(buf, iPic);
      //Close the file
      //file.close();
      Serial.println(F("Image save OK."));
      is_header = false;
      iPic = 0;
    }
    if (is_header == true)
    {
      //Write image data to buffer if not full
      if (iPic < 256)
        buf[iPic++] = temp;
      else
      {
        //Write 256 bytes image data to file
        myCAM.CS_HIGH();
        client.write(buf, 256);
        iPic = 0;
        buf[iPic++] = temp;
        myCAM.CS_LOW();
        myCAM.set_fifo_burst();
      }
    }
    else if ((temp == 0xD8) & (temp_last == 0xFF))
    {
      is_header = true;
      buf[iPic++] = temp_last;
      buf[iPic++] = temp;
    }
  }

  // End the POST request to the server
  client.println(end_request);

  myCAM.CS_HIGH();

  // Stop the client
  client.stop();
  digitalWrite(ArduCAM_Power, LOW);
  }
  else // No connection to the server.
  {
    Serial.println("Could not connect to external server!");
    Serial.println("Please check the IP address or Port");
    return;
  }
}

// Calculate the magnitude with the x, y, and z axis of the accelerometer.
// Gives an overall value that is better than just using the z-axis
float calculateMagnitude(float x, float y, float z)
{
  float magnitude = sqrt(sq(x) + sq(y) + sq(z));

  return magnitude;
}

void setup()
{
  Wire.begin();
  Serial.begin(115200);
  SPI.begin();
  SPI.setFrequency(4000000);

  pinMode(CS, OUTPUT);
  pinMode(PIR_Power, OUTPUT); // Set mosfet gate to output for PIR Sensor
  pinMode(ArduCAM_Power, OUTPUT); // Set mosfet gate to output for ArduCAM

  pinMode(statusLED, OUTPUT);      // Declare LED as output
  pinMode(buzzer, OUTPUT);         // Declare Piezo Buzzer as output
  pinMode(pirSensor, INPUT);        // Declare PIR Sensor as input

  Serial.println();

  // Check if accelerometer is properly connected/found
  if(!mma.begin())
  {
    Serial.println("Couldn't start MMA8451 Accelerometer.");
    Serial.println("Check your connections.");
    while(1);
  }
  Serial.println("MMA8451 Accelerometer found!");

  // Set the g-range for the accelerometer. Can be adjusted to 2g, 4g, or 8g.
  mma.setRange(MMA8451_RANGE_2_G);

  // Check if camera is found
  digitalWrite(ArduCAM_Power, HIGH);
  uint8_t vid, pid;
  uint8_t temp;
  while(1)
  {
    //Check if the ArduCAM SPI bus is OK
    myCAM.write_reg(ARDUCHIP_TEST1, 0x55);
    temp = myCAM.read_reg(ARDUCHIP_TEST1);
    if (temp != 0x55) {
      Serial.println(F("SPI interface Error!"));
      delay(2);
      continue;
    }
    else
      break;
  }

  #if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
  //Check if the camera module type is OV2640
  myCAM.wrSensorReg8_8(0xff, 0x01);
  myCAM.rdSensorReg8_8(OV2640_CHIPID_HIGH, &vid);
  myCAM.rdSensorReg8_8(OV2640_CHIPID_LOW, &pid);
  if ((vid != 0x26 ) && (( pid != 0x41 ) || ( pid != 0x42 )))
    Serial.println(F("Can't find OV2640 module!"));
  else
    Serial.println(F("OV2640 detected."));
  #endif

  //Change to JPEG capture mode and initialize the OV2640 module
  myCAM.set_format(JPEG);
  myCAM.InitCAM();

  myCAM.OV2640_set_JPEG_size(OV2640_640x480);
  myCAM.clear_fifo_flag();
  // Turn off Camera
  digitalWrite(ArduCAM_Power, LOW);

  // Connect to WiFi
  if (wifiType == 0)
  {
    if(!strcmp(WIFI_SSID,"SSID"))
    {
      Serial.println(F("Please set your SSID"));
      while(1);
    }
    if(!strcmp(WIFI_PASSWORD,"PASSWORD"))
    {
      Serial.println(F("Please set your PASSWORD"));
      while(1);
    }
    // Connect to WiFi network
    Serial.println();
    Serial.print(F("Connecting to: "));
    Serial.println(WIFI_SSID);

    WiFi.mode(WIFI_STA);

    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

    while (WiFi.status() != WL_CONNECTED)
    {
      delay(500);
      Serial.print(F("."));
    }

    Serial.println();
    Serial.println(F("WiFi connected"));
    Serial.println();
    Serial.println(WiFi.localIP());
  }
  else if (wifiType == 1)
  {
    Serial.println();
    Serial.println();
    Serial.print(F("Shared AP: "));
    Serial.println(AP_SSID);
    Serial.print(F("The password is: "));
    Serial.println(AP_PASSWORD);

    WiFi.mode(WIFI_AP);

    WiFi.softAP(AP_SSID, AP_PASSWORD);

    Serial.println();
    Serial.print("AP IP Address is: ");
    Serial.println(WiFi.softAPIP());
  }

  // Initialize a NTPClient to get time
  timeClient.begin();
  timeClient.setTimeOffset(-14400);

  //If Firebase is connected, turn on the LED
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);
  digitalWrite(statusLED,HIGH);

  Serial.println("------------------------------------");
  Serial.println("Path exist test...");
  if (Firebase.pathExist(firebaseData, logPath))
  {
    Serial.println("Path " + logPath + " exists");
  }
  else
  {
    Serial.println("Path " + logPath + " does not exist");
    Serial.println("Adding all necessary paths to /Log");
    Serial.println("Will have to reinitialize later once everything is set up.");

     // Initialize All  variables to 0;
    Firebase.setFloat(firebaseData, tempPath, 0.0);
    Firebase.setInt(firebaseData, pirPath, 0);
    Firebase.setInt(firebaseData, accelPath, 0);
    //Firebase.setString(firebaseData, pirDatePath, ???);
    //Firebase.setString(firebaseData, pirTimePath, ???);
    //Firebase.setString(firebaseData, accelDatePath, ???);
    //Firebase.setString(firebaseData, accelTimePath, ???);

  }
  Serial.println("------------------------------------");
  Serial.println();

  digitalWrite(PIR_Power, HIGH);

  digitalWrite(pirSensor, LOW);
  digitalWrite(statusLED, LOW);

  Serial.println("Sensors booting up...");
  delay(10000); // Let sensors boot up, 10s
  Serial.println("Sensors ready!");
}

Thank you for the really well done formatting. So many people post questions with totally crap formatting that make the question very difficult to read and understand.

@JohnRomkey Haha! Thanks, I gotta make everyone’s life a little easier somehow.

You need to add a state variable to your loop() function.
At the start of loop() add a variable declaration like:
void loop()
{
  static bool capture_sent = false;

Then change your line
  if(bool_waitForAccel == 1 && (magnitude > sensitivity))
  {

to
  if(!capture_sent && bool_waitForAccel == 1 && (magnitude > sensitivity))
  {
    capture_sent = true;

or, if you want to perform some of the logic in that stanza and just not call camCapture() then leave the if line alone and make the call to camCapture() conditional upon !capture_sent.
Then in any place in your code where you see the condition which tells you you'd want to call camCapture() again when triggered, reset capture_sent to `false. I'm leaving it up to you to decide where that goes because you understand what conditions determine that.

Awesome! Thanks for the reply! I’ll implement those changes in the morning and let you know how it goes.


text:
Using Arduino Mega with multiple HC05 Modules as masters, communicating to multiple HC05 Modules as slaves, each connected to separate Arduino
So I have not actually experimented with the HC05 Bluetooth Module yet, but I have read up about it and watched some videos. From what I understand, you cannot use one module (master) to communicate with more than one other module (slaves), or at least its pretty difficult. But, you can use a module hooked up to an arduino to communicate to to another module hooked up to another arduino (I believe pretty simply).
However, I thought it might be possible to use an Arduino Mega (because it has multiple TX/RX pins) with 3 HC05 Bluetooth modules, to each communicate to 3 separate HC05s which would each be hooked up to an arduino nano. I know this might have to do something with running multiple Software Serials (I have no idea what that is to be honest)?
The project involves using the master arduino to "listen" for a button pressed on the slave arduino (across the room without connecting wires), then listening for another button press from one of the other slaves in some sort of sequence and within a certain time frame.
Does anyone have any idea about how this might be done, even if it doesn't use the HC05 Bluetooth Module?
Thanks!

Yes, this is possible. According to arduino.cc, the Arduino Mega has 4 hardware serial ports, so you can connect 3 HC-05 modules and still have 1 serial interface left. The Mega is a good choice, when you need this many serial interfaces, so at this point you don't even need SoftwareSerial. You will have to configure the HC-05 modules correctly from the master and command them to connect to the correct slave modules.
About SoftwareSerial: The serial interfaces mentioned above are "hardware" interfaces, meaning, that the itself microcontroller contains hardware, that does the main part of the receiving/transmitting by itself, without any need for code. The Serial library then only adds a bigger buffer for the data, wrapper functions to write to it and reacts to the interrupts, that come from the hardware interface. But since most microcontrollers only have a very limited number of hardware serial interfaces (often only 1 or even none), the SoftwareSerial library comes in handy. It emulates the UART protocol (which is a more professional term for the Serial interface from the Arduino world) with software (and some help from interrupts). This means, that you can use it with any pair of pins and you can even define multiple interfaces with it. But it also has drawbacks. For example: Only 1 SoftwareSerial interface can listen at once, you cannot use high baudrates, it uses interrupts, that you might need for an application.

That said, I don't think, that Bluetooth is the best way to go, if you only want to test a small number of buttons per slave. It is simply too much hassle to configure the modules and establish the connections correctly. Instead you can use 433MHz radio modules. They don't involve such a complex protocol like Bluetooth does, so it's a very simple solution. In the simplest case, you only need transmitters for the slaves and a receiver for the master. Every slave can send a short identifier, if the button was pressed. The master can then receive this data. Of course, if more than one slave sends simultaneously, the data will be garbage. But as long, as this is not a problem, you can keep it that simple.
There are many tutorials on the web, that explain how to use these modules. You can even find libraries, that are ready to use.

Great answer! This is great because I originally tried tackling this project using the nRF24L01 module but it was by no means easy to jump into as an arduino beginner. I did a quick Google search and found this article about 433MHz modules: https://dronebotworkshop.com/433mhz-rf-modules-arduino/ I think this might be a lot better for my application!


text:
Trying to use an Arduino Uno together with an ISM330DLC communicating through SPI
I am trying to get a MEMS-module (ISM330DLC) to work together with an Arduino Uno but I can't get it to work. I am using the ism330dlc drivers.
ISM330dlc Drivers: https://github.com/STMicroelectronics/STMems_Standard_C_drivers/tree/master/ism330dlc_STdC
ISM330dlc Datasheet: http://www.farnell.com/datasheets/2339632.pdf
ISM330dlc Application Notes: https://www.st.com/content/ccc/resource/technical/document/application_note/group0/68/eb/a3/cd/2c/78/45/41/DM00468454/files/DM00468454.pdf/jcr:content/translations/en.DM00468454.pdf
I have switched out the voltage regulator to a 3.3V on the Arduino following this guide: https://learn.adafruit.com/arduino-tips-tricks-and-techniques/3-3v-conversion
I am using the STEVAL-MKI182V2 board for easier wiring.
This is the current wiring:
Arduino Pin<------------->STEVAL Pin
Pin 10 (SS)<------------->CS
Pin 11 (MOSI)<------------->SDA
Pin 12 (MISO)<------------->SDO
Pin 13 (SCK)<------------->SCL
SDx is connected to ground, SCx is connected to VddIO. The board is also connected to ground on the Arduino as well as Vin 3.3V.
Here is the code:
/* SPI Pin config (There are other pins dedicated to SPI I think) */
#define SSpin 10
#define MOSIpin 11
#define MISOpin 12
#define SCKpin 13

/* Variables used to store data */
static axis3bit16_t data_raw_acceleration;
static axis3bit16_t data_raw_angular_rate;
static float acceleration_mg[3];
static float angular_rate_mdps[3];

static int32_t platform_write(void *handle, uint8_t Reg, uint8_t *Bufp, uint16_t len) {
  SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE3));
  digitalWrite(SSpin, LOW);
  SPI.transfer(Reg);
  SPI.transfer(Bufp);
  digitalWrite(SSpin, HIGH);
  SPI.endTransaction();
  return 0;
}
static int32_t platform_read(void *handle, uint8_t Reg, uint8_t     *Bufp, uint16_t len) {
  Reg |= 0x80; //Set bit 0 (MSB) in order to read
  SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE3));
  digitalWrite(SSpin, LOW);
  SPI.transfer(Reg);
  *Bufp = SPI.transfer(0x00); //Dummy send to get value from module
  digitalWrite(SSpin, HIGH);
  SPI.endTransaction();
  return 0;
}

/* Init mems driver interface */
ism330dlc_ctx_t dev_ctx = {platform_write, platform_read, 0};
//dev_ctx.write_reg = platform_write;
//dev_ctx.read_reg = platform_read;
//dev_ctx.handle = 0; //No handler needed

void setup() {
  delay(100);
  Serial.begin(9600);
  pinMode(SSpin, OUTPUT);
  digitalWrite(SSpin, HIGH);

  /* Initialize SPI */
  SPI.begin();
  //SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0));     //MSBFIRST, SPI_MODE3

  /* Needed for setup */
  static uint8_t whoamI, rst;

  /* Check if device ID is correct */
  whoamI = 0;
  ism330dlc_device_id_get(&dev_ctx, &whoamI);
  while (whoamI != ISM330DLC_ID) {
    Serial.print("Wrong device ID!! \n"); Serial.print("whoamI: ");     Serial.print(whoamI); Serial.print("\n\n"); delay(50);     ism330dlc_device_id_get(&dev_ctx, &whoamI);
  }

  /*Restore default config */
  ism330dlc_reset_set(&dev_ctx, PROPERTY_ENABLE);
  do {
    Serial.print("reset:"); Serial.print(rst); Serial.print("\n\n");
    ism330dlc_reset_get(&dev_ctx, &rst);
  } while (rst);

The problem is that whenever I run this code I get DeviceID 255 no matter what (ism330dlc device id is 106). One thing I noticed is that if I reset the Arduino and quickly insert the USB cable and upload the code (in the time interval of a second) I can get the right device ID, but then I can't restore the default configuration (i.e not read or write again). Any tips what might cause this? I have tried SPI.setClockDivider() as well as different SPI Modes.
UPDATE: Removing ground from GND, SCx and SDx makes me get the correct deviceID but I still get stuck on trying to restore default configurations.

You are powering the STEVAL board from the VIN pin of the Arduino, while powering the Arduino through USB?

No sorry about that, I am powering the STEVAL-board using the 3.3v output on the Arduino. Edit: I have also tried powering it using an extern source at 2.8V.

Sorry there was a time limit on editing comments more than once. The Arduino is powered through USB and the STEVAL board is powered through the 3.3v output.

I realize now that I have not added any coupling capacitors to Vdd and Vdd_IO, could that affect the data?

Unlikely. The STEVAL board will have plenty of decoupling built in.

When I measure the CS pin it alternates between 2.4V and 2.6V when doing reads, is the difference too small? Vdd_IO is at 3.25V (same as Vdd).
SDO (MISO) is always 3.15V, SDA (MOSI) is switching between 0.3V and 1.3V, SCK is always 3.25. These values doesn't seem to be correct, right?


text:
Getting gibberish serial port until button is pressed, plus the button is turning the leds off instead of on
I'm connecting a button to ESP8266.
Connection goes like this:
3v to one side of button, other side connected with GND and pin number 2 (no resistor).
Every time I connect the ESP both built in LED's stay on until I press the button, they turn off until I let go (even though code states otherwise).
Plus, When I monitor the serial, gibberish runs while ignoring my print commands, until I press the button then the serial stops outputting altogether.
When I run the serial without the button, everything works fine.
Am I connecting it wrong, or is the button damaged, or any other problem source?
Thanks in advance.
EDIT: I added the pinMode(BTN_PIN, INPUT_PULLUP) to take the resistor role; to the code, still not helping.

You definitely need a resistor. Currently you are shorting your power supply. This will turn off your esp and eventually kill your power supply or the esp (depending on how you have everything connected

Thought so. Are you 100% sure I need a resistor? I think I have everything connected right as I described above.

You need a resistor somewhere. You can decide if you want to use an external one or the internal one that you activate with the INPUT_PULLUP statement

I added the statement to the input pin. But is there a work around for the GND pin resistor? or do I have to insert an actual physical one?

Got it to work eventually, apparently if I use the PULLUP command, I should remove the GND connection. Thanks for the help!

When pin 2 is connected to ground as you have done it puts the chip into an invalid boot mode. It will be spewing out messages at 74880 baud complaining about the boot mode being invalid.
You must not connect pin 2 to ground. It must, at boot time, be connected to 3.3V through a resistor (which is should be provided by the board for you if you use a development board not a bare module).
By connecting the button between 3.3V and GND you are causing a short circuit that removes the power from the module and risks damaging the power supply on your board.
The proper way of wiring a button is to use:
pinMode(2, INPUT_PULLUP);

and then connect the GPIO pin to ground through the button.
The INPUT_PULLUP acts like the required pullup resistor keeping the input HIGH while "idle", and the button connects the input to GND when you want to "activate" it, making it LOW.
Those are the only connections you should make.  If you want to use an external resistor instead of the internal one with INPUT_PULLUP, then that goes between the input pin and 3.3V.
Never ever cause 3.3V to be directly connected to GND.


text:
ESP8266 crashes when trying to copy a string into a big char
I'm trying to parse with tinyxml2 a modest XML (3.4kb) to retrieve some data.
My ESP8266 crashes every time I try to use the toCharArray method.
here's my code
// here I'm getting an http request
String payload = https.getString();

// checking the payload, it seems fine in console but I get some garbage characters when àèéùìò are printed
Serial.println(payload);

// Length (with one extra character for the null terminator)
int str_len = payload.length() + 1;

// Prepare the character array
char xml[str_len];

// Copy it over
payload.toCharArray(xml, str_len);

// there I'll parse xml with tinyxml2 but the MCU crashes before getting here

the length of the string is something around 3900, which I'm not sure can fit this kind of array on this device. If it's the case, what will be a better strategy ?
As you can imagine I'm just starting with the c language :)
EDIT: https.getString().c_str() + less variables was the right way to save memory

variables declared inside functions are created on the stack, the total size of these variables is 4kb - 3900 is getting pretty close - you'll want to use malloc (and free) to use heap memory instead

another option is, if you know the absolute maximum payload could be, create a global buffer to use

Function local variable are created on the stack, and in the case of an ESP8266, the total size is limited to 4096 Bytes - so, 3900 for one variable is cutting it close.
I would recommend you either use malloc/free
int str_len = payload.length() + 1;

// Prepare the character array
char *xml = (char *) malloc(str_len);

// Copy it over
payload.toCharArray(xml, str_len);

// there I'll parse xml with tinyxml2 but the MCU crashes before getting here
//
// when done, free the memory malloc'd

free(xml);

or, if you know an absolute maximum size for the string, e.g. 5000, make char xml[5001]; in the global scope

tried declaring a char with a size of 6000 in global and it reboots
<<<stack<<<
ets Jan  8 2013,rst cause:2, boot mode:(3,6)
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v951aeffa, the size of the string is ~5700

got a compile error with malloc -> src/main.cpp:74:35: error: invalid conversion from 'void*' to 'char*' [-fpermissive]

yeah, sorry was in a rush - hang on - there, fixed

tried declaring a char with a size of 6000 in global and it reboots - really? that does seem odd

still no luck (event with malloc, which seems to work fine) but I think the problem could be elsewhere. For the sake of documentation I'll post the gist of the main file -> https://gist.github.com/leRenart/1b72db23371839fd5a7799ece63ad8ed

so with malloc it crashes with the same "cause"?

it crashes every time I did a myString.toCharArray(), so I've finally opted to get rid of some variables, and ended with passing the result of the GET directly into the xml parser          doc.Parse( https.getString().c_str() ); I've tested it for many hours without any problem. I think I was using too much memory, but again, I'm not sure (if you wanna take a look into my code I've posted a gist of it). This is frustrating me because for no apparent reason (as the input is the same) this morning is keeping crashing and I can't figure why. To me all of this is learn by (wrong)doing...


text:
ATtiny88 ADC reference voltage setting
I'm writing a simple application that reads voltage from analog input 0. Here is the code:
#define OUT 5
#define ADC 0

void setup() {
  ADMUX &= (0<<REFS0); //Setting reference voltage to internal 1.1V
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(0);
  float voltage = sensorValue * (1.1 / 1023.0);
  if (voltage>0.5) {
    digitalWrite(OUT,HIGH);
  } else {
    digitalWrite(OUT,LOW);
  }
}

When I apply 1 V on ADC0, the OUT pin is low. Seems like the reference voltage is not set properly. When I set VREF to VCC (5V), everything works fine.
I cannot find the mistake. Would appreciate any help:)
Edit:
Link to datasheet: http://www.atmel.com/images/doc8008.pdf

Sure, here's link to datasheet: http://www.atmel.com/images/doc8008.pdf

@Rohat Kılıç I believe there is no such thing as REFS1 in ATTINY 88

The statement
ADMUX &= (0<<REFS0);

AND's the current value of ADMUX with zero, resulting in a zero value, and stores it into ADMUX.
To clear the REFS0 bit in ADMUX without affecting the rest of it, one generally would instead say
ADMUX &= ~(1<<REFS0);

which will AND its value with the complement of 1<<REFS0.
However, you should use the statement
analogReference(INTERNAL);

instead of setting ADMUX directly.  One of the first statements executed in the analogRead() source code is
ADMUX = (analog_reference << 6) | (pin & 0x07);

which overrides reference selections made by just changing ADMUX.
Parameters INTERNAL and DEFAULT to analogReference() select either the 1.1 V internal bandgap reference or the default analog reference, Vcc.

Edit 1:  If you replace ADMUX &= (0<<REFS0) with analogReference(INTERNAL) in setup and it still doesn't work, you will need to apply some more-powerful debugging aids.  For example, check that you got the sketch to correctly compile and that you uploaded it ok.  Check that AVCC is connected to Vcc, preferably through a low-pass filter, as noted in datasheet sections §1.1.2 and §17.9, “Analog Noise Canceling Techniques”.  Then, try several voltage inputs to see at what level the LED comes on.  If it doesn't ever come on, look for LED problems using a simple sketch like Blink.  If it comes on consistently at some input voltage, work out what reference is being applied.

Edit 2:  Apparently the source code of analogRead() is different for ATtiny parts vs others.  The code that I see for it in ... /arduino/avr/cores/arduino/wiring_analog.c [your path may differ] is like the following (I've elided some comments and blank lines).
uint8_t analog_reference = DEFAULT;
void analogReference(uint8_t mode) {
  analog_reference = mode;
}

int analogRead(uint8_t pin) {
  #if defined( CORE_ANALOG_FIRST )
    if ( pin >= CORE_ANALOG_FIRST ) pin -= CORE_ANALOG_FIRST; // allow for channel or pin numbers
  #endif
  ADC_SetVoltageReference( analog_reference );
  ADC_SetInputChannel( pin );
  ADC_StartConversion();
  while( ADC_ConversionInProgress() );
  return( ADC_GetDataRegister() );
}

Some ADC_... functions and constants are defined in ... avr/cores/tiny/core_adc.h; and which definition of ADC_SetVoltageReference() is used depends on conditional compilation.  For a definitive check on how analogReference() is defined for your part, look for analogReference() within the assembly listing of your program.  Obtain that listing as explained in several Arduino SE answers, for example in the  “Making assembly listings” paragraph near the end of my answer to question #33033. Also, a forum.arduino.cc thread from late April 2016 has some discussion of reading ADC inputs on tinys; I don't know if it's relevant.

@EmKa, and does it work?

OK, I put analogReference(INTERNAL) instead of ADMUX &= (0<<REFS0) in setup section, but still it doesn't work:( @jwpat7

@EmKa, see edit 1.  What test equipment do you have?  DVM?  Scope? Freq. meter?

I have a scope. When I use VCC, it works, well more or less fine. But I want more detailed measure, that's why I want to use 1.1 internal reference voltage. @jwpat7

When I use "analogReference(INTERNAL)" the output pin is always LOW. However with VCC (5V) it works more or less fine. There's a slight mistake, but it may be due to the fact, that I supply the uC from programmator, and it provides voltage under 5V. In calculations i use 5V @jwpat7

And the sketch is successfully uploaded and compiled every time. Maybe it's sometihng due to the fact that I use ATTINY 88? I mean, for this specific uC the fe. analogRead function may function differently? @jwpat7

@EmKa, see edit 2.  And please feel free to mark this answer (click green arrow)

In your setup section, you want to set or clear all relevant bits in admux.

Is it a question?


text:
How to add .h file in library
I am trying to make an ultrasonic distance meter using Arduino. For this I added the ultrasonic library. But on compiling it shows this error "ultrasonic.h
not available". Please tell me how to add this .h file.

You can literally just create one. Usually they are config files so where you initialise variables etc.

Unless this is a module that you have installed from somewhere? In which case it should have one already. If not then try putting an empty one in and see what happens.

How did you add your library ? Have you follow these steps shown on the arduino site ?

In you Arduino Sketch folder there is a folder called Libraries, create a folder there and put your header file in that folder and restart the Arduino IDE.
For example (PC):
Documents/Arduino/Libraries/ultrasonic/ultrasonic.h

You can now use it in all your projects.
If you only want to use with a particular sketch, place in in the same folder as you  sketch and restart Arduino IDE.


text:
Encoding an entire Byte for File Reading
I'm using an Arduino Yun to read from a data file, which will then populate a data structure. The file.read() function "returns: The next byte (or character), or -1 if none is available."
This functionality is identical to the SD.read() function in the SD card library.
The data file will never have any value that exceeds 1 byte with all numbers in the range 0-255. If I print these numbers as a long string in the data file, each character is read as a byte. So I need to call file.read() 3 times to read in a single 0-255 value. And then do some additional processing to construct the final 8-bit value for storing.
I could reduce this to 2 calls by printing the Hex code in the data file, but this isn't much of an improvement.
Is there a way to encode a full byte in a single character?
Effectively , is there a particular way I can format my data file so that I can read in an 8-bit unsigned value in a single call to file.read()?

"Is there a way to encode a full byte in a single character?" I have no idea what you're asking here. Characters (in single-byte encodings) normally fit a byte regardless.

You need to save the values into a binary file, instead of converting the values to a human readable string, and saving that string.

There's two parts to what you want to do, writing the file in the right form, and reading that format file.
The format of file is known as raw binary. Every byte in the file can store a separate value between 0 and 255, or between -128 and 127, dependin on how you interpret the data.  At the end of the day, every byte in a file is just a collection of 8 bits yielding 2^8 = 256 combinations. What those combinations actually mean is more of a human thing than a machine thing.
We, as humans, have decided upon three main representations of those bytes: unsigned numbers from 0 to 255, signed numbers from -128 to 127 (lookup two's complement) and finally ASCII characters.
ASCII characters are more of a lookup table placed over one of the other two representations. Some systems use unsigned bytes and some signed bytes for the basis of that lookup tabe.
Writing text into the file results in looking up the corresponding byte values for each character in that text and placing those values in the file. When you read the file the reverse is done - the byte values are read and you look them up in the ASCII table to find the corresponding letters.
To store just numbers between 0 and 255 it is far more efficient to bypass that ASCII table and store the values directly as bytes. How you do that is entirely dependent on what language you are writing your software in. Since you haven't mentioned what that language is I can't advise you on that front' only give some examples in languages I know.
Such as in C you would store your data in an array of unsigned char or uint8_t. You then use the write() function to write raw data to the file.
In Perl you might use the pack() function to store your values as bytes in a string then write that string to a file.
When reading the data you are presented with a raw value. That may be given to you as a signed or an unsigned value depending on the underlying system. I don't know what the yun is off hand. Converting from whatever is handed to you by thr file.read() function to what you expect it to be though is a very simple matter, and is called casting.
int in = file.read();
uint8_t bval = (uint8_t)in;

The bit in brackets is the cast which converts the value in the integer in into a uint8_t (Unsigned INTeger 8-bit Type) which corresponds to whatever you wrote as an unsigned char or uint8_t at the other end.

This is a fragment (untested) of how you can do it:
char datafile[512];
int ch;
int index = 0;

while ((ch = file.read()) != -1) {
  datafile[i] = (char)ch;
  if (++i == 512)
    break;
}

I was having trouble with char as the standard ASCII encoding does not handle numbers greater than 127, resulting in errors when printing.


text:
Arduino Nano with Mac OS Yosemite 10.10
I have an Arduino Nano and I’m trying to use it with Mac OS Yosemite (10.10). However, I’m having issues with the data transfer between the computer and the device. The Arduino is powered (LED is illuminated), however, I can’t upload anything to it. The serial port is not recognised and after installing a multitude of drivers, nothing seems to work.
Is there a specific driver or process I need to follow to enable data transfer?

Setting kext-dev-mode=1 allows unsigned kernel extensions to load, which is not recommended, as it lowers OS X security.
Instead, try the signed 64-bit kernel extension from FTDI here: http://www.ftdichip.com/Drivers/VCP.htm , version 2.3, which does require changing OS security permissions.

In theory that one should be much better - but I cannot get it work. It keeps unloading the kext and nothing shows up under /dev. Works for you?

This is only applicable to boards having an FTDI USB serial chip.  It is not needed for boards using an ATmega16u2 and will not help with boards having a CH340/CH341.

From this blogpost you can download signed macOS driver for CH340. Works fine on Sierra 10.12!

Without commenting on the legitimacy of the linked software, it should be noted that a CH340 driver will only work on boards using a CH340 or CH341 - it will not help for boards using an FTDI part or an ATmega16u2.  Blind installation is probably not to be recommended.

I think if this kext is signed by Apple, they trust it, aren't they?

Regardless of who allegedly signed it, that driver will not help anyone who doesn't have a CH340/CH341 or functionally identical adapter.  The actual Arduino Nano uses an FT232RL chip, requiring a different driver (which may well be built in).   The point is to figure out what you have before installing drivers - this can be determined either by reading the part numbers or from the USB tab in system report.