text:
How to load program into Arduino pro mini using FTDI cable?
Do we need a ftdi basic board to connect a ftdi 232R USB - TTL serial level converter cable via a 6 pin 0.1" male header into an Arduino pro mini/ nano 328 to upload the sketch?

you can use an UNO instead, most of us have a few laying around...

For the Arduino Nano:
NO, the Nano already includes the USB-to-TTL conversion circuitry. Just use the USB connector as you would with a Uno.
For the Arduino Pro Mini:
YES, you need an external breakout board to perform USB-to-TTL conversion. This board may use the FT232RL chip, but also any other equivalent one like the CH340G. You only need to have the adequate driver in your computer and you'll be set.
NOTE:
If you have "converter cable" you might not need a breakout board because this kind of cable already includes the FT232R (or equivalent). You don't need to use this cable with the Nano.

Note that you need the DTR signal available for board reset. Some boards or chips don't provide that. Some, like the MCP22xx only provide RTS and may not be usable without knowing how to get the RTS pin to toggle for you. UECIDE provides direct support for that though.

Well seen. But then it's all down to being careful enough as to select a breakout board whose chip implements all the required functionality, right? FT232RL or CH340G would be OK, whereas MCP2200 and others wouldn't (at least straight away, as you say).

Correct. It's all about attention to detail.


text:
Programming standalone Atmega328p-PU with NE555N timer IC
I know I may sound a little idiotic to ask, but as I have seen in the internet that to program a standalone Atmel chip like that from of the Arduino's, you need 2 22pF ceramic capacitors and a 16mhz oscillator. As the oscillator is needed is clock the frequency of the chip, so a timer IC should work just fine, isn't it? or do I have wrong information?

You can provide an external clock on pin PB6, but you'd need to set the correct fuses to select the External Clock option. But if you need to change the fuses, you might as well set the fuses to use the internal 8MHz RC oscillator, and negate the need for a 555 or crystal.

No, you won't be able to build a 16 MHz clock signal using a 555 timer. That's far beyond the 555 capabilities (see N.B.).
If you could squeeze out of the 555 a mere 1 MHz (which I seriously doubt), the clock stability and jitter would be so bad that it won't be usable but for simple sketches not requiring any timing accuracy. At that point, you would be far better off using the internal 1 MHz RC network of the ATmega328P as Majenko says, because you would at least save the 555 and its associated components.
Also, a 555-based clock would consume much more power than any of the alternatives already available to you (internal oscillator, external crystal...). Even the CMOS version.
My recommendation: forget about it, it's not worth it.
NOTE BELOW:
NE555N is a BJT version of the 555. BJTs suffer from what's called "storage time", a charge accumulation in the base that severely limits switching time. The NE555N datasheet states a storage time of about 10 microseconds (p.10), which limits the switching frequency to about 100 kHz.
TLC555 is a CMOS version of the 555. Because it uses FETs, its maximum switching frequency is much higher. The TLC555 datasheet (p.6) states that a typical value for the maximum switching frequency is 2.1 MHz (and at least > 1.2 MHz).

Yes, you could use a 555. You can also go even simpler and use an RC network. Even simpler still is to use the 1MHz RC network built in to the chip.
The main drawback of these methods, and the 555 particularly, is that of stability. Using a crystal and capacitors you can get very accurate timing at high frequencies. Using a 555 you can get ballpark timing at low frequencies. Fine if all you want to do is blink an LED, but as soon as you need to do anything that requires good timing it all falls apart. That includes things like using the UART for which accurate timing is at the heart of its operation.
The internal oscillator is better in this respect since it can be calibrated using the OSCCAL register. However changes in ambient temperature can cause unacceptable drifting of the clock frequency.

The default configuration of these chips, as they come from the factory,
is to use their internal 8 MHz RC oscillator downscaled at 1 MHz. So you
do not need any extra oscillator to program them.
Once you program the chip the first time, if you configure it to use
an external resonator/oscillator, then you do need to have that
attached in order to reprogram the chip.
A 555 may be able to run the chip, but if you want to reprogram it, the
programmer may not cope well with the extra-low frequency the chip would
be running at.

It depends on how you're programming it.
If you're using a bootloader to accept programming commands via a serial connection then you will need to use the clock method specified by the fuses currently programmed, since the chip at that point will actually be running code programmed on it.
If you're using ISP to program the chip out-of-band then you can apply a clock source directly to the XTAL1 pin as shown in the "Serial Downloading" subsection of the "Memory Programming" section of the datasheet. In this case you will need to adhere to the timing information given at the end of the subsection.

source: Stack Exchange

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

sort: votes


text:
Strings becoming empty (Arduino Uno)
I'm running a modifed code on Arduino Uno + WiFi shield (updated), and I have seen strange behaviors with String ; here is my code, the goal is to parse a HTML request to know which page was requested :
String line = client.readStringUntil("\n");
Serial.print("Line : [");
Serial.print(line);
Serial.println("]");

String cmd = line.substring(0, 3);
Serial.print("Command : [");
Serial.print(cmd);
Serial.print("]");

My problem comes from what appears in the console :
Line : [GET / HTTP/1.1
Host: 192.168.43.200
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch
Ac]
Command : []

I was expecting the cmd variable to contain GET, and I do not understand why it contains nothing.
I suspect this behavior comes from the lack of RAM (compiler says there are only 670 bytes available for local variables), but if it's the case, I do not know how to solve it, as I'm pretty inexperienced in C++ and I need to store a String containing the values that are sent as a reply to the HTTP request.
PS. I'm also wondering why the client.readStringUntil("\n") method sends the full request instead of only the first line.

readStringUntil Requires a char as argument, not a C string. So try changing "\n" to '\n'

https://hackingmajenkoblog.wordpress.com/2017/04/08/splitting-up-text-in-c/

In general, you don't want to be copying strings around when you don't have to because it's inefficient. For parsing things like command lines, you can often just work with the existing String (or better yet, string; see Majenko's tutorial).
In this particular example, you have a string and you want to know if it's an HTTP GET command. That's simple enough; the first four characters will be GET (we check the space on the end because we don't want to interpret GETMORE /foo as a GET command).
This is extremely easy:
String s = "GET /foo/bar";

if (s.startsWith("GET "))
    Serial.println("GET command");
else
    Serial.println("Not GET command");

For stuff in the middle of a string you obviously can't use startsWith, but there are other functions that can help. For example, once you know it's a GET command, you know that the URL starts at position 4 (the 5th character, since counting starts at 0). You could test to see if it starts with '/foo' with
if (s.indexOf("/foo") == 4)
    Serial.println("Path starts with /foo.");
else
    Serial.println("Path doesn't start with /foo.");

That said, while this kind of thing is workable for quick tests, in the long run you probably want to move towards parsing in C in the way that Majenko's tutorial above talks about, and likely parsing as much as possible as you do the reading (rather than reading everything into memory and then parsing it) due to HTTP requests being relatively large compared to the memory you have to handle them.

In the end I used your link to learn more about C-style strings, and translated my whole code to use them, so I'm marking your answer as a solution, however the bigger problem was the string litterals : replacing them using the 'F()' macro freed 40% of the SRAM, and solved this problem.

I'm glad to hear you got things worked out! I expect that the RAM being used by string literals being a problem didn't occur to anybody here because there's almost no use of string literals in the question, but that's certainly something to keep in mind if you have more than a few of them.

Well I'm coming here from Java, and I have this strange habit of using println()s to log everything instead of commenting my code :/ looks like it can backclash sometimes

I have an other problem with memory usage of growing strings here ... If you have any tips for this one, I'd be glad to hear them

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


text:
Actual baud rate of UNO R3 Firmata protocol
Probably a silly question. But the Internet is confusing me.
The Firmata website says the default baud rate is 57600. But AFAIK, the baud rate set for UNO R3 is 9600(In Windows device manager, it say so). I'm making the Firmata client program and have to set the baud rate. I'm confused whether it's similar to the serial protocol or not.
[Using the StandardFirmata sketch]

The baud rate is whatever the program opening the port requests it to be. The stuff in the device manager is only the default used if nothing else is specified when the port is opened.
And the Firmata protocol just squirts bytes over serial. It's based upon the MIDI protocol, which is just serial.

So clearly I should declare as 9600?

If the sketch you are running has the baud set to 57600 then the program you use to communicate with your sketch has to be set to 57600. Ignore device manager. It's completely irrelevant.


text:
Get Speed Using GPS Neo with TinyGPS++
I am trying to get the current speed of my car using the GPS Neo, but my code always returns that the speed from the GPS is invalid. The green led of the GPS Neo is blinking. What is the isValid() function? Below the code:
#include <EEPROM.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
//LOAD WIRE LIB
#include<Wire.h>
static const int RXPin = 10, TXPin = 9;
static const uint32_t GPSBaud = 9600;
// The TinyGPS++ object
TinyGPSPlus gps;
// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);
//***************************************************************
int aux = 0;
int vel_prog = 20; //programed SPEED
float vel_atual;//  actual SPEED
int val_inc = 0;
int val_dec = 0;
int led0 = 2;//led pin
int led20 = 3;//led pin
int led60 = 4;//led pin
int led80 = 5;//led pin
int ledsinal = 6;//led pin
int buzzer = 7;//buzzer pin
int incrementa = 8;//button pin
//****************************************************************
void setup()
{
  Serial.begin(115200);
  ss.begin(GPSBaud);
  pinMode(incrementa, INPUT);
  pinMode(led0, OUTPUT);  // declare LED as output
  pinMode(led20, OUTPUT);  // declare LED as output
  pinMode(led60, OUTPUT);  // declare LED as output
  pinMode(led80, OUTPUT);  // declare LED as output
  pinMode(ledsinal, OUTPUT);  // declare LED as output
  pinMode(buzzer, OUTPUT);  // dbuzeer
  delay(10);
}

void loop()
{

  smartDelay(1000);
  val_inc = digitalRead(incrementa);  // read increment button
  if (val_inc == 1) {
   if (vel_prog > 80) {
      vel_prog = -20;
   }
      vel_prog = vel_prog + 20;
  }

  if (vel_prog == 0) {
    digitalWrite(led0,HIGH);
    digitalWrite(led20,LOW);
    digitalWrite(led60,LOW);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 20) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,HIGH);
    digitalWrite(led60,LOW);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 60) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,LOW);
    digitalWrite(led60,HIGH);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 80) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,LOW);
    digitalWrite(led60,LOW);
    digitalWrite(led80,HIGH);
  }

  if (gps.speed.isValid()){
  Serial.print(gps.speed.kmph());
  } else {
  Serial.print("*");
  }

 if (gps.speed.isValid()) {
  if (gps.speed.kmph() >= vel_prog && aux == 0) { //comparacao da velocidades
    digitalWrite(ledsinal, HIGH);  // turn LED OFF
    tone(buzzer, 2200);
    delay(5000);
    digitalWrite(ledsinal, LOW);  // turn LED OFF
    noTone(buzzer);
    aux = 1;
  }
}
}

static void smartDelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

What specific device are you using?

Arduino Nano AtMega 168, and a GY-GPSV3- NEO M8N GPS

No, I mean which GPS device!

Sorry, I edited the post

Looks like it should support Velocity reporting. Maybe you don't have a good enough fix, or maybe it needs turning on in the config. Step 1 is to examine exactly what NMEA messages it's sending while running. Use the ubiquitous serial pass-through sketch to read the raw NMEA data.

Using the standar example from Arduino, it shows only "*"

These lines of code will wreak havoc with reading the GPS data:
tone(buzzer, 2200);
delay(5000);
digitalWrite(ledsinal, LOW);  // turn LED OFF
noTone(buzzer);

The Arduino is "blocked" at these lines for seconds.  During that time, the GPS keeps babbling and eventually overflows the input buffer.  The next call to smartDelay only waits for 1 second, and it may not get a complete sentence.
Here is a NeoGPS version of your sketch that does not block:
#include <EEPROM.h>
#include <NMEAGPS.h>
#include <NeoSWSerial.h>
#include <Wire.h>

NMEAGPS gps;

static const int RXPin = 10, TXPin = 9;
static const uint32_t GPSBaud = 9600;
NeoSWSerial gpsPort(RXPin, TXPin);

//***************************************************************
int aux = 0;
int vel_prog = 20; //programed SPEED
float vel_atual;//  actual SPEED
int val_inc = 0;
int val_dec = 0;
int led0 = 2;//led pin
int led20 = 3;//led pin
int led60 = 4;//led pin
int led80 = 5;//led pin
int ledsinal = 6;//led pin
int buzzer = 7;//buzzer pin
bool buzzing = false;
uint32_t buzzTime;
int incrementa = 8;//button pin
//****************************************************************
void setup()
{
  Serial.begin(115200);
  gpsPort.begin(GPSBaud);
  pinMode(incrementa, INPUT);
  pinMode(led0, OUTPUT);  // declare LED as output
  pinMode(led20, OUTPUT);  // declare LED as output
  pinMode(led60, OUTPUT);  // declare LED as output
  pinMode(led80, OUTPUT);  // declare LED as output
  pinMode(ledsinal, OUTPUT);  // declare LED as output
  pinMode(buzzer, OUTPUT);  // dbuzeer
  delay(10);
}

void loop()
{
  // Check the buttons
  val_inc = digitalRead(incrementa);  // read increment button
  if (val_inc == 1) {
   if (vel_prog > 80) {
      vel_prog = -20;
   }
      vel_prog = vel_prog + 20;
  }

  if (vel_prog == 0) {
    digitalWrite(led0,HIGH);
    digitalWrite(led20,LOW);
    digitalWrite(led60,LOW);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 20) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,HIGH);
    digitalWrite(led60,LOW);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 60) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,LOW);
    digitalWrite(led60,HIGH);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 80) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,LOW);
    digitalWrite(led60,LOW);
    digitalWrite(led80,HIGH);
  }

  // Check the GPS
  while (gps.available( gpsPort )) {
    gps_fix fix = gps.read();

    if (fix.valid.speed) {

      if ((fix.speed_kph() >= vel_prog) && (aux == 0)) { //comparacao da velocidades
        digitalWrite(ledsinal, HIGH);  // turn LED OFF
        tone(buzzer, 2200);
        aux = 1;
        buzzing = true;
        buzzTime = millis();
      }

      Serial.print( fix.speed_kph() );
    } else {
      Serial.print( '*' );
    }
  }

  // Check the buzzer
  if (buzzing && (millis() - buzzTime > 5000)) {
    digitalWrite(ledsinal, LOW);  // turn LED OFF
    noTone(buzzer);
    aux = 0; // Need this?
    buzzing = false;
  }
}

Notice how it checks millis() every time through loop to see if the buzzer has been on for 5 seconds.  It doesn't block for 5 seconds.
It only checks the speed when a new GPS fix arrives.  This happens once per second, not every time through loop.
Your original version uses 11472 bytes of program space and 786 bytes of RAM.
The NeoGPS version uses 10722 bytes of program space and 590 bytes of RAM, a significant savings.
NeoGPS is smaller, faster and more accurate than all other libraries.  If you want to try it, NeoGPS is available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.
The above sketch also uses my NeoSWSerial.  It is much more efficient than SoftwareSerial.  SoftwareSerial blocks interrupts for long periods of time, which can interfere with other parts of your sketch.
It would be even better to use AltSoftSerial on pins 8 & 9 (on an UNO).

Thanks, now it's working, but another doubt, If I put the antenna pointing to the sky towards the front glass of the car, can the glass disturb the signal? Or should I put the antenna out of the car?

It should be fine inside the car.  Unless you have a metallic mirror coating...


text:
NodeMCU does not boot up when GPIO pin is high
I have a NodeMCU board connected to a door and there is a micro switch that makes one GPIO pin (GPIO15 - D8 in this specific case) go high when the door opens.
My problem is if I lose power while the door is opened, the GPIO15 is fed high at the next boot when power is restored. And it makes the board go to a not responding state. I have to boot it again while the door is closed (pin is low) to bring it back to work. I experienced this while flashing too. I cannot flash while this pin is high (while the door is open).
How can I fix this?

Certain pins of the ESP8266 perform special functions at bootup. GPIO15, when HIGH, makes the ESP8266 boot from an SD card.
You can read more about the special functions of the pins here.
The solution? Don't use GPIO 0, 2 or 15 for things that can affect the boot sequence.


text:
Managing 2 ultrasonic sensors without blocking the other
I have an ultrasonic distance sensor. When this sensor is measuring a distance below 25 cm, a second sensor has to be measuring a distance below 5 cm. If not, there should be a one minute timespan, after which a speaker should make noise until the second sensor is measuring a distance below 5 cm.
I am having trouble with this. The first sensor has a lot of code it should be running as well, so using a while-loop to wait out one minute for the other sensor and creating noise after that isn't a possibility.
How do I go about this dilemma? I read into interrupts in Arduino but unfortunately I don't know how I'd make this work.

look at the "blink without delay" example; you need to do the same thing while "waiting" on the sensors.

I strongly advice you to use interrupts and make sure the sensors are in a cylindrical cone in order to prevent interference to each others as much as possible.
Here is code snippet which can give you an idea how the interrupts are set and used. I believe that you can adapt it to yours. It is from Arduino forum (link), credits to "cattledog".
volatile unsigned long LastPulseTimeA;
volatile unsigned long LastPulseTimeB;
int durationA;
int durationB;
//unsigned long startTime;
#define trigPinA 7
#define echoPinA 2
#define trigPinB 8
#define echoPinB 3
void setup() {
  Serial.begin (9600);
  pinMode(trigPinA, OUTPUT);
  pinMode(echoPinA, INPUT);
   pinMode(trigPinB, OUTPUT);
  pinMode(echoPinB, INPUT);
attachInterrupt(digitalPinToInterrupt(echoPinA), EchoPinA_ISR, CHANGE);  // Pin 2 interrupt on any change
attachInterrupt(digitalPinToInterrupt(echoPinB),EchoPinB_ISR, CHANGE);  // Pin3 interrupt on any change
}
void loop(){
  digitalWrite(trigPinA, LOW);
  digitalWrite(trigPinB, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPinA, HIGH);
  digitalWrite(trigPinB, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPinA, LOW);
  digitalWrite(trigPinB, LOW);
  Serial.print("Sensor A  ");
  Serial.print(LastPulseTimeA);
  Serial.print('\t');
  Serial.print((LastPulseTimeA/2) / 29.1,1);
  Serial.println("cm");
  Serial.print("Sensor B  ");
  Serial.print(LastPulseTimeB);
  Serial.print('\t');
  Serial.print((LastPulseTimeB/2) / 29.1,1);
  Serial.println("cm");

  delay(1000);
}
void EchoPinA_ISR() {
    static unsigned long startTimeA;

    if (digitalRead(echoPinA)) // Gone HIGH
        startTimeA = micros();
    else  // Gone LOW
        LastPulseTimeA = micros() - startTimeA;
}
void EchoPinB_ISR() {
    static unsigned long startTimeB;

    if (digitalRead(echoPinB)) // Gone HIGH
        startTimeB = micros();
    else  // Gone LOW
        LastPulseTimeB = micros() - startTimeB;
}

Thanks, I'll try. Question though, will there be time enough for the rest of the program to run, as I assume the pins will change value all the time, interrupting the program 24/7?

As far as I can see from the specs, the echo will take some time up to 25 ms depends on the distance, maybe even more if there is no obstacle and then can take up to 38ms. So, it won't be that busy. But, of course it is also what you want to do with the echoing data. You may then consider to switch Arduino Mega or even Cortex-M0 or further.

fairly simple:
  if (time_is_up_for_sensor1()) read_sensor1(); //read sensor1 if time is up
  if (time_is_up_for_sensor2()) read_sensor2(); //read sensor2 if time is up

in time_is_up_for_sensor1/2(), update for the next round of reading:
int time_is_up_for_sensor1(void) {
  static uint32_t millis_next = 0; //next millis
  if (millis() >= millis_next) {  //time is up for sensor1
    millis_next += INTERVAL_SENSOR1; //advance to the next measurement time
    return 1;  //needs to read sensor1
  } else return 0;
}

similarly for sensor2

The millis_next += INTERVAL_SENSOR1; ... if (millis() >= millis_next)... method miscomputes when millis() overflows.  To avoid that, instead write millis_prev = millis();  (or perhaps millis_prev += INTERVAL_SENSOR1;) and then test via if (millis()-millis_prev > INTERVAL_SENSOR1)...

what does static uint32_t millis_next = 0; do exactly? (I'm new to C++/Arduino)

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


text:
How to change this function in to a non-blocking function?
How do I modify the getTheNumber() function to satisfy the statement below??
"
This function blocks until the user is done typing the number. Try to rewrite it in a non-blocking fashion. For example, it could return -1 on every call as long as the user is not done typing the number. On the first call after the user is done it would return the valid value. If you manage to write everything non-blocking, then you loop() will restart very often, and the program will work with no significant latency."
Here is the code:
int getTheNumber()
{
    char buffer[4];
    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
            int value = atoi(buffer);
            break;
        }
    }
    return atoi(buffer);
    }

I have a post about doing serial input without blocking.
Example code:
/*
Example of processing incoming serial data without blocking.

Author:   Nick Gammon
Date:     13 November 2011.
Modified: 31 August 2013.

Released for public use.
*/

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

make buffer[] and i static.
get rid of the while() loop.

Like this:
int getTheNumber()
{
    static char buffer[4];
    static int i=0;
    // Input up to 3 numbers until we find a * or #
    char key = keypad.getKey();

    // If it's a number AND we have space left, add to our string
    if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
            return(-1)
        }
        // If it's a * or #, end
    else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
            int value = atoi(buffer);
            i=0;
            return atoi(buffer);
        }
}

make buffer() and i static ? I don't understand that Sir. How do i do that?

please show me sir..

He typed the word static as you can see in the posted code. Did you not see that?

@rjadkins static variables keep their values from one function call to another. They're basically like global variables, but they can't be accessed outside the function they're declared in (if that makes any sense).

Thanks for the reply, really appreciate it. Now, why is the value I enter does does not follow this sequence when the function ic being called:
        int v = getTheNumber();
        lcd.setCursor(2,0);
        int y = getTheNumber();
        lcd.setCursor(2,1);
        int x = getTheNumber();
        lcd.setCursor(2,2);                                                                                Why does the output in the lcd screen does not follow the setCursor stated in the code?


text:
What are the unused pins in an Arduino L293D motor shield?
What are the unused pins in an Arduino L293D motor shield? I want to connect the shield using wires instead of directly mounting on top of the Arduino board.

Please edit your question to include shield's maker and part number and  tutorials, etc.   Add a link to its schematic if you have one.

It's similar to Adafruit's motor shield and works with Adafruit's motor library.

What if I don't use servo motor, Can I still use pin 9 and 10 as normal digital pins ?

Check out this Link. Here, you can find this explanation in Code. I hope it will helpful for you.
Pin usage with the Motorshield
---------------------------------------
Analog pins: not used at all...
A0 ... A5 are still available...
They all can also be used as digital pins.
Also, I2C (A4 = SDA and A5 = SCL) can be used.
These pins have a breadboard area on the shield.
Digital pins: used: 3,4,5,6,7,8,9,10,11,12
Pin 9 and 10 are only used for the servo motors.
Already in use: 0 (RX) and 1 (TX).
Unused: 2,13
Pin 2 has an soldering hole on the board, easy to connect a wire.
Pin 13 is also connected to the system led.
I2C is possible, but SPI is not possible since those pins are used.


text:
Get when a button close the circuit
That seems to be a bit stupid to myself but I can't figure out to get to know when my button is pushed (closed) or released (open).
You must know that this not just a simple push button. Actually it is more of a complex button with multiples output (Y, G, 0V, COM, NO, NC, HORM, 12V).
With a multimeter i've been able to locale witch output are closed when the button is pressed. These are HORM (that is the name for two outputs -?!-) and on the other side COM and NO.
I've tried to plug that to my arduino Mega, on PIN 7, and getting the value with Digital.Read. Tho when i try to display it on the Serial, it doesn't work and return an error. (It did the same for HORM and COM/NO)
I also noticed something strange. When the button is pressed, Arduino seems to notice it because my "ON" led turns off and then turns back on. Like if the arduino was crashing. The 13th pin LED stay HIGH after the arduino goes back on.
Please, have a look at my code.
int ledPin = 13; // choose the pin for the LED
int inPin = 7;   // choose the input pin (for a pushbutton)
int val = 0;     // variable for reading the pin status

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  // declare LED as output
  pinMode(inPin, INPUT);    // declare pushbutton as input
}

void loop(){
  val = digitalRead(inPin);  // read input value
  Serial.write(val);
  if (val == HIGH) {         // check if the input is HIGH (button released)
    digitalWrite(ledPin, LOW);  // turn LED OFF
  } else {
    digitalWrite(ledPin, HIGH);  // turn LED ON
  }

  delay(1000);
}

Do you guys have any advice ?
Thank you very much in advance.
Also please have a look at the circuit. The only difference is that instead of having this kind of simple pushbutton, i've got my NO and COM plugged the same way.

Please show your wiring

@Majenko Added something to illustrate. Just the button is different, but the plugs are the same

If the LED is OFF and ON on the Arduino means, there is a chance you shortcut VCC and GND somewhere during the button push!

@Sener And what could that come from ?

Button's self mostly likely is doing this shortcut. You have to give us exact schematic and the datasheet of the button for a better prognosis.

We need to see your wiring, not something else entirely that may have something inconsequential in common.

Oh, and if it is you that plugged an LED in like that then remove it immediately. If you are following a tutorial that has the LED plugged in like that then comment on the tutorial to tell the author they know nothing and use a better tutorial.

@Majenko Yes I know about the resistor for the led :) I didn't plugged any led tho, just using the 13th that is already on the arduino. Way better for debug, and easier. The tutorial is actually on the official arduino.org site. I'm taking pictures for my circuit.

A good enough reason for ignoring anything even remotely technical-looking on the Arduino websites. Just goes to show how much misinformation and blatantly incorrect information they are spouting.

@Majenko, I agree with you.

Ok then.
I just tried that again and it simply seems that the wiring shown on the tutorial is not good at all.
I made another wiring that worked exactly fine.


text:
Matching the blink of an LED to midi music
I have a function that plays a song and lights an LED corresponding to the note that is being played. when the same note is played consecutively(i.e E in bar 6) instead of the LED turning on and off for each time the note is played the LED appears to remain lit. how do i get the LED to go no and off for these notes to better synchronize with the music being played? The delay of 414 is being used as quarter notes etc.
void songlist (int song){
if (song==1){
songpage=1;
playpage=0;
mainpage=0;
tonepage=0;
lcd.clear();
lcd.setCursor(4,0);
lcd.print("ListeningTo:");// Print a message to the LCD.
lcd.setCursor(1, 1);
lcd.print(menuP1);
//Plays Mary Had a Little Lamb
//Bar 1
 noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x3E,100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3C, 100); //Quarter note: C
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[2], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[2], HIGH);
noteOff(0x90, 0x3C, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

//Bar 2
noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Half note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(828);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

//Bar 3
noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3E, 100); //Half note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(828);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

//Bar 4
noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x43, 100); //Quarter note: G
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x43, 0);

noteOn(0x90, 0x43, 100); //Half note: G
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[4], LOW);
delay(828);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x43, 0);

//Bar5
noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3C, 100); //Quarter note: C
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[2], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[2], HIGH);
noteOff(0x90, 0x3C, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

//Bar 6
noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);

delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);

delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);

delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);

delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

//Bar 7
noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

noteOn(0x90, 0x40, 100); //Quarter note: E
digitalWrite(LedR[3], HIGH);
digitalWrite(LedC[1], LOW);
delay(414);
digitalWrite(LedR[3], LOW);
digitalWrite(LedC[1], HIGH);
noteOff(0x90, 0x40, 0);

noteOn(0x90, 0x3E, 100); //Quarter note: D
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[4], LOW);
delay(414);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[4], HIGH);
noteOff(0x90, 0x3E, 0);

//Bar 8
noteOn(0x90, 0x3C, 100); //Whole note: C
digitalWrite(LedR[2], HIGH);
digitalWrite(LedC[2], LOW);
delay(1656);
digitalWrite(LedR[2], LOW);
digitalWrite(LedC[2], HIGH);
noteOn(0x90, 0x3C, 0x00); //"Silent" note that makes sure the note stops playing.
delay(2000);
//End song
}
}

First, write a helper function so that you do not have so much repeated code, and call it for each note:
void playNote(int midi, int row, int col, int len)
{
    noteOn(0x90, midi, 100);
    digitalWrite(LedR[row], HIGH);
    digitalWrite(LedC[col], LOW);
    delay(len);
    digitalWrite(LedR[row], LOW);
    digitalWrite(LedC[col], HIGH);
    noteOn(0x90, midi, 0x00);
}

...
//Bar 1
playNote(0x40, 3, 1, 414); //Quarter note: E
playNote(0x3e, 2, 4, 414); //Quarter note: D
...

Then, change it so that the note-off command and the LED switching can be done at different times:
void playNote(int midi, int row, int col, int len, bool short_led = false)
{
    int len1, len2;
    if (short_led) {
        len1 = len * 3 / 4;
        len2 = len * 1 / 4;
    } else {
        len1 = len;
        len2 = 0;
    }
    noteOn(0x90, midi, 100);
    digitalWrite(LedR[row], HIGH);
    digitalWrite(LedC[col], LOW);
    delay(len1);
    digitalWrite(LedR[row], LOW);
    digitalWrite(LedC[col], HIGH);
    delay(len2);
    noteOn(0x90, midi, 0x00);
}

can you explain the use of the bool short  led?

wouldn't a second delay effect the timing of the notes?

Set short_led to make the LED light for a short time. The sum of len1 and len2 is always the same as len.

when i try to add a back button in the songlist function it dosent work

if (songpage==1){
if (BackState==HIGH){//leaving song
posP=0;
Page=2;
Play(posP);
}
}

i want to be able to go back once the song starts playing to stop the song.

The back button has nothing to do with this question.


text:
Why is one part of my code being executed over the part before it?
The following code doesn't behave the way I would like it to. Inside the loop function im measuring the distance in front of the robot and if it is less than 15cm than the robot should move back and if it is less than 15cm on the left then move forward. When i run the program however only the left side is being checked and acted upon whilst the the if statement about the front and moving back is not doing anything. Something to note also is that when i swap the if statements and put the front checking ahead of the left checking it works but the left side is no longer being checked. Why is it that the if statement block in front is being executed over the previous one?
     void loop(){

     if(front.calculateDistance() < 15){
     MoveBack(200);
     }else{
      stopMoving();
     }

      if(left.calculateDistance() < 15){
     MoveForward(200);
     }else{
      stopMoving();
     }
   }

This is what the move methods do (move back and stopmoving just change input directions):
void MoveForward(int rspeed) {
 // turn on motor A
 digitalWrite(in1, HIGH);
 digitalWrite(in2, LOW);
 analogWrite(enA, rspeed);
 // turn on motor B
 digitalWrite(in3, HIGH);
 digitalWrite(in4, LOW);
 analogWrite(enB, rspeed);
}

The problem is with your logic. You are saying:

If it's too close in front then move backwards
Otherwise stop all movement
If it's too close on the left then move forwards
Otherwise stop all movement.

That means that if it's too close in front, but not too close on the left, then it will think about moving backwards, but then immediately stop because it's not too close on the left.
You need to think more about the whole space at once, not just one individual direction. For instance, what do you do if it's too close in front and too close on the left? At the moment you'll crash into whatever is in front.
So you should be thinking about four conditions:

Too close in front AND too close on the left
Too close in front BUT NOT too close on the left
NOT too close in front BUT too close on the left
NOT too close in front AND NOT too close on the left.

Then you can choose the right action to perform.
If your specific setup means that it can never be too close in front at the same time as being too close on the left you can collapse it into a simpler form:

IF it's too close in front then move backwards
ELSE IF it's too close on the left then move forwards
ELSE stop all movement.


text:
Moving cursor on LCD and changing highlighted value
I have the code shown below. The goal is to change the value of hours, minutes or seconds based on where the cursor is placed.
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2); //format of display
}

void loop() {
    int hours = 11;
    int minutes = 11;
    int seconds = 11;
    lcd.setCursor(0,0);
    lcd.print(hours);
    lcd.print(":");
    lcd.print(minutes);
    lcd.print(":");
    lcd.print(seconds);
    lcd.noBlink();
    delay(300);
    lcd.blink();
    delay(300);

    if (buttons & BUTTON_RIGHT) {
      move cursor right;
      if(lcd.setCursor == lcd.setCursor(0,3) {
        minutes += 1 }

}

I though of a way to do this. I would have three variables and print each of these out with a default value. With the use of the buttons, the user should be able to move the blinking cursor to hours, minutes or seconds, and increase or decrease the value of the variable.
I would do this by seeing what location the cursor is at. For example, if the cursor was on minutes, I would write something like if(lcd.setCursor == lcd.setCursor(0,3) or lcd.setCursor == lcd.setCursor(0,4)) { minutes += 1}.
Of course these functions don't exist, so I am wondering what I can do to move a cursor and check its position.
Thanks in advance

Just keep track on where you put your cursor.

Firstly, you should set the time variables outside the main loop (as a global variable). If you put them in the main loop, the time would always reset to 11:11:11 after 0.6s of delay.

lcd.setCursor == lcd.setCursor(0,3)

I dont think you can do this (unless the function returns you with the location of the cursor, have to check the header file of the library).
Instead, you should keep track of the location of the cursor with another variable (as mentioned by gre_gor), say int curLoc. But note that you have to keep track of the range of values it can go. (0 < curLoc < 16)
To summarise, the code could look like this:
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

int hours = 11;
int minutes = 11;
int seconds = 11;

int curLoc = 0; //Current cursor location (x-axis)

void setup() {
  lcd.begin(16, 2); //format of display
}

void loop() {
  lcd.setCursor(0,0);
  lcd.print(hours);
  lcd.print(":");
  lcd.print(minutes);
  lcd.print(":");
  lcd.print(seconds);
  lcd.noBlink();
  delay(300);
  lcd.blink();
  delay(300);

  //move cursor right;
  if (buttons & BUTTON_RIGHT) {
    //Keep the tracker in range
    if(curLoc >= 0 && curLoc < 16){
    curLoc += 1;
    }

    if(curLoc == 3)
    {
      minutes += 1
     }

}


text:
How to control low power devices when implementing Low Power Mode strategy?
As part of implementing Low Power Mode, I wish to control power to attached devices, such as the HC12 transmitter/receiver.  I've read of the usage of MOSFETs to control motors and lighting systems, but don't understand the applicability of such implementations to control something like an HC12, which consumes approximately 200ma.
Should I be using MOSFET and, if so which one?  Else, what is a better solution?  The circuit I am now working on is essentially a PRO Micro, an HC12, and a small led, though I will later add a camera module, approx. 100ma.

my fav is the IRLZ44N, which are easy to drive from ardunio with a Vgs(th) of a couple volts, built-in dioide, a tiny on-resistance, and up to 55v of switching at 47amps. if you switch less than 20v, a common ground works perfectly with a simple N-chan circuit w/o extra bjt helpers

Yes, MOSFETs are what you want.
The temptation is to just insert any old logic-level N-channel MOSFET in the ground connection to the device like you would when driving a relay, etc. However that method is fraught with danger. You get such issues as ground-level offsets (where ground isn't actually ground but some mV above ground) which can result in logic level mismatch problems. You get the possibility of power trying to make its way to ground through the device's IO pins and your MCU, etc.
So it is best to instead use a P-channel MOSFET to switch the positive power rail to the device. If the voltage you are switching is the same as the voltage you are doing the switching with (i.e., you are switching 5V using a 5V-level GPIO pin such as on an Arduino) then that is really all you need. However if the voltage you want to switch is higher then you will need to switch the P-channel MOSFET with an N-channel MOSFET, or an NPN BJT.
Here's two schemes:

simulate this circuit – Schematic created using CircuitLab
In the left schematic M1 is kept off by R2, and pulling the control GPIO low it turns M1 on allowing the current to flow.
In the right schematic M1 is kept off by R2 in the same way, but M2, when turned on by the GPIO being driven HIGH. R3 keeps M2 off while the MCU is not ready to drive the GPIO pin yet (in the bootloader, etc).
One thing to remember when switching the power off on either schematic is to first set all the GPIO pins that communicate directly with the device to INPUT mode. That will prevent them trying to power the target device through the IO pins (which will typically have ESD diodes that would feed current to Vcc).
All MOSFETs should be logic level (except M1 in the right schematic which can have a higher threshold depending on the voltage you are switching - best to keep it all logic level though as a rule).

How, then, do I go about the process of selecting a suitable MOSFET to utilise?

Find one where a) the on resistance is low enough (you want sub 1Ω, better sub 0.1Ω) when V_GS is at your switching voltage (5V), so one with a threshold of no more than a volt or two, and b) can handle the current flow (and heat dissipation) that you require at that V_GS.

IRF540 seems like a suitable choice.  However, I am rather less than confident in my ability to properly analyse the myriad of spec. sheets.  I will use that until I determine it is a bad decision..


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

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

Schematic:

simulate this circuit – Schematic created using CircuitLab

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

Documentation

Sensor's Data Sheet
Library used

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

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

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

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

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

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

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

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

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

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

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


text:
Program crashes when I use Serial.println()?
I'm working with a fuzzy logic controller with Arduino, I'm trying to emulate an AC by entering inputs [temperature and humidity] using two potentiometers and the output is the AC power.
This is the basic part of the program, every thing is good, I can print the values of Temp and HU. But when I try to print the value of the Power, nothing happens, and the serial monitor displays nothing. By trial and error, I can see that Serial.println with power or any variable related to power crashes the program. What may be the reason?
    void loop()
{
    // Read Input: Temperature
    ttemp = analogRead(temp);

    Serial.println("the analoge Tempreture is ");
    Serial.println (ttemp);

    ttemp = map(ttemp, 0, 1023, 5, 65);
    ttemp = constrain(ttemp, 5, 65);

    Serial.println("the actual Tempreture is ");
    Serial.println (ttemp);
    Serial.println("-------------------------");
    delay(100);

    g_fisInput[0] = ttemp;

    // Read Input: Humidity
    hhu = analogRead(hu);
    Serial.println("the analoge Humidity is ");
    Serial.println (hhu);

    hhu = map(hhu, 0, 1023, 16, 100);
    hhu = constrain(hhu, 16, 100);

    Serial.println("the actual Humidity is ");
    Serial.println (hhu);
    Serial.println("-----------------------");
    delay(100);
    g_fisInput[1] = hhu;

    g_fisOutput[0] = 0;

    fis_evaluate();

    // Set output vlaue: Power
    int ppower1 = g_fisOutput[0];
   // Serial.println("the actual Power is ");
   // Serial.println (ppower1);
    ppower = map(ppower1,100,3000,0,255);
    ppower = constrain (ppower, 0,255);
    analogWrite(power , ppower);

   // Serial.println("the analoge Tempreture is ");
    //Serial.println (ppower);
   // Serial.println("--------------------------");

}

Too much RAM usage from all those strings in SRAM?

With the complete program we could try to compile it and possibly run it. But without the globals and setup() function, we can't really do much more than guess.

Try using the Serial.println(F("String")); instead of Serial.println("String") to utilize progmem rather than SRAM.

You should have provided your full Arduino code. Without setup() part of Arduino code, we can not exactly tell what might be wrong. Please provide it and I'll revise my answer as well.
Check if you have this code in your setup() function:
Serial.begin(9600);

9600 is baud rate and it could be any other supported baud rate(you can see those by opening a Serial monitor and clicking on 9600 baud rate on bottom right edge).
Related to to comments above, from experience and it can be easily "counted", RAM shouldn't be a problem in such short code.


text:
Executing machine code at runtime Uno
I want to create a small single threaded os for my arduino.The first thing I want to do is to allow my arduino to read a section from flash/eeprom and execute it. I have some question regarding the memory. The microcontroller is executing one command at a time from..where? Does it directly acces the flash containing the code and take every command at a time?(that would be slow) Or does it first load the entire program into sram?(also wouldn't make sense because sram is 2k while flash is 32k). Either way,if I can find in sram /flash my code( or the header to some void) then i could jump there.Am i wrong?Is it possible(to do such os)?
Something like this:
uint16_t addr=0x1234;
void (*function)(void)=addr;
function();

(or maybe with some avr like assembly code?)

The microcontroller is executing one command at a time from..where?

Flash memory directly. The AVR core can only execute instructions from Flash memory. It uses a two-bus system known as Harvard Architecture, where the Instruction Bus is connected to Flash and is used to execute instructions, and the Data Bus is connected to SRAM, EEPROM, all the peripherals, GPIO pins, etc.
It is possible to jump to any location in memory in a similar way as you have depicted, but in order to know where you first need to know the functions you want to call.  You can get the address of any function and assign it to a pointer, and then call that pointer as a function, but what would that achieve? You may as well just call the function directly and save time. Unless you want to store the addresses of those functions in an array or something to maybe associate them with a command to trigger the execution of that function. In which case you don't need anything "fancy", just pointers to the functions you want to use.

I was thinking i could execute from sd card. Just find an empty sector in flash...write there the code from sd and then jump. I believe then this is possible right?

No, you can't. You can only write to the flash memory from code executed from the bootloader portion of flash (which means the bootloader has to do it), so you can't write to flash from your program. Also you'd wear out your flash pretty quick.

Basically you are going from Arduino to AVR :) (Still can use the same HW+IDE+such, but you overgrown Arduino's limits) Next step should be download datasheat for your AVR to study and have it handy and read it (not need to understand it yet (too much info), but to have some idea, what are you going to play with)

@Majenko: "...what would that achieve?..."  Actually, its a game-changer, as can be seen using 3-instruction Forth approach discussed here.  The key is to get the bootloaded code to do it (remote store, fetch, and call instructions), but requires a generic header/hook/container into which machine code can be injected dynamically.


text:
Multiple MFRC522 RFID reader on Uno bugs
I have a problem!
I need to connect 5 MFRC522 readers on an Arduino Uno but it is not working !
With one or two MFRC522 modules it works, when I use three or more nothing works anymore... The serial reading is not working, nothing is read with more than 2 modules. I'm so sad. So tonight I need your help, tell me what is not working in my code or on my setup!
I first thought that it was the Arduino that was not delivering enough current to the modules (on the 3.3v line) but this does not seem to be the case. We added some external ATX PSU power, and connected grounds. Nothing changed.
So we had a look at the code and we believe that it is a library problem. Nobody seems to have successfully connected more than 3 MFRC522 modules. Is there really a problem in the library? How could we achieve success?
#include <SPI.h>
#include <MFRC522.h>
#include <EEPROM.h>

#define SS_PIN_1 10 // PIN SDA pour le module RFID (1)
#define RST_PIN_1 9 // PIN RESET pour le module RFID (1)
#define SS_PIN_2 8 // PIN SDA pour le module RFID (2)
#define RST_PIN_2 7 // PIN RESET pour le module RFID (2)
#define SS_PIN_3 6 // PIN SDA pour le module RFID (3)
#define RST_PIN_3 5 // PIN RESET pour le module RFID (3)
#define SS_PIN_4 4 // PIN SDA pour le module RFID (4)
#define RST_PIN_4 3 // PIN RESET pour le module RFID (4)
#define SS_PIN_5 2 // PIN SDA pour le module RFID (5)
#define RST_PIN_5 A0 // PIN RESET pour le module RFID (5)
#define RELAY_PIN A1 // Pin du signal du Relais
#define RELAY_ON 1024 // Valeur de seuil d'activation du relais
#define RELAY_OFF 0 // Valeur de seuil de désactivation du relais
#define MASTER_BUTTON_PIN A2 // Pin du bouton d'ouverture prioritaire
#define CONFIGURE_BUTTON_PIN A3 // Pin du bouton de reprogrammation des badges
MFRC522 rfid1(SS_PIN_1, RST_PIN_1);
MFRC522 rfid2(SS_PIN_2, RST_PIN_2);
MFRC522 rfid3(SS_PIN_3, RST_PIN_3);
MFRC522 rfid4(SS_PIN_4, RST_PIN_4);
MFRC522 rfid5(SS_PIN_5, RST_PIN_5);
byte tag1[4] = {0xD6, 0x92, 0xBF, 0x93};
byte tag2[4] = {0xC6, 0xA3, 0xC0, 0x93};
byte tag3[4] = {0x96, 0x58, 0x68, 0x8E};
byte tag4[4] = {0x06, 0xFB, 0xC1, 0x93};
byte tag5[4] = {0x66, 0xF3, 0x63, 0x8E};

void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid1.PCD_Init();
  rfid2.PCD_Init();
  rfid3.PCD_Init();
  rfid4.PCD_Init();
  rfid5.PCD_Init();
  Serial.println("Initialisation du système terminé, en attente de badges...");
}

void activate_relay(){
  analogWrite(RELAY_PIN, RELAY_ON);
  Serial.println("Le relay est activé");
}

void desactivate_relay(){
  analogWrite(RELAY_PIN, RELAY_OFF);
  Serial.println("Le relay est désactivé");
}

void loop() {
  if (! rfid1.PICC_IsNewCardPresent()) {
    return;
  }
  if (! rfid1.PICC_ReadCardSerial()) {
    return;
  }
  if (! rfid2.PICC_IsNewCardPresent()) {
    return;
  }
  if (! rfid2.PICC_ReadCardSerial()) {
    return;
  }
   if (! rfid3.PICC_IsNewCardPresent()) {
    return;
  }
  if ( ! rfid3.PICC_ReadCardSerial()) {
    return;
  }
   if (! rfid4.PICC_IsNewCardPresent()) {
    return;
  }
  if ( ! rfid4.PICC_ReadCardSerial()) {
    return;
  }
   if (! rfid5.PICC_IsNewCardPresent()) {
    return;
  }
  if ( ! rfid5.PICC_ReadCardSerial()) {
    return;
  }
  if (rfid1.uid.uidByte[0] == tag1[0]  & rfid1.uid.uidByte[1] == tag1[1] & rfid1.uid.uidByte[2] == tag1[2] & rfid1.uid.uidByte[3] == tag1[3]) {
    if (rfid2.uid.uidByte[0] == tag2[0]  & rfid2.uid.uidByte[1] == tag2[1] & rfid2.uid.uidByte[2] == tag2[2] & rfid2.uid.uidByte[3] == tag2[3]) {
      if (rfid3.uid.uidByte[0] == tag3[0]  & rfid3.uid.uidByte[1] == tag3[1] & rfid3.uid.uidByte[2] == tag3[2] & rfid3.uid.uidByte[3] == tag3[3]) {
        if (rfid4.uid.uidByte[0] == tag4[0]  & rfid4.uid.uidByte[1] == tag4[1] & rfid4.uid.uidByte[2] == tag4[2] & rfid4.uid.uidByte[3] == tag4[3]) {
          if (rfid5.uid.uidByte[0] == tag5[0]  & rfid5.uid.uidByte[1] == tag5[1] & rfid5.uid.uidByte[2] == tag5[2] & rfid5.uid.uidByte[3] == tag5[3]) {
          } else {desactivate_relay();}
        } else {desactivate_relay();}
      } else {desactivate_relay();}
    } else {desactivate_relay();}
  } else {desactivate_relay();}
}

I've tried the code above but it didn't work. I also tried the ReadUidMultiReader example code but only one reader is working. Both Readers are working individually but only one when I connect them. I shared the SCK, MISO, MOSI, RST, and have different SS pins.

Thank you in advance.

I don't see the code

@Mazaryk Hello ! I'm glad you'r here to help the comunity ^^.
The code has been added. Enjoy :D

You can use analog pins as digital. You don't need to use analogWrite. Also your code could be a lot shorter with arrays and for loops.

I'm working on a schematic for you, fritzing <3

@gre_gor That's a good idea indeed ! Will try it tomorrow when I go back to my local Fablab.

I have noticed that this problem is very common.
Have a look here :
https://github.com/miguelbalboa/rfid/issues/290

For convenience, here is a comment:  You wrote, “I've tried the code above but it didn't work”.   That is inadequate to convey what happened and what you wanted to happen.    Please edit your question to include a clear statement of symptoms and desired results.
Now on to an answer.
From “I'm only using 2 readers to find the correct and make it work”, I deduce that you have two readers attached.  This by itself is enough to keep the code from producing output.  Assuming those two readers identify as rfid1 and rfid2, when execution gets to if ( ! rfid3.PICC_IsNewCardPresent()), it executes return; which terminates loop() processing.  That is, execution will never get past if ( ! rfid3.PICC_IsNewCardPresent()).  To clear up that problem, remove all the code that references rfid variables other than rfid1 and rfid2 (more properly, other than whichever two you have attached).
That will entail removing 18 lines in the early part of loop(), and three lines in the big nested-if part of loop().
Here is another comment:  When you are debugging code, it makes sense to report lots of intermediate results, and to report them as soon as they are available.  Don't go through a long stack of if statements and get no output and then say it doesn't work; instead, display and check results when you first read them in.

I upvoted this question when it used to help me but now I can not un-vote it ? stange website.
The project still does not work.

“still does not work” doesn't tell what happened and what you want to happen. Please edit your question to include a clear statement of symptoms and desired results.  You edited the question to add a diagram but still just say "didn't work" instead of anything about intermediate results. ¶ The notion that you should unvote this that used to help, but now doesn't because you changed things, is perverted.  It discourages me from replying further:  If I edit my reply, then you can change your vote; so now I won't change it and probably won't reply further.  Oh well.

However, you could write a new question with a clear statement of symptoms, desired results, current code, and intermediate-values printout.

No, don't worry I won't down-vote your question, so I'm going to edit my question and make a better schematic.

Ok, great.  Printing intermediate-values probably would be the most useful item to add.  Also, the sequence of 10 if (...) {  return;  } statements is such that if any one of those tests fail, you return from loop() with no further processing on that pass.  You could instead set status variables (or status bits in a word) so at least something gets reported.

after around million of trying and trying I discovered that the correct way to connect 4 RFID RC522 is to put them in the same line on test board except SS pins and the code as usual is ReadUidMultiReader from RFID library ... like this :

yes that is how SPI works. you can read about it on wikipedia, but the topic of the question above is different. OP does know how to wire the readers. they don't ask about wiring.

This way has solved the same problem because if you don't put them in the same line on test board you don't get enough current to 2 or 3 of them.

authors: هبة الجبه جي


text:
what pins are attached to ethernet shield SD card?
I have ARDUINO ETH SHIELD 06 - Rev 03. https://www.adafruit.com/product/201
what pins are attached to Ethernet shield SD card?

Arduino communicates with both the W5100 and SD card using the SPI bus (through the ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used to select the W5100 and pin 4 for the SD card.


text:
Arduino Audio Recorder - Speed Correct but Wrong Pitch
I'm working on an audio recorder project on an Adafruit Adalogger with SAMD21 ARM-based processor using the Arduino IDE. The desired sampling frequency is 10 kHz, 12-bit resolution with an analog (MEMS) microphone. I'm saving data to an SD card in binary format.
The code I've provided below is working almost nearly exactly as desired. My only issue comes about when playing back the recorded data on my PC. The recording speed is correct if I playback at 10 kHz sampling frequency, but the pitch of the sound recorded is much too low (exactly 0.5 times what it should be). On my PC, if I playback at 20 kHz, the speed is of course 2x, but the pitch is now correct. FYI pitch and speed are related quantities, when increasing one, the other should also increase linearly (i.e. increase speed 2x, pitch should be increased 2x as well).
If I record in 8-bit resolution, I have no issues; both the playback speed and pitch are as desired. The speed/pitch issue only comes about when saving in 16-bit mode. I should note as well the Adafruit only has a 12-bit ADC, however by selecting 16-bit analog read resolution, it pads the initial four spots with zeros. My issue keeps coming back to the way in which I'm saving the data, I think it's a simple solution, but just can't seem to figure out where the mismatch is coming from.

#include <SPI.h>
#include <SdFat.h>
#include <stdint.h>

SdFat SD;
File myFile;
#define SD_CS_PIN 4

int mic = A0;
const int btnStart = 5;
const int btnStop = 6;
const int ledStart = 12;
const int ledStop = 13;
int recPressed = 0;
int stopPressed = 0;
int flag = 0;
uint16_t buf00[512]; // buffer array 1
uint16_t buf01[512]; // buffer array 2
unsigned int bufByteCount;
unsigned long recByteCount = 0L;
unsigned long recByteSaved = 0L;
byte bufWrite;

static void   ADCsync() {
  while (ADC->STATUS.bit.SYNCBUSY == 1); //Just wait till the ADC is free
}

void setup() {

  // ADC Setup
  // ---------------------------------------------------------------------------------------------------------

  // Set gain and voltage reference
  ADCsync();
  ADC->INPUTCTRL.bit.GAIN = ADC_INPUTCTRL_GAIN_1X_Val;      // Gain factor select as x1
  ADC->REFCTRL.bit.REFSEL = ADC_REFCTRL_REFSEL_INTVCC0_Val; // Internal voltage reference used

  // Set sample length and averaging
  ADCsync();
  ADC->AVGCTRL.reg = 0x00; //Single conversion no averaging
  ADCsync();
  ADC->SAMPCTRL.reg = 0x0A; //sample length in 1/2 CLK_ADC cycles Default is 3F

  // Set prescaler, resolution, and mode
  int16_t ctrlb = 0x0400; // Control register B hibyte = prescale, lobyte is resolution and mode
  ADCsync();
  ADC->CTRLB.reg =  ctrlb;

  analogReadResolution(16); //Set bit-resoltion of ADC (12-bit max)
  // ---------------------------------------------------------------------------------------------------------

  // Clock timer setup used for interrupts
  // ---------------------------------------------------------------------------------------------------------

  // Set up the generic clock (GCLK4) used to clock timers
  REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                    GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                     GCLK_GENCTRL_GENEN |         // Enable GCLK4
                     GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                     GCLK_GENCTRL_ID(4);          // Select GCLK4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  // Feed GCLK4 to TC4 and TC5
  REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                     GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                     GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  //REG_TC4_COUNT16_CC0 = 0x0087;                 // Set the TC4 CC0 register for standard audio range (22.05kHz sampling rate)
  REG_TC4_COUNT16_CC0 = 0x0095;                   // Set the TC4 CC0 register for standard audio range (20 kHz sampling rate)
  //REG_TC4_COUNT16_CC0 = 0x012B;                 // Set the TC4 CC0 register for sleep apnea range (10 kHz sampling rate)
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

  //NVIC_DisableIRQ(TC4_IRQn);
  //NVIC_ClearPendingIRQ(TC4_IRQn);
  NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
  NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

  REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
  // REG_TC4_INTENSET = TC_INTENSET_OVF;          // Enable TC4 interrupts
  // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

  REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV16 |     // Set prescaler to 16, 48MHz/16 = 3MHz
                   TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                   TC_CTRLA_ENABLE;               // Enable TC4
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization
  // ---------------------------------------------------------------------------------------------------------

  pinMode(10, OUTPUT); // DON'T change this - Hardware CS pin must be left as output for SD library functions to work correctly
  pinMode(ledStart, OUTPUT);
  pinMode(ledStop, OUTPUT);
  pinMode(btnStop, INPUT_PULLUP);
  pinMode(btnStart, INPUT_PULLUP);

  if (SD.begin(SD_CS_PIN, SPI_FULL_SPEED)) { // initialise card on SPI to 8MHz SPI bus speed
    for (int dloop = 0; dloop < 4; dloop++) {
      digitalWrite(ledStart,!digitalRead(ledStart));
      delay(100);
    }
  } else { // if error, flash LED twice per second, until reset
    while(1) {
      digitalWrite(ledStart,!digitalRead(ledStart));
      delay(500);
    }
  }
}

void loop() {

  if (digitalRead(btnStart) == LOW && recPressed == 0) {
    StartRec(); // launch StartRec method
  }
  if (digitalRead(btnStop) == LOW) {
    StopRec(); // launch StopRec method
  }

  if (flag == 1) {
    recByteCount++; // increment sample counter
    bufByteCount++;
    if (bufByteCount == 512 && bufWrite == 0) {
      bufByteCount = 0;
      bufWrite = 1;
    } else if (bufByteCount == 512 & bufWrite == 1) {
      bufByteCount = 0;
      bufWrite = 0;
    }

    if (bufWrite == 0) {
      buf00[bufByteCount] = analogRead(mic);
    }
    if (bufWrite == 1) {
      buf01[bufByteCount] = analogRead(mic);
    }
    flag = 0; // clear interrupt triggered flag
  }

  if (recByteCount % 1024 == 512 && recPressed == 1) { myFile.write(buf00,512); recByteSaved+= 512; } // save buf01 to SD card
  if (recByteCount % 1024 == 0 && recPressed == 1) { myFile.write(buf01,512); recByteSaved+= 512; } // save buf02 to SD card
}

void StartRec() { // Start recording method

  digitalWrite(ledStart,HIGH);
  digitalWrite(ledStop,LOW);
  recByteCount = 0;
  recByteSaved = 0;
  recPressed = 1;
  stopPressed = 0;
  myFile = SD.open("recordingvoice.bin", FILE_WRITE);
  REG_TC4_INTENSET = TC_INTENSET_OVF;
}

void StopRec() { // Stop recording method

  REG_TC4_INTENCLR = TC_INTENCLR_OVF;
  myFile.close();
  digitalWrite(ledStart,LOW);
  digitalWrite(ledStop,HIGH);
  recPressed = 0;
}

void TC4_Handler() { // Interrupt method
  if (TC4->COUNT16.INTFLAG.bit.OVF && TC4->COUNT16.INTENSET.bit.OVF) {

    flag = 1; // set interrupt triggered flag

    REG_TC4_INTFLAG = TC_INTFLAG_OVF;         // Clear the OVF interrupt flag
  }
}

I'm using a MATLAB script I've written to playback the data, notably v.2012 since it provides the "specgramdemo" function which I'm utilizing to visualize the spectrogram and also, but less importantly, provides playback functionality of the recording.
close all
clear all
clc

[inStr, pathStr] = uigetfile('*.bin','input files','D:');
A2 = inStr;
fid = fopen([pathStr, inStr], 'r');
% [filename, permission, machineformat] = fopen(fid)
sixteen_bit_pad = fread(fid, inf, 'uint16', 'ieee-le');
fclose(fid);
sixteen_bit_pad = sixteen_bit_pad';

% prompt = {'Enter sampling frequency for recording in Hz:'};
% dlg_title = 'Sampling Frequency';
% num_lines = 1;
% defaultans = {'10000'};

% Fs = str2double(inputdlg(prompt,dlg_title,num_lines,defaultans));
Fs = 20000;

twelve_bit = zeros(size(sixteen_bit_pad));
twelve_bit(1:1:end) = bitshift(sixteen_bit_pad(1:1:end),-4);

time = linspace(0, length(twelve_bit)/Fs, length(twelve_bit));

figure, plot(time, twelve_bit)
xlabel('Time (seconds)'); ylabel('Amplitude (12-bit Value)');
specgramdemo(twelve_bit, Fs)

If you happen to have these tools at your disposal and want to hear first-hand the mismatch, I've included a .bin file that has some voice/breathing sounds recorded. File here: Binary File

How many bytes/second are in the recorded file? eg. if you record for 10 seconds what is the file size / 10? flag should be declared volatile.

What are you using to play back the audio on the PC? Are you remembering to tell it about the difference between files containing 8-bit samples and files containing 16-bit samples? It sounds like you're trying to play back the 16-bit files with software that is expecting 8-bit samples. Are you also getting a lot of distortion on loud sounds?

@BruceAbbott Thanks Bruce, noted and will update my code to reflect such! By no means am I a programmer, still learning as I go and appreciate the quick tip. For a duration of 10.2016 seconds, I've recorded 204,032 samples. With each sample being 2 bytes length, total of 408,064 bytes. 408,064/10.2016 gives 40,000 bytes/second.

@DaveTweed, I'm using a MATLAB script I've written to playback the data, notably v.2012 since it provides the "specgramdemo" function which I'm utilizing to visualize the spectrogram and also, but less importantly, provides playback functionality of the recording. I've updated my original post to include the script. I do get some distortion yes, some "clicking" sounds in the recording and saturation of the signal with high amplitude sounds.

"For a duration of 10.2016 seconds, I've recorded 204,032 samples" - you have twice as many samples as you should have, which suggests that you are recording 2 samples per interrupt - which would mean the flag is not working as expected.

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


text:
Recording and storing Midi data with arduino and midi shield
i need help getting started on writing a sketch that would let me record and store midi data from a midi controller connected to a arduino mega through a midi shield. are there any functions in the midi library that will aid in this task?

The Arduino MIDI Library allows you to read and write MIDI messages, but only in real time.
Storing MIDI data makes sense only with timestamps, so you have to call millis() or micros() when you receive a message.
How to actually store the data is something that you have to design yourself; which data structure to use depends on what you want to do with the data later.

once i have the data stored i want to be able to play it back


text:
Do I really need Ramps 1.4 for laser engraver
I'm making 2-axis laser engraver like system. Arduino waits command from pc, on receive moves laser to next coordinate and send current coordinate to pc.
I have 3 step motors and I'm controlling them with Arduino Uno which is connected to A4988 drivers which is on breadboard. But almost all samples using Ramps. Do I miss something?

Ramps 1.4 is one of the proof of concept standards for 3D printer systems. It is a motherboard mostly runs Marlin firmware on it. I advice to to take a look at the firmware if you didn't yet. It is also supporting many motherboards, hardware.
When you open the configuration.h file in the firmware and search for this definition #define MOTHERBOARD you will be seeing many options available.
After all, the firmware is the key factor. It contains many engineering solutions in it. So, you shouldn't re-invent the wheel.
All you have to do is to adapt it with some tweaks as per your design specifications.
But, I would worry more about your motherboard (Arduino Uno)
if your design is relatively simple, using less memory and IO pins, it may be just fine. I would consider Mega 2560 instead If I were you.
Good luck with your project.


text:
Too low voltage on digital input on attiny45
I'm using one of my attiny's pins as digital input. I use it with a pulldown resistor. As input I use simple square wave generated by a separate waveform generator. igh state for square wave is 5V, low is 0V.
However, when I look at the voltage on the digital input, voltage of high state is below 2V, while low state is 0V. My arduino doesnt detect high state as "1".
Here is the code:
/*
 * Sketch for testing sleep mode with wake up on WDT.
 * Donal Morrissey - 2011.
 * ATTINY85
 */

#include <TinyWireM.h>                  // I2C Master lib for ATTinys which use USI - comment this out to use with standard arduinos
#include <LiquidCrystal_attiny.h>          // for LCD w/ GPIO MODIFIED for the ATtiny85

#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>

//uwaga na numer pinu! nie używać tego z resetem
#define STATUS_PIN  1
#define IN_PIN     4
#define LOOP_TIME 5000
#define TIMEOUT 100

#define GPIO_ADDR     0x27
LiquidCrystal_I2C lcd(GPIO_ADDR, 16, 2); // set address & 16 chars / 2 lines

/* f_wdt is a flag used to monitor watchdog status */
volatile int f_wdt=1;

/***************************************************
 *  Name:        ISR(WDT_vect)
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Watchdog Interrupt Service. This
 *               is executed when watchdog timed out.
 *
 ***************************************************/
ISR( WDT_vect){
  if(f_wdt == 0){
    f_wdt=1;
  }
  else{
  }
}

/***************************************************
 *  Name:        enterSleep
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Enters the arduino into sleep mode.
 *
 ***************************************************/
void enterSleep(void)
{
  lcd.clear();
  lcd.print("Asleep...");

  /* Enable the WD interrupt (note no reset). */
  WDTCR |= (1<<WDIE);

  set_sleep_mode( SLEEP_MODE_PWR_DOWN );   /* EDIT: could also use SLEEP_MODE_PWR_DOWN for lowest power consumption. */
  sleep_enable();
  // Status pin goes low
  digitalWrite( STATUS_PIN, LOW );
  /* Now enter sleep mode. */
  sleep_mode();

  /* The program will continue from here after the WDT timeout*/
  sleep_disable(); /* First thing to do is disable sleep. */

  // Status pin goes low
  digitalWrite( STATUS_PIN, HIGH );

  /* Re-enable the peripherals. */
  power_all_enable();

  /* Disable the WD interrupt */
  WDTCR &= ~_BV(WDIE);
}

/***************************************************
 *  Name:        setup
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Setup for the serial comms and the
 *                Watch dog timeout.
 *
 ***************************************************/
void setup()
{
  /*  Setup the LCD */
  lcd.init();                           // initialize the lcd
  lcd.backlight();                      // Print a message to the LCD.
  lcd.clear();
  lcd.setCursor(0,0);

  /* Inform the user about initialization process */
  lcd.print("Initializing...");
  delay(1000);

  /* Config pins */
  pinMode( IN_PIN, OUTPUT );
  pinMode( STATUS_PIN, OUTPUT );

  /* Initialize pins */
  digitalWrite( STATUS_PIN, HIGH );

  /*** Setup the WDT ***/

  /* Clear the reset flag of watchdog interrupts, so that they are available again. */
  MCUSR &= ~(1<<WDRF);

  /* Enable configuration changes
   */
  WDTCR |= (1<<WDCE) | (1<<WDE);

/*
WDP3       WDP2    WDP1     WDP0         Number of WDT     Typical Time-out at
                                         Oscillator Cycles     VCC = 5.0V
  0         0      0        0             2K (2048) cycles       16 ms
  0         0      0        1             4K (4096) cycles       32 ms
  0         0      1        0             8K (8192) cycles       64 ms
  0         0      1        1            16K (16384) cycles    0.125 s
  0         1      0        0            32K (32768) cycles    0.25 s
  0         1      0        1            64K (65536) cycles    0.5 s
  0         1      1        0            128K (131072) cycles 1.0 s
  0         1      1        1            256K (262144) cycles 2.0 s
  1         0      0        0            512K (524288) cycles 4.0 s
  1         0      0        1            1024K (1048576) cycles 8.0 s
*/
  /* set new watchdog timeout prescaler value */
  WDTCR =  0<<WDP3 | 1<<WDP2 | 1<<WDP1 | 0<<WDP0 ;

  lcd.clear();
  lcd.print("Initialisation");
  lcd.setCursor(0,1);
  lcd.print("complete.");
  delay(500);
}

/***************************************************
 *  Name:        enterSleep
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Main application loop.
 *
 ***************************************************/
void loop()
{
  if(f_wdt == 1)
  {
    lcd.clear();
    lcd.print("Awake!");
    int start = millis();
    int end = 0;
    bool movement = false;
    int read = 0;
    lcd.clear();
    lcd.print( "Executing loop" );
    do{
      if( read = digitalRead(IN_PIN) ){
        lcd.setCursor(0,1);
        lcd.print( "Read value: " );
        lcd.print( read );

        //Wait for falling edge
        while( digitalRead(IN_PIN) != 0 );
        //Start counting time
        int endMov = 0;
        int startMov = millis();
        do{
          if( digitalRead( IN_PIN ) ){
            movement = true;
          }
          endMov=millis();
        }while( endMov - startMov < TIMEOUT && !movement );
            if( endMov - startMov >=LOOP_TIME ){
              lcd.clear();
              lcd.print("Time is out");
            }

            else{
              lcd.clear();
              lcd.print("Movement detected");
              lcd.setCursor(0,1);
              lcd.print( "Time: " );
              lcd.print( end-start );
            }
      }
      end=millis();
    }
    while( (end-start<LOOP_TIME) && !movement );

    if( end-start>=LOOP_TIME ){
      lcd.clear();
      lcd.print("Time is out");
    }

    else{
      lcd.clear();
      lcd.print("Movement detected");
      lcd.setCursor(0,1);
      lcd.print( "Time: " );
      lcd.print( end-start );
    }
    delay(1000);
    /* Don't forget to clear the flag. */
    f_wdt = 0;
    /* Re-enter sleep mode. */
    enterSleep();
  }
  else
  {
    /* Do nothing. */
  }
}

Does anyone has any idea why is it so?

Ideas, yes, but since you don't tell name or model number of  waveform generator, or the value of the pulldown resistor, or which ATtiny, or which pin, or if anything else is in the circuit, who can say?  Please edit your question to include that information.

What value pulldown resistor? What is the output impedance of your waveform generator?

First thing in my mind would be to check/change the pull-down resistor value.
The pull-down resistor must have a larger resistance than the impedance of the logic circuit, or else it might be able to pull the voltage down by too much and the input voltage at the pin would remain at a constant logical low value
Read more here.

I changed the pull down resistor to 360 ohms and 100k ohms, but it did not change a thing, unfortunately. Voltage levels are still too low.

Typical pull-down resistors 4.7K and 10K. But, it is also depending on your device connected to the pin. Do you know the impedance of your waveform generator?
And another thing is how you set-up the pin in your firmware? Can you show us your code?

Impedance of my waveform generator is close to 0 ohms. I edited the post, code is available now

Are you sure you use that Pin as INPUT;
This line;
pinMode( IN_PIN, OUTPUT );
should be
pinMode( IN_PIN, INPUT );

Oh my god, this is embarassing... Thanks:) Now it works

Good to hear that, I know this feeling, you are not alone ;)

But last note, I hope you are using some sort of protection for your input since the wave generator output can swing also in negative area which is not good for your uC. 1N4733A from input to GND will protect from this. And additionally a serial resistor (1K) to your generator would be good for your input.

So you suggest to put a zener diode between input pin and gnd?

Yes, it is zener diode, Anode to GND and Cathode to input #4.
Note that: please confirm my comment as your answer.

if the generator is close to zero ohms, how much current would such a diode arrangement draw from the generator?

@Dandavis: Since the zener diode will dissipate through the 1k resistor, it won't be more than appx. 5 mA.
We can  also replace that resistor with equivalence resettable fuse.


text:
Blinking cursor on Arduino is inconsistent and misses inputs
I am trying to write a part of a program that prints time and allows the user to move a cursor across it. I have the following code, but there are a few issues with it.
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
#include <Time.h>
#include <TimeLib.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16,2);
  setTime(12,30,15,0,0,0);
}
int col = 0;

void loop() {
  uint8_t buttons = lcd.readButtons(); //create readable buttons
  char time_out[16];
  lcd.setCursor(0,0);
  sprintf(time_out, "%02u:%02u:%02u",hour(),minute(),second());
  lcd.print(time_out);
  lcd.setCursor(col,0);
  lcd.blink();
  delay(100);
  if (buttons) {
    lcd.clear();
    if (buttons & BUTTON_RIGHT) {
      col += 1;
    }
    if (buttons & BUTTON_LEFT) {
      col -= 1;
    }
  } //buttons
}

If you upload this to your board, you can tell that the blinking is highly irregular, not at all aesthetically pleasing.
You'll also notice that sometimes, when pressing left/right, the input isn't registered.
I suspect this has to do something with the delay() function used, which pauses the entire program.
I looked into the following method, but this does not work when needing to print something in a loop (as the time library requires).
Any idea how I could make this work better (regular blinking times and no miss of user input)?
Thanks a lot!

the code needs to check the variable col to assure it is inside the valid range before incrementing/decrementing.  This is to avoid the cursor being set outside the valid range.  I.E. if the valid range is 0...15 then check col >0 before decrementing and check col<15 before incrementing.

I think the statement lcd.clear() turns all the LEDs off,  that does not seem like a good idea

strongly suggest using a timer interrupt to handle the blinking, using a keypress interrupt for the cursor motion.

I don't have the hardware to test but, it should be more or less like this;
(I have also normalized the code into several functions for better readability.)
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
#include <Time.h>
#include <TimeLib.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

unsigned long timerBlink; //Required for periodic blinking
int intervalBlink = 100;

void setup() {
    lcd.begin(16, 2);
    setTime(12, 30, 15, 0, 0, 0);
    timerBlink = 0;
}
int col = 0;

void loop() {
    readButtons();
    printDate();
    if (millis() - timerBlink > intervalBlink) {
        blink();
    }
}

void readButtons() {
    uint8_t buttons = lcd.readButtons(); //create readable buttons
    if (buttons) {
        lcd.clear();
        if (buttons & BUTTON_RIGHT) {
            col += 1;
        }
        if (buttons & BUTTON_LEFT) {
            col -= 1;
        }
    } //buttons
}

void blink() {
    lcd.setCursor(col, 0);
    lcd.blink();
    timerBlink = millis();//Start timer for intervalBlink
}

void printDate() {
    char time_out[16];
    lcd.setCursor(0, 0);
    sprintf(time_out, "%02u:%02u:%02u", hour(), minute(), second());
    lcd.print(time_out);
}

Instead of blocking delay function, using timeout with timestamp is a better practice.


text:
Do I Have to Change Internal Interrupt Setups when I Change Clock Speed?
Do I Have to Change Internal Interrupt Setups when I Change Clock Speed? The reason I ask is because I am trying to modify this code:
https://github.com/DccPlusPlus/BaseStation/blob/master/DCCpp_Uno/DCCpp_Uno.ino (Beginning at Line 289)
so that if will work on an ATmega328P-derivative board running at 3.3V and 8 MHz. I need the waveforms to be generated at the same speed, so is there anything I have to change? The original code is written for a 16 MHz uno or mega.

Yes, you will have to recalculate all the timer compare values (halve them for half the clock speed?)

Halve the values and round down: 3199 → 1599, etc.

The equation for timer period is given by the following formula, where N is the value of the prescaler, TOP is the value given by either MAX (i.e. 0xFF, 0xFFFF) or the value in register OCRnx, and f is the frequency of the I/O clock.

If you're using phase-correct or phase- and frequency-correct mode, the factor (TOP+1) in the formula above should be replaced by 2 × TOP.

It's not TOP. It's either 2 × TOP (in the phase-correct and phase-and-frequency-correct PWM modes) or TOP + 1 (in any other mode).


text:
How to break connection HM10 Bluetooth?
I have 2 HM10 Bluetooth modules connected to 2 Arduino Teensy running the following code.
void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  // If the baudrate of the HM-10 module has been updated,
  // you may need to change 9600 by another value
  // Once you have found the correct baudrate,
  // you can update it using AT+BAUDx command
  // e.g. AT+BAUD0 for 9600 bauds
}

void loop() {
  char c;
  if (Serial.available()) {
    c = Serial.read();
    Serial1.println(c);
  }
  if (Serial1.available()) {
    c = Serial1.read();
    Serial.print(c);
  }
}

By pairing them using the AT commands I was able to send messages back and forth by writing to Serial1. However now when I try to send AT commands it will just send the string to the other module instead of replying OK etc. How do I break the connection and make the AT commands work again?
The tutorial I used to pair the modules.

Give us the final set of commands you sent to the Bluetooth modules to get them to pair and then forward your input to each other.

I'm voting to close this question as off-topic because it is about the command set of the HM10 module, not Arduino.

I'd say this is something you only encounter on Arduinos (Serial.println(), Arduino Teensy and etc.) so I think this suits Arduino SE. Neither can I think of a better SE community to answer this question.

I was able to break the connection with:
AT
The data sheet says to use AT+PWRM1, but it didn't work for me. Instead the above command dropped the connection to the remote device.
From the Datasheet:

Execute “AT+PWRM1” command, Module will auto into sleep mode when
power on or disconnect from remote device.

To Break Connection via BT Commands, I do the following (programmatically):
command 1: AT
command 2: AT+IMME1
When the BT is in Work Mode it does not recognize regular BT commands.  The exception to this is the AT command by itself. But, it must be followed by another command (#2) within the Supervision Timeout Period which is fairly quick. IMME1 takes the BT back to AT Mode where it is no longer connected and will recognize your AT[+...] commands. If the Save Setting is enabled, it will attempt auto-reconnect too quickly...

From the device datasheet:
System KEY function (PIO0) if Low > 1000ms:
7.3.1 If Module is in sleep mode Module will wake up immediately, if AT+NOTI value is “1”, module will send “OK+WAKE” string through UART.
7.3.2 If Module has already connected to remote device Module will disconnect from remote device.
7.3.3 If Module is standby mode Module will reset to default configuration. Then restart.

Somehow I ended up in such an endless auto-reconnect loop after activating AT+ROLE1 without setting AT+IMME1 first. Nothing seemed to help, not even pulling PIO0 low for 1s. I still don't even know which device my HM-10 was connecting to. It just autoconnected to something on boot...
The only way I could find to break out of this endless loop  was using this sketch below. The trick was that I had to wait for "OK" response after "AT" before issuing the follow-up command "AT+RENEW" to restore factory settings.
#include <SoftwareSerial.h>

SoftwareSerial BTserial(8, 9);

void waitForOK()
{
  while (!BTserial.available());

  char c = BTserial.read();
  Serial.write(c);
  c = BTserial.read();
  Serial.write(c);
}

void setup()
{
  Serial.begin(9600);
  BTserial.begin(115200); // fw v700 changed default to 115200, otherwise use 9600
  Serial.println("BTserial started at 115200");

  BTserial.write("AT");
  waitForOK();
  BTserial.write("AT+RENEW");
  waitForOK();
  BTserial.write("AT+IMME1");
  waitForOK();
}