text:
How can I control 4 DC motors with an Arduino?
In a few months, I am planning to construct an Arduino robot with multiple sensors etc. I will use an arduino mega and a 4wd chassis like the one here: Chassis.  The chassis uses 4 DC motors. I was planning to use a motor shield, but I realized that it only fits an Arduino Uno(not Mega) and it controls only 2 DC motors. What can I do to make all 4 DC motors move forward and backward? If I use a motor driver board that controls 2 motors, can I connect the 2 right and 2 left motors in parallel together and the control it through the Arduino?

Use motor drivers that aren't on a shield.

@Majenko would I have to use 2 drivers then?

Each motor needs a driver. If a driver board can drive two motors then you need 2 driver boards for 4 motors. If a driver board can only drive 1 motor then you need 4 driver boards for 4 motors. Find a driver board that is powerful enough for your motors and then do the (very simple) maths.

If it can help, I have some code I'm using exactly for that purpose: https://github.com/igor-stoppa/ChibiOS/tree/car I haven't had much time lately to spend on it, but it does the basic. I'm using 2 of these: http://www.ebay.com/itm/111671736661?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

In theory, it's true that the 2 wheels on each side could be controlled by the same driver (assuming it can output enough power), however I'm not sure how this would play out when motors are either not sufficiently similar or subject to different load (say one has to overcome a small bump). So I preferred to play it safe and have each wheel controlled independently.

@IgorStoppa Each motor draws 120mA at 6 Volts. I have read about people controlling 2 motors together. I will probably control them individually so that I don't risk anything.

If you want to add a feedback loop to each motor, I found these optical end stop detectors to work quite well: http://www.ebay.com/itm/1-x-Optical-Endstop-End-Stop-Limit-Switch-Solution-for-3D-Printer-or-CNC-NEW-DE-/281983545137?hash=item41a7876f31:g:6UsAAOSwxcRW-UHJ

@IgorStoppa Do you recommend getting the Sparkfun driver or did the one you got from ebay work fine?

@NickSolonko when dealing with motors, you laso have to account for peak current consumption: overcoming the initial inertia will draw much more current than when steadily cruising. In general any change of speed (including steering) will cause a temporary increase.

So far, the driver I linked seems to be ok. I do not have experience with the one from Sparkfun. But I can advice to not buy any based on L298N because of the much higher internal power loss: http://www.ebay.com/itm/Dual-H-Bridge-DC-Stepper-Motor-Drive-Controller-Board-Module-Arduino-L298N-HG-/281551893660?hash=item418dccf49c:g:sm8AAOSwYGFUsJ9I

@IgorStoppa I was looking at buying something based on L298N. Thank you for warning me. Now I will probably get the one you advised. The one I was previously planning to get: http://www.ebay.com/itm/L298N-4-Channels-DC-Motor-Step-motor-Driver-Module-Robot-4WD-Car-for-Arduino-DG-/262482009259?hash=item3d1d259cab:g:srwAAOSw9eVXXnyk

Let us continue this discussion in chat.

6 volt motors expected to be well under an app would probably point to a TB6612FNG.  Some of the newer motor shields use those, as FET devices they are much lower loss.

@ChrisStratton: that's what I linked to.

Yes, you can do this using 2 L293D motor drivers, each motor driver can run 2 motors and it is very easy to use.

You should connect Vcc 1(used to power on the chip) to 5V and Vcc 2 to a power supply that is needed to run your motors, Enable 1,2 and Enable 3,4 are used to enable the 2 sides of the chip and should be connected to 5V. Outputs 1-4 are the outputs to 2 motors and Inputs 1-4 are the inputs from the micro-controller.

But, what if I want to use a separate power supply, such as a 9V battery?  How am I supposed to connect it to the L293D motor driver?  I think, I should connect the positive side of the 9V battery to the VCC 2 pin of the L293D motor driver.  But, where should I connect the negative side of the 9V battery?

You should connect the negative side to the 4 ground pins.

Yes, you can actually do this, but you have to consider the current of the motors and the motor driver. For example, if you have 12V, 2 Amps motors, then you need a 2-channel motor driver that is able to output a little higher that 4 Amps (2*2 Amps) for each channel at 12V. You will need to connect each two motors on the same side in parallel to one channel.


text:
Why doesn't my 1602A LCD display text with this code?
#include <SPI.h>
#include <MFRC522.h>
#include <LiquidCrystal.h>
#include <Servo.h>

#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
Servo myservo; // create servo object to control a servo

String read_rfid;
String ok_rfid_1 = "6722323b";
String ok_rfid_2 = "99be859e";
int posClosed = 180; // variable to store the servo position for locked
int posOpen = 0; //same for open...

/*
  Initialize.
*/
void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin(); // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  lcd.begin(16, 2);
  lcd.clear();
  lcd.print("Scan your card:");
  Serial.println("Scan your card:");
  //Choose which lock below:
  myservo.attach(7); // attaches the servo on pin 7 to the servo object
}

/*
  Helper routine to dump a byte array as hex values to Serial.
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
  read_rfid = "";
  for (byte i = 0; i < bufferSize; i++) {
    read_rfid = read_rfid + String(buffer[i], HEX);
  }
}

void open_lock() {
  //Use this routine when working with Servos.
  lcd.print("Servo Unlocking");
  myservo.write(posOpen);
  Serial.println("Servo Unlocking");
  delay(10000);
  myservo.write(posClosed);
  lcd.clear();
  lcd.print("Servo Locking");
  Serial.println("Servo Locking");
}

void loop() {
  lcd.clear();
  lcd.print("test");
  // Look for new cards
  if (!mfrc522.PICC_IsNewCardPresent())
    return;
  // Select one of the cards
  if (!mfrc522.PICC_ReadCardSerial())
    return;
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  if (read_rfid == ok_rfid_1) {
    open_lock();
    lcd.clear();
    lcd.print(read_rfid + " (FRED FARMER)" + " -Access Granted");
    Serial.println(read_rfid + " (FRED FARMER)" + " -Access Granted");
    delay(10000);
    lcd.clear();
    lcd.print("Scan a card:");
    Serial.println("Scan a card:");
  }
  if (read_rfid == ok_rfid_2) {
    open_lock();
    lcd.clear();
    lcd.print(read_rfid + " (JOHN DOE) " + " -Access Granted");
    Serial.println(read_rfid + " (JOHN DOE) " + " -Access Granted");
    delay(10000);
    lcd.clear();
    lcd.print("Scan a card:");
    Serial.println("Scan a card:");
  } else {
    lcd.clear();
    lcd.print(read_rfid + " -Access Denied");
    Serial.println(read_rfid + " -Access Denied");
    delay(10000);
    lcd.clear();
    lcd.print("Scan your card:");
    Serial.println("Scan your card:");
  }
}

I have tried running the Arduino library's "Hello World" example, and it successfully runs the text onto the screen. Therefore I have determined that it is not a hardware problem, rather a code problem. It occasionally does display "ff" on the LCD, but that's it.

Pins number 12, 11 are used by some other library in your code. And that's the reason there is no LCD output. Change pins/connections from 12, 11 to 7, 6.
Then your code uses lcd.clear() too often, so whatever data you display vanishes before you were able to read. Don't clear the display unnecessarily.

I use the ISCP pins, not all the digital outputs for the MFRC.

Yes, but those pins are connected to the same pins on the chip.  If you use SPI, it doesn't matter what connector you get it from, 11, 12, and 13 are off limits and 10 must be an output.

I just love it when someone gives the correct answer, and the OP says no it's not right without testing it first...

source: Stack Exchange

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

sort: votes


text:
Program does not seem to be passing from setup to loop, or printing to SD card
I am trying to write code to test servo motors using an encoder. I create a file in the setup part, and then set 1500 microseconds to 0 for the encoder. However, if I try to print something to the SD card after I create the file, it will not print to the card. The file is always created but nothing is written to it. I have tested the mapping function separately and it works, but the code never reaches that point. It quits sometime after creating the mapping.txt file but before starting the loop.

// voltage to servo is divided by 3 to get to something usable for teensy

#include <Encoder.h>
#include <SD.h>
#include <SPI.h>
#define numFrame 6750

float twopi = 2.0 * PI;
float hz2rps = twopi;
float rps2hz = 1/hz2rps;

//for the encoder
// Encoder Pins for Channel A and B.
int encPin1=6;
int encPin2=7;

// Per the label on the Encoder this should be 1250 CPR, but 5000 gives actual angle (and is an option that could have been added after purchase)
int pos[numFrame]; // Array to store positions
int pw[numFrame]; // Array to store analog input of PWM

// for writitng to the SD card
File mappingandrange;
File step_file[10];
File bandwidth_file[10];
int filenum=0;
int chipSelect=10;
char buffer[10];

// Encoder
Encoder myEnc(encPin1, encPin2);

float poscmd;
int8_t poscmdInt[numFrame];

// timing variables to stabilize the frame
unsigned long start_frame;
unsigned long stop_frame;
unsigned long stopstop_frame;
unsigned long delta_frame;

int freqFrame_hz = 2000;
int timeFrame_us = 1000000/freqFrame_hz;
int writePwmPin = 5;
int readPwmPin = 2; // Analog pin to readback the PWM out
float freqWritePwm_hz = 333;
float freqPwmCenter_us = 1520.0;
float pulse = (freqWritePwm_hz / 1000000.0) * 65535.0;

float mag = 500.00;
float magScale = pow(2, 15) / mag;
float tEnd_s = 3.0;
float timeCurr_s = 0.0;
float freqStart_rps = 1 * hz2rps; // Start Frequency**
float freqEnd_rps = 30 * hz2rps; // End Frequency**
float freqK = (freqEnd_rps - freqStart_rps) / (2.0 * tEnd_s); // Parameter for Sweep

//things leftover from when i tried to write code
int freq=250;
double average;
double lengthtotalmicros;
double percent;
int analogfreq;
const int servopin=5;
int num=0;
int j=0;
int i=0;
float mapp;
double resistance=1; //resistance of resistor used to measure current though servo
int voltagepin1=1;//very high resistance bridged in parallel with servo
int voltagepin2=2;//very high resistance in parallel with servo
int voltagepin3=3;//low resistance in series with the servo

void setup()
{
  pinMode(servopin, OUTPUT);

  //setup for the sd card
  pinMode(chipSelect, OUTPUT);
  SD.begin();
  mappingandrange=SD.open("mapping.txt", FILE_WRITE);

  //initalize the servo to 1500 microseconds and the position to 0
  servowrite(1500, freqWritePwm_hz, servopin);
  delay(500);
  myEnc.write(0);

}

void loop()
{
  mapp=mapping();

  //setup to run servo_step with magnitude 10 degrees
  filenum=1;
  freqFrame_hz=2000;
  freqWritePwm_hz=333;
  mag=10.0;//magnitude in degrees
  servo_step(filenum, freqFrame_hz, writePwmPin, freqWritePwm_hz, mag, mapp, tEnd_s);

  //setup to run servo_step with magnitude 60 degrees
  filenum=2;
  mag=60.0;//magnitude in degrees
  servo_step(filenum, freqFrame_hz, writePwmPin, freqWritePwm_hz, mag, mapp, tEnd_s);

  //then do setup for the servo_bandwidth function.
   freqFrame_hz = 151; // Command frame rate **** how fast teensy loop runs
   timeFrame_us = 1000000/freqFrame_hz;
   writePwmPin = 5; // PWM write pin # ****servo input pin
   freqWritePwm_hz = 333; // PWM rate **** pwm pulse frequency
   freqPwmCenter_us = 1520.0; // PWM center frequency
   pulse = (freqWritePwm_hz / 1000000.0) * 65535.0; // Scaling for pulse width duty cycle

   mag = 40.0; // This is the PWM magnitude, need to convert from angle to PWM **** need to later convert from degrees using mapping
   magScale = pow(2, 7) / mag; // Scalling so that PWM change can be logged as int8
   tEnd_s = numFrame / freqFrame_hz; // End Time** three below possibly part of function call and change run to run
   timeCurr_s; // Current Time
   freqStart_rps = 1 * hz2rps; // Start Frequency**
   freqEnd_rps = 30 * hz2rps; // End Frequency**
   freqK = (freqEnd_rps - freqStart_rps) / (2.0 * tEnd_s); // Parameter for Sweep

   mag=1;
   filenum=1;
   servo_bandwidth(filenum, freqFrame_hz, writePwmPin, freqWritePwm_hz, mag, mapp,tEnd_s, freqStart_rps, freqEnd_rps);
   mag=3;
   filenum=2;
   servo_bandwidth(filenum, freqFrame_hz, writePwmPin, freqWritePwm_hz, mag, mapp,tEnd_s, freqStart_rps, freqEnd_rps);
   mag=5;
   filenum=3;
   servo_bandwidth(filenum, freqFrame_hz, writePwmPin, freqWritePwm_hz, mag, mapp,tEnd_s, freqStart_rps, freqEnd_rps);
   mag=10;
   filenum=4;
   servo_bandwidth(filenum, freqFrame_hz, writePwmPin, freqWritePwm_hz, mag, mapp,tEnd_s, freqStart_rps, freqEnd_rps);
   mag=20;
   filenum=5;
   servo_bandwidth(filenum, freqFrame_hz, writePwmPin, freqWritePwm_hz, mag, mapp,tEnd_s, freqStart_rps, freqEnd_rps);

for( ; ; )
{
}

}

float mapping()
{

  servowrite(1200, freqWritePwm_hz, servopin);
  delay(250);
  pos[0]=myEnc.read();
  j=1300;
  for(int i=1; i<7; i++)
  {
    servowrite(j, freqWritePwm_hz, servopin);
    delay(200);
    pos[i]=myEnc.read();
    j=j+100;
    mappingandrange.println(pos[i]);
  }
  average=0;
  for(i=0; i<7; i++)
  {
    average=average+pos[i];
    pos[i]=0;
  }
  average=average/i;
  mappingandrange.print("The average number of positions per microsecond lengthened is ");
  mappingandrange.println(average);
  mappingandrange.print("Which corresponds to ");
  mappingandrange.print((average/5000.0)*360.0);
  mappingandrange.print("degrees per microsecond lengthened, or ");
  mappingandrange.print((average/5000.0)*3600.0);
  mappingandrange.println(" degrees per 100 microsecond change");

  mapp=(average/5000.0)*360.0;
  mappingandrange.close();
  return mapp;
}

void servowrite(int widthmicros, int freq, int servopin)
{
  analogWriteFrequency(servopin, freq);
  lengthtotalmicros=(1.0/freq)*1000000.0;
  percent=widthmicros/lengthtotalmicros;
  analogfreq=percent*256.0; // changes how much of the duty cycle is up from 0 to 256
  analogWrite(servopin, analogfreq);
}

//input the magnitude in degrees and then the function will convert them to pwm values necessary
void servo_step(int filenum, int freqFrame_hz, int writePwmPin, float freqWritePwm_hz, float mag, float mapping, float tEnd_s)
{
    //sd assumes that pinMode(chipSelect, OUTPUT) and SD.begin, and file has been declared
  sprintf(buffer, "servo_step %d.txt", filenum);
  step_file[filenum]=SD.open(buffer, FILE_WRITE);
  step_file[filenum].println("Frequency sweep for the given parameters");
  step_file[filenum].print("Command frame rate: ");
  step_file[filenum].println(freqFrame_hz);
  step_file[filenum].print("PWM pulse frequency: ");
  step_file[filenum].println(freqWritePwm_hz);
  step_file[filenum].print("The magnitude of the sweep in PWM microseconds is: ");
  step_file[filenum].println(mag/mapping);
  step_file[filenum].print("This corresponds to a magnitude in degrees of: ");
  step_file[filenum].println(mag);

  //converting degrees magnitude to pwm magnitude
  mag=mag/mapping;

  analogWriteResolution(16); // Setting the write resolution for PWM
  analogWriteFrequency(writePwmPin, freqWritePwm_hz); // Setting the frequency for the PWM update rate
  analogWrite(writePwmPin, freqPwmCenter_us * pulse); // sending the servo to neutral

  analogReadRes(16); // set A/D converter to 16 bit

  delay(1000); // waiting for user to pull up debug serial channel

  //end of setup part of function now moving on to the loop part of function which only actually runs once anyway
  //should run through the frequewncy sweep and print the data to the sd card for the given parameters

  delay(1000); // waiting for starting the test

  poscmd = 0.0;
  int i = 0;
  while(timeCurr_s < tEnd_s){
    start_frame = micros(); // get the start of the frame

    timeCurr_s = (float)(i * timeFrame_us) / 1000000.0;
    if(timeCurr_s > 1 & timeCurr_s <= 2)
    {
      poscmd = mag;
    }
    else if(timeCurr_s > 2)
    {
      poscmd = 0.0;
    }

    poscmdInt[i] = (int)(poscmd/magScale);

    analogWrite(writePwmPin,(freqPwmCenter_us + poscmd) * pulse); // write servo command
    pw[i] = analogRead(readPwmPin); // read the pwm signal
    pos[i] = myEnc.read();

    i++;

    stop_frame = micros(); // get the end of the frame
    delta_frame = stop_frame - start_frame;
    if(delta_frame < timeFrame_us){
      delayMicroseconds(timeFrame_us - delta_frame); // sleeping to stabilize the frame at 100 Hz
    }
  }

  delay(1000); // wait to get the serial monitor open
  for(int j = 0; j < i; j++){ // printing out the stored data so we can import to MATLAB
    step_file[filenum].print(pos[j]);
    step_file[filenum].print("\t");
    step_file[filenum].print(freqPwmCenter_us + (float)(poscmdInt[j]*magScale));
    step_file[filenum].print("\t");
    step_file[filenum].println((float)(pw[j]));

  }
  step_file[filenum].close();
}

void servo_bandwidth(int filenum, int freqFrame_hz, int writePwmPin, float freqWritePwm_hz, float mag, float mapping, float tEnd_s, float freqStart_rps, float freqEnd_rps)
{
    // assumes that pinMode(chipSelect, OUTPUT) and SD.begin();
  sprintf(buffer, "servo_bandwidth %d.txt", filenum);
  bandwidth_file[filenum]=SD.open(buffer, FILE_WRITE);
  bandwidth_file[filenum]=SD.open(buffer, FILE_WRITE);
  bandwidth_file[filenum].println("Frequency sweep for the given parameters");
  bandwidth_file[filenum].print("Command frame rate: ");
  bandwidth_file[filenum].println(freqFrame_hz);
  bandwidth_file[filenum].print("PWM pulse frequency: ");
  bandwidth_file[filenum].println(freqWritePwm_hz);
  bandwidth_file[filenum].print("The magnitude of the sweep in PWM microseconds is: ");
  bandwidth_file[filenum].println(mag/mapping);
  bandwidth_file[filenum].print("This corresponds to a magnitude in degrees of: ");
  bandwidth_file[filenum].println(mag);
  bandwidth_file[filenum].print("The starting frequency is: ");
  bandwidth_file[filenum].println(freqStart_rps);
  bandwidth_file[filenum].print("The ending frequency is: ");
  bandwidth_file[filenum].println(freqEnd_rps);

  mag=mag/mapping;

  analogWriteResolution(16); // Setting the write resolution for PWM
  analogWriteFrequency(writePwmPin, freqWritePwm_hz); // Setting the frequency for the PWM update rate
  analogWrite(writePwmPin, freqPwmCenter_us * pulse); // sending the servo to neutral
  delay(1000); // waiting for user to pull up debug serial channel

  // loop part of function below
    delay(1000); // waiting for starting the test

  for(int i = 0; i < numFrame; i++){
    start_frame = micros(); // get the start of the frame

    timeCurr_s = (float)(i * timeFrame_us) / 1000000.0; // Current time
    poscmd = mag * sin(freqStart_rps * timeCurr_s + freqK * timeCurr_s * timeCurr_s); // Sweep signal
    poscmdInt[i] = (int)(poscmd*magScale); // integer conversion for logging
    analogWrite(writePwmPin,(freqPwmCenter_us + poscmd) * pulse); // write servo command
    pos[i] = myEnc.read(); // read encoder value

    stop_frame = micros(); // get the end of the frame
    delta_frame = stop_frame - start_frame;
    if(delta_frame < timeFrame_us){
      delayMicroseconds(timeFrame_us - delta_frame); // sleeping to stabilize the frame
    }
  }
  //delay(1000); // wait to open the serial monitor
  for(int j = 0; j < numFrame; j++){ // printing out the stored data
    bandwidth_file[filenum].print(pos[j]);
    bandwidth_file[filenum].print("\t");
    bandwidth_file[filenum].println(freqPwmCenter_us + (float)(poscmdInt[j]/magScale));
  }
  bandwidth_file[filenum].close();
}

You can't really expect people to wade through over 300 lines of poorly formatted code to find your bugs. At the very least, you should have isolated the part of the code you suspect is wrong, as well as say what individual tests you run to ensure it's not some piece of hardware that's failing.

Its very difficult to try and guess what is happening in your code.  Why have you declared the FILE variables at global scope when they could be within the functions?   If your code isn't executing mapping(), but is opening the file, then one of the last three lines of setup has to be the caused, can you focus on that, add Serial.Print to the code to see where it is dying.

Literal buffer overflow in servo_step.   You define it as array of 10 chars waaay up top, then attempt to put more than 14 chars via sprintf in servo_step.   Bad Things™ happen thusly.   May be other issues, but that one is bad enough to cause failure.

On first view: You open the SD-Card file but you don't close it in setup. I am not sure if that will work. When I use the SD card I open the file, write, close the file, and continue with other steps. If any "external" value is written to the card then I save that value to a variable before I open the file to make sure when the SD card is busy nothing else is used.

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


text:
How can I made my Arduino follow the time exactly?
I am making an Arduino clock. You can set time to it, and then it keeps on going. The problem is that it is always within a minute off. It is not a major issue, but one that I would like to fix. I use the millis function. The program checks if millis is evenly divisible by 60,000(1 minute). After I set the time, millis is NOT at 0, meaning that is ahead of what I set by a number of seconds. How can I fix this? Code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int hours=0;
int minutes=0;
const int modePin=6; //button
int prevModeState=HIGH; //prev state of button
unsigned long timer;
int modeState;//current state
int mode=0;//mode of alarm
int buttonCounter=0;
const int incrementPin=9;
const int switchPin=7;
int incrementState;
int switchState;
int prevIncrementState=HIGH;
int prevSwitchState=HIGH;
int switching=0;

void setup() {
lcd.begin(16, 2);
lcd.setCursor(6, 0);
lcd.print("Time:");
lcd.setCursor(6, 1);
lcd.print("00:00");
pinMode(modePin, INPUT_PULLUP);
pinMode(incrementPin, INPUT_PULLUP);
pinMode(switchPin, INPUT_PULLUP);
}

void loop() {
modeState=digitalRead(modePin);
if(prevModeState!=modeState){
      prevModeState=modeState;
   if(modeState==LOW){
    buttonCounter++;
  if(buttonCounter%2==0){
    mode=0;
    lcd.clear();
    lcd.setCursor(6, 0);
    lcd.print("Time:");
    writeTime();
}
  else{
    mode=1;
    switching=0;
    lcd.clear();
    lcd.setCursor(4, 0);
    lcd.print("Set Time:");
}

   }
  }
if(mode==0){
  timer=millis();
  if(timer%60000==0){
     minutes++;
    writeTime();
    }
}
else if(mode==1){
 incrementState=digitalRead(incrementPin);
  switchState=digitalRead(switchPin);
  if(prevSwitchState!=switchState){
    prevSwitchState=switchState;
    if(switchState==LOW){
    switching++;
    }
    if(switching==4){
      switching=0;
    }

    }

  if(prevIncrementState!=incrementState){
    prevIncrementState=incrementState;
    if(incrementState==LOW){
      if(switching==0){
        if(hours<14){
        hours+=10;
        }
        else if((hours>=14)&&(hours<20)){
        hours-=10;
        }
        else{
          hours-=20;
        }
        }

        else if(switching==1){
          if((hours==9)||(hours==19)){
            hours-=9;
          }
          else if(hours==23){
            hours-=3;
          }
          else{
          hours++;
          }
        }

        else if(switching==2){
          if(minutes<50){
             minutes+=10;
          }
          else{
            minutes-=50;
          }

        }
        else if(switching==3){
          if(minutes%10==9){
            minutes-=9;
          }
          else{
          minutes++;
          }
        }

    }

  }

  writeTime();
}
}

void writeTime(){
  lcd.setCursor(6, 1);
   if(minutes>=60){
        minutes=0;
        hours++;
        }
     if(hours>=24){
        hours=0;
     }
if(minutes<10){

      if(hours<10){
        lcd.print(String("0")+hours+":"+"0"+minutes);
      }
      else{
        lcd.print(hours+String(":")+"0"+minutes);
      }
    }
    else{
      if(hours<10){
         lcd.print(String("0")+hours+":"+minutes);
      }
      else{
         lcd.print(hours+String(":")+minutes);//possibly split if problems arise
      }

    }
}

Three things you can do - any combination of these is good, but the more the better:

Use an RTC module to keep more accurate track of the time.
Connect the Arduino to the internet and use NTP to get the exact time.
Use the time provided by GPS.

The RTC chip can keep track of time when there is no external power, using just a very small button cell.
The GPS and internet time are both very accurate.
Using either or both of those sources to set and maintain the correct time in the RTC chip is the best and most accurate way of keeping the right time on the Arduino.
To increase the accuracy of your existing method you should count seconds, not minutes.
Start by recording the current millis. When 1000 of them have passed you can increase your seconds.  Don't rely on millis() % 1000 since you may miss it whilst doing other things. Also don't rely on your millisecond counter check executing at exactly 1000ms intervals - work on the principle of "at least 1000ms" and move the next check to 1000ms from where it should have happened, not where it did happen.  This can help to combat some clock drift.
static unsigned long mscount = millis();

if (millis() - mscount >= 1000) {
    mscount += 1000;
    seconds ++;
}

Then every 60 seconds you can increase your minutes:
if (seconds == 60) {
    seconds = 0;
    minutes ++;
}

I am completely satisfied with the accuracy of the method I am using. What I need is a way to have the program to start at 0 milliseconds once I set the time.

@NickSolonko You could count in seconds instead of minutes - that would increase your accuracy to 1 second.  Every 1000ms increase a seconds counter by 1. Every 60 seconds increase the minutes by 1. You control the seconds then, and decide where 0 seconds starts from. You can even include it in your display if you want. Also, don't look for "exactly % 1000" since you may miss it. Instead look for "at least 1000ms since I last ticked" and subtract 1000 from your tick counter.

I am doing %60000 now and it works fine. I have been testing the clock for the last 3 hours and it is still only 7 seconds off. Is there a reason why doing %1000 will not work?

You only have a 1 millisecond window with %, and there is now way of saying only to execute it once for that millisecond. It is very unsafe. Do it the way I have shown you.

@NickSolonko If your loop takes less than 1ms to execute then you may execute your % 60000 more than once, thus incrementing multiple minutes together. If your loop takes more than 1ms to execute then you may miss out on a % 60000 altogether and not increment a minute at all.

Will there be a difference if I declare unsigned long timer before the setup? You declared it using the static keyword inside the loop.

@NickSolonko: On the Uno, millis() does not count every millisecond: it is updated only every 1024 µs, which means it has to skip roughly one out of 43 milliseconds.

The GPS and internet time are both very accurate.; GPS is actually 36 seconds ahead of UTC.

@Gerben But it is very accurately 36 seconds ahead. Or is UTC 36 seconds behind GPS?

@Majenko :-) . I think the word you are looking for is precision. GPS is very precise, but 36 seconds from being accurate. As GPS doesn't do leapseconds, and was already 10 seconds ahead at launch, it's safe to say UTC would be the more appropriate time unit.

@Gerben No, UTC was 10 seconds behind at launch, and keeps leaping around the place :P

It seems the Time Wars have started :-P. We should just strap some rockets to the earth to make it spin at a consistent speed, so we don't need leap seconds anymore.

@Gerben Nah - we should decimalize time. 100 seconds to the minute, 100 seconds to the hour, 10 hours to the day :P

First of all, let me second Majenko in suggesting the use of an RTC. The
Arduino Uno is clocked from a ceramic resonator, and these are nowhere
accurate enough for proper timekeeping. C.f. the answers to How do I
get an accurate time?.
Next, instead of counting seconds, I suggest you instead count
milliseconds. I know it sounds like overkill, but it's actually
simpler because you already have millis() returning a millisecond
count:
void loop()
{
    uint32_t now = millis();
    static uint32_t last_minute;

    // Increment the time every minute.
    if (now - last_minute >= 60000) {
        last_minute += 60000;
        if (++minutes >= 60) {
            minutes = 0;
            if (++hours >= 24)
                hours = 0;
        }
    }

    // Do not advance the seconds when the user sets the time.
    if (time_is_being_set_by_the_user()) {
        last_minute = now;
    }
}

Oh, wait! No! Do not count milliseconds, instead count microseconds:
void loop()
{
    uint32_t now = micros();
    static uint32_t last_minute;

    // Increment the time every minute.
    if (now - last_minute >= 60000000) {
        last_minute += 60000000;

        // The rest does not change...
    }
}

Why? Because, as I said before, the ceramic resonator of your Arduino is
not very accurate. You will eventually find out that it drifts
significantly. However, if you compare to a good reference, you will be
able to calibrate the drift. If, for example, you find that it drifts
forward by 0.0025% (about 15 seconds per week, quite optimistic), you
will be able to fix it simply by replacing 60000000 by 60001500. The
same would work if counting milliseconds, except that you would only be
able to do a coarse tuning. Oh, and do not worry about micros()
overflowing.

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


text:
ESP8266 - Error: unknown opcode or format name 'jmp'
I bought a nodeMCU 8266 and I'm hoping that it can replace my bulkier UNO+WiFi 101.
I'm getting an error when I compile:
Error: unknown opcode or format name 'jmp'
I'm using it in void SoftReset() function:
void softReset() {
  delay(1000);
  asm volatile ("  jmp 0");
}

This reset works great with my Uno+101 setup but, for whatever reason, doesn't like the ESP8266.  I removed the WiFi101 library and added the ESP8266 WiFi libraries.  That has been the only change.
Can you please help me understand why I'm receiving this error?
EDIT:  I have read this SO answer but the "syntactical sugar" didn't work for me.
I am also perusing various ESP8266 sites but they are not as well managed as SE/SO and answers are tough to find.

The proper way to reset the esp8266 when using the Arduino IDE is to call ESP.reset(). You may need to #include <Esp.h>, but almost all esp8266 headers you include to use any of its functionality will have included it already.

The ESP8266 is not an Arduino Uno. It talks a completely different language.
It's like you're talking Spanish to a Chinese person. It can't understand you.
If you want to use assembly language then you have to use the assembly language of the chip you are programming for - not the assembly language of a completely different chip.
The assembly language is detailed here: http://techblog.realisaatio.fi/wp-content/uploads/2015/04/xtensalx_overview_handbook.pdf
Bear in mind, though, that jumping to 0 may not reset the device - it may do something nasty.
The only sure-fire way of resetting a chip where you don't really know what is going on inside is to connect a GPIO signal to the RESET pin and use that GPIO to pull RESET low and reset the board that way.
If you want to call address 0 and don't know how to do it in assembly there are ways of arranging it in C using a function pointer:
void (*addressZero)() = 0;

void setup() {
    addressZero(); // Call address 0
}

void loop() {
}

That way it will work on multiple different architectures without having to understand the underlying assembly language.  That, of course, is assuming that calling address 0 is a valid way of resetting the board on the target chip.
Browsing through the document I link to above it looks most likely that you would first have to load a register with 0 and then use JX to jump to the address stored in the register (i.e., zero).

The answer here (http://arduino.stackexchange.com/questions/19985/esp8266-arduino-ide-vs-lua-script/19987#comment49000_19987) seems to disagree.  Specifically, my question: "Is using the Arduino IDE with a fresh out of the box ESP8266 as simple as compiling and uploading or do you need to "clean out" the ESP first? I've held off on buying an ESP because I'm not clear on what I need to do to make it work with the Arduino IDE."  Answered: "Yes, you just compile and upload...."

Compiling C is not assembling ASM code. The two are very different. When you compile C it first converts it into the assembly code of your target chip. Each chip family has its own compiler that creates the ASM code that is specific to that chip.

In my experience, the ESP8266 is very particular about what you do in the loop function - running while(true); will (OK, may, I've never done this) trigger a reboot (eventually, matter of a few seconds I think) -

@JaromandaX That is probably the watchdog I would guess. It may well be enabled by default on there.

@Majenko - yes, it is the watchdog that triggers the reboot. I've accidentally written code that takes WAY too long in the loop, and have triggered this type of reset. As I said though, I've not deliberately triggered a watchdog initiated reboot

Alright. If I understand this correctly, an ESP8266 can run an Arduino sketch provided that I'm not asking it to assemble a language it doesn't understand, asm volatile ('  jmp 0') in this case.  Also, jumping to zero isn't necessarily the right thing to do.

That is correct. As long as you stick to c and c++ using the Arduino API and the libraries written for the ESP8266 all will be well.


text:
Need help on HC05 and Nano
I am new to Arduino programming and currently working on this instructable
http://www.instructables.com/id/Control-Led-RGB/ (following this diagram http://cdn.instructables.com/F6Q/IMHF/I0LCDK6B/F6QIMHFI0LCDK6B.LARGE.jpg)
I have ordered these parts as well.

Arduino Nano: www.ebay.in/itm/Arduino-Nano-SOLDERED-PINS-V3-0-ATmega328-CH340G-BUY-2-GET-1-USB-CABLE-FREE-/172117729247?
HC-05: www.amazon.in/Bluetooth-Transceiver-Module-TTL-Outputs-HC05/dp/B00R95Y0AK?ie=UTF8&psc=1&redirect=true&ref_=ox_sc_act_title_2&smid=A1NDZY44BCNIQJ

My questions are:

Is there need to add voltage divider? If yes can you please provide link?
Can I connect two 5050 RGB modules?
Will 12 V, 1 A will be enough to power this board.

1A will be enough to power you arduino but the total powerconsumtion will depend on the amount of leds that you want to drive. If you follow the instuctable, it should be enoug but it's never a good idea to use your power source at max capacity all the time.
It allows you to connect 2 modules indeed.
Why would you need a voltage divider?

hc05  logic works on 3.3v please check the ebay link  thats why l want know about divider

Your arduino can give you 3.3V for powering it. If your board doesn't accept 5V logic, then you'll need a voltage level shifter.

do you have any link or example which I can use?

https://www.sparkfun.com/products/12009


text:
Piezo not loud enough
I'm trying to get 110dB out of a 25khz Piezo Transducer.  This piezo resonates at 25khz and as per the illustration in its datasheet should emit 110dB with 10 volts and 25khz frequency.
Any assistence as to what I'm doing wrong here would be GREATLY appreciated !!
My code is bit-banging it.  With an oscilloscope, I confirmed that I'm getting a nice clean 25khz square wave.
I have attached a step-up circuit to the device and am seeing 10volts across the terminals of the piezo while it is emitting it's 25khz frequency.
However, instead of 110dB, I'm only getting 50dB.
I've tried upping the voltage to 20, and still get the same volume level.  The voltage is adjustable via the screw on the top of the blue capacitor on the Voltage Step Up (pictured below).
I've tried changing the duty cycle having HIGH go for 25microseconds and LOW go for 5microseconds.  I've tried several combinations and a 50/50 duty cycle appears to achieve maximum volume which is 50dB.
Here's how I'm connected:
1.  The inputs of the Step Up are attached to GND and 3.3V pins on the Arduino.
2.  The output+ of the Step Up is connected to 1 pin of the Piezo.
3.  The output- of the Step Up is NOT connected to anything. (tried to connect it to GND but it didn't change anything.
3.  The other pin on the Piezo is connected to D11 on the Arduino.
I'm Running the following code:
 #include<Wire.h>

const int SPK = 11;

void setup()
{
  Serial.begin(9600);
  pinMode(SPK, OUTPUT);
  digitalWrite(SPK, LOW);
}

void loop()
{
  long startTime = millis();
  for (int i = 0; i < 25000; i++)
  {
    digitalWrite(SPK, HIGH);
    delayMicroseconds(15);
    digitalWrite(SPK, LOW);
    delayMicroseconds(15);
  }

  Serial.println(millis() - startTime);
}

UPDATE:
Ok, I am now set up to look like this:

Is this the next step (ie: Adding an Inducer) ?

How have you mounted the piezo? Just like speakers, it's all about the enclosure. Also, solidly mounting it to something, means any deflection of the piezo means movements of air, instead of movement of the piezo if it's just hanging in free air.

The device you pictured seems to be a switch-mode power module which will output 10V DC. Get rid of it before you do any damage.
You don't post any link to data, but I assume you mean the Transducer needs 10V peak-to-peak.
This can easily be accomplished by using 2 digital outputs, connected to the transducer, and driven in anti-phase.
The answer to Push-Pull tone code may be an answer to your problem, but may be overkill. If you just want to output a single tone it is easily done with simple code.
I don't know why you think the transducer outputs 50dB. If it really is doubling the drive voltage will only give 56dB.

Ye HAAA!!!  We're getting closer..  I'm at 85dB now at 1" away from the piezo.  Any ideas how to get 25 more db out of the piezo??  It may not need a full 10 volts to achieve 110db.  We're really close, but I need 110db.  Any ideas how to achieve this?

@Milliways, isn't your anti-phase comment more like 2.5 volts peak-to-peak for a 5 volt Arduino?  That is, if you put an AC coupled scope across the transducer ... I think you would see it deflect up 2.5 volts then down 2.5 volts.

@st2000 the same misinterpretation was made in a comment to  my original linked question. The answer I made then still applies. It is simple circuit theory.

@Milliways, I'm here to learn, so tell me why you are right. The linked question was about an inductive load.  Guessing, a piezo may appear as a capacitive load?  Is that why you are saying it will retain a potential for a total of 5v + 5v = 10v after the switch?  If so would adding a (tuned) capacitor-resistor-circuit in series add to this effect?

@st2000 I am quite willing to help, although this would be better asked as a question on the EE site. Unfortunately I can't give a lesson in circuit theory in comments. Marenko's comment is correct, but it has nothing to do with inductive or capacitative loads. My original Q was about piezo (which is capacitative) - in fact the push-pull is better, because it puts no nett DC across the transducer. You just have to work out the instantaneous voltages at either end then TRANSFORM to a common reference. Why not give it a try - it works, and is common method- previously used in power amplifiers.

I'll put a question on the EE site.  Thanks for the advice. I really appreciate it !!

Alternatively there are COTS parts (Common Off The Shelf) which are simpler to use and may satisfy your requirements.  This is just the 1st one I found (search for "5 volt piezo buzzer").  Of course you have no control over the frequency.  These type of devices are just to get your attention (you didn't say what your application was for).   While it works at 5 volts it is only rated at 85dB @ 10cm.  It appears to contain an internal driver so (apparently) only needs 3 to 15 volts to start making noise.  It is specified to draw 10mA at 12V.  So be careful and measure the current (using a power supply, not from an Arduino) demand at 5 volts.  I think the GPIO pins on an Arduino can only handle less than 40mA.  So stay well below that to be safe.


text:
trying to discover other nrf24 modules
Today I started messing with the idea of getting an arduino uno to autoconnect with another arduino uno using the nrf24l01 breakouts.
I dont have a particular goal in mind per se but was just wanting to get the logistics down so I started simple as pie.  One arduino at address 0x0000000B LL sends a one element array over and over.  Easy.
The second arduino goes through a for loop in the void loop().
The for loop is set to loop 16 times.  It starts with the address 0x00000000 LL and checks to see if radio.available is true.  if it is, the program simply states it has found an address over serial.  If not it states the address is invalid.  afterwards it increments the address by one and repeats until the address gets to 0x0000000F LL (or the for loop repeats 16 times.)
once the address gets to 0x0000000B (or the transmitter address) it states that it has found an address over serial.  So far so good!
Now the problem arises when the address increments to the next address.  No matter what I seem to do or change, once radio.available() becomes true once....it seems to stay true until the function is called again from the main loop in which case it repeats the same scenario.  I have worked hours on such a small program to no avail.  Can someone help please???  I must be overlooking the most simple of things but for the life of me I have no idea what.
Super Simple TX Code.
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(8,9);
uint64_t myAddress = 0x0000000BLL;
byte txData[] = {1};

void setup()
{
  while (!Serial);
    Serial.begin(9600);

  radio.begin();
  radio.setRetries(15, 15);
  radio.openWritingPipe(myAddress);
}

void loop()
{
  if( Serial.available() )
    {;}

  radio.write(txData,sizeof(txData) );
  Serial.println("Sent a packet");
}

RX CODE
#include <nRF24L01.h>
#include <RF24.h>

RF24 myRadio(8, 9);

byte rxData[] = {0};

void setup()
{
  while (!Serial);
    Serial.begin(9600);

  myRadio.begin();
  myRadio.setRetries(15, 15);
}

void loop()
{
  if( Serial.available() )
    {;}
    //function that searches through a set of 16 addresses
    searchAddresses();
}

void searchAddresses()
{
  //declare a temp address variable
  //and initialize it to first possible address
  uint64_t tempAddress = 0x00000000LL;

  myRadio.openReadingPipe(1, tempAddress);
  myRadio.startListening();

  for (int x =0; x < 16; x++)
  {
      if ( myRadio.available() )
      {
        myRadio.read(rxData, sizeof(rxData) );
        Serial.println("Found an address");
      }
      else
      {
        Serial.println("Address Invalid");
      }
      //increment temporary address to next address
      tempAddress++;

      myRadio.openReadingPipe(1, tempAddress);
      myRadio.startListening();
  }
}


text:
Lighting LED Strip via HC-06 Bluetooth Module
What I Am Working With:
I am working on a project involving an Arduino, some RGB led strip, and my PC.
My Project:
The PC sends UART (serial) data to the Arduino over Bluetooth (through a HC-06 Bluetooth module connected to the Arduino) to change the color of the LED strip. The user could also change "lighting modes" to instruct the Arduino to make the LED blink, fade, etc.
My Problem:
Having no RTOS nor interruptions on data reception, it would be impossible for me to make the LED fade and, also, to receive Bluetooth data to change the lighting mode.
I would appreciate whatever input the community has regarding this problem.
Thanks in advance,
Stanislas.

Welcome. Possibly adding the code you have so far, a schematic and possibly what else you have done to attempt the project.

I'm not at home at the moment, but I'll post that as soon as I get home.

Received serial data is being buffered (in the background). So you only need to occasionally call Serial.available to see if there's any new data.

There are numerous tutorials available online for controlling LEDs from the Arduino over a Bluetooth connection. You might find some of them helpful: Circuit Magic's tutorial, SoldererTV's tutorial. To change the behavior of the LED, just manipulate the serial data you communicate over the HC-06 in much the same way described in these tutorials

Also, it would be helpful to know what model of Arduino you are using when it comes to specifying the appropriate pins to use.

I'm using the arduino uno and plan to use the arduino nano

Thanks you for the edit, this is my first post on this forum, my apologies for this badly written post!

Yes, it can be done. You don't need a realtime OS for something as simple as that. Basically in your loop function you would check the serial port and parse the input (if available) to see if the PC instructed the arduino to change its mode. Then you would call a function - say nextstep() - which would perform whatever the next step is, depending on your current mode. True, when you get serial input your loop() will take longer to execute, which will alter the 'rhythm' of your fades etc. If this is important, you should replace the call to delay() with a loop checking millis() against a value stored at the start of loop().
int currentmode ;
int previousmode ;

void loop()
{
   previousmode = currentmode ;
   currentmode = getnewmode(currentmode) ;
   if (currentmode != previousmode)
      initmode(currentmode) ;  // turn new mode on e.g. change LED color
   nextstep(currentmode) ;     // if current mode is dynamic, make change
   delay(DELAY_INTERVAL) ;
}

int getnewmode(oldmode)
{
   if (!serialpending()) // no serial input
      return oldmode ;
   return parseinput() ;
}


text:
Is it possible to overclock the baudrate from the mega to 230400 bps?
i have a Arduino Mega 2560 and want send data with 230400bps to my laptop without any framingerror.
I want send the data over USB with serial.print ist that possible or must i use the ethernet?
When that is possible it will be really nice when someone can write what i have to do.
With friendly wishes sniffi

This might interest you; http://forum.arduino.cc/index.php?topic=150299.555. See section on UART optimization and the benchmark https://github.com/mikaelpatel/Cosa/blob/master/examples/Benchmarks/CosaBenchmarkUARTburst/CosaBenchmarkUARTburst.ino. What effective baud-rate are you looking for?

I need 230400 bps, my protocol has 38400 and i add 5 bytes (4 timestamp 1 byte filled with flags) so 6*38400= 230400 i think.

The error rate at 230400 bps with system clock 16 MHz is very high. 250000 bps is much better. Please see the AVR baud-rate calculation.

Is it possible to overclock the baudrate from the mega to 230400 bps?

Yes, setting that baud-rate is not a problem but this specific baud-rate may will give a high error rate. According to the AVR baud-rate calculation (UBRRn Settings for 16 Mhz system clock) the error is 8.5% (U2Xn=0) and -3.5% (U2Xn=1).
Simply choosing 250000 bps will remove this error.
Cheers!

Ok i can use 250kbps that will be work but what means -3.5% is 0% not the best?

How can i change the baudrate? I have switch the buffer from 8 bit to 16 bit because i need the second byte for my statusbit´s (e.g. my 9 bit protocol), is that still possible?

The error is generated sampling frequency relative optimal. Negative (as -3.5%) means the generated frequency is too low. To change the baudrate see Serial.begin() https://www.arduino.cc/en/Serial/Begin

You need to open a new question for the 8 to 16 bit. That is a new "can of worms". And you need to acknowledge if you think the original question has been answered :)


text:
AVRDUDE Error (Arduino Leonardo)
I, like many others, have encountered the avrdude error. However, I am not sure how to go about fixing mine after looking at numerous forums, etc.
avrdude: verification error, first mismatch at byte 0x0002
     0x74 != 0xe6
avrdude: verification error; content mismatch

I am simply trying to upload a simple sketch, but right when it seems it is about to finish, I get this error and the uploading loading bar simply never finishes...
Thanks for the help!

I had lots of issues when I first started.  these are all things I tried and at least one of them stopped this problem occurring, but I haven't a clue which.

Close the IDE (if you are using it and open it again)
Disconnect your board, wait 10 seconds and reconnect it.
Check you settings, are you using the correct board, etc.
Use a different cable.
Update your drivers.
Update your IDE/Toolset.
Use a different physical port on your PC.
Load the Blink example, if that doesn't work you serious have issues.
Reboot your PC.
If you can, try a different PC.

So I have tried all of those except for 5 and 6. I have a mac so I am not sure how to update my drivers since they were automatically downloaded.

Damn, always makes it more difficult when people have odd hardware platforms :).   Does it work when you try and upload blink?

I does not, gives me the same error actually.

Do you have a spare board?
Are you communicating via a 3rd party board (a USB to TTL device?)

I do have a spare board, another Arduino Leonardo that works just fine. It is only this one that for some reason has been giving me this error. And I am not sure what to do.

You can try to use your spare board to flash bootloader as ArduinoISP. It can be used to upload sketches too, but it is not so comfortable as direct upload. And if this doesn't work, you have some more serious problem.

I have a USB socket on the PC which causes the Arduino to lose track of its COM port although apparently Ok with other USB devices. Check your COM port before and after you try uploading.


text:
Overwritten EEPROM
I have a problem with the Teensy, its EEPROM and another Array.
My program contains two Arrays, the first one is a 128x4 long Array, the other one a 2560x2 double Array. The first Array is meant to be written to the EEPROM once a certain time (=number of loops) is reached. The other Array is meant to be written to an SD-Card or just the terminal, can't deiced yet.
My problem is that whenever I uncomment the save()-function the first 17 data-quadruples in the EEPROM get somehow overwritten by random data. Always the first 17 with would be the first 68 numbers or 272 byte.
I have tried renameing the save()-function, but the onlything that works for now is to comment the function in the loop()-function out so that it won't be called at all. I even have enough RAM left, the Arduino IDE tells me I am using about 73% of the RAM for variables.
Could it be that be creating more variables somewhere else the Teensy overwrites the Array for the EEPROM? But than again why doesn't that happen if I don't write into the everything-Array?
Thank you in advance for any help!
Greetings,
John
PS: Please excuse my not perfect English for it's not my native language.
//Includes
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <SPI.h>
#include <String.h>
#include <EEPROM.h>

elapsedMillis looptime = 0; //time for each loop in ms
int loopnumber = 0; //number of loops
elapsedMillis overalltime = 0; //overalltime in ms
const int iterationtime = 25; //time for each loop in ms

//EEPROM
//Deklarations
int nsd = 0; //counter for saving into eepromArray
const int maxArrayrows = 128; //Max number of row in eepromArray
int iArray = 0; //Number of used rows in eepromArray
long eepromArray[128][4]; //Array for EEPROM-storage
bool writtentoEEPROM = false;
double everything[2560][2]; //Big Araay with a pair of numbers of each loop

// Some more variables
double z, zpunkt, alpha, angle;

void setup() {
 // Just inititialing stuff, nothing to do with the Arrays
}

void loop() {
  //Calculating more stuff

  ++nsd;
  if (nsd >= 20) {
    WritetoArray();
  }

  save(loopnumber);

  ++loopnumber;

  looptime = 0;
}

//********************************************************
//
// Save Data in Array. If full write into EEPROM
//
// long: 4 byte
// Storeage needed for each quadruple: 4*4 byte = 16 byte
// EEPROM-size: 2 kibyte
// Max number of quadruples: 2048 byte / 16 byte = 128
// Quadrupels per second: 2
// Max time: 128 / 2 = 64 s
//
//********************************************************
void WritetoArray() {
  int scale = 10000;
  long zArray = (long)(scale * z);
  long zpunktArray = (long)(scale * zpunkt);
  long alphaArray = (long)(scale * alpha);
  long angleArray = (long)(scale * angle);
  if (iArray < maxArrayrows) {
    eepromArray[iArray][0] = zArray;
    eepromArray[iArray][1] = zpunktArray;
    eepromArray[iArray][2] = alphaArray;
    eepromArray[iArray][3] = angleArray;
    ++iArray;
  }
  else {
    if (writtentoEEPROM == false) {
      WritetoEEPROM();
      writtentoEEPROM = true;
    }
    while(true){
      for(int n = 0; n < 2560; ++n){
        Serial.printf("%f, %f\n", everything[n][0], everything[n][1]);
      }
      Serial.println("----------");
    }
  }
  nsd = 0;
}

//********************************************************
//
// Write Data to EEPROM
//
//********************************************************
void WritetoEEPROM() {
  byte data;
  int adress = 0;
  int  i = 0;
  while (adress < 2048) {
    for (int n = 0; n <= 3; ++n) {
      for (int a = 0; a <= 3; ++a) {
        data = (eepromArray[i][n] >> ((3 - a) * 8)) & 0x000000ff;
        EEPROM.write(adress + a, data);
      }
      adress = adress + 4;
    }
    ++i;
  }
}

//********************************************************
//
// Save data-pair for later usage
//
//********************************************************
void save(int l) {
  everything[l][0] = z;
  everything[l][1] = angle;
}

Are you never resetting loopnumber to 0 once it gets greater than 2559?

In your loop(), you increment repeatedly loopnumber without ever resetting it. You should at the very least replace
loopnumber++ ;

with
loopnumber = (loopnumber+1)%2560 ;

Otherwise, when loopnumber becomes >= 2560, your save() function will begin writing outside the 'everything' array and overwriting whatever is written in the adjacent positions of memory.

You mean loopnumber = (loopnumber+1)%2560. What you wrote is undefined behavior.

@Edgar Bonet : You seem to be right. I fixed the code accordingly.


text:
What is using up all the RAM in my program?
I am running a program on the ATtiny and for some reason I am way over the 512 bytes of RAM that are available to me. This is confusing because when I did the math by hand I should have 432 bytes. Here is my code:
#include <SoftwareSerial.h>

#define FASTADC 1

// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

SoftwareSerial mySerial(0,1);    //This uses 47 bytes of RAM

byte i = 0;      This uses 1 byte of RAM

byte pixelsArray1[128];   //Arrays use 128 bytes of RAM each
byte pixelsArray2[128];
byte pixelsArray3[128];

void setup()
{
#if FASTADC
// set prescale to 16
sbi(ADCSRA,ADPS2);
cbi(ADCSRA,ADPS1);
cbi(ADCSRA,ADPS0);
#endif

pinMode(1,OUTPUT);        //Setting the 1 pin to be used for output
pinMode(0,OUTPUT);        //Setting the 0 pin to be used for output
pinMode(A3,INPUT);         //Input for Camera 3
pinMode(A2,INPUT);         //Input for Camera 2
pinMode(A1,INPUT);         //Input for Camera 1

mySerial.begin(9600);     //Setting the data transfer rate
}

It's telling me that I am using 510 Bytes of memory but my math gave me 432 bytes of RAM. Does anyone see what I'm missing?

You should ask avr-objdump.

Out of interest how did you come up with your 432?

3*128 Arrays + 47 SoftwareSerial + 1 byte variable = 432

Which ATtiny are you using? Are you using SoftwareSerial for sending, receiving or both?

I'm using the ATtiny85 which has 512 bytes of RAM. Also I'm using the ATtiny to program a camera so I'm assuming that SoftwareSerial is used for both. Sorry, but this is my first Arduino Project ever.

What are you going to store in those pixel arrays? Since they already use 384 of the 512 bytes, it's the best candidate to save memory. If e.g. you pixels are only the values 0-16, you could compress to pixels into a single byte.

The pixels are the most important part of this entire program. The program is basically working a camera and storing the output.

There is a lot you are missing.  Such as:

SoftwareSerial is using RAM.
The system stack is using RAM.
The Arduino core software is using RAM.

There's plenty more going on than just your sketch. For instance, where do you think it stores the current millis() and micros() counts? Where do you think incoming serial data gets buffered? Where do you think your registers, PC, etc, get stashed when a function (such as setup()) is called? All that takes RAM.

She already counted SoftwareSerial, and the stack is not in the 510 bytes reported by the compiler. So this leaves only the Arduino core.

So is there any way I can reduce the amount of memory being used without scrapping my Arrays? For example, is there a way to NOT store the current millis() and micros() or is there an alternative to SoftwareSerial?

You should use avr-objdump to examine all the section sizes and determine what can be removed - then remove it. That means manual editing of core code.

How can I edit the avr-objdump? It's a .exe file and how do I know what I can remove. Again, I'm sorry but this is my first ever Arduino project.

You don't edit avr-objdump - you use it to examine your .elf file. That will allow you, if used right, to list all the variables in your .elf file. You can then look to see what there is. You can then match those up to variables in the core software and determine if you need the functionality associated with those variables - and if not then delete it wholesale.

@CrystalPritzker: Did you miss the link in my first comment?

@EdgarBonet No I found the avr-objdump file but couldn't execute the command he gave. It's probably because I'm using Windows.

@Majenko Does avr-objdump work on Windows? If so can you please tell me how?


text:
Extracting a specific sequence of characters from an array
I have a character array called storebuffer that contains data from a POST submission and its in the format ssid=abcdef&pswd=ghijk. I wanted to extract everything after ssid= into one array called acqSSID and the portion after &pswd= into another array called acqPaswd. I tried using this but it does not seem to be working. MAX_STORE_BUFFER_LEN is 255. Can anyone help?
int ctr = 0;
for (ctr = 5; ctr < MAX_STORE_BUFFER_LEN; ctr++)
{
  if ( (storebuffer[ctr] == '&') && (storebuffer[ctr+1] == 'p') && (storebuffer[ctr+2] == 's') && (storebuffer[ctr+3] == 'w') && (storebuffer[ctr+4] == 'd') && (storebuffer[ctr+5] == '=') )
  {
    break;
  }
  acqSSID[ctr] = storebuffer[ctr];
}

Serial.print("acqSSID: ");
Serial.println(acqSSID);
Serial.print("ctr: ");
Serial.println(ctr);

You can simply chop it up in place without requiring more than a few extra bytes of RAM using strtok():
char storebuffer[] = "ssid=abcdef&pswd=ghijk";

// Slice it into two parts around the &:
char *lefthalf = strtok(storebuffer, "&");
if (lefthalf != NULL) { // We found a & and split the string OK
    char *righthalf = strtok(NULL, "&");

    // Now you can slice each half around the =
    char *ssidtag = strtok(lefthalf, "=");
    char *ssid = strtok(NULL, "=");
    char *pswdtag = strtok(righthalf, "=");
    char *pswdtag = strtok(NULL, "=");

    Serial.print("SSID: ");
    Serial.println(ssid);
    Serial.print("Password: ");
    Serial.println(pswd);
}

The existing string gets chopped up and the pointers point to different places:
ssid\0abcdef\0pswd\0ghijk
^     ^       ^     ^
1     2       3     4

1: ssidtag
2: ssid
3: pswdtag
4: pswd

Rather than acqSSID[ctr] = storebuffer[ctr];, say (eg) acqSSID[ctr-5] = storebuffer[ctr];.  Also, after the break but before printing acqSSID, say acqSSID[ctr-5] = 0; to terminate the string.
Note, rather than coding a literal 5, you might say enum { acqOffset=5 }; up front, and subsequently use acqOffset in place of the literal.


text:
Would rewriting my code in C help reduce RAM usage?
So my program fails to run because there is not enough room for my variables as well as the Arduino Core and Stack. I can't find any more ways to optimize my program so I'm thinking about just rewriting it in C.
However, I'm not sure if that will actually help me. For example I know that in C my program will run faster because things like digitalWrite() and analogRead() have a bunch of "extras" that make it go slower, but I don't know if this will affect RAM.
So can any of the experts on here tell me if writing my code will help before I waste time doing so?
Here is my code:
#include <SoftwareSerial.h>
#include <avr/pgmspace.h>

#define FASTADC 1

// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

SoftwareSerial mySerial(0,1) PROGMEM;

byte i;

byte pixelsArray1[128];   //Array to hold the values of the individual pixles.
byte pixelsArray2[128];   //Array to hold the values of the individual pixles.
byte pixelsArray3[128];   //Array to hold the values of the individual pixles.

void setup()
{
  #if FASTADC
   // set prescale to 16
   sbi(ADCSRA,ADPS2);
   cbi(ADCSRA,ADPS1);
   cbi(ADCSRA,ADPS0);
  #endif

  pinMode(1,OUTPUT);        //Setting the 1 pin to be used for output
  pinMode(0,OUTPUT);        //Setting the 0 pin to be used for output
  pinMode(A3,INPUT);        //Input for Camera 3
  pinMode(A2,INPUT);        //Input for Camera 2
  pinMode(A1,INPUT);        //Input for Camera 1

  mySerial.begin(9600);     //Setting the data transfer rate
}

Notes:

I'm programming on the ATtiny85
I'm running Windows 10
I've never programmed in Arduino before

What does your RAM usage currently look like?

The three arrays, SoftwareSerial, and byte variable use 432 of the total 512 bytes of RAM on the ATtiny. Leaving the remaining 128 for the Core and Stack which I'm assuming is not enough because when I upload the program it fails to run. However when I reduce the size of the arrays the program runs just fine.

Personally I would look at ditching SoftwareSerial and running the USI by hand, but have you tried the code on a larger device yet?

Yes it work just fine on my Mega. But doesn't SoftwareSerial not affect the memory in my code since I'm using PROGMEM to store it in flash? Also can you expand on what you mean by "running the USI by hand".

SoftwareSerial has a buffer that takes up RAM regardless of where the object itself is located. AVR307

The only time I'm using it is when I'm setting the data transfer rate. Is there another way that I can do this?

See the document I linked.

I don't think I'm going to be able to understand that document in the near future. Thank you though.

I see you never use mySerial in your code, however this allocates some buffers that may take a lot of your precious memory. For me you should just completely remove it from your code as I don't see its purpose, it would probably be a gain of more than 50 bytes SRAM.

The simplest approach to reducing RAM usage of the program shown is to get rid of the three 128-byte pixel arrays.  They are not needed for the program to function.
Instead of writing
pixelsArray1[i]=analogRead(A1)/4;
pixelsArray2[i]=analogRead(A2)/4;
pixelsArray3[i]=analogRead(A3)/4;

write
if (analogRead(A1)/4 == 0 && analogRead(A2)/4 == 0 && analogRead(A3)/4 == 0) ++foundZero;

where foundZero is initialized to zero before the loop.  After the loop, you say something like
while (foundZero--) {
  digitalWrite(1, HIGH);
  delay(2000);
  digitalWrite(1, LOW);
  delay(2000);
}

to toggle pin 1 as many times as there were three zero pixels.
Note, the timing of the if (...) ++foundZero; statement may differ from pixel to pixel because the && evaluation may short circuit.  If the timing matters, save data in temporary variables, or check if the sum of the three is zero, etc.

Thanks but eventually I will need all three arrays to do some calculations once the project nears completion. I need the three arrays and can't do without them.

If timing of reading pixels isn't critical, just do those other calculations online also.  If possible.  Or if your later processing needs some context but not the whole array, keep a dozen or two of pixels in a circular buffer.  Or just reread all the pixels when you need to work with them.

I don't believe that rewriting it in C is going to help you much: the framework is pretty tight already, and you'd only get the C library's versions of the various drivers' buffers etc.
I do think your only solution (apart from getting larger hardware!) is to 'optimise' the pixelArrays. To do that, could you consider the following questions:

What is the worst value resolution that you'll get away with? You're currently compressing each camera feeds' pixel to the range 0-255, to store them into their individual bytes. What about 0-31? (See why below)
Will you always be comparing each feed's individual pixels against the same pixel in another feed? If so, perhaps you could pack all three values into one 16-bit quantity:
X 11111 22222 33333
where each quintet of bits is that feed's value compressed down. The X is cute: before compressing, you could compare all three values with each other, or zero, or something, and if true set the X bit to 1. That then means that you can later test for that exact condition in the triple-pixel with a <0 check - the sign bit will be set, so the condition will be true.
Or, if compressing down to 0-31 is too extreme, what about storing a 'master' copy of the pixel, and then two (scaled) differences from there: 11111111 2222 3333 where the master 1 value is unscaled (other than /4), while the other values are from the following table:
0000 - Identical pixel value
0001 - Within +2
1111 - Within -2
0010 - Within +4
1110 - Within -4
0011 - Within +8
1101 - Within -8
0100 - Within +16
1100 - Within -16
0101 - Within +32
1011 - Within -32
0110 - Within +64
1010 - Within -64
0111 - Within +128
1001 - Within -128
1000 - More than ±128
Even more radical: could you do all the tests when you read the data (do you have time???), and then simply store a one-bit result for each pixel? Such a packed-bit array is VERY efficient - if you can boil down your decision to yes/no...

I'd be happy to help write (reasonably) efficient C code to implement the TriplePixel functions - or even attempt it in assembly...


text:
Unable to create a desired periodic signal with Arduino Mega 2560 and DAC0808
I wrote the code to produce the periodic signal by using arduino and DAC0808 where i turned on and off the respectively pins of PORTA by using a logic in iterative manner and created the periodic signal. But even without using delay logic, i couldn't get signal time period as comparable to 50 Hz voltage signal. And what i seek to get is to decrease the time period of generated signal. Pls note, blue signal is reference signal of 50Hz frequency.
float increment = 3.14159 / 500;
float initial = 0;
float value = 0;

void setup() {
  Serial.begin(115200);
  DDRA  = B11111111;
}

void loop() {
  // put your main code here, to run repeatedly:

  PORTA = B00000000;
  while (1)
  {
    initial = initial + increment;
    value = sin(initial)  * 255;
    PORTA = abs(value);
  }

}

Your goal is to optimize the code to run faster? Start by using a look-up table instead of sin() and minimize float arithmetics. Are you sure your increment is correct?

You should make more clear what you expect to get and what you get instead.

Please edit question and indicate the timebase (seconds per division).  Also, if wiring diagram as shown is different than what you actually have, say so.  (The diagram apparently wires the bits backwards, LSB to MSB and vice versa.)

jwpat7 sir, blue signal is output signal of 50hz. So, time period per box is around 25 milli second.sorry for the inconvenience as am i operating from mobile.

As Vicente said, floating point math, especially transcendental functions, can be time-consuming. Instead of calculating the sine inside every repetition, you should build up a lookup table in your setup() function, then get the values from this table inside loop(). In order to minimise the size of the lookup table, note that you only need to calculate the sines of values from 0 to pi/2. If you still can not get your arduino to produce a 50Hz signal after that, consider decreasing the 'resolution' - that is, increasing the value of 'increment' from pi/500 to, say, pi/100.

As has been mentioned before, in comments and in jwpat7's answer, your
main problem here is the time taken to compute the sines. I already
provided a link to a faster fixed-point implementation of
sin() but, since you have an Mega2560 with loads of RAM, I
would go to the simpler look-up table method. I would not even bother
optimizing the size of the table.
For controlling the timing, you can use the canonical method described
in the Blink Without Delay Arduino tutorial, with one twist: times
should be measures with micros() instead of millis(). Here is a
first version of the program:
const float FREQUENCY = 50;            // hertz
const float PERIOD = 1e6 / FREQUENCY;  // microseconds
const size_t TABLE_SIZE = 512;
const uint16_t SAMPLE_TIME = PERIOD/TABLE_SIZE + 0.5;
uint8_t wavetable[TABLE_SIZE];

void setup()
{
    // Prepare the wavetable.
    for (size_t i = 0; i < TABLE_SIZE; i++) {
        wavetable[i] = 255 * abs(sin(M_PI * i / TABLE_SIZE));
    }

    // Set port A as output.
    DDRA = 0xff;
}

void loop()
{
    uint16_t now = micros();
    static uint16_t last_sample;
    static size_t phase;

    if (now - last_sample > SAMPLE_TIME) {
        last_sample += SAMPLE_TIME;
        PORTA = wavetable[phase];
        phase = (phase + 1) % TABLE_SIZE;
    }
}

A few things worth noting:

The float constants FREQUENCY and PERIOD are used only at compile
time.
The table size is a power of two because wrapping a table index
modulo a power of two is way faster than modulo, say, 500: the
compiler optimizes the modulo into a bitwise AND.
The + 0.5 in the expression of SAMPLE_TIME is intended to ensure
that the result is rounded to the nearest integer. In this instance
it happens to be useless because rounding down would give the same
result.
The micros() function returns a 32-bit integer, but in this
application it is sufficient and faster to track only the 16 least
significant bits, hence the uint16_t timing variables. And no,
these variables overflowing is not a problem.

This should give you, in theory, a frequency of 50.08 Hz, i.e.
0.16% too fast. The discrepancy is due to SAMPLE_TIME, which should be
39.0625 µs, being rounded to 39 µs. You could fix this by
counting time with a higher resolution, but given the poor accuracy of
the ceramic resonator clocking the Arduino, this is probably not worth
the trouble.
A potentially worse problem is the large jitter you have with this
approach, on the order of 10 µs. This is due both to the time taken
to run through the loop and the occasional timer interrupt taking some
extra time. You can get rid of this jitter by using a timer interrupt
instead of micros(). Here is a second version of the program that uses
this approach:
#include <avr/sleep.h>

const float FREQUENCY = 50;              // hertz
const float PERIOD = F_CPU / FREQUENCY;  // CPU cycles
const size_t TABLE_SIZE = 512;
const uint16_t SAMPLE_TIME = PERIOD/TABLE_SIZE + 0.5;
uint8_t wavetable[TABLE_SIZE];

int main()
{
    // Prepare the wavetable.
    for (size_t i = 0; i < TABLE_SIZE; i++) {
        wavetable[i] = 255 * abs(sin(M_PI * i / TABLE_SIZE));
    }

    // Set port A as output.
    DDRA = 0xff;

    // Configure Timer 1.
    OCR1A = SAMPLE_TIME - 1;  // set the period
    TIMSK1 = _BV(OCIE1A);     // enable TIMER1_COMPA interrupt
    TCCR1B = _BV(WGM12)       // CTC mode with TOP = OCR1A
           | _BV(CS10);       // clock at F_CPU / 1

    // Sleep while waiting for interrupts.
    sei();
    sleep_enable();
    for (;;) sleep_cpu();
}

// Service routine for the Timer 1 interrupt.
ISR(TIMER1_COMPA_vect)
{
    static size_t phase;

    PORTA = wavetable[phase];
    phase = (phase + 1) % TABLE_SIZE;
}

Again, a few notes:

The SAMPLE_TIME is now computed in CPU cycles and, since it is an
integer number of cycles (namely 625), there should in principle be
no frequency discrepancy.
For counting 625 cycles we need a 16-bit timer clocked at the full
CPU speed (prescaler = 1). We are using Timer 1 here. See the
datasheet of the ATmega2560, chapter 17, for details on
using the timer.
Sleeping between interrupts is needed in order to obtain
cycle-accurate timings. If we had simply an infinite loop, there
could be a few CPU cycles of jitter, which may not be a big deal.
Writing main() instead of setup() and loop() is a way to skip
the initialization normally done by the Arduino core library. In this
application that initialization is better avoided, because it creates
an extra jitter-inducing interrupt and it messes with Timer 1 in a
way that we would need to undo.

I'm interpreting your phrase “even without using delay logic, i couldn't get signal time period as comparable to 50 Hz” as meaning that the code shown runs Too Slow.  At 1000 samples per cycle and 50 Hz on an 8-bit 16-MHz processor, you only have 320 clocks to compute a sin(), which probably is not enough to compute a 32-bit floating sin().
To speed it up, you can either issue fewer samples per cycle or make the loop go faster.
For the “fewer samples per cycle” approach, you would make increment bigger; for example, instead of 3.14159/500, or 1000 samples per cycle, perhaps an interval of 2π/500, or 500 samples per cycle.
For the “make the loop go faster” approach, you could use a lookup table or fixed-point integer arithmetic or both.  Note, the lookup table only needs to cover 90° (or π/2 radians); index in reverse for quadrants 2 and 4, and negate values for quadrants 3 and 4.
Note, after you speed up the code, you will need to set up a time base for issuing samples.  This could use a clock-based interrupt routine that gets and issues the next array value, or that sets a flag so your main loop can get and issue a value.  Or you could spin until micros() exceeds a deadline, at which time you (1) issue a value, (2) set the next deadline, and (3) compute the next value.

320 clock cycles is indeed not enough for sin(): I have timed it at 1725.1 cycles average. I've also written a fixed-point sin() that takes 110.25 cycles (page in French, but code documented in English). It's 16 bits, with a maximum error of 9.53e-5, so somewhat overkill for this 8-bit application. But a simpler alternative polynomial is given in the text.

@EdgarBonet, thanks for mentioning that –  it provides a viable alternative to table lookup methods.


text:
Is the a low memory alternative to SoftwareSerial?
I'm running a program on a ATtiny85 and running into problems because of a lack of available RAM. When I ran avr-nm on my ELF file I found that SoftwareSerial was taking up a lot of RAM even though I'm just using it to set the data transfer rate with mySerial.begin(9600); and nowhere else.
So I'm wondering if there is another way of doing this without using so much memory:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(0,1);

mySerial.begin(9600);

Simplest thing would probably be to edit your copy of SoftwareSerial.h
and replace #define _SS_MAX_RX_BUFF 64 on line
42
by something smaller. If your loop() runs fast enough (no delays, no
blocking code) you could probably get away with buffering only a very
few bytes.
Or you could rewrite the library so that, instead of buffering the
incoming bytes, it handles them to you for processing. See for example
this receive-only UART code based on the USI
port for an illustration of the
approach.

Where would I go to edit my SoftwareSerial.h? Also my program is working with a camera and I am using delays to send a clock impulse does that mean that lowering the buffer rate would not work for me?

@AngelLockhart: It's probably somewhere like $ARDUINO_HOME/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h, where $ARDUINO_HOME is you Arduino installation directory. You can use the search facilities of your OS. If your clock pulses are very short (a few microseconds or so), the delays may be OK. Otherwise you should learn to control timings without delay().

My ESP8266 was randomly crashing any time I used SoftwareSerial from framework-arduinoespressif8266 or https://github.com/plerup/espsoftwareserial, due to too low memory.
https://github.com/CrazyRobMiles/Esp8266EdgeSoftwareSerial fixed this problem. I still receive data from the sensor via SoftwareSerial, and there is 4000 bytes more RAM compared to the alternative implementations.

how should it help with the problem in the question?

@Juraj Well, the arduino SoftwareSerial.h somehow requires more 4000 bytes of RAM to transfer a buffer of 64 bytes (why???).  The linked library can be used as a direct replacement for SoftwareSerial, and has a much smaller footprint.
I now realize the code is called Esp8266EdgeSoftwareSerial, and might not run on other architectures. Is that your implied question?

I doubt that the standard SoftwareSerial has a 4000 byte RAM overhead, this must be something else. Anyway, the OP uses an ATtiny85, so answers for Esp8266 don't help.

@thebusybee: Okay, I'll delete my answer. SoftwareSerial.h seems to have a huge overhead for the projects I work on. If I include it and use it, without changing any other parameter, ESP.getMaxFreeBlockSize() and ESP.getFreeHeap() both take a huge hit. I'll keep on investigating, and file a bug report (I'm not the only one complaining about memory use). For what it's worth, OP's question still need a proper answer : the accepted one leads to 404 and tells OP to rewrite the lib. :-/

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


text:
Create a library without a class?
I'd like to know if it's possible to create a library for Arduino that does not contain a class, just functions.
I know how to create a library with a class, but I'd like to create a library of general purpose functions that don't need to be instantiated to be used. Just used like the standard functions included in the Arduino IDE:  sizeof(), etc..
Is this possible?  If so, can anyone point me in the direction of a template?  I've been searching, but haven't found anything.
Thanks!

Have you tried creating a library like you've done before but not putting any classes in it?

Although this is not directly relevant to your question, sizeof(), like if() is NOT a function (although its syntax looks like one), it is an operator evaluated at compile time.

Ok, I was hoping this was possible, I read here that it wasn't possible: http://stackoverflow.com/questions/1735990/using-classes-with-the-arduino A few points down the page, someone wrote: > On Arduino you can use classes, but there are a few restrictions:

No new and delete keywords
No exceptions
No libstdc++, hence no standard functions, templates or classes
You also need to make new files for your classes, you can't just declare them in your main sketch. You also will need to close the Arduino IDE when recompiling a library. That is why I use Eclipse as my Arduino IDE. No standard

No new and delete keywords 2. No exceptions 3. No libstdc++, hence no standard functions, templates or classes - most of that is nonsense. You can use new and delete these days. You can use templates and classes. You can get the STL (standard template library) from StandardCplusplus. You have standard functions like malloc, memcpy, strcpy, etc.

You also will need to close the Arduino IDE when recompiling a library - when I am developing a library I use a standalone editor for editing the library. I don't need to close the IDE to test it.

May I suggest the use of static class methods?

Yeah, I use Notepad++ when I'm editing libraries with the Arduino IDE open to a sketch that includes those libraries.. seems to work ok.

Yes, it's possible.
Just don't make a class. Just make functions instead.
Like a class-based one, have a .cpp and a .h file. In the .cpp file (or .c file if you don't want any of the C++ functionality or 90% of the Arduino API available to you) place your functions.
In the .h file place prototypes for them. I am in the habit of adding the extern keyword, but you don't actually need to for functions.
For example:
foo.cpp:

void doSomething() {
    // whatever
}

foo.h:

extern void doSomething();

Then you can include your .h file and call your functions:
#include <foo.h>

// ...

doSomething();


text:
Arduino mega 2560 Stacked with Ethernet/SD card Shield Heat up
Stacked mega and ethernet/sd shield:

When I do this stacking, it heats up. I tried connecting the SPI via ports 13-10 (no stacking), it doesn't work. Also tried connecting the ICSP (red circled mark) via male-female wires without stacking, it works, but still heats up. So I think the ICSP has a defect? or does it? Is it supposed to be like this and I'm just being paranoid?
*PS: the heat in the "pain" level when I touch it, no burning IC odor. Maybe it's because I unplug it immediately after short use? IDK.
**update, I think I got it working, the problem was not about the heating, but the program. Consulted a more experienced person, he said what's happening is normal.

Since this is not a programming question and relates to hardware you might have a better audience on [arduino.se]. I suggest posting it there.

Or you should try on the electronics site, as it's less an issue with the Arduino framework and hardware, but more with the electronics.

the heat in the "pain" level when I touch it, no burning IC odor. Maybe it's because I unplug it immediately after short use? IDK.
  So I think the ICSP has a defect? or does it? Is it supposed to be like this and I'm just being paranoid?

Well you're right in being a bit paranoid. And temperature building up is very likely to mean you've got a short somewhere, it might be a bad solder or a component that fails (like a cap that conducts).
So you've got to isolate the issue:

Isolate the faulty board: whichever board is getting hot, it might be that one that has a failure or the other one ruining it

you need to try the shield with another arduino (whatever version it is) and see if the issue is replicating
then you need to try the arduino you were using with another shield running on ICSP (like another ethernet shield, or an SDCard shield), which will confirm the hypothesis that only one component of the two is failing.

Once you've isolated the board, you need to isolate the component.

you first have to isolate which component is building up heat.
If you've got access to a thermal camera, it's a good idea to use it.
If not: start locating the area where heat is building with your finger, and then test each component of the area with a thermometer (like the ones you plug on a multimeter, or simply a "meat" thermometer for cooking).

Once you've isolated the component, then look it up on the schematics and layout, and lookup all connected components. Either that component or one on the track is failing, or there's a short on that track.

If the solution is not obvious, you can come back on Stack Exchange (get on the electronics QA site with your results), and some EE expert will help you find out what's wrong!
HTH

Wow sir! Thanks! I'll look up to it, although I don't have some equipments you said, this would help a lot, not only on my arduino but other projects. I also tried the arduino forum for this suspected problem.


text:
Basic Question - ESP8266 Board Pins
I have an embarrassingly simple question.
My experience to date has been limited to Arduino Uno + Wifi101.  I bought an ESP8266 and noticed that the GPIO pins don't match the printed numbers on the board.
When programming and defining pins, does #define <pin name> 16 call the pin with the printed designation D0?
I can't find a straight answer to this anywhere.
Image credit: http://crufti.com/content/images/2015/11/nodemcudevkit_v1-0_io.jpg

When you use it with what libraries?

The Arduino IDE: ESP8266WiFi.h, SPI.h

Looks like you're using https://github.com/esp8266/Arduino, in which case - yes, 16 is GPIO16, which on the NodeMCU board you have is labeled D0.
I am not entirely sure why the NodeMCU guys had to do this "pin remapping", but the end result is inconvenience when using the module with anything but their Lua.

It looks like they are using a similar system to the Arduino pin mappings, for example:

(Image credit: https://www.arduino.cc/en/Hacking/PinMapping168)
There, for example, pin 2 on the chip, is D0 (digital pin 0) on the board.
Their board will use their own mappings, but the concept is the same.

does #define  16 call the pin with the printed designation D0?

That doesn't "call" anything. It would depend on the code. If the code in question addresses the actual chip pins, then it is chip pin 16. If it goes through a library and the library maps the chip pins to the board pins, that it will refer to board pin 16. I notice BTW that the board doesn't have a pin 16.

Pardon my ignorance.  By pin 16 I meant GPIO 16.

I know what you meant. I'm just saying that a line #define foo 16 can only be read when you see what is done with foo. On its own it could mean anything.

Well based on my experience with NodeMcu and Arduino, in Arduino you use the GPIO by reffering its pin number (like 0-13), whereas in NodeMcu you will have to use D0-D8.
It's better to use D0 to use GPIO 16.


text:
Serial available doesn't work right after upload
I have 2 programs to test serial communication, an simple arduino program that echoes whatever is on the serial port and a python program that writes to the serial port and prints the reply.
I'm having an issue where whenever I upload the arduino program and try to run the python code the arduino code wouldn't detect serial available on the first run.  I would have to either

open and close serial monitor before I run python program
run the python program, quit, and run it again

and it would continue to work until I re-upload the arduino then the same thing happens.  Does anyone know what is the issue?  This is on Ubuntu.
arduino
String str;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(115200);
}

void loop() {
  if (Serial.available()) {
      str = Serial.readStringUntil('\n');     // Read the serial input
      Serial.println(str);             // sends ascii code

  }
}

Python
import serial

ser = serial.Serial('/dev/ttyACM1', 115200)

for i in range(0,4):
    str = "test string\n"
    ser.write(str)
    print ser.readline()

Even: void setup() {                   Serial.begin(115200); Serial.println("Hello, World!"); } fails right after upload. This seems to have happened relatively recently in the development of the IDE; I've no idea why but I'd sure like to fix it.

This fails due to the typical auto-reset-on-open serial port configuration interacting with a problematic assumption made by the PC code.
The first issue means that it will typically take a few seconds between when the port is opened (unless the port is configured not to manipulate modem control signals on open) and when the usual bootloader times out, yields to the custom sketch loaded in the Arduino, and the latter becomes able to accept input and potentially respond.
The second issue is with the PC side code:
for i in range(0,4):
    str = "test string\n"
    ser.write(str)
    print ser.readline()

Assuming that import serial refers to pySerial, then because you did not specify a timeout when opening the port, the ser.readline() is an eternally blocking read.  To quote the documentation:

Be carefully when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received.

If we look at what happens with your python program and a typical serial port configuration where modem status lines change on open, then the first thing your program does is implicitly reset the Arduino.  Next, it writes "test string\n" - but because of the reset, it writes this at the bootloader, not the sketch which is not running yet.  Finally your program eternally waits for a newline terminated reply - which it will never receive, because your sketch will not send that until it receives something from the PC, which will not send anything else until it receives the newline terminated response to its first message.
Your programs are thus stuck in a "no, after you" deadlock.
There are many potential ways to work around this.  For example, you might open the port with a timeout, wait a few seconds, and conduct this test write and attempt to read a reasonable number of times, but declare an error to the user if success is not achieved in ten or so seconds of those attempts.
Note also that the sketch may start running midway through transmission of the test string, so you will have to handle the possibility of a message with the beginning missing, either by declaring an error or discarding it and waiting for a subsequent intact one.


text:
Remove certain characters from char*
I've got an array of char* with serial data that I'm trying to remove ':' from. I have tried to iterate through the char*, find and remove any colons but it just comes out as garbage.
  char* espData[15];

  // pull data from serial and tokenize with strtok > feed to espData

  for(int x = 0; x < index-1; x++){
    size_t nullTerm = strlen(espData[x]);
    espData[x][nullTerm - 1] = '\0';
    char* output
    for(size_t i = 0; i < strlen(espData[x]); ++i){
      if(espData[x][i] != ':') output += espData[x][i];
    }
    espData[x] = output;
    Serial.println(espData[x]);
  }

Moving the null character works fine (I wanted to get rid of the last character in every string). Most of the answers I found for general C++ used std::string which we don't have access to.

Arithmetic on a char* does nothing to its contents.

the comment tokenize with strtok suggests your code uses strtok, which would be one (probably bloated) solution - yet your code doesn't use strtok!!?

espData[x][nullTerm - 1] = '\0'; is redundant code

@Jaromanda Actually, it overwrites the last character in the string - or underflows the buffer if nullTerm is 0!

@JohnBurger - of course you're right

@JaromandaX the comment is just placeholder for code that I already had working correctly with strtok so I left it out for brevity.

@JohnBurger I hadn't thought of underflow on the buffer, I will put it a check for that. Do you know what kind of problems that could cause if it did underflow?

@Tri42 Shudder! I don't want to think about it! It depends on where you got espData[x] from: the heap? You're going to trash the previous object on the heap. The stack? You've going to corrupt another variable - or worse, the return address from a function. The data section? You're simply going to alter an unintended variable.

You've assumed that a char * is some kind of string object, since you've got the following line of code: output += espData[x][i];, and then later espData[x] = output;
It quite simply doesn't work like that. At best you can point output inside espData[x] and then do some other logic: but your attempt to "accumulate" the correct characters is incorrect.
Please consider the following code instead:
char* espData[15];

for(int x = 0; x < index-1; x++){
    size_t nullTerm = strlen(espData[x]); // Get current length
    char* output = espData[x];            // Start of string
    for (size_t i = 0; i < nullTerm; ++i){
        if(espData[x][i] != ':') {        // If it's NOT a colon
            *output++ = espData[x][i];    // Copy character 'up'
        } // if
                                          // If it WAS a colon, then
                                          // output does NOT get incremented
    } // for
    *output = '\0'; // End string off with NUL
    Serial.println(espData[x]);
} // for

That works perfectly, thank you! I have never been great with pointers

@Tri42 I just finished a pointer-post on another question. Take a look: http://arduino.stackexchange.com/a/25317/22924