body:
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.
<!-- language-all: lang-cpp -->

    // 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();
    }

title: Program does not seem to be passing from setup to loop, or printing to SD card

Answers: 0


body:
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`000==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==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
          }

        }
    }

title: How can I made my Arduino follow the time exactly?

Answers: 2

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

1. Use an RTC module to keep more accurate track of the time.
2. Connect the Arduino to the internet and use NTP to get the exact time.
3. 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 ++;
    }

body:
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?](https://arduino.stackexchange.com/questions/27).

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](https://arduino.stackexchange.com/a/12588).


body:
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][1] 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.

  [1]: https://stackoverflow.com/questions/18517634/tiny-c-compiler-error-unknown-opcode-jmp

title: ESP8266 - Error: unknown opcode or format name 'jmp'

Answers: 2

body:
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).

body: 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.


body:
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.

 1. Arduino Nano: www.ebay.in/itm/Arduino-Nano-SOLDERED-PINS-V3-0-ATmega328-CH340G-BUY-2-GET-1-USB-CABLE-FREE-/172117729247?
 2. 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:

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

title: Need help on HC05 and Nano

Answers: 1

body:
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?


body:
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);
    }

[![Voltage Step-Up Module][1]][1]

UPDATE:

Ok, I am now set up to look like this:
[![enter image description here][2]][2]

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

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/bW2yi.jpg
  [2]: https://i.stack.imgur.com/bEQx6.png
  [3]: https://i.stack.imgur.com/lGx5b.png

title: Piezo not loud enough

Answers: 2

body:
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 https://arduino.stackexchange.com/questions/19250/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.

body:
Alternatively there are [COTS parts][1] (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][2].  So stay well below that to be safe.

  [1]: http://www.alliedelec.com/m/d/884b78cb9e915349d3e84cb62d58bd3e.pdf
  [2]: http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations


body:
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();
      }
    }

title: trying to discover other nrf24 modules

Answers: 0


body:
**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.

title: Lighting LED Strip via HC-06 Bluetooth Module

Answers: 1

body:
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() ;
    }


body:
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

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

Answers: 1

body:
> 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!


body:
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!

title: AVRDUDE Error (Arduino Leonardo)

Answers: 2

body:
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.

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

body: 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.


body:
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;
    }

title: Overwritten EEPROM

Answers: 1

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

    loopnumber++ ;

with

    loopnumber = (loopnumber+1)%60 ;

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.


body:
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?

title: What is using up all the RAM in my program?

Answers: 1

body:
There is a lot you are missing.  Such as:

1. SoftwareSerial is using RAM.
2. The system stack is using RAM.
3. 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.


body:
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);

title: Extracting a specific sequence of characters from an array

Answers: 2

body:
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.

body:
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


body:
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

title: Would rewriting my code in C help reduce RAM usage?

Answers: 2

body:
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.

body:
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 `pixelArray`s. To do that, could you consider the following questions:

1. 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)
2. 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.
3. 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
4. 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...


body:
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);
      }

    }
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/UyZ8f.png

title: Unable to create a desired periodic signal with Arduino Mega 2560 and DAC0808

Answers: 2

body:
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.

body:
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()`][sin_fix] 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:

<!-- language-all: lang-c++ -->

    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:

1. The float constants `FREQUENCY` and `PERIOD` are used only at compile
   time.
2. 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.
3. 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.
4. 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][millis rollover].

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:

1. 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.
2. 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][ATmega2560], chapter 17, for details on
   using the timer.
3. 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.
4. 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.

[sin_fix]: https://www.logre.eu/wiki/Trigonométrie_en_virgule_fixe
[Blink Without Delay]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
[millis rollover]: https://arduino.stackexchange.com/questions/12587

[ATmega2560]: http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf


body:
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);

title: Is the a low memory alternative to SoftwareSerial?

Answers: 2

body:
Simplest thing would probably be to edit your copy of SoftwareSerial.h
and replace [`#define _SS_MAX_RX_BUFF 64` on line
42](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h#L42)
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](http://www.technoblogy.com/show?VSX) for an illustration of the
approach.

body:
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.


body:
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!

title: Create a library without a class?

Answers: 1

body:
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();


body:
Stacked mega and ethernet/sd shield:

[![enter image description here][1]][1]

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.

  [1]: https://i.stack.imgur.com/Ufrib.png

title: Arduino mega 2560 Stacked with Ethernet/SD card Shield Heat up

Answers: 1

body:
> *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:

1. 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.
2. 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).
3. 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](http://electronics.stackexchange.com) with your results), and some EE expert will help you find out what's wrong!

HTH


body:
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

[![NodeMCU ESP8266][1]][1]

  [1]: https://i.stack.imgur.com/93qIq.jpg

title: Basic Question - ESP8266 Board Pins

Answers: 3

body:
Looks like you're using [https://github.com/esp8266/Arduino][1], in which case - yes, 16 is GPIO16, which on the NodeMCU board you have is labeled D0.  <br>
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.

  [1]: https://github.com/esp8266/Arduino

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

[![Arduino Uno pin mappings][1]][1]

(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 <pin name> 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.

  [1]: https://i.stack.imgur.com/W6hdF.png

body:
Well based on my experience with [NodeMcu][1] 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.

  [1]: http://www.nodemcu.com/index_en.html


body:
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()

title: Serial available doesn't work right after upload

Answers: 1

body:
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][1], 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.

  [1]: https://pythonhosted.org/pyserial/index.html


body:
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.

<!-- language: c -->

      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.

title: Remove certain characters from char*

Answers: 1

body:
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


body:
I want to create a dynamic sized array of chars as a member in a class.
This is being done inside a library that I've created.
I have the `.h` and the `.cpp` files created. I'm not sure how to declare the array in the `.h` file. I've tried a few things so far:
`char* content;`
`char content[];`
But these don't seem to work.

Here's what I have in my `.h` file:

    class bufr{
     public:
  //constructor and deconstructor
  bufr(char* _chars, uint8_t _len);
  ~bufr();

  //variables
  uint8_t len;
  char content[];

    };

Here's what I have in my `.cpp` file (this is the constructor):

    bufr::bufr(char* _chars, uint8_t _len){
     char* content = new char[_len];
     content = _chars;
     len = _len;
 }

I've also tried replacing the line `content = _chars` with:

    for (int i = 0; i < _len; i++){
        content[i] = _chars[i];
    }
But this also doesn't work.  When I print the `content` member to the serial port from within the constructor, or in the main loop it prints nonsense characters, not what I passed it.

Here's my main loop:

    void loop(){
        char chars[] = "1234";
        bufr buf(chars, 4);
    }

Have I explained myself well enough?  Can anyone give me a hand?
Much appreciated!

Oh, and yes, I know - in my deconstructor that's not shown, I have `delete [] content`

I plan on using this class nested inside another class in a few spots and hoping to take advantage of the dynamic mem allocation.  I know I can simply declare an array of fixed length, but I wanted to learn the proper way to use `new` and `delete`.

Thanks!

title: Dynamicly sized array as a class member

Answers: 2

body:
This is wrong on a number of levels. First in the class declaration:

    char content[];

<s>That gives you a pointer to an array of zero length.</s>

This gives you an array of char, of zero length. This is not useful.

    char* content = new char[_len];
    content = _chars;

That does a `new` into a **new** variable `content` - not the class variable. Then you assign (overwrite) the passed pointer into `content` (discarding the memory you just allocated). That pointer is then discarded when the constructor ends. Perhaps using `strcpy` would be better.

I made up a small example based on your code which prints the correct result:

    class bufr
      {
      public:
        //constructor and deconstructor
        bufr(char* chars, uint8_t len);
        ~bufr();

        //variables
        uint8_t len_;
        char * content_;
      };    // end of class bufr

    bufr::bufr(char* chars, uint8_t len)
      {
      content_ = new char[len];
      memcpy (content_, chars, len);  // copy into allocated memory
      len_ = len;   // remember length
      }   // end of constructor

    bufr::~bufr()
    {
      delete [] content_;
    } // end of destructor

    void setup()
    {
      Serial.begin (115200);

      char chars[] = "1234 ";
      bufr buf(chars, sizeof chars);

      Serial.println (buf.content_);
    } // end of setup

    void loop()
    {
    } // end of loop

---

> Can you explain to me why it was making a new variable content and not using the class variable?

Small example:

    char * content;

    void loop ()
      {
      char * content = "foo";  // makes a NEW variable
      }

In this example there are **two** variables named `content`. The one in the function "shadows" the global one. However the code below only has one variable:

    char * content;

    void loop ()
      {
      content = "foo";  // uses existing variable
      }

---

> In the destructor, when you delete the pointer to the array, does this free up the memory allocated to the array? It's now free to be assigned again by something else? Or does it sit there still initialized as that array, not being able to be used again?

You aren't deleting the pointer. You are deleting the *memory it points to*. The pointer is now pointing to freed memory, so using it as a pointer at this stage would be wrong. You can do another `new` to make it point to something else.

---

> they delete pointer and then delete[] pointer.

You misinterpreted that. You either `delete pointer` **or** `delete [] pointer` depending on whether `pointer` is an array or not. I reworked `content` to not be an array, <s>thus deleting it without the brackets is correct</s> however as it is allocated using `new []` it must be deleted with `delete []`.

---

> on the link posted above they say to use delete this way: delete pointer if it was a single element allocated with new or delete [] pointer to release memory allocation for arrays of elements allocated with new and a size in []'s. So in my case I want to use delete [] content_?

No, you don't want to be setting up an array in the first place. Take a look at this small example:

    struct   {
      char bar [];
      } foo;

    void setup()
    {
    Serial.begin (115200);
    Serial.println ("Starting");
    Serial.println (sizeof (foo));
    Serial.println (sizeof (foo.bar));
    }

    void loop()
    {
    }

That prints:

    Starting
    0
    0

The variable `bar` is a zero-length array. Thus the entire struct `foo` is also zero length. It isn't even a pointer (that would be two bytes on this platform).

It is wrong to use an array of char like that, when you want to dynamically allocate memory. Look at this:

    char foo [4];

That allocates 4 bytes of memory for `foo`. You can't later on make it longer by doing a `new`.

What you want is:

    char * foo;

Now you have allocated a **pointer** and can do a `new`, like this:

    foo = new char [10];  // allocate 10 bytes

And then delete it:

    delete [] foo;

You use the brackets on the delete, as you used them with the `new`.

If you allocated **one char** you wouldn't use brackets. eg.

    char * foo;
    foo = new char;  // allocate a pointer to one byte
    ...
    delete foo;

body:
# Many programmers have a disjoint between a pointer and an array. Here's an explanation.

### Here is a variable of type `char`, initialised with the value `'A'`:

    char c = 'A';

`'A'` has the ASCII value of 65, so that means that there's a byte in memory that holds the value 65. Let's say that byte in memory is at address `0x2000`. If you were to add `1` to that byte, it would become 66, and if you were to print it as a character, it would print `B` (ASCII 66).

### Here is a pointer to a `char`, initialised with the address in memory of `c`:

    char *p_c = &c; // Get the address of c into p_c

> [Note that `char *p_c = c;` would be invalid: you can't initialise a pointer with a `char`! That'd give `p_c` the value `65` - not what you want!]

In Arduino, `p_c` represents two successive bytes of memory that together store the address of a `char`: in this case the value 0x2000. Where those two bytes are doesn't matter for this explanation - but trust that they too have an address...

If you were to change `c` into a 'Z', that would change `c`'s contents, but not `p_c`'s (it would still be `0x2000`). But if you were to use `p_c` to look at the byte it was pointing to (`c`), then you'd see the 'Z'.

- If you were to do a `printf("%c", c);` you'd get a 'Z'.
  > `%c` means "I've got a character as the next variable in the `printf()` list".
- If you were to do a `printf("%c", *p_c);` you'd also get a 'Z'.
- If you were to do a `printf("%c", p_c);` you'd get horrible results.
  > You lied to `printf()` - you didn't give it a one-byte character, you gave it a two-byte pointer!

Now let's move on to arrays.
### Here is a variable of type `char []`, initialised with the value `"John"`.

    char s[] = "John";

`'J'` has the ASCII value 74, `'o'` 112, `'h'` 104, and `'n'` 111. That means that in memory there are four sequential bytes with the values 74, 112, 104, 111. Let's say that those bytes are at addresses 0x3000 through 0x3003.

### And here is another pointer to `char`, this time initialised with the address in memory of `s`.

    char *p_s = s; // Point to s with p_s

> I hate that the C language allows the above. It is one of the roots of the whole array/pointer confusion. It kind-of implies that `p_s` somehow gets all of `"John"` assigned to it. Nope!

A better statement would have been:

    char *p_s = &s; // Initialise p_s with the address of s // ILLEGAL!

That gives a MUCH better idea of what's happening - alas, it's not how it's done...

But also note that neither of the above could possibly store `0x3000-0x3003` (the addresses for all of `s`), so they have to be satisfied with only storing the start of the string: `p_s` will get the value `0x3000`.

Note that `s` does **NOT** have the value `0x3000` in it. That is its address, like `0x2000` was `c`'s address (it too doesn't have `0x2000` in it). But `p_s` _does_ have `0x3000` in it - and don’t forget that `p_s` also has its own address (I won't bother with that here).

### And this is where the "equivalency" (they're not) between a pointer and an array starts to get people confused:

- `s[2] = 'h';` and `p_s[2] = 'h';` do the same thing - but in different ways!
  - The first accesses `0x3002` directly.
  - The second needs to find out that `p_s` is `0x3000` and add `2` to it before it can access `0x3002`.
- `*(p_s + 2) = 'h';` is yet a third way to do the same thing.

So now let's `printf()` these new variables:

- `printf("%c", *s);` wouldn’t compile.
  > `s` is not a pointer, so you can’t dereference it with `*`.
- `printf("%c", *p_s);` would print the **character** at where `p_s` was pointing.
  > This would print out `J`.
- `printf("%c", s[0]);` would print the **character** at `s[0]`.
  > This would print out `J`.
- `printf("%c", s);` would give horrible results.
  > Again, you lied to `printf()`!
- `printf("%s", s);` would work (but see below).
  > `%s` means "I've got a sequence of characters that I'd like you to print. I've provided the address of the first character."
- `printf("%s", p_s);` would be identical to the previous one.
  > After all, the same address value was passed!
- `printf("%s", *p_s);` would give horrible results.
  > Again, you lied to `printf()`!

But note something: you've given `printf()` the beginning of the string, so it can start printing. How does `printf()` know where the end of the string is? You didn't provide the number `4`; it's not stored anywhere; how can it know when to stop?

That's where a C convention for strings steps in. By convention, when the compiler sees a string `"between quotes"`, it stores the ASCII values of the characters, and _then follows them with a `0`_. Not an ASCII `'0'` (with value 48), but an ASCII `NUL` (with value 0). Thus if you looked at address `0x3004` (the byte directly after `John`), you'd see a 0 in that memory byte. That's how `printf()` knows to stop printing - and yes, many a bug has resulted from forgetting to maintain a `NUL` at the end of a sequence of chars!

### That then leads me to the `sizeof()` function
`sizeof()` always returns a constant _at compile time_ using information that the compiler _then_ knows about:

- `sizeof(c)` would return `1`.
- `sizeof(p_c)` would return `2`.
- `sizeof(p_s)` would _also_ return `2`.
  > It is after all merely a pointer too.
- `sizeof(*p_c)` would return `1`.
- `sizeof(*p_s)` would **also** return `1`.
  > It's only pointing to a single char...
- `sizeof(s)` would return `5`.
  > The compiler knows what `s` is: an array of **5** bytes (including the final `NUL`).
- Given a pointer, there is _no (native) way_ to find out how large the buffer it is pointing to can be.

OK: so if you've got a `char []` you can find out its size. Note that that is its maximum size - the string inside it could be a lot shorter! If you did the following:

    s[3] = 0; // Overwrite the fourth character (arrays start at 0)
    printf("%s", s);

> [Note a better version of the first line would be `s[3] = '\0';` which means "store the ASCII character `0` (**NOT** `'0'`)" instead of "store the number `0`".]

you'd get `Joh` printed out. Note:

- `sizeof(s)` remains `5`;
- You can't get the length with `sizeof(*p_s)`;
- The string inside it is only 3 characters long.

So... if you've got a string buffer, or a pointer to one, how do you know how long it is? Count the number of characters until you reach a `NUL` - and there's already a function to do that for you: `strlen()`.

### Which now leads to the final point about pointers: dynamic allocation of memory.
The array `s` above was sized by the compiler at compile time: it could count the characters, add one for the `NUL`, and reserve the right number of bytes. You could also have written:

    char s[10] = "John";

which would have reserved 10 bytes and only initialised the first **5** of them. The following would be an error:

    char s[3] = "John"; // Buffer too small!

> Scarily, `char s[4] = "John";` works... (The compiler says to itself "No room for the `NUL`?! Ah well...”) Better never pass that string to `strlen()` or `printf()` then!

What if you don't know at compile time how big a string is going to be? If you know at runtime, you can ask the system for a lump of memory from the heap - a reserved area that can have chunks taken from it and returned as required. There are two ways to do this:

    char *p_b = (char *)malloc(size); // Where size is a variable
    char *buffer = new char[size];    // Grab 'size' new chars

The first calls `malloc()`, passing in the number of desired bytes. If `malloc()` can give those bytes it will reserve them and return a pointer to them. If it can't it will return `0`. You should always test the return value! If not, you'll corrupt things horribly...

The second uses the more sophisticated `new[]` syntax, which is more object oriented. Notice how `malloc()`'s return value needed to be turned into a `(char *)`? That's because it doesn't know what type of pointer it's returning, so it just picks `void *`. `new` does know, so it returns the correct type - but it still may return `0` if there's no room!

Once you've got either pointer, you use them just like `p_s` before. There is nothing stopping you from accessing outside the boundaries of the buffer - just like there isn't for `p_s`! Be careful!

Oh, and once you've finished with the lump of memory, you need to return it to the heap:

    free(p_b);
    delete [] buffer;

If you used `malloc()`, return it with `free()`. If you used `new[]`, return it with `delete[]`.

### And all of the above is why they invented the `String` object.
It manages the memory; keeps track of the string's length; lets you access and modify individual characters; lets you resize the string as needed; and gets rid of the used memory once you're finished with it. No wonder people start to use `String` syntax when they see string pointers...

But `String`s are only useful for `char`s. Arrays and pointers can be of and to anything - including `String`s and (_**GASP!**_) pointers! Uh oh - here we go again...


body:
I'm trying to have a `millis()` timer run to emulate a hardware timer inside a library, but I'm having issues compiling the code. I want the callback (pseudo ISR) to be part of the class, and not use global variables.

I'm using [Christensen's / Monk's Timer library](https://github.com/JChristensen/Timer/tree/v2.1), but I'm open to suggestions if there are other better/easier timer libraries out there.

This is what I have so far. It's just an example for me to understand how this might work. I'm sure there are better ways of making an LED blink, but this is just for illustrative purposes.

Compiling gives a bunch of "invalid use of member variables in static functions" errors.

> error: invalid use of member 'Blink::_led_status' in static member function
         int _led_status;

EDIT
------
After trying to add glue routines as per your other answer I can seem to get one instance working, but adding another stops the first light from blinking, and the second one blinks on and off at the wrong times.

The test library is on [github](https://github.com/waspinator/test-timer)

Blink.h

<!-- language: c++ -->

    #ifndef Blink_h
    #define Blink_h

    #include "Arduino.h"
    #include <Timer.h> // https://github.com/JChristensen/Timer/master
        // Timer.h uses millis() instead of built in timers

    class Blink {
    public:
      Blink (int led_pin, int duration);
      void begin ();
      void updateTimer();

    private:
      static void _callbackGlue();
      void _callback();

      static Blink *_instance;
      Timer *_blink_timer;
      int _led_pin;
      int _duration;
      int _led_status;
      int _blink_event;
    };
    #endif

blink.cpp

<!-- language: c++ -->

    #include "Arduino.h"
    #include "Blink.h"

    Blink *Blink::_instance;

    Blink::Blink (int led_pin, int duration) {
      _blink_timer = new Timer();
      _led_status = 0;
      _led_pin = led_pin;
      _duration = duration;
      pinMode(_led_pin, OUTPUT);
      digitalWrite(_led_pin, LOW);
    }

    void Blink::begin () {
      _blink_event = _blink_timer->every(_duration, _callbackGlue);
      _instance = this;
    }

    void Blink::_callbackGlue() {
      _instance->_callback();
    }

    void Blink::_callback() {
      if (_led_status == 0) {
        digitalWrite(_led_pin, HIGH);
        _led_status = 1;
      } else if (_led_status == 1) {
        digitalWrite(_led_pin, LOW);
        _led_status = 0;
      }
    }

    void Blink::updateTimer() {
      _blink_timer->update();
    }

test/test.ino

<!-- language: c++ -->

    #include "Blink.h"

    Blink first_blink (13, 500);
    //Blink second_blink (12, 1000);

    void setup() {
      Serial.begin(9600);
      Serial.println("Starting...");
      first_blink.begin();
      //second_blink.begin();
    }

    void loop() {
      first_blink.updateTimer();
      //second_blink.updateTimer();
    }

title: How do I use interrupt service routines inside libraries and classes?

Answers: 2

body:
Nick Gammon's answer is good for one `Timer` - but now you want two!

OK, then you can take advantage of the Timer Library's `context` parameter. What's that? If you take a look at the header for `every()`, you'll see as well as passing in the function to call, you can _also_ pass in another value (called `context`) to pass back to that function when it fires*. So instead of you remembering just one copy of `instance`, get each `Timer` to remember it for you.
> *If you can't see the `context` parameter in `Timer.h`, then make sure you're using the [`v2.1`][1] branch, _**not**_ `master`.

So:

1. Get rid of `_instance` everywhere.
2. Change:
   `static void _callbackGlue();`
   to
   `static void _callbackGlue(void *context);`
3. Change:
   `void Blink::_callbackGlue()`
   `{`
   `_instance->_callback();`
   `}`
   to
   `void Blink::_callbackGlue(void *context)`
   `{`
   `((Blink *)context)->_callback();`
   `}`
4. Change:
   `_blink_event = _blink_timer->every(_duration, _callbackGlue);`
   to
   `_blink_event = _blink_timer->every(_duration, _callbackGlue, this);`

Note that I've submitted these changes as a Pull Request on your GitHub repo.

----

Incidentally:

You don't need `_blink_timer` to be a pointer. Get rid of the `*`, get rid of the line with `new Timer()` in it, and replace all your `_blink_timer->` with `_blink_timer.`

  [1]: https://github.com/JChristensen/Timer/tree/v2.1

body:
You may add handler (AKA hook) functions using function pointer to the Timer0 ISR inside the core wiring.c source file shipped with Arduino core, and assign latter (attache) this function pointer to any desired function in the other library/class or in the main application code.

More about this trick in this [article here][1].

  [1]: https://atadiat.com/en/micros/e-arduino-trick-share-interrupt-service-routines-between-libraries-application/


body:
First time coding for Arduino. I'm working on code to operate an electronic valve switch. We have a laptop connected to an Arduino Mega, and that Arduino is hooked up to the valve (hardware) on Pin 53.

I was trying to work off of the "blink" example originally, but that gives no basis for user prompted control. Basically I want to have the computer ask me if I should turn it on or off, type in my response (I was using "HIGH" for on and "LOW" for off, as in voltage control), and have that activate or deactivate the hardware.

My main problem right now stems from how best to ask for that input. I've been trying to work with the Messenger.h library thus far. I'm definitely getting hung up on how to define the pin, or what the simplest method for user input would be. (HIGH or LOW? 0 or 1? Something else?)

Code is below. Thanks!

<!-- language: c -->

    #include <Messenger.h>

    Messenger message = Messenger();

    // Variable definitions. Switchinput is what the user commands, current state is whether the air is flowing or not.
    boolean currentstate;
    boolean switchinput;
    String pin53; // Something is up on this line?? How to define this pin??

    // FUNCTION DEFINITIONS
    // Startup fxn
    void start()
    {
      Serial.print("LOW = off, HIGH = on. Switch is ");
      Serial.println(currentstate);
      Serial.print("Enter LOW to turn on or HIGH to turn off: ");
      switchinput = Serial.read();
    }

    // Go off to on
    void offtoon()
    {
        digitalWrite(pin53,HIGH);
        currentstate = switchinput;
    }

    // Go on to off
    void ontooff()
    {
        digitalWrite(pin53,LOW);
        currentstate = switchinput;
    }

    // Stay same -- already off
    void staysameoff()
    {
      if ((currentstate = switchinput) && (switchinput = LOW))
      {
          void start();
      }
    }

    // Stay same -- already on
    void staysameon()
    {
      if ((currentstate = switchinput) && (switchinput = HIGH))
      {
        void start();
      }
    }

    // Running actual code
    void setup()
    {
      // initialize digital pin 53 as an output.
      pinMode(pin53, OUTPUT);

      // Sets default state to switch being off (Off = LOW, On = HIGH)
      String currentstate = LOW;
    }

    void loop()
    {
       if ((currentstate != switchinput) && (switchinput = HIGH))
      {
          void offtoon();
      }

      if ((currentstate != switchinput) && (switchinput = LOW))
      {
          void ontooff();
      }

      if ((currentstate = switchinput) && (switchinput = LOW))
      {
          void staysameoff();
      }

      if ((currentstate = switchinput) && (switchinput = HIGH))
      {
          void samestayon();
      }
    }

title: Computer to Arduino to hardware, controlling on / off state of hardware via user input on computer

Answers: 1

body:
This seems way too complex for your purpose:

* you really do not need to do anything to stay in the same state
* if you want to switch the valve ON, no need to check whether it's OFF:
  there is no harm in switching ON a valve that is already ON.

Here is a simplified version of the program:

<!-- language: lang-c++ -->

    void setup()
    {
        Serial.begin(9600);
        Serial.println("Type '0' to turn OFF, '1' to turn ON");
    }

    void loop()
    {
        int command = Serial.read();
        if (command == '0') digitalWrite(53, LOW);
        if (command == '1') digitalWrite(53, HIGH);
    }

Notice that `Serial.read()` returns -1 if there is nothing in the input
buffer, and since -1 is neither '0' nor '1', this will not change the
output.

If you want to use more elaborate commands (not single characters), you
may want to take a look at this [simple command-line
interpreter][interpreter.ino]. It is intended to be easy to adapt to
different purposes.

[interpreter.ino]: https://gist.github.com/edgar-bonet/607b387260388be77e96


body:
I just started with Arduino programming and currently I'm using this Sparkfun clone board:

o http://nl.aliexpress.com/item/Digispark-kickstarter-Micro-development-board-ATTINY85-module-for-Arduino-usb/32584975067.html

It's really nice and like the way to program it and 'burn' it, it's easy to do. For the first project, I came along this instructable, an USB volume knob:

o http://www.instructables.com/id/Digispark-Volume-Control/

I'm using the Sparkfun Arduino programming IDE with added AdaFruit Trinket USB library (Trinket is also ATtiny85), download source, tweak it a bit to my needs and it's working perfectly. Had some programming question though, see also:

o https://stackoverflow.com/questions/37740026/change-override-trinket-attiny85-usb-identification-name-device-name/37743886#37743886

o  https://stackoverflow.com/questions/37769451/arduino-make-a-library-more-optional-by-project?lq=1

o https://stackoverflow.com/questions/37824336/arduino-trinket-attiny85-usb-possible-to-read-the-state-of-all-keys

Anyway, optimized the source code (original not really a beauty), play with it and added also a fade-In/fade-out idle feature to the LED on PIN 1 and it blinks when turning the dial encoder.

I want to add add some more features to this knob, such as pushbuttons to change some internal modes. For example:

 - Toggle button for knob sensitivity (3-modes: slow (default), normal, fast)
 - A mute button

I want to that device 'remember' the state of the toggle button but there is no option (flash memory) to save the state. So I came with the idea to use a backup button cell to keep the device 'alive' when disconnected from USB (or computer turned off). A Button cell is 3V and USB is 5V so maybe is possible to 'test' the input voltage. If this is possible you can put the device in sleep mode (low power mode) directly after detecting USB connection lost and this voltage drop.

I have read already an article how to put the device into sleep mode (and awake from it):

o https://bigdanzblog.wordpress.com/2014/08/10/attiny85-wake-from-sleep-on-pin-state-change-code-example/

**Question is:**

Can I measure somehow the voltage is used to power the device? Any ideas (code example please if it is possible)?

title: ATtiny85 (Sparfun Clone/Trinket), detect/read operation voltage

Answers: 1

body:
There are a few solutions.

 - If you want to save te state of your toggle button you can save it in the eeprom of your attiny85
 - You can use an ADC pin to check your VCC against the internal 1.1V reference
 - alternatively you can read the 1.1ref aganist Avcc. https://digistump.com/board/index.php?topic=1104.0