text:
Program doesn't read memory well
My program does not read the contents of the memory card, in this case the file "objects.txt". What I wanted to do was: the program reads the objects contained in the text file and allocates the table, then organizes the table alphabetically.
Something is escaping me. Another thing, how do I put a function recognizing if the user pressed a button and if pressed, the program continues?
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
int x = 0;
String files, memo, memo1;
int sizef = 0;
int sizef1 = 0;
int sizef2 = 0;
int y = 0;
int z = 0;

struct objeto_celeste_s {
  char nome[20];
  float ar;
  float dec;
};
typedef struct objeto_celeste_s objeto_celeste;

char * tab1 [6];
int myCompareFunction (const void * arg1, const void * arg2) {
  return strcmp (*(char **) arg1, *(char **) arg2);
}

File root;
File file;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

char * list[] = {"1.Modo Normal    ", "2.Modo Teste    ", "3.Modo GoTo     ", "4.Modo Manual  "};

// read the buttons
int read_LCD_buttons() {
  adc_key_in = analogRead(0);
  if (adc_key_in > 1000) return btnNONE;
  if (adc_key_in < 50)   return btnRIGHT;
  if (adc_key_in < 250)  return btnUP;
  if (adc_key_in < 400)  return btnDOWN;
  if (adc_key_in < 450)  return btnLEFT;
  if (adc_key_in < 650)  return btnSELECT;
  return btnNONE; // when all others fail, return this...
}

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println ("Welcome!");
  Serial.println ("Selecione um modo no lcd.");
  lcd.begin (16, 2);
  lcd.setCursor (0, 0);
  lcd.print ("  Selecione um");
  lcd.setCursor (0, 1);
  lcd.print ("      modo    ");
  delay (1000);
  lcd.clear ();
  lcd.setCursor(0, 0);
  lcd.print(">");
  lcd.println(list[0]);
  lcd.setCursor(0, 1);
  lcd.print (" ");
  lcd.println(list[1]);
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
}

void loop() {
  lcd_key = read_LCD_buttons();  // read the buttons
  switch (lcd_key) {
    // depending on which button was pushed, we perform an action
    case btnRIGHT:
      break;
    case btnLEFT:
      break;
    case btnUP:
      if (x == 1) {
        x--;
        lcd.clear ();
        lcd.setCursor(0, 0);
        lcd.print(">");
        lcd.println(list[0]);
        lcd.setCursor(0, 1);
        lcd.print (" ");
        lcd.println(list[1]);
      }
      break;
      if (x == 3) {
        x--;
        lcd.clear ();
        lcd.setCursor(0, 0);
        lcd.print(">");
        lcd.println(list[2]);
        lcd.setCursor(0, 1);
        lcd.print (" ");
        lcd.println(list[3]);
      }
      break;
    case btnDOWN:
      if (x == 0) {
        x++;
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(">");
        lcd.println(list[1]);
        lcd.setCursor(0, 1);
        lcd.println("                ");
      }
      break;
      if (x == 2) {
        x++;
        lcd.clear ();
        lcd.setCursor(0, 0);
        lcd.print(">");
        lcd.println(list[3]);
        lcd.setCursor(0, 1);
        lcd.println("                ");
      }
      break;
    case btnSELECT:
      if (x == 0) {
        lcd.clear ();
        lcd.print ("Modo Normal");
        Serial.println ("Selecionou o modo normal!");
        delay (1000);
        if (SD.exists("objectos.txt")) {
          Serial.println("O ficheiro 'objetos' foi encontrado!");
          lcd.clear ();
          lcd.setCursor (0, 0);
          lcd.print ("Modo Normal");
          delay (1000);
          file = SD.open("objectos.txt", FILE_READ);
          if (file) {
            while (file.available()) {
              String line = file.readStringUntil('\n');
              sizef++;
            }
          } else {
            //se houver erro a abrir o ficheiro
            Serial.println("Erro a abrir o ficheiro 'objectos.txt'.");
          }
          objeto_celeste *tab = (objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));
          Serial.print ("Contados ");
          Serial.print (sizef);
          Serial.println (" objetos no ficheiro objectos.txt.");
          if (tab == NULL) {
            lcd.clear ();
            lcd.print ("Erro a alocar memoria");
            Serial.println ("Erro a alocar memória");
            while (1) { };
          } else {
            Serial.print ("Memória alocada para ");
            Serial.print (sizef);
            Serial.println (" objectos.");
            lcd.setCursor (0, 1);
            lcd.print ("Alocados ");
            lcd.print (sizef);
            lcd.print (" obj");
          }
          file.close();
          char * line1 = (char*) malloc(15);
          file = SD.open("objectos.txt", FILE_READ);
          if (file) {
            Serial.println ("Carregando informação para a memória:");
            while (file.available()) {
              if (file.read() == '\n') {
                char * justafun = strtok (line1, " "); //divide em tokens
                while (justafun != NULL) {
                  if (y == 0) {
                    strcpy (tab[sizef2].nome, justafun);
                    Serial.print ("[");
                    Serial.print (sizef2);
                    Serial.print ("] ");
                    Serial.print(tab[sizef2].nome);
                    Serial.print (" ");
                    y++;
                  }
                  if (y == 1) {
                    tab[sizef2].ar = atof (justafun);
                    Serial.print (tab[sizef2].ar);
                    Serial.print (" ");
                    y++;
                  }
                  if (y == 2) {
                    tab[sizef2].dec = atof (justafun);
                    Serial.println (tab[sizef2].dec);
                    sizef2++;
                    y = 0;
                  }
                  justafun = strtok (NULL, " ");
                }
              }
            }
          }
          file.close ();
          delay (1500);
          lcd.clear ();
          Serial.println ("Proceda ao alinhamento manual do telescópio.");
          lcd.setCursor (0, 0);
          lcd.print ("Proceda ao ");
          lcd.setCursor (0, 1);
          lcd.print ("Alinhamento man.");
          Serial.println ("Depois de o alinhamento estar concluido, pressione o botão Select para prosseguir o programa.");
          //colocar aqui função para reconhecer quando pressiona select
          if (Serial1.available()) {
            int inByte = "V"; //Se o alinhamento está concluido, 0 para não e 1 para sim
            Serial1.write (inByte);
          }
          while (!Serial1) {
            if (Serial1.available()) {
              int inByte = "V";
              Serial1.write (inByte);
              int inByte1 = "e";
              Serial1.write (inByte1);
            }
          }
          delay (1000);
          Serial.println ("Tabela ordenada alfabeticamente:");
          qsort (tab->nome, sizef, sizeof (char *), myCompareFunction);
          for (int i = 0; i < sizef; i++)
            Serial.println (tab[i].nome);
          delay (1000);
          lcd.clear ();
          lcd.print ("Carregue Select");
          lcd.setCursor (0, 1);
          lcd.print ("Para modo manual");
          Serial.println ("Carregue em Select para ir para o modo manual e assim continuar com o programa.");
        } else {
          Serial.println ("O ficheiro 'objetos' não existe.");
          lcd.clear ();
          lcd.print ("Erro nao encontrado");
          delay (2000);
          while (1) { };
        }
      }
      if (x == 1) {
        lcd.clear ();
        lcd.print ("Modo Teste");
        Serial.println ("Selecionou o modo teste!");
        delay (2000);
        if (SD.exists("teste.txt")) {
          Serial.println("O ficheiro 'teste.txt' foi encontrado!");
          lcd.clear ();
          lcd.setCursor (0, 0);
          lcd.print ("Modo Teste");
          lcd.setCursor (0, 1);
          lcd.print ("Ficheiro encontrado");
          delay (2000);
          file = SD.open("teste.txt", FILE_READ);
          if (file) {
            while (file.available()) {//ler o ficheiro
              String line = file.readStringUntil('\n');
              sizef++;
            }
            files = "Contados " + String (sizef) + " objetos no ficheiro teste.txt.";
            Serial.println (files);
            objeto_celeste *tab = (objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));
            memo = "Alocados " + String (sizef) + " obj  ";
            memo1 = "Memória alocada para " + String (sizef) + " objetos.";
            if (tab == NULL) {
              lcd.clear ();
              lcd.print ("Erro alocar memoria");
              Serial.println ("Erro a alocar memória");
              while (1) { };
            } else {
              Serial.println (memo1);
              lcd.setCursor (0, 1);
              lcd.print (memo);
            }
            file.close();
          } else {
            //se houver erro a abrir o ficheiro
            Serial.println("Erro a abrir o ficheiro 'teste.txt'.");
          }
        } else {
          Serial.println ("O ficheiro 'teste.txt' não foi encontrado.");
          lcd.clear ();
          lcd.print ("Erro nao encontrado");
          delay (2000);
          while (1) { };
        }
      }
      break;
    case btnNONE:
      break;
  }
  delay (200);
}

You are never using anything of the content oft objects.txt. in the first read you only count the lines in the file and in the second read loop you only do something, when a newline is read, nothing else

Thank you, so in the second read i should do what?

How about actually reading the lines you counted previously and then extracting the data you need from them.

How i do that? :/

Read bytes into a buffer with the read() function and then use the data. Since you havent described what kind of data you have in the file, we cannot help you doing this

How come that you have this big program with two loops for reading from a file but don't know how to read a file? Is this really your code?

Yes, it's my code. My data is "name  ar coordenates dec coordenates" ex: Alnitak 05h40m45.5s -01°56'34"

My english is not good enough, chrisl. But yes, i know how to read a file, ofc!

In first loop i want to know how many lines of text i have, so i do a loop and a container o increase loop for loop, in second loop i want to divide date lines in tokens and save that token in the respective tab.

@1manonearth, your code is very poorly indented. ... most of it is just a blob of text ... it is difficult to follow the program flow because of the way it is. ... it requires reformatting before it can be looked at .... most people do not have the time to format your code so that it can be debugged .... you may get a good answer if you spend some time and clean up your code

here is an example of properly formatted code ... https://arduino.stackexchange.com/questions/51944/sending-data-from-webserver-to-arduino

I would say you can't add a button that restarts/continues the program. Because of all the delay(...) in your code. The arduino chip cant read your input and your button, while it is in a delay mode and hence no reading from the button. Read more about non-blocking delay
You need to keep the main loop method ongoing so the microcontroller-cpu can do it's work. Instead of waiting in a delay loop, doing nothing.
So don't use any delay, they are good for beginner to jump start into Arduino.


text:
ArduCAM OV2640 and microSD card module -- SPI problems
So what I'm trying to do is use the ArduCAM OV2640 (2MP Mini) to take a timelapse. Of course the first thing I have to do it to get it to take a picture and write it to an SD card. The thing is, the camera works fine by itself, however when I hook up the SD card something happens where the SPI no longer works (I have a general understanding of how SPI works -- not a highly technical understanding though).
So my main question is if it's possible for a device using SPI to 'use up' the entire SPI bus so that other peripheral devices can't interact with the microcontroller?
And if so, is there any software or way to visualize this? Like something that monitors the SPI bus?
And as for how to actually fix the problem, would it be practical to use a shield with a built in SD card module? Or use a logic gate to determine which device to allow access?
I really don't have the greatest understanding of this, so any help would be appreciated.
EDIT:
I'm using this camera module with this sd card module. As for my wireup, the camera follows as below:
The common pins between the SD card module and camera are VCC,GND,MISO (pin 12) , MOSI (pin 11), and SCK (pin 13). I have an individual CS pin for each.

What exactly are the used modules and your wireup? You could maybe have the same problem as described in https://arduino.stackexchange.com/questions/43707/multiple-spi-device/43709.

I'll take a look at the link you referenced, and I have updated my post with wireups/modules. Also, should I be using resistors?

In this case, I don't think that a device is "using SPI to 'use up' the entire SPI bus so that other peripheral devices can't interact with the microcontroller". I think that your problem probably lies with how your SD card is connecting via the SPI bus.
The problem is that a lot of Serial Peripheral Interface (SPI) devices, particularly the cheaper ones, don't properly put the MISO pin into high-impedance when SS is pulled high.
I had almost exactly this situation with one of my projects. I eventually resolved it by placing a tri-state buffer in the MISO line for each of the SPI devices.
In that case, I used a 74HC125 (4-channel tri-state buffer).
This is the page on Better SPI Bus Design in 3 steps that finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).

This is very common with SD cards. I always use a separate SPI bus for SD cards (and of course an MCU with multiple SPI buses).

@Majenko I thought arduino only had 1 spi bus?

@LukeThistlethwaite Many Arduino branded boards have only one SPI bus. There are a myriad of other options though, some with many SPI busses (one I use regularly has 4 busses).

@Majenko My bad, I just thought that you were referencing an arduino board since, after all, this is arduino.stackexchange.com

@LukeThistlethwaite There are Arduino boards with multiple SPI busses.Generally the ARM based boards like the Arduino Due.

@LukeThistlethwaite Personally, though, I always use chipKIT boards (PIC32) since I am a PIC32 engineer.

source: Stack Exchange

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

sort: votes


text:
Get IR Signal and its strength
Using an IR sensor, how can I get and decode signals from other IR devices? I've seen the IRRemote library and its forks, but it doesn't fulfill my second requirement which is that I need to be able to tell the signal strength of the IR signal.
In addition, do I have to use a higher-end TSOP module? Or could I just use one of these?
Thank you!

An IR signal is modulated. To understand the data you need to demodulate the signal. The simplest way is with an IR receiver module.  However they condition the signal into a digital signal - it's impossible (on the majority of modules) to get the signal strength.
The devices you link to are IR Photodiodes. They form the optical receiver portion of the IR modules. You need to couple them with some form of demodulating system - either in hardware or, if your MCU is powerful enough, in software.  However, you can get at the raw analog voltages that the photodiode generates to get a signal strength value.
So you have either an easy time of it but no signal strength, or signal strength but a very hard job of interfacing.
So why not take the best bits of both?  Use an IR module to demodulate the signal and give you the data, and next to it use a photodiode and op-amp (to boost the tiny signal) to give you the raw optical intensity?  Yes, it would cost you more, and the circuitry would be more complex, but it's really the only way that you can do it without using specialist modules.
But of course, it begs the question: why do you really want to get this kind of information? Of what use can it be? The "signal strength" is of little benefit since there are so many factors that influence it - incidence angle, distance, transmitter battery voltage, etc.

I want to be able to estimate distance. I was hoping to be able to create something like Pololu's IR Beacon because to buy one is way out of my price range.

Do you think I could build one with 360 degree vision + demodulation for under $5, or is it hopeless ;)?

If all you care about is the distance and there is no data in the signal then yes, you can just shine infra-red light at a photodiode and the generated voltage will be proportional to the distance. It's crude, but works.

But I probably couldn't with a signal?

As in the output of a remote control? Not easily, no.

The pololu beacons doesn’t measure distance. Only direction as far as I can see.

Unmodulated infrared light measured with a simple photodiode would not give you reliable distance measuring dependent in the circumstances. For example if you have too much sunlight, the diode will not make a difference between the suns IR and the beacons IR light. In direct sunlight this also might stop working at all. Under controlled circumstances this might work with a relative low precision (depends also on the noise in your analog signal.

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


text:
Communication between 2 Bluetooth modules
I successfully connected two Bluetooth modules, HC-05 and HC-06 like on this website:
http://www.martyncurrey.com/connecting-2-arduinos-by-bluetooth-using-a-hc-05-and-a-hc-06-pair-bind-and-link/
I have an Arduino Nano that's the slave (HC-06) and an Arduino Mega that is the master (HC - 05) and there's is the code for both of them:
Reveiver - Master
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX | TX
String Data = "";
void setup() {
    Serial.begin(9600);
    mySerial.begin(9600);
}

void loop(){
    while (mySerial.available()){
        Serial.println(mySerial.read())
    }
}

Sender - Slave
#include <SoftwareSerial.h>
SoftwareSerial BTserial(11, 10); // RX | TX

int c = 100;

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

void loop(){
     BTserial.println(c);
}

I tried
BTserial.write(c)

and doesn't work either, I receive numbers like 245,255. And when I change the data that I'm sending the numbers are different, so I know that they are communicating, I think it's a variable problem, but I tried a bunch of codes of the internet that supposedly work, but it doesn't seem to work for this case.

use write() to write a byte to Bluetooth and to Serial Monitor

A Mega has 4 hardware serial interfaces. Why are you using software serial?

look at the bytes sent     int send=BTserial.write(c);    c is not a single byte, and I am not sure how it reacts to 4 byte int.   you could also change it to BTserial.write(100); and see if that changes anything

println prints the int variable c as string "100" with /r/n at the end. And you read it as bytes with read and print the bytes as numbers with new line at the end. So you get ascii values of 1, 0, 0, \r and \n.
use write() to write a byte to Bluetooth and to Serial Monitor

How could I solve the problem? If i use the write function do I have the same problem?

When forwarding serial traffic through the Arduino you have to use only the read() and write() functions, not the print() functions.


text:
Why does Serial.print print only a value for 0-84 for a 100 integer array?
int a[100],i;
void setup() {
  Serial.begin(9600);
}

void loop() {
  for(i=0; i<100; i++) {
    a[i] = i;
    Serial.println(a[i]);
  }
  exit(0);
}

It's because you're using exit(0).  That turns off interrupts and goes into an infinite loop. However, serial printing is first placed into a buffer, and each character is then removed from that buffer in turn and sent out through the serial port.
That's all fine, up until the end when you use exit(0);, and what is left in the serial buffer to send never gets sent because interrupts are disabled.
There is never really any cause to use exit() on a microcontroller - after all, where can it "exit" to? There's no OS to exit to. So it does the next best thing which is as close to doing nothing as reasonably possible.
Instead, if you want to "stop" your program you should use a simple while(1); which will allow interrupts to still trigger.
Alternatively, if you really want to use exit(), you should flush the serial first:
Serial.flush();

That function will block until the transmit buffer has been fully emptied by the interrupt and the last byte has left the UART's TX shift register.

And from this answer (assuming more than 1000 bytes of RAM) the UART's buffer will be 64 bytes, which is just enough to hold the remaining 15 numbers (two bytes + CR + LF each) with four bytes left over.

I wouldn't say that one shouldn't call exit() on a microcontroller. Rather, one shouldn't call a simple infinite loop exit(), suggesting it's a proper POSIX function.


text:
How to stop a loop when using attachInterrupt to catch the change of a button
This what the program does:

There is 1 button to start/stop the engine, when the motor is running
  the green LED will go on, when stopped the red LED is on. The second
  button is used to change the direction of the DC-motor. When the
  temperature is above 20° the motor will stop and the servo motor will
  go to the position of the red LED. Otherwise the servo motor is in a
  neutral position. When the engine is running there a music playing that should sound as a car.

So what my problem is if I pressed the button to stop the DC-motor but the music is still playing it won't stop. I read something about a break. Can you combine this with the attachInterrupt()? I also found something called interrupts() and noInterrupts(). What do I need to so when I pressed the button the DC-Motor directly stops and the led turns red?
The init
#include <Servo.h>
#include "notebook.h";
#include "themes.h";

const int input1OfTheDCMotor = 9;
const int input2OfTheDCMotor = 10;
const int pwmInputOfTheDCMotor = 6;
const int buttonToStartStopTheDcMotor = 2;
const int buttonToShowToChangeTheDirectionOfTheDCMotor = 3;
const int greenLed = 12;
const int redLed = 8;
const int tempSensor = A0;
const int servoPin = 11;
Servo servo;

volatile byte stateOfTheButtonToStartStopTheDCMotor = LOW;
bool isRunning = LOW;
bool changeDirection = LOW;
bool isEngineSoundsPlaying = HIGH;

The setup()
void setup() {
  //Leds setup
  pinMode(greenLed, OUTPUT);
  pinMode(redLed, OUTPUT);
  digitalWrite(redLed, HIGH);
  //buttons
  pinMode(buttonToStartStopTheDcMotor, INPUT);
  pinMode(buttonToShowToChangeTheDirectionOfTheDCMotor, INPUT);
  //DC motor
  pinMode(input1OfTheDCMotor, OUTPUT);
  pinMode(input2OfTheDCMotor, OUTPUT);
  digitalWrite(input1OfTheDCMotor, LOW);
  digitalWrite(input2OfTheDCMotor, HIGH);
  //pwm signal
  pinMode(pwmInputOfTheDCMotor, OUTPUT);
  //Servo
  servo.attach(servoPin);
  //interrupts
  attachInterrupt(digitalPinToInterrupt(buttonToStartStopTheDcMotor), readTheChangeToStartStop, RISING );
  attachInterrupt(digitalPinToInterrupt(buttonToShowToChangeTheDirectionOfTheDCMotor), readTheChangeToChangeDirection, RISING );
}

The loop()
void loop() {
  int valueOfTheSensor = analogRead(tempSensor);
  float voltage = (valueOfTheSensor / 1024.0) * 5.0;
  float temp = (voltage -0.5) * 100;
  if (temp >= 20.00)
    isRunning = LOW;
  }
  changeTheStateOfTheLights(isRunning);
  startTheDCMotorAndStopIt(isRunning);
  changeTheDirectionOfTheDCMotor(changeDirection);
}

The function readTheChangeToStartStop():
void readTheChangeToStartStop () {
  isRunning  = !isRunning;
  changeTheStatusOfTheEnginePlaying();
}

The function readTheChangeToChangeDirection():
void readTheChangeToChangeDirection () {
  changeDirection = !changeDirection;
}

The function changeTheStatusOfTheEnginePlaying():
void changeTheStatusOfTheEnginePlaying (){
  if (isRunning == HIGH){
    isEngineSoundsPlaying = HIGH;
  } else {
    isEngineSoundsPlaying = LOW;
  }
}

The function changeTheStateOfTheLights():
void changeTheStateOfTheLights(bool stateOfLight) {
  digitalWrite(greenLed, stateOfLight);
  digitalWrite(redLed, !stateOfLight);
}

The function startTheDCMotorAndStopIt():
void startTheDCMotorAndStopIt(bool isRunning){
  if (isRunning == HIGH) {
    digitalWrite(pwmInputOfTheDCMotor, HIGH);
    playCarMusicStart();
    changeToNeutral();
  } else {
    digitalWrite(pwmInputOfTheDCMotor, LOW);
    changeToRedLight();
  }
}

The function changeTheDirectionOfTheDCMotor():
void changeTheDirectionOfTheDCMotor(bool changeDirection) {
  digitalWrite(input1OfTheDCMotor, changeDirection);
  digitalWrite(input2OfTheDCMotor, !changeDirection);
}

The function changeToRedLight():
void changeToRedLight() {
  servo.write(0);
  delay(15);
}

The function changeToNeutral():
void changeToNeutral() {
  servo.write(40);
  delay(15);
}

The function playCarMusicStart():
void playCarMusicStart(){
  if (isEngineSoundsPlaying == HIGH) {
    for (int thisNote = 0; thisNote < (sizeof(carSounds_note)/sizeof(int)); thisNote++) {
      int noteDuration = 1000 / carsounds_duration[thisNote];
      tone(4, carSounds_note[thisNote], noteDuration);
      int pauseBetweenNotes = noteDuration * 2.70;
      delay(pauseBetweenNotes);
      noTone(4);
      isEngineSoundsPlaying = LOW;
    }
  }
}

Solution
A big thanks to @ratchet freak
I need to change my loop() to this:
void loop() {
  int valueOfTheSensor = analogRead(tempSensor);
  float voltage = (valueOfTheSensor / 1024.0) * 5.0;
  float temp = (voltage -0.5) * 100;
  if (temp >= 20.00) {
    isRunning = LOW;
  }
  changeTheStateOfTheLights(isRunning);
  startTheDCMotorAndStopIt(isRunning);
  changeTheDirectionOfTheDCMotor(changeDirection);

  playCarMusicStart();
}

I also needed to change the PlayCarMusicStart():
void playCarMusicStart(){
  if (isEngineSoundsPlaying == HIGH && currentNote < (sizeof(carSounds_note)/sizeof(int))) {
      int noteDuration = 1000 / carsounds_duration[currentNote];
      tone(4, carSounds_note[currentNote], noteDuration);
      int pauseBetweenNotes = noteDuration * 2.70;
      delay(pauseBetweenNotes);
      noTone(4);
      currentNote++;
   } else {
      currentNote = 0;
   }
}

And the least is to set the isEngineSoundsPlaying equal to HIGH, I changed the function startTheDCMotorAndStopIt() for:
void startTheDCMotorAndStopIt(bool isRunning){
  if (isRunning == HIGH) {
    isEngineSoundsPlaying = HIGH;
    digitalWrite(pwmInputOfTheDCMotor, HIGH);
    changeToNeutral();
  } else {
    isEngineSoundsPlaying = LOW;
    digitalWrite(pwmInputOfTheDCMotor, LOW);
    changeToRedLight();
  }
}

The key will be to split up playCarMusicStart and instead create a playCarMusicStep that will do just one iteration of the loop and returns. Call it every time in loop() akin to blinkWithoutDelay.
In playCarMusicStart you then setup the playing state so it starts playing correctly.
And when you need to stop it you then stop the music by setting the correct variable.

You mean this with blinkWithoutDelay https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

The music loops takes 7400ms so when I pressed the button how can I stopped immediately without waiting 7400ms

by returning immediately after starting the music and calling the function again when new processing needs to occur for the next note/pauze

Thanks I updated the question with the solution a big thanks for helping me!


text:
Comparing button presses to correct sequence
I am creating a memory game with the Arduino. It has four buttons, each for a different colored led. The leds will blink in a random sequence and either fail or add another light in the next sequence if the user presses the correct buttons. I have also attached an lcd screen to late implement a score tally.
Right now, the welcome lights display and the sound is working fine, but when the sequence starts, it will act as though I am pressing a button and proceed through the fail light method. I think the last method is causing this issue where I am comparing the button pressed to the sequence.
I would appreciate any help!
This is essentially my wiring just with different pins chosen:

What have you done to try to understand the problem? Put some debug prints in, see where it's going wrong.

I have outputted the button states as well as the button state right before it checks the sequence along with the seq. In the serial monitor it will say button3 = 1 when I have not pressed any buttons since the start of the program.

the buttons in schema have pull-down resistors

That was one of the things I was thinking could be wrong since I declare the pinModes with INPUT_PULLUP. Should I instead just use INPUT? Or would it be more efficient to not have the pull down resistors?

I found that I did not need the pull down resistors for each button since I had declared the pinMode for each button to be INPUT_PULLUP. So instead of the schematic above, I took out the resistors for the buttons and instead wired one side of the buttons to ground.

The problem might be that you do not debounce the buttons. When you press a button, there is somehwere between fully pressed and not pressed (or backwards) a state there it 'bounces', e.g. you get lots of state transitions, resulting in seeing a button pressed twice or many times instead of once.
Check the debounce example in the default Arduino Tutorial

Thank you. I don't even press any buttons though, and it does this.

Check the variable button just before FailLight, is it -1 (expected) or has it a button (press) value?

the button value is 0 before the fail light

Are you sure that if(button0 == LOW){
should be LOW and not HIGH?

well for the pinMode of the buttons, i set them to INPUT_PULLUP so doesn't that make the states opposite? (HIGH when not pressed and LOW when pressed)

I think it would be best just to load the most simple example from using buttons and check the result... also you will probably need the debounce algorithm anyway.

Let us continue this discussion in chat.


text:
Arduino JSON foreach loop
I'm trying to extract values using ArduinoJson. The values aren't fixed, therefore I need to use the foreach loop.
I'm trying this, but I can't seem to use the values like I could with.
root["0"]["value"].as<const char*>();

Here is my code.
void loop(){
  int httpCode = http.GET();
  if(httpCode > 0) {
    // if Get request has processed
    if(httpCode == HTTP_CODE_OK) {
      payload = http.getString();
    }
    if(payload.length() > 0) {
      Serial.println(payload);
      JsonObject& root = jsonBuffer.parseObject(payload);
      if (!root.success()) {
        Serial.println("parseObject() failed");
        jsonBuffer.clear();
      } else {
        Serial.println("Data Fetched");
        for(JsonPair& node : root) {
          Serial.print("0 State: ");
          Serial.println(*node);
        }
        http.end();
      }
    } else {
      Serial.println("Payload Empty");
    }
  }
}

Please avoid any missing brackets. Thanks in advance.
[{"state": true, "value": 10}, {"state": false, "value": 8}, {"state": false, "value": 5}, {"state": false, "value": 13}]

How can we possible answer this question if we don't know what JSON will be fed in and what error occurs?

wouldn't it be root[0]["value"]?

what does this mean? avoid any missing brackets .... how do you avoid something that does not exist?

@jsotola I meant to say please avoid if I missed some bracket in the code above. Nevermind...

You should press ctrl-T and indent your code properly, as a start...

I found another way around the solution.
Idk if this is helpful to anyone but the problem was that I had an unknown number of nodes I wanted to loop through, Example of the json format above.
void loop(){
int httpCode = http.GET();
  if(httpCode > 0) {
    // if Get request has processed
    if(httpCode == HTTP_CODE_OK) {
          payload = http.getString();
      }
      if(payload.length() > 0){
          JsonArray& nodes = jsonBuffer.parseArray(payload);
          if (!nodes.success()) {
            Serial.println("parseObject() failed");
            jsonBuffer.clear();
          }else{
            int node_length = nodes.size();
            for(int i=0; i<node_length;i++){
              Serial.printf("node-%i\nValue : ",i );
              String value = nodes[i]["value"].as<const char*>();
              String state = nodes[i]["state"].as<const char*>();
              Serial.println(value);
              Serial.print("State : ");
              Serial.println(state);
            }
            http.end();
        }
    }else{
      Serial.println("Payload Empty");
    }
  }

  jsonBuffer.clear();
  delay(8000);
}

so you found out that the json array has a size property?

Yes both jsonArray and jsonObject has size property


text:
STM32 VGA Output - don't understand why lines are jagged
I am using "blue-pill" STM32F103C8 (http://wiki.stm32duino.com/index.php?title=Blue_Pill) to create VGA output. I am connecting PB6 to VSync, PB0 to HSync, and PA0 to red using 278 Ohm resistor.
I don't understand why the lines are "jagged", like in the picture:
I would appreciate any input.
By the way, my real code is more complex and can display 256x192 with 64 colors. Since this board has 20K memory, I am using separate areas for pixels and colors, like Sinclair ZX (https://en.wikipedia.org/wiki/ZX_Spectrum_graphic_modes).
This is my code:
// interrupt handlers
void EndVBackPorch();
void ShockAbsorber();

volatile uint8 *GPIO_ODR;
volatile int vflag = 0; /* When 1, can draw on the screen */

void setup()
{
  pinMode(PB6, PWM); // VSync
  pinMode(PB0, PWM); // HSync

  // PA0..PA5 set to OUTPUT with max speed 50 MHz
  GPIOA->regs->CRL = 0x88333333;
  GPIO_ODR = (volatile uint8_t *)&GPIOA->regs->ODR;

  // 640 x 480 @ 60 Hz (Standard, pixel clock frequency 25.17 MHz)
  //InitHSync(false, 2287, 275, 400);
  //InitVSync(false, 525, 2, 35 + 48);

  // 640 x 480 @ 60 Hz (non-standard, pixel clock frequency 24.0 MHz)
  InitHSync(true, 2376, 264, 370);
  InitVSync(true, 505, 5, 10 + 74);
}

void loop()
{
    // Everything happens in the interrupts
}

void InitVSync(
  bool isNegative,
  int wholeFrame,
  int syncPulse,
  int startDraw)
{
  HardwareTimer timerVSync(4);

  timerVSync.pause();
  timerVSync.setPrescaleFactor(1);
  timerVSync.setOverflow(wholeFrame); /* Vertical lines */

  // VSync on pin PB6
  timer_oc_set_mode(timerVSync.c_dev(), TIMER_CH1,
            isNegative ? TIMER_OC_MODE_PWM_2 : TIMER_OC_MODE_PWM_1, TIMER_OC_PE);
  timerVSync.setCompare(TIMER_CH1, syncPulse);

  timerVSync.setChannelMode(TIMER_CH4, TIMER_OUTPUT_COMPARE);
  timerVSync.setCompare(TIMER_CH4, startDraw);
  timerVSync.attachInterrupt(TIMER_CH4, EndVBackPorch);

  // Slave mode Gated, triggered by TIM3
  timerVSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_SMS);
  timerVSync.c_dev()->regs.adv->SMCR |= ((uint16_t)TIMER_SMCR_SMS_GATED);
  timerVSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_TS);
  timerVSync.c_dev()->regs.adv->SMCR |= (uint16_t)TIMER_SMCR_TS_ITR2;

  //nvic_irq_set_priority(NVIC_TIMER4, 1);

  timerVSync.refresh();
  timerVSync.resume();
}

void InitHSync(
  bool isNegative,
  int wholeLine,
  int syncPulse,
  int startDraw)
{
  HardwareTimer timerShockAbsorber(2);
  timerShockAbsorber.pause();
  timerShockAbsorber.setPrescaleFactor(1);
  timerShockAbsorber.setOverflow(wholeLine);

  timerShockAbsorber.setChannelMode(TIMER_CH1, TIMER_OUTPUT_COMPARE);
  timerShockAbsorber.setCompare(TIMER_CH1, 0);

  timerShockAbsorber.setChannelMode(TIMER_CH2, TIMER_OUTPUT_COMPARE);
  timerShockAbsorber.setCompare(TIMER_CH2, startDraw - 12);
  timerShockAbsorber.attachInterrupt(TIMER_CH2, ShockAbsorber);

  // Master mode, TIM_TRGOSource_Enable
  bitSet(timerShockAbsorber.c_dev()->regs.adv->SMCR, TIMER_SMCR_MSM_BIT);
  timerShockAbsorber.setMasterModeTrGo(TIMER_CR2_MMS_ENABLE);

  timerShockAbsorber.refresh();

  HardwareTimer timerHSync(3);
  timerHSync.pause();
  timerHSync.setPrescaleFactor(1);
  timerHSync.setOverflow(wholeLine);

  // HSYNC on pin PB0
  timer_oc_set_mode(timerHSync.c_dev(), TIMER_CH3,
            isNegative ? TIMER_OC_MODE_PWM_2 : TIMER_OC_MODE_PWM_1, TIMER_OC_PE);
  timerHSync.setCompare(TIMER_CH3, syncPulse);

  timerHSync.setChannelMode(TIMER_CH4, TIMER_OUTPUT_COMPARE);
  timerHSync.setCompare(TIMER_CH4, startDraw);
  timerHSync.attachInterrupt(TIMER_CH4, Draw);

  // Slave mode Trigger, triggered by TIM2
  timerHSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_SMS);
  timerHSync.c_dev()->regs.adv->SMCR |= ((uint16_t)TIMER_SMCR_SMS_TRIGGER);
  timerHSync.c_dev()->regs.adv->SMCR &= (uint16_t) ~((uint16_t)TIMER_SMCR_TS);
  timerHSync.c_dev()->regs.adv->SMCR |= (uint16_t)TIMER_SMCR_TS_ITR1;

  // Master mode, TIM_TRGOSource_Update
  bitSet(timerHSync.c_dev()->regs.adv->SMCR, TIMER_SMCR_MSM_BIT);
  timerHSync.setMasterModeTrGo(TIMER_CR2_MMS_UPDATE);

  nvic_irq_set_priority(NVIC_TIMER3, 0);

  timerHSync.refresh();

  // Starts timerHSync as well
  timerShockAbsorber.resume();
}

void EndVBackPorch()
{
  vflag = 1;
}

void ShockAbsorber()
{
  // Wait for interrupt
  __asm__ volatile("wfi \n\t" :::);
}

void Draw()
{
  if (!vflag)
  {
    return;
  }

  noInterrupts();

  __asm__ volatile(

    "  mov r0, #3        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #0        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #3        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #0        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #3        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"
    "  mov r0, #0        \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  nop               \n\t"
    "  strb r0, [%[odr]] \n\t"

    :
    : [odr] "r"(GPIO_ODR)
    : "r0");

  interrupts();
}

You haven't said which Arduino you are using, which would help inform the answers.

I found a similar issue when I developed code to display on a VGA monitor.
The reason for the slight jitter is that when an interrupt fires, it can't stop in the middle of an instruction. So there are potentially one or two extra clock cycles before the interrupt is processed.
Those clock cycles would account for the slight jaggedness on the right. The way to avoid that is to go to sleep between horizontal lines (idle sleep mode). This wakes up instantly, but the important thing is it wakes up at the start of an instruction cycle, so you don't get a one or two cycle delay.
I can't see any sleeping in your code, and I'm not sure if your STM32F103C8 would compensate for that, but certainly it is worth trying.
I can't see a "main" loop, presumably it doesn't do much until an interrupt fires.
My main loop is this:
void loop()
  {
  // sleep to ensure we start up in a predictable way
  sleep_mode ();
  doOneScanLine ();
 }  // end of loop

Note the sleep which ensures that it starts the drawing at the same time each time (of course the interrupt will take time, but at least it takes the same time every scan line).

Thank you for your quick response! I will try your idea as soon as I get home.

I can't see any sleeping in your code, and I'm not sure if your STM32F103C8 would compensate for that, but certainly it is worth trying<< I am using "shock absorber" idea (on NVIC_TIMER3) as described here: http://cliffle.com/article/2015/06/11/matrix/.
I can't see a "main" loop, presumably it doesn't do much until an interrupt fires. << Sorry, missed it, it actually doesn't do anything

It must do something, or nothing would execute. Does it call some other function which loops? The main loop (or should I say, main function?) is where code starts executing.

I updated the source, added empty loop. It is empty because everything happens in the interrupts. There are 3 interrupts: EndVBackPorch - updates "vertical" flag; ShockAbsorber - happens a little before Draw, its goal to reduce random delays; and Draw - that draws horizontal line (in this example, just 6 "dots"). Each "dot" is actually at least 2 real "dots", however my resolution is 256, and real resolution is 640, so it is OK.

The objective is to be sleeping before the interrupt occurs so that the interrupt wakes in a predictable way.


text:
How to use use 2 or more HC-SR04 sensors as one single sensor?
I'm new to Arduino and this is my problem. I need to track an object in a room. For now I have placed 3 sensors on the edges of each axis (x, y, z), where the x axis will the line between the east and the west walls of the room, the y axis will be the north and south walls of the room, and the z axis will be the ceiling of the room.
I have written code to get the output as x, y, z coordinates. But since the HC-SR04 has no horizontal range it can only track objects in its line of sight. Due to this I'm not able to fulfil my requirements. So I thought if I could couple up an array of HC-SR04s together to work as one sensor I can get more horizontal range.
Is this possible using an Arduino Uno R3? If it's possible, please guide me through it.

You can try to use them sequentially. Or try triggering all sensors for one axis at once an wait for an echo signal at any of the echo pins (each one at it's own Arduino pin). For the first approach you may run into performance issues depending on the number of sensors. For the second you may see interference effects with the multiple sound waves interacting. Try and test. If this is successfull, please come back and answer your own question, so that everyone can profit from it.

You can try attaching your HC-SR04 sensor to a servo, then you will have a range of detecting an object in 180 degree span.

Of course you will have to make modifications to fit your purpose. Using three ultrasonic sensors with each of them having their own servo of 180 degree range will surely increase accuracy. To get started visit here.
Hope this was what you were looking for.
(Image credits: Dejan Nedelkovski)


text:
MQ135 Gas Sensor Calibration
I have bought a MQ135 gas sensor. I have read online from multiple sources that a calibration/warm-up period of between 12-24hrs is required for the sensor to give its most accurate readings. I currently have it attached to one of my UNO's just spitting out Analog readings to the Serial monitor and seems (just after an hour!) to have settled at a reading of 50 which it has stayed at now for a period of around 20 minutes. My questions surrounding this process really are:

What is the point in doing this process if when a project that uses this sensor is powered off for some number of hours? Will you have to let it warm-up/calibrate again before having faith in the readings?
How do I actually identify PPM for a gas such as C02? Is there some form of constant that I should be comparing the reading obtained to or something similar?

Welcome to Arduino SE.  Feel free to take the tour at https://arduino.stackexchange.com/Tour that will help you get the most from this site.  The warm-up period has to do with the physics of how the sensors work.  This is a device primarily used with Arduino so I believe it is OK here.  But you might want to edit your post to indicate which kind of Arduino you are using and show some of your code so you can pose an Arduino-specific question.

By my opinion, it is impossible to calibrate these solid electrolyte based sensors. I achieved best results when I measured the CO2 level in 5 minute intervals, by heating the sensor for 100 seconds. I cant remember these times precisely, but by heating and allowing it to cool down I was able to get quite reliable results. But then I realized that the sensor is getting some offset. If you want to do a two-point calibration, you can put it to fresh air, it should read about 0.04%, or you can breathe directly to the sensor for a short while and it shoud read 4%. But I highly recommend using NDIR CO2 sensor, those are used in home air monitoring devices.


text:
Creating public instance of class in another class's initialization
I'm using several TM1637 displays to create timers, so I decided to make a Timer class. Every time I initialize an instance of the Timer class, I want it to create an instance of the TM1637Display class. So I started out with this, but the display object can't be accessed from within updateDisplay.
class Timer {
public:
    Timer(uint8_t CLK, uint8_t DIO) {
        TM1637Display display(CLK, DIO);
        ...
    }
    void updateDisplay() {
        ...
        display.setSegments(displayData);
    }
}

And if I do this I get the compile time error In constructor 'Timer::Timer(uint8_t, uint8_t)': src\main.cpp:16:37: error: no matching function for call to 'TM1637Display::TM1637Display()'
    TM1637Display display;
    Timer(uint8_t CLK, uint8_t DIO) {
        display(CLK, DIO);
        ...
    }

What should I try? Maybe make an empty pointer before the display instance is created with a public scope, assign the pointer to the display instance, then hand the updateDisplay function the pointer? That seems really convoluted.

As it's now in the first example, it's local variable in Timer constructor.
In the second one you have to use member initializer list in constructor as there is no default constructor in your display class.
class Timer {
public:
    Timer(uint8_t CLK, uint8_t DIO)
    : display(CLK, DIO) // constructor's initializer list
    {
        ...
    }
    void updateDisplay() {
        ...
        display.setSegments(displayData);
    }

    // member variable:
    TM1637Display display;
}

Thank you! I had never heard of initializer lists before.


text:
Run python in Windows OS installed in micro SD card which is read by Arduino microcontroller board
I have a python code which runs in my computer with Windows operating system. The code reads some images as input, extends some cognitive services apis from Microsoft azure and finally give an audio output. I would like to run this code on an independent device, for which I am thinking to have a motherboard like Arduino (I can use raspberry pi, but it's a small project and I don't want to invest that much). However being an amateur in this genre, I have some questions and would really like if someone could help.
I want the system to have an independent processing power, with the operating system loaded in a micro SD card. I do not want to connect  Arduino with my pc and run the code from there. It will not make any sense since the PC/laptop is already able to do the work, what would I need Arduino for?
Can someone please tell me if it is possible to have an operating system installed in a micro SD card (bootable) and have it inserted in the Arduino board so that I can run the python code within the SD card?

please delete the first two paragraphs of your question because they are just fluff and they confuse the issue. ... your real question is the last paragraph only .... also remove the reference to windows OS in the title.

With some Arduino boards, yes.  You want a board like the Yun (unfortunately retired now, but there are probably others similar) which has a MIPS SoC on it that runs Linux (specifically OpenWRT).  The OS is installed into the SoC, but there is an SD card slot that will allow you to read your code.
An alternative is a Yun shield (available from third parties, such as the Dragino Yun Shield).  This turns any Uno-like Arduino into a Yun.   Of course, you can run it without any Arduino attached if you so wish to wire it manually.
However, with all these, you're getting into the price bracket of a Raspberry Pi, so you may as well do it properly and just get a Raspberry.


text:
Flashing ATmega8U2 using another Arduino
I have an Anduino Uno R1 and the ATmega8U2 on. It does not respond correctly. How can I use another Arduino Uno R3 in order to reinstall the correct firmware? What I want to avoid it to solder the resistor because I am not very good with the soldering iron.
As fas as I understand there are some pins close to the AREF pin that can be used in order to attach a programmer. Also how can I temporally attach them without the need of a soldering iron? On the R1 the pins are just some exposed metal. How can I connect to them?
Also, if I load into the other Arduino the programmer, then how can I load the firmware using GNU/Linux into the ATmega8U2?

Those pads are actually plated through-holes. But the are filled with solder during manufacturing. You can suck the solder out with a solder sucker. Then solder in some headers. It helps to first add some leaded solder to the “pads”. That way the unleaded solder that’s already there will mix with the leaded, and will lower it’s melting point. The other option is to use the DFU method of updating the firmware (which I think you were talking about in you question).

Even if I solder the header then how I will load the firmware on GNU/Linux?

I think there is a guide on the Arduino website for this. Can’t really check at this moment.

it does not respond correctly - in what way? It is extremely unlikely that the Atmega8u2 has become corrupted.

You can suck the solder out with a solder sucker. - you can also solder wires to them. However the OP said that he is not very good with a soldering iron.

I am kinda in a hurry to fix it - the fastest thing would be to find another Uno.

https://www.arduino.cc/en/Hacking/DFUProgramming8U2 . Are you sure it's an R1, as that's quite an old model?

Yes I am sure but I want to use another method instead the ones mentiuoned in the instructions because I want to use external programmer in order to flash the atmega8u2.

There is an official guide. Arduino as ISP and Arduino Bootloaders
But you need to add the 2x3 ISP pin header since some of the signals isn't available on D0-D13 or any other pins.

None of the signals on the '8U2 are available on Female headers except power & Gnd. One must connect to the 2x3 ISP header for the '8U2 that is shown below the chip in the picture.

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


text:
SIM900 and Mega 2560 not sending SMS
I just bought a SIM900 Arduino shield from AZDelivery. I only have a Mega 2560 board, thus I am trying to use this although most examples (like the tutorial from AZDelivery) are with the Uno board. I am using the SIM card from my mobile phone, not having any PIN. This is the Arduino library I am using.

I didn't flash anything on the SIM900 board prior to testing, because in the instructions from AZDelivery Ebook this was not mentioned.
My NetLight LED is blinking constantly (1 blink per second) I guess it is not finding the mobile network.
At the momemt, I only have a 1A supply, though I've already ordered a new one with 2A. Could this be the reason for point 2? Does the board need 2A to log into the network?
Asuming it would log into the network, the AZDelivery Instruction Sketch/Example is using "SoftwareSerial.h" due to its compatibility to the Uno board. Since I am using a Mega board, can I just use D30 and D31 and set them as Rx and Tx using the SoftwareSerial library?
Can you give me a link to an up-to-date library and/or example for SIM900 working with the Mega 2560 Rev3 and Arduino 1.8.4?

I hope you can help me getting started with the SIM900 module.

I was just able to send an SMS (even with the 1A supply). Here the answers to my questions.

No, it is not necessary to flash the SIM900 board
I was not connected, because I didn't insert the SIM card properly on the shield.
No it does not necessarily need 2A for logging into network and obviously not for sending SMS though there might be reasons for the board consuming 2A during SMS sending, e.g. bad network connection.
If you want to use Sotware Serial, you need certain digital lines allowing software interrupts. In the case of the MEGA board, e.g. D10, D11 or for the UNO D7,D8.
I was using this tutorial to get communication via SoftwareSerial working. Afterwards I added the code for sending SMS.

I hope I can help some others who are looking for a low level description of how to get started with MEGA and SIM900.

the mega board has 4 hardware serial ports; why use software?


text:
Check if servo is connected to arduino
#include <Servo.h>

Servo esc;

void setup(void) {
  esc.attach(7, 1000, 2000);

  if (esc.attached()) {
    // this always runs
    // even if there's no servo connected to pin 7
  }
}

I've written code kind of like the above.
The problem is that after using Servo.attach the method Servo.attached always returns true, even if there's nothing in the pin that I've attached to.
How can I check if the pin, in this case 7, actually has a wire in it?

Welcome to Arduino:SE. You might find this helpful: How to ask a good question for Arduino Stack Exchange

You cannot check, if a servo or a wire is physically connected to the pin, without extra effort. The Servo library uses Timer interrupts to create a PWM signal for the servo on the used pin. For this the pin is configured as OUTPUT and cannot measure anything except of the value, that was written to it. In most servo motors the PWM input is high impedance, so that the current draw from the PWM pin is very low.
To solve your problem you have 2 possibilities:

Use a special connector, that has 2 extra pins with a mechanical switch, which gets closed, when the connector is put together. (The same principle as in SD card holders)
Measure the current, that the servo uses through it's power supply pins, with a suitable circuit.


text:
Arduino Uno R1 I soldered resistor but I cannot DFU program atmega8u2
I have an Arduino R1 board (the very first one) and I managed to solder the resistor into Arduino's Atmega8u2 (I went to a specialist in order to do that). Then I reset atmega8u2 and by wiring the pins mentioned in: https://www.arduino.cc/en/Hacking/DFUProgramming8U2
I can confirm it via this message over my GNU/Linux machine by running dmesg:
[ 1544.679504] usb 1-6: new full-speed USB device number 42 using xhci_hcd
[ 1544.808341] usb 1-6: New USB device found, idVendor=03eb, idProduct=2ff7
[ 1544.808350] usb 1-6: New USB device strings: Mfr=0, Product=1, SerialNumber=0
[ 1544.808356] usb 1-6: Product: Arduino Uno DFU

I also to confirm that I run lsusb and I got the following result:
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 002: ID 248a:8367
Bus 001 Device 058: ID 03eb:2ff7 Atmel Corp.
Bus 001 Device 003: ID 058f:6362 Alcor Micro Corp. Flash Card Reader/Writer
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Further indicating to me that arduino is in DFU mode over my ubuntu 16.04 machine. Also I further verify via dfu-util -l command:
Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2014 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to dfu-util@lists.gnumonks.org

Found DFU: [03eb:2ff7] ver=0000, devnum=63, cfg=1, intf=0, alt=0, name="UNKNOWN", serial="UNKNOWN"

The I try to run:
sudo dfu-programmer atmega8u2 erase
But for some reason I get the following error:
dfu-programmer: no device present.
Do you know why I get this error and how I can fix it?
Edit 1
I installed the latest version of dfu-programmer and compiled from source via https://sourceforge.net/projects/dfu-programmer/files/dfu-programmer/0.7.2/ but still I get the error. I also tried to compile it with libusb-1.0.0
Edit2
I also tried this version with libusb-1.0.0 but still the same error occurs.
Edit 3
As many suggest I tried to do multiple times but still I get this error.
Edit 4
I also used dfu-util and I try to insert the data into the atmega8u2 via:
 sudo dfu-util -d 03eb:2ff7 -D ./Arduino-usbserial-uno.hex -R

But I get the error:
dfu-util 0.8

Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2014 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to dfu-util@lists.gnumonks.org

dfu-util: Invalid DFU suffix signature
dfu-util: A valid DFU suffix will be required in a future dfu-util release!!!
Opening DFU capable USB device...
ID 03eb:2ff7
Run-time device DFU version 0100
Claiming USB DFU Interface...
Setting Alternate Setting #0 ...
Determining device status: state = dfuIDLE, status = 0
dfuIDLE, continuing
DFU mode device DFU version 0100
Device returned transfer size 3072
Copying data from PC to DFU device
Download    [                         ]   0%            0 bytesdfu-util: Error during download
dfu-util: can't detach
Resetting USB to switch back to runtime mode

According to https://gebloggendings.wordpress.com/category/elektronik/arduino/ it is sometimes not to assume that the atmega8u2 is always the correct value in my case was the at90usb82 resulting into using the following command sequence:
sudo dfu-programmer at90usb82 erase
# Flashing the arduino provided .hex
sudo dfu-programmer at90usb82 /usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/arduino-usbserial/Arduino-usbserial-uno.hex
# reset the board
sudo dfu-programmer at90usb82 reset

Further information you can find into:

https://forum.arduino.cc/index.php?topic=53443.0
https://forum.arduino.cc/index.php?topic=542854.0


text:
How does Peggy2 drive rows with 74HC154 Decoder?
Trying to program Evil Mad Scientist's Peggy 2 board without their Library.
The board drives a LED Matrix with

Source  74HC154 Decoder
Sink    STP16CPSO5  LED Sink Driver

Schematic
What has me confused is the 74HC154 Outputs can only have one output set to Low at at time. See table below. This means all but one row is "on". Isn't this backwards?  Shouldn't all outputs be low except one that is high?  Selecting what row you want on, rather than selecting what row you want off.  It looks more like the 74HC154 is a Sink.  Thanks.

Not sure how this relates to Arduino as written.  You might find this helpful: How to ask a good question for Arduino Stack Exchange

If you look into the datasheet of 74HC154, you can see that each output has an Active Low State. Also in the schematic, the leds row part use a pnp transistor (see page two). As so, they will be active if the input is low.

This means all but one row is "on". Isn't this backwards?

Since they are PNP, the only active row is the one with Low value and the current of that row is sink through the selected column(s) in the STP16CPS05

Ahh!!!    Makes perfect sense!  Low turns PNP on!   Thank you brtiberio!


text:
How can I connect an Arduino / ESP8266 to an Azure MySQL database?
I am currently trying to connect an ESP8266 to my Azure MySQL database via WiFi, but have not yet been successful.
I have tried a bunch of guides, but no luck and I'm running out of ideas. I have made a connection to an IoT Hub in Azure but could not forward the messages to the MySQL database in the cloud. I managed to get it stored in a blob datatype but had so many issues with it that I kinda scratched that idea.
Last thing I tried was trying to implement the example from
https://github.com/ChuckBell/MySQL_Connector_Arduino
more specifically the 'connect_wifi' example. I was unable to find the ip of my azure server so i tried using some of the code from the 'connect_by_hostname' but no luck there.
I'm new to Arduino and cloud in general so any help is appreciated.

if you can get it stored at all, but not in sql, then it's not really an arduino question. typically you hit some http gateway that does all the fancy stuff like DBs for you.

How would I go about let's say getting the blob type files which are stored in a storage account in my Azure server sent to my SQL DB (also in the azure cloud) using http gateway?

usually a small snip of php or something like that, that listens on the URL then makes backend calls to the services mentioned once there's something for it to do.

Not sure how you would directly connect with an C++ embedded file. One way you could achieve this is by creating a computer application and connect to the machine via Bluetooth.
{Arduino}
* Intake information
* Process into commands
* Push through software serial ----(Blue Tooth-----> { PC or MAC}
                                                    *Create C# or Swift App
                                                    *Intake information via COM-PORT
                                                    *Prepare SQL command with serial data
                                                    *Push to database server

This may of not of been the method you were looking for, but it's a way I found around the issue when working with Azure Databases and Arduino Micro-Controllers. An alternative is going to Raspberry Pi which has a little more resources to deal with server functions.
Hope this helps.


text:
don't save on tab
Ok, I made some changes to the code and I wish they would see it.
At the moment the program has a bug, it is not saving the contents of the txt file to the table, can someone give some lights?
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
int x = 1;
String files, memo, memo1;
int sizef = 0;
int sizef1 = 0;
int sizef2 = 0;
int y=0;
int z=1;
int d=0;
int u=0;
int r=0;
int l=0;
int indice_objetos=0;

struct objeto_celeste_s {
  char nome[20];
  float ar;
  float dec;
  };
typedef struct objeto_celeste_s objeto_celeste;

void rightfunction (int rate){
 char cmd[] = {'P',2,16,36,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);

}

void leftfunction (int rate){
 char cmd[] = {'P',2,16,37,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);

}

void upfunction (int rate){
 char cmd[] = {'P',2,17,36,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);
}

void downfunction (int rate){
 char cmd[] = {'P',2,17,37,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);
}

File file;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

char * list[]={"1.Modo Normal    ","2.Modo Teste    "};

// read the buttons
int read_LCD_buttons()
{

adc_key_in = analogRead(0);
if (adc_key_in > 1000) return btnNONE;
if (adc_key_in < 50)   return btnRIGHT;
if (adc_key_in < 250)  return btnUP;
if (adc_key_in < 400)  return btnDOWN;
if (adc_key_in < 450)  return btnLEFT;
if (adc_key_in < 650)  return btnSELECT;

return btnNONE;  // when all others fail, return this...
}

void setup() {

 Serial.begin(9600);
 Serial1.begin(9600);
 while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
 }
 Serial.println ("Welcome!");
 Serial.println ("Efectue o alinhamento do telescópio, depois carregue no botão UP.");
 lcd.begin (16,2);
 lcd.setCursor (0,0);
 lcd.print ("Efectue alinham.");
 lcd.setCursor (0,1);
 lcd.print ("E carregue UP");
 delay (1000);

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
}

void loop() {

lcd_key = read_LCD_buttons();  // read the buttons

 switch (lcd_key)  // depending on which button was pushed, we perform an action
 {
   case btnRIGHT:
     if (z==0){
      rightfunction (9);
      Serial.println ("Andar para a direita a uma velocidade de 9.");
      z=1;
      r=1;
      break;
     }

     if (r==1){
      rightfunction (0);
      Serial.println ("Parar de andar para a direita.");
      z=0;
      r==0;
      break;
     }

   case btnLEFT:
     if (z==0){
      leftfunction (9);
      Serial.println ("Andar para a esquerda a uma velocidade de 9");
      z=1;
      l=1;
      break;
     }

     if (l==1){
      leftfunction (0);
      Serial.println ("Parar de andar para a esquerda.");
      z=0;
      l=0;
      break;
     }

   case btnUP:
      if (z==0){
       upfunction (9);
       Serial.println ("Andar para cima a uma velocidade de 9");
       z=1;
       u=1;
       break;
     }

      if (u==1){
       upfunction (0);
       Serial.println ("Parar de andar para cima.");
       z=0;
       u=0;
       break;
     }

      if(x==1){
        x--;
        lcd.clear ();
        lcd.setCursor(0,0);
        lcd.print(">");
        lcd.println(list[0]);
        lcd.setCursor(0,1);
        lcd.print (" ");
        lcd.println(list[1]);
        break;
      }
   case btnDOWN:
      if (z==0){
       downfunction (9);
       Serial.println ("Andar para baixo a uma velocidade de 9.");
       z=1;
       d=1;
       break;
      }

      if (d==1){
       downfunction (0);
       Serial.println ("Parar de andar para baixo.");
       z=0;
       d=0;
       break;
      }

      if(x==0){
        x++;
        lcd.clear ();
        lcd.setCursor(0,0);
        lcd.print(">");
        lcd.println(list[1]);
        lcd.setCursor(0,1);
        lcd.println("                ");
        break;
      }

   case btnSELECT:
    if (x==2){
      Serial.println ("Bem-vindo ao Modo Manual.");
      lcd.clear ();
      lcd.print ("Modo Manual");
      lcd.setCursor (0,1);
      lcd.print ("Reset p/mod GoTo");
      Serial.println ("Pressione os botões UP, DOWN, RIGHT ou LEFT no arduíno para controlar o telescópio.");
      z=0;
      break;
    }

    if (x==0){
    lcd.clear ();
    lcd.print ("Modo Normal");
    Serial.println ("Selecionou o modo normal!");
    delay (1000);
    if (SD.exists("objectos.txt")) {
    Serial.println("O ficheiro 'objetos' foi encontrado!");
    lcd.clear ();
    lcd.setCursor (0,0);
    lcd.print ("Modo Normal");
    delay (1000);

    file = SD.open("objectos.txt", FILE_READ);
    if (file) {
    while (file.available()) {
     String line = file.readStringUntil('\n');
     sizef++;
    }
    } else {//se houver erro a abrir o ficheiro
     Serial.println("Erro a abrir o ficheiro 'objectos.txt'.");
    }
     Serial.print ("Contados ");
     Serial.print (sizef);
     Serial.println (" objetos no ficheiro objectos.txt.");

     objeto_celeste *tab =(objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));

     if (tab==NULL){
      lcd.clear ();
      lcd.print ("Erro a alocar memoria");
      Serial.println ("Erro a alocar memória");
      while (1){ };

     }else{

      Serial.print ("Memória alocada para ");
      Serial.print (sizef);
      Serial.println (" objectos.");
      lcd.setCursor (0,1);
      lcd.print ("Alocados ");
      lcd.print (sizef);
      lcd.print (" obj");
      }

      file.close();

    char * line1 =(char*) malloc(sizeof(String));

    file = SD.open("objectos.txt", FILE_READ);

    if (file) {
     Serial.println ("Carregando informação para a memória:");

     while (file.available()) {

     char c = file.read ();

     if (c=='\n'){

     char * justafun = strtok (line1," "); //divide em tokens

     while (justafun !=NULL){

      switch (indice_objetos) {
          case 1:
            tab[sizef2].ar = atof(justafun); //to float

            indice_objetos++;
            break;
          case 2:
            tab[sizef2].dec = atof(justafun);

            sizef2++;
            indice_objetos=0;
            break;
          case 0:
            strcpy(tab[sizef2].nome, justafun); //this one is a string
            indice_objetos++;
            break;
      }
      justafun = strtok (NULL, " ");
      }

      if (line1==NULL){
      Serial.print ("Falhou na linha ");
      Serial.println (sizef2);

     }else{
       line1="";
    }
   }else{
     sprintf(line1, "%s%c", line1, char(c));
     }
    }
   }
  file.close ();

  delay (1500);

  if (Serial1.available()) {
   int inByte = 'V';
   Serial1.write (inByte);
   int inByte1 = 'e';
   Serial1.write (inByte1);
  }

delay (1000);

Serial.println ("Tabela ordenada alfabeticamente:");

 x=2;
 delay (1000);
 lcd.clear ();
 Serial.println ("Modo GoTo. Para entrar em Modo Manual pressione o botão select.");
 lcd.print ("Modo GoTo");
 lcd.setCursor (0,1);
 lcd.print ("Slct p/Modo Man.");

 }else {

    Serial.println ("O ficheiro 'objetos' não existe.");
    lcd.clear ();
    lcd.print ("Erro nao encontrado");
    delay (2000);
    while(1) { };
  }
 }

    if (x==1){
      lcd.clear ();
      lcd.print ("Modo Teste");
      Serial.println ("Selecionou o modo teste!");
      delay (2000);

      if (SD.exists("teste.txt")) {
      Serial.println("O ficheiro 'teste.txt' foi encontrado!");
      lcd.clear ();
      lcd.setCursor (0,0);
      lcd.print ("Modo Teste");
      lcd.setCursor (0,1);
      lcd.print ("Ficheiro encontrado");
      delay (2000);

      file = SD.open("teste.txt", FILE_READ);

      if (file) {
      while (file.available()) {//ler o ficheiro
      String line = file.readStringUntil('\n');
      sizef++;
     }

      files = "Contados " + String (sizef) + " objetos no ficheiro teste.txt.";
      Serial.println (files);
      objeto_celeste *tab = (objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));
      memo = "Alocados " + String (sizef) + " obj  ";
      memo1= "Memória alocada para " + String (sizef) + " objetos.";

      if (tab==NULL){
        lcd.clear ();
        lcd.print ("Erro alocar memoria");
        Serial.println ("Erro a alocar memória");
        while (1){ };

      }else{

        Serial.println (memo1);
        lcd.setCursor (0,1);
        lcd.print (memo);
      }

      file.close();

     } else {//se houver erro a abrir o ficheiro
      Serial.println("Erro a abrir o ficheiro 'teste.txt'.");
     }

    }else {
      Serial.println ("O ficheiro 'teste.txt' não foi encontrado.");
      lcd.clear ();
      lcd.print ("Erro nao encontrado");
      delay (2000);
      while(1) { };
    }
   }
     break;

   case btnNONE:
      break;
 }
 delay (200);
}

This is the content of txt.
P.S. I know the "Ar" section is wrong, it's just for test purposes.
Syrius 6.45 -16.42
Deneb 20.41 +45.16
Capella 5.16 +45.59
Rigel 5.14 -8.12
Vega 18.36 +38.47
Alnitak 05.40 -01.56

Possible duplicate of https://arduino.stackexchange.com/questions/51957/program-dont-read-memory-well

Hi, this is too long for a comment in other post.

And the code is not the same...

Why do you except the contents of your textfile to be saved into the array tab? You read one character at a time but aren't doing anything else with it than using it in an if-statement. You have to actually put your information into your data array

Consider that you always can edit your question. Code or other long things should not be placed in code, but the question should be edited. For me it seems, that you have the same problem as last time. If not, please be more specific

else{sprintf(line1, "%s%c", line1, char(c));

You should edit the code in your question to be a minimal, complete, verifiable example of the problem. Very likely you'll discover the problem in the process of creating it, and if not, you'll create a question which might be of use to someone else in the future, which is what this site is about.

@1manonearth: This line is not in the code of your question. Edit it, so that it reflects the code you are actually using

I have edited. Can u see?

Maybe I have found your problem:
Before reading the file you are allocating memory with malloc() and creating a pointer line1 to it. malloc() takes the number of bytes to allocate as a parameter. Here you use sizeof(String), which would give you the size of a new String object. But the point of the String object is, that is dynamically allocates the memory for the string of characters. So the created buffer line1 is most likely to small for your text. You have to allocate the buffer with the maximum number of characters of all lines.
But you should consider, that using malloc() or any other dynamic memory allocation is dangerous on microcontrollers, which don't have much RAM. If you are doing it to often you get heap fragmentation, essentially making swiss cheese of your heap. If possible you should use a statically declared array or at least allocate memory only once during the lifecycle of your program.


text:
Arduino Uno board with male header pins
I am currently working on a project that would greatly benefit from an arduino uno board with male headers soldered on instead of the female connectors. My question is hence extremely simple, yet I was not able to find an answer myself. Are there uno formfactor boards out there, with male header pins. I have found versions without headers for other boards, but not for the uno. Since I have already designed and 3d printed an enclosure that fits the uno and want to lower the overall height this seems like the easiest way to achieve this.

Several of the cheap Chinese clones that I've bought on eBay have come without soldered headers. Exactly the same form-factor as the Uno. Usual caveats about clone boards apply!

Along with various low-cost boards, the Adafruit Metro 328 is offered without headers soldered.  They consider this board to be a derivative of the Uno R3, but it does use the FT231X which may required different drivers than an Uno's ATMega16u2.  Also the USB connector is different so you may need to adjust your housing slightly.  Kind of ironic that while soldering headers is an extra step even with their selective solder machine, they charge slightly more for the no-headers version, perhaps stocking (or even return?) costs dominate manufacturing ones.

I often unsolder the female connectors to solder wires directly. I would simply unsolder then and solder male headers in their place.


text:
How to deal with unusual neopixel grid
I have built a custom installation in my home with 896 WS2812 LED driven by an ArduinoMega 2560 and powered by several rails just fine. However, the installation is arranged in a checkerboard-like pattern. There are 14 panels with 8 strips of 8 LED each (64 LED per panel), The strips are soldered in zigzag pattern within a panel, and the tiles are connected via leads in a "column progressive" fashion.
Hooking this up and running it works well but I'm trying to deal with the unusual pattern I've created, and having a hard time scaling with my current solution. I am worried that my solution is not very graceful and will use up a lot of unnecessary RAM. I am currently using Adafruit's NeoMatrix library.
My solution is to "fake" like I have many more pixels and use the setRemapFunction() to throw these fake grid points away. But as I continue to add fake pixels, I assume the overhead RAM is set aside for them and I will max out before getting done. I have 896 real pixels total, but at this rate I'll be declaring that I have 1,792. This is my attempt to deal with the offset, and is a work in progress. This is utilizing about half of my total grid so far:
const int16_t grid[] = {
0,  15,  16,  31,  32,  47,  48,  63,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 256, 271, 272, 287, 288, 303, 304, 319,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
1,  14,  17,  30,  33,  46,  49,  62,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 257, 270, 273, 286, 289, 302, 305, 318,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
2,  13,  18,  29,  34,  45,  50,  61,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 258, 269, 274, 285, 290, 301, 306, 317,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
3,  12,  19,  28,  35,  44,  51,  60,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 259, 268, 275, 284, 291, 300, 307, 316,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
4,  11,  20,  27,  36,  43,  52,  59,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 260, 267, 276, 283, 292, 299, 308, 315,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
5,  10,  21,  26,  37,  42,  53,  58,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 261, 266, 277, 282, 293, 298, 309, 314,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
6,   9,  22,  25,  38,  41,  54,  57,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 262, 265, 278, 281, 294, 297, 310, 313,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
7,   8,  23,  24,  39,  40,  55,  56,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 263, 264, 279, 280, 295, 296, 311, 312,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,

-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 128, 143, 144, 159, 160, 175, 176, 191,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 384, 399, 400, 415, 416, 431, 432, 447,
-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 129, 142, 145, 158, 161, 174, 177, 190,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 385, 398, 401, 414, 417, 430, 433, 446,
-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 130, 141, 146, 157, 162, 173, 178, 189,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 386, 397, 402, 413, 418, 429, 434, 445,
-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 131, 140, 147, 156, 163, 172, 179, 188,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 387, 396, 403, 412, 419, 428, 435, 444,
-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 132, 139, 148, 155, 164, 171, 180, 187,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 388, 395, 404, 411, 420, 427, 436, 443,
-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 133, 138, 149, 154, 165, 170, 181, 186,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 389, 394, 405, 410, 421, 426, 437, 442,
-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 134, 137, 150, 153, 166, 169, 182, 185,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 390, 393, 406, 409, 422, 425, 438, 441,
-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 135, 136, 151, 152, 167, 168, 183, 184,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 391, 392, 407, 408, 423, 424, 439, 440,

64,  79,  80,  95,  96, 111, 112, 127,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 320, 335, 336, 351, 352, 367, 368, 383,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
65,  78,  81,  94,  97, 110, 113, 126,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 321, 334, 337, 350, 353, 366, 369, 382,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
66,  77,  82,  93,  98, 109, 114, 125,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 322, 333, 338, 349, 354, 365, 370, 381,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
67,  76,  83,  92,  99, 108, 115, 124,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 323, 332, 339, 348, 355, 364, 371, 380,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
68,  75,  84,  91, 100, 107, 116, 123,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 324, 331, 340, 347, 356, 363, 372, 379,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
69,  74,  85,  90, 101, 106, 117, 122,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 325, 330, 341, 346, 357, 362, 373, 378,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
70,  73,  86,  89, 102, 105, 118, 121,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 326, 329, 342, 345, 358, 361, 374, 377,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,
71,  72,  87,  88, 103, 104, 119, 120,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 327, 328, 343, 344, 359, 360, 375, 376,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,

-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 192, 207, 208, 223, 224, 239, 240, 255,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 448, 463, 464, 479, 480, 495, 496, 511,
-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 193, 206, 209, 222, 225, 238, 241, 254,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 449, 462, 465, 478, 481, 494, 497, 510,
-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 194, 205, 210, 221, 226, 237, 242, 253,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 450, 461, 466, 477, 482, 493, 498, 509,
-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 195, 204, 211, 220, 227, 236, 243, 252,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 451, 460, 467, 476, 483, 492, 499, 508,
-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 196, 203, 212, 219, 228, 235, 244, 251,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 452, 459, 468, 475, 484, 491, 500, 507,
-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 197, 202, 213, 218, 229, 234, 245, 250,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 453, 458, 469, 474, 485, 490, 501, 506,
-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 198, 201, 214, 217, 230, 233, 246, 249,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 454, 457, 470, 473, 486, 489, 502, 505,
-1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 199, 200, 215, 216, 231, 232, 247, 248,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1, 455, 456, 471, 472, 487, 488, 503, 504,

};

I am using this like so:
#define PIN 6

#define WIDTH 32 // So far. Will be 56 when I finish creating array.
#define HEIGHT 32

/**
 * Setup the lightwall matrix.
 *
 * Each panel is 8x8 pixels. There are 7 columns and 2 rows,
 * but they are arranged in a checkerboard pattern.
 */
Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(WIDTH, HEIGHT,PIN,
  NEO_MATRIX_TOP     + NEO_MATRIX_LEFT +
  NEO_MATRIX_COLUMNS + NEO_MATRIX_ZIGZAG,
  NEO_GRBW           + NEO_KHZ800
);

uint16_t remapXY(uint16_t x, uint16_t y) {
  y = y * WIDTH + x;
  return grid[y];
}

void setup() {
  matrix.setRemapFunction(remapXY);
  matrix.begin();
}

So the remapXY() returns the correct key of the array, thus the reason for the crazy array pasted above. And that array is only halfway complete (tediously typing it out!)
But so far it is working. I have a pacman animation (not pictured) scrolling across the screen and being "off screen" for a believable  amount of time. That is the whole point of this madness. But am I going about it all wrong? Attached is also a picture of the full visible matrix for visual aid.

Starting from the upper left corner is panel 1, then lower left panel 2. Next column top is panel 3, bottom panel 4. And so on.
So will I need more RAM in order for this to be performant? Or is there a better way to code my way out of this problem? I have a lot of animations and ambient effects planned, not all of which will strictly require this offset.
Is there another way to "mask" or delay some pixels off screen temporarily based on where they should be? Only to put them back where they belong afterward?

that is an absolutely cool prroject

you can use a spreadsheet program, like excel, to generate arrays like the one that you have. ... then cut and past from the range of cells to the  program editor

Your room looks more high-tech than mine, and that's saying something!

break it down into blocks to determine the upper left corner of any 8x8 grid
const int16_t grid[8][8] = {
       {0,  15,  16,  31,  32,  47,  48,  63},
       {1,  14,  17,  30,  33,  46,  49,  62},
       {2,  13,  18,  29,  34,  45,  50,  61},
       {3,  12,  19,  28,  35,  44,  51,  60},
       {4,  11,  20,  27,  36,  43,  52,  59},
       {5,  10,  21,  26,  37,  42,  53,  58},
       {6,   9,  22,  25,  38,  41,  54,  57},
       {7,   8,  23,  24,  39,  40,  55,  56}
};

const int16_t block[7][4] = {
       { 0,  -1,   4,  -1,   8,  -1,  12},
       {-1,   2,  -1,   6,  -1,  10,  -1},
       { 1,  -1,   5,  -1,   9,  -1,  13},
       {-1,   3,  -1,   7,  -1,  11,  -1}
};

blockNumber = block[x/8][y/8];

// some checking for the -1 value

pixelNumber = blockNumber * 64 + grid[x%8][y%8]

//

This looks really promising - I think I understand. I'm going to try this out and get back to you on how it goes. Thank you!

thanks again! this is working. i had to fix a couple minor nuances but this was immensely helpful!

If I add more, I run out of RAM. Each pixel needs 3bytes of RAM. If I make it 10 "boxes" wide, that becomes a grid of 80x32, or 2560 pixels. That's 7680 bytes of RAM, which is just too much for this weak little board.

i would have a serious look at @edgarbonet's answer and accept that one instead of this one if it allows for larger panels

make the grid and block arrays of type uint8_t instead of int16_t for starters .... you could subdivide the grid array into 4 sections horizontally to save a few more bytes ..... you could add more unused blocks to follow the actual layout more closely ..... top row of block array would be { 0, -1,  -1,  -1,  4,  -1,  -1,  -1,  8,  -1,  -1,  -1,  12},

This indeed looks awesome!
I suggest getting rid of the big grid array, and instead generate the
mapping programmatically. Given that it is very regular, the mapping can
be computed instead of stored:
uint16_t remapXY(uint16_t x, uint16_t y) {

    // Compute panel position and offset of pixel within that panel.
    uint8_t pannel_x = x / 8;
    uint8_t offset_x = x % 8;
    uint8_t pannel_y = y / 8;
    uint8_t offset_y = y % 8;

    // Is this a missing panel?
    if ((pannel_x + pannel_y) & 1)
        return -1;

    // Compute panel number.
    uint8_t pannel = pannel_y / 2 + pannel_x * 2;

    // LED index within the panel.
    uint8_t led = 8 * offset_x;

    if (offset_x & 1)  // numbered bottom to top
        led += 7 - offset_y;
    else               // numbered top to bottom
        led += offset_y;

    return pannel * 64 + led;
}

I hope this will save enough memory to make the whole thing work.

This is also a very elegant solution and also works! It doesn't allow me to add even more fake panels as @jsotola hoped, but definitely feels like less overhead (though I wonder if doing the computations repeatedly is savings vs having the constants defined? Suppose it's CPU vs RAM question). The Mega just doesn't have enough RAM to pretend beyond what I've got it doing.

It occurs to me I could store the lookup tables in PROGMEM too and save some SRAM that way. Reading this: https://www.arduino.cc/en/Tutorial/Memory


text:
Small Arduino with Bluetooth HID interface
I am trying to create a bluetooth gamepad for my phone.
I saw this:
https://www.amazon.com/DFRobot-Beetle-BLE-Arduino-Bluetooth/dp/B014KQHEH6/ref=cm_cr_arp_d_product_top?ie=UTF8
It says its bluetooth HID, but there are some conflicting comments saying it is serial over bluetooth. Is there something similar in a small form factor with an hid bluetooth module that I can use?

schematic ... https://github.com/Arduinolibrary/DFRobot_Bluno_Bettle/blob/master/DFR0339-Bluno%20beetle%20V1.0.pdf?raw=true .......... uses the cc2540 .... http://www.ti.com/product/cc2540   .... that might tell you what it actually is

Based on the fact that the controller you mentioned has a TI CC2540 Bluetooth processor, I have found a few webpages with information about HID capabilities in the CC2540. Based this the CC2540 should support HID.
Some example code.
Question on the TI forums, with a link to example code.


text:
Does the ESP8266 somehow remember wifi access data?
Today I did some tinkering with an ESP8266, trying out OTA and writing a webserver. To find an error, I reduced the sketch to just the following lines:
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

void setup() {
  Serial.begin(115200);
  server.on("/", []() {
    Serial.println("Sending response...");
    server.send(200, "text/plain", "Hi there!");
  });
  server.begin();
}

void loop() {
  server.handleClient();
}

Notice that there is no code to connect to a Wifi network. However, the chip still connects to my local, WPA2-secured, network on every boot. I can ping the chip, my browser can get the "Hi there!" message via http, the Serial message gets printed.
How is this possible? Does the ESP8266 somehow retain the Wifi information, maybe because of some old OTA data that was not completely overwritten?
I'm using platformio. Here's my entire platformio.ini:
[env:d1_mini]
platform = espressif8266
board = d1_mini
framework = arduino

I posted the compile and upload log here: https://pastebin.com/BtGrFZiu

Yes, normally the last WiFi credentials will be saved in flash and the ESP8266 loads this data on bootup and reconnect to the last known WiFi. See https://github.com/esp8266/Arduino/issues/2843#issuecomment-334250100:

the SDK stores some info, including the wifi credentials, in a sector of the flash.
That sector is kept between flashings to allow for a quick startup after update. On boot, before your sketch is executed, the SDK will retrieve the wifi credentials and attempt a quick connection.

This behaviour can be controlled by using the function WiFi.setAutoConnect(autoConnect) as documented in https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/station-class.rst#setautoconnect. This in turn calls the Espressif SDK function wifi_station_set_auto_connect (API reference)

In short: This is normal behaviour. If you want to make sure that your ESP8266 does not connect to any WiFi unless you tell it do it explicitly, call WiFi.setAutoConnect(autoConnect) at the beginning.
Edit: From within the firmware code, you can use system_restore. The documentation says that it would reset WiFi related data. This should destroy previous settings. The function can be included from https://github.com/esp8266/Arduino/blob/master/tools/sdk/include/user_interface.h within Arduino-ESP8266. I have not tried this myself nor can I say that it actually erases security-critical information from flash though.

Or, as you also have found out, hard-erasing the entire flash will purge the WiFi data with absolute certainty. This can be achieved by using esptool.py with the erase_flash option, e.g. python esptool.py -p COM6 erase_flash. Then you can flash the new firmware which will not use previous WiFi settings (but will probably open up the default access point again).
Then there's also ESP.eraseConfig which erases only the relevant flash sectors.

Thank you. Is there a way to erase credentials that were previously set from the flash? EDIT: Found that it's possible with esptool: https://www.esp8266.com/viewtopic.php?f=32&t=8204

@Geier updated.

WiFi.disconnect() removes the remembered credentials too


text:
When RFID tag is removed
After rewriting and getting a good grip on what I have got in my sketch so far, I need some assistance.
So in my sketch I can play an MP3 track with a certain tag, but when that tag is removed I can't  start the fading out process.
So for all that helped on previous ones, where I just mashed a lot of code together and hoped for the best, this one should start to have some good foundations to build on.
But I'm stuck on the part that's commented out.
//rfid
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN         9  // reset pin 9
#define SS_PIN          10 // sda pin 10
MFRC522 rfid(SS_PIN, RST_PIN); // Create MFRC522 instance

// = 0001.mp3    8C DE 63 A9   uid's for me to relate to mp3 tracks.
// = 0002.mp3    0A 97 F3 16 /
// = 0003.mp3    3A 5F DE 16

//mp3 player
#include<SoftwareSerial.h>
int mp3Pin[2] = { 5, 4 }; //Rx/Rx

// For the checksum to the mp3
#define startByte 0x7E
#define endByte 0xEF
#define versionByte 0xFF
#define dataLength 0x06
#define infoReq 0x01

SoftwareSerial mp3(mp3Pin[0], mp3Pin[1]); // Rx, Tx

void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin(); // Init SPI bus
  rfid.PCD_Init(); // Init MFRC522
  rfid.PCD_DumpVersionToSerial(); // Print version of RFID

  //Mp3
  mp3.begin(9600); // Init mp3
  delay(1000);
  sendMP3Command(0x3F, 0, 0); // Send request for initialization parameters
  sendMP3Command(0x06, 0, 20); // Vol set to 30
  sendMP3Command(0x07, 0, 0); // EQ = pop
}

void loop() {
  // Look for new cards
  if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial()) {
    //In new card found and new serial
    /*printHex(rfid.uid.uidByte, rfid.uid.size); // Print the Hex uid &
      Serial.println(); // use to get new uids.*/
    {
      String content = "";
      byte letter;
      for (byte i = 0; i < rfid.uid.size; i++) {
        content.concat(String(rfid.uid.uidByte[i] < 0x10 ? " 0" : " "));
        content.concat(String(rfid.uid.uidByte[i], HEX));
      }
      content.toUpperCase();
      if (content.substring(1) == "0A 97 F3 16") {
        //change here the UID of the card/cards that you want to give access
        //Serial.println("hello World");
        Serial.println("0002.mp3");
        sendMP3Command(0x03, 0, 0002); // Play track 0002.mp3
        sendMP3Command(0x19, 0, 0); // Loop track playing
        delay(30);
      }
      /*else !rfid.PICC_IsNewCardPresent();{
        sendMP3Command(0x06, 0, 28); // Reduce vol by 2 and fade out
        delay(30);
        sendMP3Command(0x06, 0, 26);
        delay(30);
        sendMP3Command(0x06, 0, 24);
        delay(30);
        sendMP3Command(0x06, 0, 22);
        delay(30);
        sendMP3Command(0x06, 0, 20);
        delay(30);
        sendMP3Command(0x06, 0, 18);
        delay(30);
        sendMP3Command(0x06, 0, 16);
        delay(30);
        sendMP3Command(0x06, 0, 14);
        delay(30);
        sendMP3Command(0x06, 0, 12);
        delay(30);
        sendMP3Command(0x06, 0, 10);
        delay(30);
        sendMP3Command(0x06, 0, 8);
        delay(30);
        sendMP3Command(0x06, 0, 6);
        delay(30);
        sendMP3Command(0x06, 0, 4);
        delay(30);
        sendMP3Command(0x06, 0, 2);
        delay(30);
        sendMP3Command(0x06, 0, 0);
        //sendMP3Command(0x16, 0, 0); // Stop
        delay(500); // Change value if you want to read cards faster
        }*/
    }
    // Halt PICC
    rfid.PICC_HaltA();
    // Stop encryption on PCD
    rfid.PCD_StopCrypto1();
  }
}

void sendMP3Command(byte Command, byte Param1, byte Param2) {
  // Calculate the checksum
  unsigned int checkSum = -(versionByte + dataLength + Command + infoReq + Param1 + Param2);
  // Construct the command line
  byte commandBuffer[10] = { startByte, versionByte, dataLength, Command, infoReq, Param1, Param2, highByte(checkSum), lowByte(checkSum), endByte };
  for (int cnt = 0; cnt < 10; cnt++) {
    mp3.write(commandBuffer[cnt]);
  } // Delay needed between successive commands delay(30); }
  /*   // Print the Hex uid & use to get new uids.
    void printHex(byte * buffer, byte bufferSize) {
    for (byte i = 0; i < bufferSize; i++) {
      Serial.print(buffer[i] < 0x10 ? " 0" : " ");
      Serial.print(buffer[i], HEX);
    }
    }*/

how is it that you write several for loops and then you write linear code like that commented out code?

Which RFID reader? Which Arduino? Using "programming" as a tag is rather generic. Obviously it is programming.

In general, RFID readers send a message when a card is presented. They don't send a message when a card is moved out of range. Unless you have a fancy reader that tells you that (and in that case it would help to mention the reader type).

Thank you for your quick replies. Sorry, a mfrc522 reader coupled with a nano and a dfplayer MP3. Regards

Basically, you have written this code:
void loop()
{
  // Look for new cards
  if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial())
  {
    {
      // ...
      if (content.substring(1) == "0A 97 F3 16")
      {
        // play
      } else
      {
        // stop
      }
    }
    // ...
  }
}

Try something like this:
bool playing = false;

void loop()
{
  // Look for new cards
  if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial())
  {
    // ...
    if (content.substring(1) == "0A 97 F3 16")
    {
      // play
      playing = true;
    }
    // ...
  }
  if (playing && !anyCardPresent())
  {
    // stop
    playing = false;
  }
}

and for the implementation od anyCardPresent refer to this discussion - if more consecutive calls of PICC_ReadCardSerial fail, you can consider this as card being removed

Thank you gabonator, I will try this when I'm home. I did use some code that could tell when the card was removed but the person who wrote it and myself didn't really understand it or how it worked. I can post it later if that might help. Regards


text:
Do prototypes need to follow the order of the functions?
I define prototypes prior to calling the functions.
Does the order of the prototypes have to match the order of the functions in the code?
I'd like to sort the prototypes alphabetically, while I wouldn't care in which order they appear in the code.
I am after common or best practice.

Why don't you try it and find out?

I am after common or best practice... and what a lame/flippant way to reply (and with a down vote)... I can try a lot of things, but would rather stick to what is considered good practice.

Your question as you originally posted it, with no mention of best practice, deserved the down vote, in my opinion: you could have tested whether the order mattered very easily, and prior research is expected here. With your edits there's now a sensible question, and I'll remove my downvote. You shouldn't take this personally - it's about the quality of the question, not a slight on your character.

how is this C question arduino related? you don't need function forward declaration in ino files (unless you use a pointer to function before setup()).

@Juraj: "unless"... and then you need to. The Arduino is programmed in C, hence it is Arduino related (so I thought).

@MarkSmith: fair enough... I have tried quite a few things as novice to C, and see how I have evolved to doing things I can share with others than rather the strange ways a newbie comes up with. It were also questions like these, that helped me to write better code... and also code, that compiles in IDEs other than the standard Arduino IDE.

There is no specific best practice in this regard.
The rest of this answer is primarily opinion based, and hence off topic for this site.
If you have classes it's common, but in no way required, universal or "bad" not to do, to group the public, private and protected methods together.
Really, group them in a way which makes sense for your program - related functions together. If you have so many methods / functions that they need a lot of organizing, split them into groups of related functionality - using classes or whatever.

It is sometimes a catch 22 to determine, whether a question will have a sort of standard answer or only an 'opinion'ated one. :)

Does the order of the prototypes have to match the order of the functions in the code?

No.

I'd like to sort the prototypes alphabetically, while I wouldn't care in which order they appear in the code.

You can do that. It would make the prototype easier to find, I suppose, however most editors these days have search functions.

I am after common or best practice.

Because the Arduino IDE automatically generates function prototypes the common practice is not to use them at all.
If you want to know best practice in general I suggest you ask on Stack Overflow.

Years ago I programmed Burroughs Medium Systems in BPL (Burroughs Programming Language), a language similar to Algol (which Pascal looks a bit like).
In BPL you could not use a function or variable which had not been previously defined. Thus, the "main" function would always appear at the end of the source file. Major functions (called by the main function) would therefore precede it, and minor functions would appear earlier again. Thus you could tell the hierarchy of function calls, roughly, by the order in which the functions appeared.
In C (and C++) you don't need function prototypes if you have all your code in a single file, and if you follow that convention. Put the main code at the end and the things it calls before them. You only need function prototypes then in unusual cases where A might call B but B might call A.