text:
Setting Time to UTC with Data Logger Shield (with RTC DS1387)
I own an Adafruit Data Logger Shield https://www.adafruit.com/product/1141
I followed this tutorial
https://learn.adafruit.com/adafruit-data-logger-shield/using-the-real-time-clock
This part of code
if (! rtc.initialized()) {
  Serial.println("RTC is NOT running!");
  // following line sets the RTC to the date & time this sketch was compiled
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

adjust RTC to computer date/time... but it's using computer local date/time.
I'd prefer to use UTC date/time but I haven't find a convenient way to do this (except modifying computer date/time which is not very convenient as I want to always be able to reprogram Arduino without hassle of changing local time each time).

F(__DATE__), F(__TIME__) gives compile time local date/time. There will be a few seconds error as the sketch must be uploaded and run to set the clock. Given this I would suggest that you modify the sketch by reading back the setting and adjust to UTC plus the seconds error.

Problem here is that I don't want to adjust my computer to UTC when I'm programming and to local otherwise. It should be possible to have a function on computer side to return UTC time instead of local time.

You are getting a string from the compiler. Modify it to UTC before setting the RTC (in the sketch).

Do you know where __DATE__ and __TIME__ macros are defined?

Yes, see here https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html

There are several approaches you could use.
• Edit 1: On your development system, you could write a shell script or a batch file to write a file, say myUTCtime.h, containing a source-code line like char *MyUTCtime = "23:59:01"; and somewhere in your sketch say #include "myUTCtime.h".  Eg, to create the file in Linux: echo "char *MyUTCtime = \"$(date -u '+%H:%M:%S')\";" > myUTCtime.h which on my system produced file myUTCtime.h containing char *MyUTCtime = "08:20:36";
• You could define a different time constant, for example by adding -DMyUTCtime="23:59:01" into the gcc or g++ command line.  (Substitute an appropriate time.)  On Linux, this might look like -DMyUTCtime=$(date -u '+%H:%M:%S').  In your code you would write #MyUTCtime in place of  __TIME__.  Edit 1: Note, this is difficult to automate when using the Arduino IDE.  It is somewhat easier if using an Arduino Makefile.  For example, on Linux one might say MyUTCtime=$(date -u '+%H:%M:%S') make (which defines MyUTCtime with the current UTC time, and passes the MyUTCtime into make) and within the makefile, say (eg)
ifdef MyUTCtime
  CPPFLAGS += -DMyUTCtime=${MyUTCtime}
endif

• You could write your sketch to accept a time-setting command via serial input.  To set the time, you would send the time-setting command and the current time in UTC, via serial monitor.
• As Mikael Patel mentioned, you could modify the __TIME__ string to represent UTC before using it to set the RTC.  Here is an example of how to add or subtract an appropriate offset to __TIME__ to adjust it to UTC.  For example, if your offset is an hour ahead of UTC, you would change
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

to
char *compileTime = __TIME__;
compileTime[1] += 1;
if (compileTime[1] > '9')   // Check for carry
   ++compileTime[0];        // Add the carry
rtc.adjust(DateTime(F(__DATE__), compileTime));

This code has at least two problems:
• If the compile occurs between 23:00:00 and midnight, the resulting hour will show as 24 instead of as 00 on the next day. One could of course adjust the day of the date, and if that overflows, adjust the month, and if that overflows, adjust the year; or, more simply, one could produce an error in the compile.
• While a 1-hour offset may be appropriate during DST, a 2-hour offset may be appropriate most of the year.  One could of course check the date and use a date-appropriate offset of 1 or 2.

I like the second bullet approach but I don't know where I can provide this option flag -D within Arduino IDE. I'm not even sure that's possible http://forum.arduino.cc/index.php?topic=48693.0

@scls, in Arduino IDE, some compiler flags can be supplied via boards.txt; so, it may be possible but is clumsy and difficult if so.  Note, in Edit 1 of the answer I replaced first bullet with a simple approach using an include file, and in bullet 2 made some comments about  entering stuff like -DMyUTCtime="23:59:01" as a compiler flag when using a makefile.

authors: สถิตคุณ สังข์ประไพ


text:
ESP32 start BLE after deep sleep
I'm new to using the esp32 as a microcontroller. I'm currently working on a so-to-say remote control. Since I want to use the esp32 with an external battery I need to put it in deep-sleep after I pressed some buttons to preserve battery.
All that works fine I've connected a small touchpad to put the esp32 into deep sleep mode using the esp_deep_sleep_start() function . The controller itself goes to sleep and can be woken up using the following 2 lines:
  touchAttachInterrupt(T0, wakeCallback, TOUCH_THRESHOLD);
  esp_sleep_enable_touchpad_wakeup();

In order to communicate with my Raspberry Pi 'Base Station' I decided to use BLE.
My server is configured the following way (where bleServer, bleCharacteristic and bleService are global variables):
  BLEDevice::init("esp-32-remote");
  bleServer = BLEDevice::createServer();
  bleServer->setCallbacks(new ServerCallbacks());

  bleService = bleServer->createService(SERVICE_UUID);
  bleCharacteristic = bleService->createCharacteristic(
                        CHARACTERISTIC_UUID,
                        BLECharacteristic::PROPERTY_READ |
                        BLECharacteristic::PROPERTY_WRITE
                      );

  bleCharacteristic->addDescriptor(new BLE2902());
  bleService->start();

  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID);
  pAdvertising->setScanResponse(true);
  pAdvertising->setMinPreferred(0x06);
  pAdvertising->setMinPreferred(0x12);
  BLEDevice::startAdvertising();

Upon regular restart using the buttons everything works fine. I can connect to the device using python and the bluepy library.
If I now wake the controller I can't do anything anymore. The setup() function gets called and there are no errors, nor does the controller crash due to any code errors (seemingly).
Then the loop function gets called once, and thats it. I can't connect to the device anymore until I press the hardware reset button.
The questions that arise are:

might there be some error in the way I shutdown the bluetooth module?
Does the loop function work after being woken up from deep sleep?

Maybe one of you has an idea regarding my issue. If there are more information that I need to provide, don't hesitate to tell me, I'm new to the whole mcu topic and I don't know whats best to provide here.

Does the loop function work after being woken up from deep sleep? YES
loop function isn't magical.  its just a function that gets called over and over.  In other words, if it gets called once, it can be called again except if

it did something to deactivate itself
never reached the end

during that first call.  Check that you are not activating some sort of state inside the loop or going into a blocking call awaiting a signal that is never sent.
For good measure, make sure to reset all your variables to their expected states - expecting something to be 0 or set via the original definition may be insufficient.  This is something that occurs on a power reset so if reset is making it work again, thats a likely culprit.  Use a bare minimum of code in the loop for debug so you can figure it out.

Thanks for the answer I'll look into that.
Do you have any recommendation regarding the BLE issue?

I do not at this time.  I did read that a "the TV Begone remote control" intentionally went to a sleep without wake upon sending a power off signal, and tied into the reset button for waking again, so be careful what you copy and from where.  https://www.gammon.com.au/power

There's a good tutorial here on how to connect the BLE server client to the ESP32. And a Good fix here for reconnection issues.
Below is a piece of prototype code I wrote for BLE server client connectivity:
class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
      deviceDisconnected=false;
      interface->onBoardLED->led[0] = interface->onBoardLED->LED_GREEN;
      interface->onBoardLED->statusLED(100, 1);
      BLEDevice::startAdvertising();
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
      interface->onBoardLED->led[0] = interface->onBoardLED->LED_BLUE;
      interface->onBoardLED->statusLED(100, 1);
      interface->onBoardLED->led[0] = interface->onBoardLED->LED_BLUE;
      interface->onBoardLED->statusLED(100, 1);
      interface->onBoardLED->led[0] = interface->onBoardLED->LED_BLUE;
      interface->onBoardLED->statusLED(100, 1);
      pServer->getAdvertising()->start();
    }
};

class pCharacteristicTX_Callbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      std::string rxValue = pCharacteristic->getValue();

      if (rxValue.length() > 0) {
        String msg="";
        mserial->printStrln("*********");
        mserial->printStr("Received Value: ");
        for (int i = 0; i < rxValue.length(); i++) {
           msg=msg+String(rxValue[i]);
           mserial->printStr(String(rxValue[i]));
        }

        mserial->printStrln("");
        mserial->printStrln("*********");

        //valueReceived=msg;
      }
    }

    void onRead(BLECharacteristic *pCharacteristic) {
      mserial->printStrln("*********");
      mserial->printStr("onRead...");
      pCharacteristic->setValue("OK");
    }

  };

class pCharacteristicRX_Callbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      std::string rxValue = pCharacteristic->getValue();

      mserial->ble=false;

      if (rxValue.length() > 0) {
        String msg="";
        mserial->printStr("Received Value: ");
        for (int i = 0; i < rxValue.length(); i++) {
           msg=msg+String(rxValue[i]);
           mserial->printStr(String(rxValue[i]));
        }

        msg.trim();
        $BLE_CMD=msg;
        mserial->ble=true;
        newCMDarrived=true;
      }
    }

    void onRead(BLECharacteristic *pCharacteristic) {
      mserial->printStrln("*********");
      mserial->printStr("onRead...");
      pCharacteristic->setValue("OK");
    }

  };

//------------------------------------------------------------------

// Create the BLE Device
  BLEDevice::init("Smart Concrete Curing");  // Give it a name

  // Create the BLE Server
  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  // Create the BLE Service
  pService = pServer->createService(SERVICE_UUID);

  // Create a BLE Characteristic

  pCharacteristicTX = pService->createCharacteristic(
                      CHARACTERISTIC_UUID_TX,
                      BLECharacteristic::PROPERTY_NOTIFY
                    );

  pCharacteristicTX->addDescriptor(new BLE2902());

  pCharacteristicRX = pService->createCharacteristic(
                      CHARACTERISTIC_UUID_RX,
                      BLECharacteristic::PROPERTY_READ   |
                      BLECharacteristic::PROPERTY_WRITE  |
                      BLECharacteristic::PROPERTY_NOTIFY |
                      BLECharacteristic::PROPERTY_INDICATE
                    );

  pCharacteristicTX->setCallbacks(new pCharacteristicTX_Callbacks());
  pCharacteristicRX->setCallbacks(new pCharacteristicRX_Callbacks());

  interface->init_BLE(pCharacteristicTX);

  // Start the service
  pService->start();

on this particular code, I'm using light sleep , so to go to sleep :
      btStop();
      delay(1000);
      WiFi.disconnect(true);
      WiFi.mode(WIFI_OFF);

      changeMcuFreq(interface, interface->MIN_MCU_FREQUENCY);

and to wake up :
changeMcuFreq(interface, interface->WIFI_FREQUENCY);
btStart();

source: Stack Exchange

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

sort: votes


text:
Client or WiFiClient wrapper for adafruit CC3000 wifi other than web
Basically I want a contact to a socket (keep open) for sending strings and characters as well as receiving them. I do not want anything to do with web. I am writing my own server in vb and actually have that working. I also have working the Arduino ethernetshield. I just wanted an alternative wifi solution.

As far as I can tell, your question question is effectively a duplicate of this one. The only difference is that you're asking that it's nothing to do with the web. That doesn't really make sense because your network sockets will usually be the same, whether you're connecting to a local server or a remote one.

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


text:
Wifi server to control led on and off from local webpage.. - ..if statement doesnt work...
Im a newbie on this arduino thing and I would like to build a curtain remotecontrolled from a local webpage with 2 buttons... a up an a down...
I got the connection via my phone the the local page with the buttons. :D
My problem on this one is that the buttons' if statement (command == on); doesnt work or in other words the client.println(command); get the "on" command and write it on the page... but it dont do the function in the if statement (the button)...
Can anybody help me...? it should be simple..:D
    #include <Bridge.h>
    #include <YunServer.h>
    #include <YunClient.h>

    int LEDPIN = 3; // your LED PIN
    YunServer server;

    String readString;

    void setup() {
  // Start our connection
  Serial.begin(9600);
  pinMode(LEDPIN,OUTPUT);
  digitalWrite(LEDPIN,HIGH); // turn on Led while connecting
  Bridge.begin();

  // Show a fancy flash pattern once connected
  digitalWrite(LEDPIN,LOW);
  delay(150);
  digitalWrite(LEDPIN,HIGH);
  delay(150);
  digitalWrite(LEDPIN,LOW);
  delay(150);
  digitalWrite(LEDPIN,HIGH);
  delay(150);
  digitalWrite(LEDPIN,LOW);
  delay(150);

  // Disable for some connections:
  // Start listening for connections

  // server.listenOnLocalhost();
  server.begin();

}

/* ------------------------------------------------*/
/* --------------- End WIFI connection ------------*/
/* ------------------------------------------------*/

void loop() {
  YunClient client = server.accept();
  if (client) {
      process(client);
    client.stop();
  }
  delay(50);
}

void process(YunClient client) {
  String command = client.readStringUntil('\\');

  client.println("Status: 200");
  client.println("Content-type: text/html");
  client.println();
  client.println("

");
  client.println("ON

");
  client.println("OFF

");
  client.print("Command: ");
  client.println(command);
  client.println("");

/* ------------------------------------------------*/
/* ------------------- Buttons --------------------*/
/* ------------------------------------------------*/

  if (command == "on") {
    digitalWrite(LEDPIN,HIGH);
    digitalWrite(13,HIGH);
  }

  if (command == "off") {
    digitalWrite(LEDPIN,LOW);
     digitalWrite(13,LOW);
  }
}

Perhaps your command isn't exactly "on" or "off"  - could it have trailing characters?  Try displaying its length in your debugging message, or only comparing only the beginning with startsWith.  Also, comparing your code to a reference example, you seem to have replaced a single forward slash with an escaped backslash in the readStringUntil() so perhaps you are mistakenly reading the whole thing.

Is it possible you have a case sensitivity issue ("ON" != "on")?

Pretty sure your problem is coming from the fact that you chose to use the backslash as your terminator character. The backslash requires special handling when encoded as a URL. You can observe this by Googling for "\" and and the results page you'll see your query in the address bar assigned to the "q" variable:
q=%5C
my entire URL looked like this, you may have something a bit different:
https://www.google.com/?gws_rd=ssl#q=%5C
Ok - so if you want a quick fix, stop using the \ to terminate your commands, since backslashes are often used to help sort out special characters (like "TAB" as \t) it's a a really bad choice, but an honest mistake.
If you change your code to generate links terminated with dashes you can get around the issue
client.println("ON

");
client.println("OFF

");

and of course change your readStringUntil invocation too
client.readStringUntil('-');

Edit:
You might want to use the "" if the hostname part of your URL contains a space:
http://my-web-server.com/on
And one more alternative, seek the "%" instead since that's going to be used to encode the backslash. In that case you just need to change the readStringUntil()

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


text:
Multiple Definition of "_Vectors"?
I'm working on an arduino project that uses the GSM Shield and the eHealthSensor from Cooking Hacks. However I ran into an issue in which the interrupt vectors from the header/cpp files used are being defined multiple time.
While I know where the definitions are, I am unsure as to how to circumvent this issue either by Arduino programming or modifying the files since I'm not too experienced in this field. Below are the code for the conflicting files.
Below are the vectors that are in conflict.
PinChangeInt.h
    #ifndef NO_PORTA_PINCHANGES
    ISR(PCINT0_vect) {
        #ifdef PINMODE
        PCintPort::s_PORT='A';
        #endif
        PCintPort::curr = portA.portInputReg;
        portA.PCint();
    }
    #define PORTBVECT PCINT1_vect
    #define PORTCVECT PCINT2_vect
    #define PORTDVECT PCINT3_vect
    #else
    #define PORTBVECT PCINT0_vect
    #define PORTCVECT PCINT1_vect
    #define PORTDVECT PCINT2_vect
    #endif

    #ifndef NO_PORTB_PINCHANGES
    ISR(PORTBVECT) {
        #ifdef PINMODE
        PCintPort::s_PORT='B';
        #endif
        PCintPort::curr = portB.portInputReg;
        portB.PCint();
    }
    #endif

    #ifndef NO_PORTC_PINCHANGES
    ISR(PORTCVECT) {
        #ifdef PINMODE
        PCintPort::s_PORT='C';
        #endif
        PCintPort::curr = portC.portInputReg;
        portC.PCint();
    }
    #endif

    #ifndef NO_PORTD_PINCHANGES
    ISR(PORTDVECT){
        #ifdef PINMODE
        PCintPort::s_PORT='D';
        #endif
        PCintPort::curr = portD.portInputReg;
        portD.PCint();
    }
    #endif

    #ifdef __USE_PORT_JK
    #ifndef NO_PORTJ_PINCHANGES
    ISR(PCINT1_vect) {
        #ifdef PINMODE
        PCintPort::s_PORT='J';
        #endif
        PCintPort::curr = portJ.portInputReg;
        portJ.PCint();
    }
    #endif

    #ifndef NO_PORTK_PINCHANGES
    ISR(PCINT2_vect){
        #ifdef PINMODE
        PCintPort::s_PORT='K';
        #endif
        PCintPort::curr = portK.portInputReg;
        portK.PCint();
    }
    #endif

    #endif // __USE_PORT_JK

GSM3SoftSerial.cpp
// This is here to avoid problems with Arduino compiler
void GSM3SoftSerialMgr::manageMsg(byte from, byte to){};

//#define PCINT1_vect _VECTOR(2)
//#undef PCINT1_vect

#if defined(PCINT0_vect)
ISR(PCINT0_vect)
{
  GSM3SoftSerial::handle_interrupt();
}
#endif

#if defined(PCINT1_vect)
ISR(PCINT1_vect)
{
  GSM3SoftSerial::handle_interrupt();
}
#endif

#if defined(PCINT2_vect)
ISR(PCINT2_vect)
{
  GSM3SoftSerial::handle_interrupt();
}
#endif

#if defined(PCINT3_vect)
ISR(PCINT3_vect)
{
  GSM3SoftSerial::handle_interrupt();
}
#endif

Any advice on how to fix this will be greatly appreciated.
If it helps, I am using an Arduino Mega 2560.

You need to rewrite the GSM library to use the pcint library instead of handling the interrupts itself.

It's linking problem. More .o files included in linking declares identical global symbol eg. ISR(PCINT1_vect). Ideally write own makefile and compile via standard make. As hack you can loook in PinChangeInt.h conditional parts and make global definitions not to avoid *ISR()*s, e.g. #define __USE_PORT_JK


text:
Change XBee shield TX/RX Software serial?
I am looking to have an Arduino UNO stack with a GSM Shield and an XBEE shield for wireless communication.
However, since the GSM Shield requires digital pins 2 and 3, I would have to reroute the RX/TX of the XBee to another digital pin.
I have tried changing
SoftwareSerial XBee(2, 3); // RX, TX

to other values, but this does not work.
How would I go about doing this?

Did you reroute the XBEE RX and TX lines to the new pins?

You won't be able to use the same pins for serial with the GSM shield and the Xbee. I would try moving the xbee shield so that its sits on a different series of pins. Make sure to be careful with the power and ground pine (ie don't hook them up to active IOs and do hook them up to the appropriate location)

@geometrikal Thanks for the advice, I forgotten to add jumper wires between the RX/TX to the new ports. That fixed it. Thanks for your help!


text:
Enable free fall detection using Arduino
I'm trying to get an arduino board to detect simple free fall condtions. Currently, I have a 9DOF sensor (https://learn.sparkfun.com/tutorials/lsm9ds0-hookup-guide) and am able to get the raw data from the sensor.
However I am unsure what to do from here onwards. From what I manage to gather, there is an alternative sensor ADXL345 accelerometer that has an inbuilt free fall component. I have tried modfying the code in such a way that it will work with the sensor I am using but to no avail.
The free fall detection does not need to be extremely accurate/precise considering there are many fall/jerk patterns. It is just for a proof of concept for a project of mine. With that in mind, any suggestions on how to proceed will be greatly appreciated (or if I should just get the ADXL345 accelerometer).
Thank you.

From the LSM9DS0 datasheet; "The LSM9DS0 may also be configured to generate an inertial
wake-up
and
free-fall
interrupt
signal according to a programmed acceleration event along the enabled axes.". So it should be possible, just like with the ADXL345.

Hi, thanks for the reply. I got a sort of rudimentary fall detection working. Just wondering if there is any methods in which I can utilize the other two sensors (Gyrometer)/(Magnenometer) to further improve its precision. Much Appreciated

Sitting an accelerometer flatly on a bench will produce a value of 1G in one of the 3 axes.
Free fall of an accelerometer (assuming you haven't reached terminal velocity) should read near zero on all 3 axes.
I am not aware of a mode you can set for this, but if you check the values of the 3 axes and all are close to zero, you are probably in a free fall condition.

Hi, thanks for the reply. I got a sort of rudimentary fall detection working. Just wondering if there is any methods in which I can utilize the other two sensors (Gyrometer)/(Magnenometer) to further improve its precision. Much Appreciated.

I'm not if the gyro will be of use, given that a falling object may or may not be spinning.

Take the root sum squared [sqrt(acc_x^2 + acc_y^2 + acc_z^2)] of your accelerometer readings.  This is your total acceleration vector.  Then write a function that triggers the free fall variable when that equation is less than or equal to a certain threshold near to zero (the value itself depends on your accelerometer).
Your gyro and magnetometer will not help as they relate to the attitude (facing direction) and rotational speed of your thing, not the linear motion.  Test and play with the threshold and you will get the most accurate result possible.

You don't need to take the square root but can just compare against a squared threshold.  And it may not even be necessary to even combine the axis - it's probably sufficient to determine if there is or is not any individual axis reading above, +/-.707g (increased or decreased for reliability), as once the device has rotated through 45 degrees a different axis will start increasing.


text:
Setting a Pin to HIGH to simulate a button with a "pull up" resistor
in the below Fritzing diagram, I have a button that has a pull-up resistor, which when pressed, sets the GPIO Pin 23 to HIGH. On the Raspberry Pi, when the button is released, the GPIO goes LOW. The Raspberry Pi detects when the button is released and pressed. This is my desired behavior.
However, in my current configuration, I have PIN 13 connected to the Base of a NPN transistor to try to simulate the same behavior as the button with a pull-up resistor. When pin 13 is set to high, it sets the GPIO 22 Pin to high. When I set the Arduino Pin 13 to low, The GPIO Pin goes low but the Raspberry PI does not detect that GPIO 22 pin went low. Is there a way to simulate the same behavior as a button with a pull-up resistor with an OUTPUT pin from the arduino?

So the solution to this was to remove the transistor all together and connect the Arduino pin directly to the Pi. However, I need to change my Arduino sketch. The approach was to set the pin HIGH and go LOW when selected. I had it backwards.

I don't think your circuit is correct. If red is positive and your switch is momentary closed then it actually pulls GPIO23 low.
Likewise with the NPN transistor, using it in this way gives you an inverter. It should work if internal pull ups are enabled on GPIO22 and you remove the resistor.
IF GPIO23 is 5V tolerant, you can instead connect the resistor to 5V and GPIO23 straight to the collector.
You should also have a 1K resistor between the arduino pin 13 and the base of the transistor to limit the base current.
This all assumes that the VCE of the transistor is lower than the 0.8V low-level cutoff of the GPIO pins (it should be).
In any case, if GPIO23 is 5V tolerant, just connect it straight to the Arduino. If it isn't, follow penguins advice and use a voltage divider.

I think you are correct. I tried all the suggestions and I believe the issue is the program running on the pi that translates the HIGH/LOWS key presses. The program is on GIT HUB and asked for clarification there. Thanks for the help

First of all, I don't think you will need full simulation of a button. There are a couple of things this approach won't have:

Bouncing: it'll be (kinda, minus interference) a square wave. With a real button, the metal contacts "bounce," thus creating a weird waveform. Depending on interference, you'll still need debouncing code, although I would be surprised if it was necessary. I'd inlcude it in case I modified it to add a real button and/or there's some weird interference.
The time it's "pushed" may be very short, depending on your code. Keep this in mind when designing this.

Basically, you're hooking up the Arduino and the RPi together, with a voltage divider or a level shifter between the two.
Voltage divider:

Sparkfun
That is a voltage regulator (drawn four different ways; it's the same circuit). I calculated the values you will need: 1700 ohm for R1, 3300 ohm for R2.
Of course, serial (with USB of the Arduino) communication would be a lot easier...

If you don't mind using SMD components you could use the NX3V1G66 analog switch.
When you send a signal to the IC it will simulate a push button.
Maybe there are leaded versions of this IC but I haven't found them on the website where I order all my components.


text:
Using lambdas as callback functions
Using the Ticker library for the ESP32, how can I use a lambda as an argument to the attach method?
tickerSystemManager.attach(1000, [&](){
  systemManager->sync();
});

Attempting to use the above, I get the following error:
Matrx.cpp:11:4: error: no matching function for call to 'Ticker::attach(int, Matrx::setup()::<lambda()>)'
...
Ticker.h:40:8: note: candidate: void Ticker::attach(float, Ticker::callback_t)

How can I capp a lambda into this method?

Lambda expressions that take have no captures generate some implementation type that is implicitly convertible to a basic pointer to function type.  Lambda expressions that have a capture group don't qualify for that and are generally speaking not going to be compatible, because in practice what the compiler generates is a class whose members represent the captures, which makes the pointer into a pointer to class member function and therefore incompatible with regular pointer to function.

So what can I do to call the sync method of my object? It seems as if every attempt to do so give me some error or another.

If systemManager is a global, just remove the & from the capture.

As @timemage explains in a comment, you cannot pass a capturing lambda
to a function that expects a plain pointer to function. There is,
however, a way out of this: the Ticker class provides an overload of
the attach() method that allows you to provide a parameter of any type
to tour callback:
template<typename TArg>
void attach(float seconds, void (*callback)(TArg), TArg arg)

You can use this version of attach() and provide it both

a non-capturing lambda that gets a pointer to systemManager
that pointer as a third argument.

Edit: I did a few tests, and it seems my compiler cannot properly
perform template argument deduction in this case, but the approach works
if you explicitly specialize the template. Namely:
tickerSystemManager.attach<typeof systemManager>(
    1000,
    [](typeof systemManager p){ p->sync(); },
    systemManager);

You've managed to make this on topic.  Might as well go a step further and show the user-data-capable overload in the context of a lambda expression.

@timemage: Good  suggestion. I updated the answer.

I really appreciate the answer, this compiled and seems to run as expected! I am still trying to learn Cpp while setting up an ESP project and you are definitely giving me more to look into!

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


text:
Leonardo with xbee shield?
I'm trying to get a XBEE shield to operate on an Arduino Leonardo. Usually i use the AltSerialLibrary to emulate an extra serial for the xbee. However since the Leonardo comes with two sets of serial, i figured I use that instead.
//#include <AltSoftSerial.h>

//AltSoftSerial XBee(5,13); // RX, TX

void setup() {

  Serial1.begin(9600);
  Serial.begin(9600);

}

void loop() {

  Serial.println("Odds");
  Serial1.println("Ends");

  delay(1000);

}

The code above aims to write values to both the serial monitor (serial) and xbee (serial1). However in the Xbee's XCTU program, the remote xbee does not recieve any data.
Any feedback on how I might fix this will be appreciated.

How is the Xbee connected? You have a SoftSerial connection commented out, but Serial1 does not use the same pins as the SoftSerial would have.

kinda obvious question, but how did you configure the XBee previously?

You said you are using a Xbee shield.  What shield is it, and what pins does it use for Serial communications?
If you were using software to emulate the second serial port on other arduinos, you were probably using different pins, and so if the shield is designed to communicate over (as an example) pins 2 and 3 then it will most likely not work with pin 0 and 1 without moving jumpers or switches.  For example, this
Xbee Shield: http://core-electronics.com.au/xbee-shield.html/?acc=9f61408e3afb633e50cdf1b20de6f466 has a switch to switch between pins 0 and 1 and pins 2 and 3.
You could also try some code that reads from Serial and prints the data to Serial1 and visa versa.  This means you can experiment to get a greater understanding of the problem.


text:
Getting Push Button Logic To Stick?
I'm trying to get a sensor to activate if a push button is clicked. And deactivate when a certain condition is met and reactivate when the push button is pressed again.
#include <SPI.h> // Included for SFE_LSM9DS0 library
#include <Wire.h>
#include <SFE_LSM9DS0.h>

#define LSM9DS0_XM  0x1D // Would be 0x1E if SDO_XM is LOW
#define LSM9DS0_G   0x6B // Would be 0x6A if SDO_G is LOW
// Create an instance of the LSM9DS0 library called `dof` the
// parameters for this constructor are:
// [SPI or I2C Mode declaration], [gyro I2C address], [xm I2C address]
LSM9DS0 dof(MODE_I2C, LSM9DS0_G, LSM9DS0_XM);

const byte INT1XM = 4; // INT1XM tells us when accel data is ready
//const byte INT2XM = 8; // INT2XM tells us when mag data is ready
//const byte DRDYG = 7;  // DRDYG tells us when gyro data is ready
const int buttonPin = 15;     // the number of the pushbutton pin

int buttonState = 0;

double X;
double Y;
double Z;

void setup(){

  pinMode(INT1XM, INPUT);
  pinMode(buttonPin, INPUT);

  Serial.begin(9600);
  Serial1.begin(9600); // Start serial at 115200 bps
  // Use the begin() function to initialize the LSM9DS0 library.
  // You can either call it with no parameters (the easy way):

  uint16_t status = dof.begin();
  // Or call it with declarations for sensor scales and data rates:
  //uint16_t status = dof.begin(dof.G_SCALE_2000DPS, dof.A_SCALE_6G, dof.M_SCALE_2GS);

  // begin() returns a 16-bit value which includes both the gyro and
  // accelerometers WHO_AM_I response. You can check this to make sure
  // communication was successful.
  // Serial.println(status, HEX);
  setODR();
}

void loop(){

  buttonState = digitalRead(buttonPin); //Read push button logic.

 // Serial.println(buttonState);

  if (buttonState == 1) {   //if push button is pressed

    printAccel(); //print sensor data

  }

}

void printAccel()
{
  // Only read from the accelerometer if the accel interrupts,
  // which means that new data is ready.
  if (digitalRead(INT1XM))
  {
    // Use the readAccel() function to get new data from the accel.
    // After calling this function, new values will be stored in
    // the ax, ay, and az variables.
    dof.readAccel();

    //Serial.print("A: ");

    // Using the calcAccel helper function, we can get the
    // accelerometer readings in g's.
    X=dof.calcAccel(dof.ax);
    Y=dof.calcAccel(dof.ay);
    Z=dof.calcAccel(dof.az);

    Serial.print(X);
    Serial.print(", ");
    Serial.print(Y);
    Serial.print(", ");
    Serial.println(Z);

    // Serial1.println(Z);

    fall(); //jump to check condition

  }
}

void setODR(){

  dof.setAccelODR(dof.A_ODR_25);
  dof.setAccelScale(dof.A_SCALE_16G);
}

void fall(){

  if(-0.08<X && X<0.08){
    if(-0.08<Y && Y<0.08){
      if(-0.08<Z && Z<0.08){

        Serial1.println("N");
        Serial.println("Fallen!");

        loop(); //if condition is met, jump to loop to wait for push button to be pressed again.

        }
      }
    }
  //else{

    printAccel(); //else continue printing sensor data

  //}
}

However I am having some trouble getting it to work, above is what I have worked out thus far.

What does your DFA look like?

@IgnacioVazquez-Abrams I'm a little new to this, what does DFA stands for?

You'll need to store whether the button has been pressed.
bool buttonActivated = false;

...

void loop(){

  buttonState = digitalRead(buttonPin); //Read push button logic.
  if (buttonState == 1 ) {
    buttonActivated = true;
  }

  if( buttonActivated ) {
    printAccel(); //print sensor data
  }

}

to deactivate, use:
buttonActivated = false;


text:
Atmel STK500 and Atmel Studio
Is the Atmel STK500 worth using as a AVR programmer and Dev board? I am starting to get to into AVR programming with Atmel studio. I plan on purchasing the AVRDragon and also looking into purchasing the Atmel STK500. This might be too broad of a question, but are their any benefits in using the Atmel STK500?
Atmel STK500

From reports, no. Stick to the Dragon.

Realize you don't need any of this - any ATmega-based Arduino with it's existing bootloader will do, completely unmodified.

@ChrisStratton - yes of course, but the Arduino does not have debugging and its also a pain when switching from prototyping on the arduino to flashing the AVR.

Did you try connecting to the ISP header?

No, never tried. Perhaps I should.

It's pretty antique (doesn't even has usb). I'm not even sure if it does debug-wire. Stick to the Dragon. Maybe buy a cheap USBASP on eBay, for spare/convenience. They work great for ISCP programming.

Benefits of STK500? Sure:
- It has push buttons
- It has LEDs
- It has easy accessible connectors to any controller pin

Actually that's all. If you want/need to make use of this, buy both. Use the STK for "rapid prototyping" and the Dragon for debugging.
But if your budget allows it, have a look at the STK600 instead of 500. It's more expensive, but not so "old-fashioned", and it has much more features.


text:
Intializing Serial crashes UNO
I have a somewhat large sketch that uses the Adafruit_ssd1306(I2C) library for a 128X64 LCD. The sketch is a designed to be an alarm clock. When I upload the sketch with out initializing serial, it works as designed. However if I do intialize serial:
Serial.begin(9600);

the program fails to run on my UNO. After many hours of troubleshooting I noticed I have several large char arrays that may be the culprit.
const char *menusDisplay[] = {"1. Alarm-is Off", "2. Month", "3. Hour", "4. Minute", "5. Exit", "6. Alarm Set", NULL};
const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep" , "Oct", "Nov", "Dec", NULL};
const int days[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

The months array as 12 elements. If I shorted it down to 2 elements and upload the programs with serial initialized, the program runs. At first I thought is was a memory leak in perhaps the Adafruit_ssd1306. But I also have another LCD library Adafruit_ssd1306syp that the issue occurred too. So that ruled out those libraries.
When I compile the sketch without Serial:
Sketch uses 16,846 bytes (52%) of program storage space. Maximum is 32,256 bytes.
Global variables use 737 bytes (35%) of dynamic memory, leaving 1,311 bytes for local variables. Maximum is 2,048 bytes.

With Serial:
Sketch uses 17,862 bytes (55%) of program storage space. Maximum is 32,256 bytes.
Global variables use 910 bytes (44%) of dynamic memory, leaving 1,138 bytes for local variables. Maximum is 2,048 bytes.

Any ideas of what may be going on? I would load the sketch but its very large. If needed, I can try to cut it down and reproduce the issue.

The reported percentage of “dynamic memory” used is actually the percentage of RAM used by static and global variables. A significant amount of RAM can be used by the heap and the stack, which is not reported here as it can only be measured at run time. C.f. this answer and this answer on how to measure the amount of free RAM.

@EdgarBonet That was it. I ran out ram. Make this answer so you can get the credit. I have 2k of ram (Arduino) to start with. With serial initialized & my code, I have around 100 at the start of the program. I am sure that's the issue.

@EdgarBonet pointed out in a comment, I need to check my dynamic ram, which could be used by the Heap and Stack. The class can be found here to measure ram usage. Since links can die, here is the code:
Here is the header:
/* MemoryFree.h */

// MemoryFree library based on code posted here:
// http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1213583720/15
// Extended by Matthew Murdoch to include walking of the free list.

#ifndef MEMORY_FREE_H
#define MEMORY_FREE_H

#ifdef __cplusplus
extern "C" {
#endif

int freeMemory();

#ifdef  __cplusplus
}
#endif

#endif

Here is the .cpp
/* MemoryFree.cpp */

#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif

extern unsigned int __heap_start;
extern void *__brkval;

/*
 * The free list structure as maintained by the
 * avr-libc memory allocation routines.
 */
struct __freelist {
  size_t sz;
  struct __freelist *nx;
};

/* The head of the free list structure */
extern struct __freelist *__flp;

#include "MemoryFree.h"

/* Calculates the size of the free list */
int freeListSize() {
  struct __freelist* current;
  int total = 0;
  for (current = __flp; current; current = current->nx) {
    total += 2; /* Add two bytes for the memory block's header  */
    total += (int) current->sz;
  }
  return total;
}

int freeMemory() {
  int free_memory;
  if ((int)__brkval == 0) {
    free_memory = ((int)&free_memory) - ((int)&__heap_start);
  } else {
    free_memory = ((int)&free_memory) - ((int)__brkval);
    free_memory += freeListSize();
  }
  return free_memory;
}

From this I was able to see how much ram was used. Of the avialable 2k, I had only 100k left. So now I know why my program is crashing, I need a solution. The solution was to store the static content in program memory (PROGMEM):
const char* const months[] PROGMEM =
    {
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    };

const uint8_t days_of_month[] PROGMEM =
    {
        31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };

Since no other code is posted, I am going to guess that you're performing a loop on months[], which has 13 elements (last one is NULL).
You are likely also trying to walk the days[] array (or some other array), which only has 12 elements.
Since days[] or the other (not pasted) array doesn't have 13 elements, you're probably overriding a critical bootloader memory which causes a crash.


text:
Attiny84 and 2-Axis Joystick
I have a Parallax 27800 2-Axis Joystick wired up to a AVR 14 Pin 20MHz 8K 12A/D - ATtiny84. The joy stick sends out a x y analog signal. I have programmed the Attiny84 to read the signals and set one of the attiny84 pins (high or low) depending on the direction of the joystick. In this example, each pin is wired up to a LED. The problem I am having is there is about a 1 second delay for the LED to light. The Attiny84 has a built in 8MHz clock. Would connecting an external 20MHz crystal fix this issue?
int UD = 0;
int LR = 0;

int DWN = 0;
int UP = 1;
int LEFT = 4;
int RT = 5;

int LRMID = 0;
int UPMID = 0;
void setup(){

  pinMode(DWN, OUTPUT);
  pinMode(UP, OUTPUT);
  pinMode(LEFT, OUTPUT);
  pinMode(RT, OUTPUT);

  digitalWrite(DWN, LOW);
  digitalWrite(UP, LOW);
  digitalWrite(LEFT, LOW);
  digitalWrite(RT, LOW);

  //calabrate center
  LRMID = analogRead(3);
  UPMID = analogRead(2);
}

void loop(){

  UD = analogRead(2);
  LR = analogRead(3);
  // UP-DOWN
  if(UD < UPMID - 5){
   digitalWrite(DWN, HIGH);
  }else{
   digitalWrite(DWN, LOW);
  }

  if(UD > UPMID + 5){
   digitalWrite(UP, HIGH);
  }else{
   digitalWrite(UP, LOW);
  }
  // LEFT-RIGHT
  if(LR < LRMID-5){
   digitalWrite(LEFT, HIGH);
  }else{
   digitalWrite(LEFT, LOW);
  }

  if(LR > LRMID +5){
   digitalWrite(RT, HIGH);
  }else{
   digitalWrite(RT, LOW);
  }

  delay(100);

}

Have you tried removing the delay?

Do you have capacities somewhere in your circuit?

Thee delay(100) is only 1/10th of a second, and its there to give the code time to respond. And there are no caps in the circuit. Its pretty straight forward design.

While @alexan_e’s suggestion fixed your practical problem, I would argue that it did not address your root cause, which is that whatever board setting you’re working from in boards.txt assumes a clock rate of 8MHz, while in reality your fuses are set to boot the microcontroller at 1MHz. This caused your delay(100) to take 800ms, and was the entire reason for the slowdown.
Instead of fixing this at runtime, as aleman_e suggested, it seems more natural to me to bring your fuse settings into alignment with your compiler settings, using the “burn boot loader” Arduino command (which on Attinys generally does NOT burn a boot loader, but only sets the fuses to be in sync with the compiler settings).
If your application is not going to become much more complex, running at 1MHz might be a more efficient choice than running at 8MHz.

Thank you. I will give it a try. I thought I ran the "burn boot loader" at 8Mhz. I'll try again.

Fair point, although I originally suggested the runtime function so that he could check if that was indeed the problem, when we were not sure that this was the actual cause. In my reply I explained both methods to change the prescaler and just repeated the same suggestion I made in the comments because he asked me to post it as an answer, but it didn't occur to me to make a suggestion about changing the fuse.

@alexan_e I did not mean to disparage your runtime function (It did, after all, help diagnose the issue correctly), I was merely arguing that it was not necessarily the best solution for a permanent fix.

Running the boot loader did indeed fix the issue.

Several AVR devices including ATtiny 84, have a clock prescaler that can be used to lower the core frequency.
The divider can be controlled two ways.
The first way is the CKDIV8 fuse that controls the default loaded value to CLKPR (Clock prescale register) to either

fuse disabled:  Clock Division Factor 1 (clk/1)
fuse enabled: Clock Division Factor 8 (clk/8)

The fuse is enabled by default and applies the clk/8 setting, it can be changed with a programmer.
The second way is by changing the prescaler value during runtime. All you need to do is to include the following header
#include <avr/power.h>

and call one of following functions with the appropriate value you want to use
   clock_prescale_set(clock_div_1);    // Clock Division Factor 1
   clock_prescale_set(clock_div_2);    // Clock Division Factor 2
   clock_prescale_set(clock_div_4);    // Clock Division Factor 4
   clock_prescale_set(clock_div_8);    // Clock Division Factor 8
   clock_prescale_set(clock_div_16);   // Clock Division Factor 16
   clock_prescale_set(clock_div_32);   // Clock Division Factor 32
   clock_prescale_set(clock_div_64);   // Clock Division Factor 64
   clock_prescale_set(lock_div_128);   // Clock Division Factor 128
   clock_prescale_set(clock_div_256);  // Clock Division Factor 256

power.h manual
Note that the above functions can be applied at any part of the program, for example you can lower the cpu frequency to reserve battery and then set it higher again for intensive tasks. Just be aware that all peripheral will work with the divided clock too so PWM, timers, SPI, UART etc will all be affected.
If the problem you are facing is caused by the clock divider being in the /8 setting then you can change it at runtime.
Add the header at the start of the sketch
#include <avr/power.h>

And then set the prescaler value to 1 at the start of setup()
void setup() {
               clock_prescale_set(clock_div_1);  // set the clock prescaler to /1
}

Also note that changing the prescaler will affect delay() and millis(), since they assume a (predetermined) fixed clock frequency.

@IgnacioVazquez-Abrams The mentioned functions are based on the use of timers, and I mentioned that they get affected. In any case it's worth pointing for users that are not aware of that.

Are you absolutely sure your AVR is running at 8MHz, because default I believe it is scaling the 8MHz internal RC-oscillator down to 1MHz system clock. Change your F_CPU macro to 1MHz to see what happens.

..the internal 16MHz clock What are you referring to? The only available internal clocks for the mentioned device are 125KHz and 8MHz

I'm probably confused with ATtiny85 which does. @alexan_e

@PhilVallone If the problem is caused by the clock divider (CKDIV8 fuse) then you can set the divider to 1 in run time by including power.h #include <avr/power.h> and using clock_prescale_set(clock_div_1); in setup(). Although if this was related to the clock divider I would have expected problems during programing too, caused by the low UART BAUD rate.

@jippie - once the code is was uploaded I burned the bootloader at 8Mhz. Would I be doing harm to the chip if I try the bootloader again?

@alexan_e - I'll try your suggestions and report back

@PhilVallone Did you write the bootloader using the Arduino IDE? If so then the IDE writes the fuses too, so I doubt that the CKDIV8 fuse is still in the default set state. In any case rewriting the bootloaded doesn't damage the device in any way.

@alexan_e setting the clock_prescale_set(clock_div_1); did the trick. Response time is almost instant. If you put it as answer, I'll make as correct.


text:
Use Arduino's PWM to control motor direction?
I'm looking for a way to allow Arduino to control a motor using PWM.
So far what I have gathered is that using Arduino's PWM sets the digital value of 255 to 5v and 0 to 0v.
However what I am looking to do is to set the motors to stop at 2.5v, move forward as it approaches 5v and move backwards as it approaches 0v.
Any suggestion on how I would go about accomplishing this will be highly appreciated.

Just use two pins. One for ground and the other for 5v (with PWM). To reverse, have the first do the 5v (pwm) and the second be ground. Just note that the arduino pins can only provide enough current to power a small motor. Alternatively use an H-bridge

You seem to have misunderstood PWM here. It's actually a digital signal which is constantly pulsing on and off very quickly (several hundred times per second). You don't actually change the output voltage at all -- it's only ever HIGH or LOW (+5v or +0v). The thing you change is how long the signal is HIGH for on each pulse.
This page gives a deeper explanation: http://arduino.cc/en/Tutorial/PWM
When you're controlling a DC motor, this approach is actually better than varying the voltage. The constant pulses still make the motor turn at an adjustable speed, but without losing torque. PWM is also useful for controlling the brightness of LEDs, which don't respond so well to changes in current/voltage.
To address your original motor control question, there's no sensible way to change the motor's direction using the PWM value. You will need some additional circuitry which is able to reverse the polarity of the connections to the motor (meaning your PWM value just controls speed, and doesn't care about direction).
An H-bridge is the usual approach for this. Here's a fairly good tutorial which covers the basic principles: http://www.instructables.com/id/H-Bridge-on-a-Breadboard
Obviously you'd need to modify it for use with your Arduino project. The push switches could easily be replaced by digital signals from a couple of Arduino pins. The motor's power supply would be controlled by the PWM signal. You'll need an extra transistor for that, because you can't safely power the motor directly from an Arduino pin.

continuous rotation servo demonstrates a different approach of using PWM.
A continuous rotation servo is a standard servo modified in 2 ways. First the "position feedback" in the servo is disconnected and set to always read as if the servo was in the center position. Second the "stop" which physically prevents the motor from turning 360 degrees is removed.
Then if you set the servo to 0 degrees it rotates fast in one direction if you set it 180 degrees it move in the opposite direction.
More information:

http://www.instructables.com/id/How-to-modify-a-servo-motor-for-continuous-rotatio/
https://learn.adafruit.com/modifying-servos-for-continuous-rotation

You can use a MOSFET to control a DC motor directly from an Arduino. Using a H-Bridge is another way to control DC motors. Probably the L298N is the most used one but I prefer TB6612FNG. It's a bit expensive, but uses much less current and is something with a better response.
You will find tons of tutorial with both modules.
Good luck!


text:
Arduino GSM Module with network GPS
I have looked through the AT command set of Arduino GSM Shield boards. I dont find any AT command that provides network GPS. I wonder what I am missing. Why isn't it possible for GSM module to provide NetworkGPS (the one that is not really accurate) ?

A very simple answer could be that the firmware does not support it.

I believe the SIM900 has a command for it: http://www.puntoflotante.net/SIM900-Gsm-Location-AT-commands.pdf
But other manufacturers may have it aswell. (EDIT: the answers seem to differ and I must agree that it may not work depending on which carrier you use)

Simple answer is that it is function of cellular network (phone company) instead of the module.
More informative answer is, Position is calculated by network via

serving cell base station ID and location
when phone on standby, it monitors signal strength from multiple base stations and signal strength is roughly related to distance
when phone on transmitting, base station has one more piece of information. It calculates distance through time taken for signal to travel to multiple base stations (called 'time advance' in original GSM)

US E911 utilizes these to locate the phone.
Good technical paper with diagrams
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=6&cad=rja&uact=8&ved=0CEUQFjAF&url=https%3A%2F%2Fwww.fig.net%2Fpub%2Fcostarica_1%2Fpapers%2Fts08%2Fts08_01_schwieger_2407.pdf&ei=Ms3bU8-DItfr8AXT7oLQCg&usg=AFQjCNHImn4G34WC0Naw8IH6g1gfLzykuQ&bvm=bv.72197243,d.dGc
http://en.wikipedia.org/wiki/Positioning_%28telecommunications%29

I would agree that much of the functionality is in the carrier's network infrastructure, but that wouldn't explain why it's not available on a module that is almost certainly a network who's phone clients do receive this service.

The AT command set follows international technical standard, now 3GPP, was GSMMOU. The function you want is not there, according to the standard.  Individual network use what i describe above, also in the detailed tech paper I quote, for their own use, like E911 and other commercial LBS (locate based service). Some network make the info available on commercial terms. For example, one actual implementation is auto advertisement for long distance phone call (to call home) when user pass to a new country border.

You are right in that info is available as part of the overall structure, but, not via the module AT command.  If you like more detailed tech info. http://www.telecomsys.com/products/location-based-services/infrastructure-gsm/smlc.aspx  http://en.wikipedia.org/wiki/Location-based_service  http://en.wikipedia.org/wiki/GMLC

This is a very complicated situation.  In short, the module itself does not provide Assisted GPS without both the handset's help, and the help of the carrier.
Since the module is sold as an OEM or embeddable object, the manufacturer either hasn't included such functionality, or hasn't enabled it, or hasn't documented it.
Even if it were included, enabled, and documented, it has to work with the carrier, and each carrier provides different services for different modules.  Some locate solely based on triangulation using cell towers and the module's command channel.  Others depend on the module capturing a short sequence of RF from the GPS network, sending it to the carrier's AGPS server to be processed, which then reports back a very accurate position.
At any rate, this is not a standardized function for embedded cellular modules because cellular networks and carriers vary in how they've chosen to implement AGPS.
If you want to use AGPS in an embedded cellular module, you'll need to work with both the module manufacturer and the cellular carrier to enable that functionality.  It usually involves additional charges - renting an AGPS server, for instance.  These often involve a monthly fee in addition to a per-request fee.  Some companies set up their own AGPS servers to do the processing, but the cellular company still has to provide gross location information based on the tower signal reception.
Suffice to say, this is not something that is common or cheap enough for low volume projects.  Unless you're going to be working with thousands of these devices it's typically cheaper to integrate a standalone GPS chipset in your device.


text:
Arduino Nano and SIM300 module for http calls for location
I am new to Arduino and SIM300/900 world. But I see that there is a possibility of building a vehicle tracker (approximate locality since I will use GPRS network location) using just these 2 boards.
My question is, is my assumption correct ? Can I build a vehicle tracker using just Arduino Nano and SIM300 mobule ? Is there a board that has both of them on one board so that I dont have to buy them separately ? Cost is a major factor on the decision.

Not really.
Module can read the cell ID by below command. However, only phone company has the list of cell ID and their location. This information is only accurate to serving range of a cell, mostly in range of, 0.1 to 15km, from very dense city to country
Module can also read network ID and know, from public information, the country and network operator name.
Example taken from web:
AT+CREG?

This should give you a result like:
+CREG: 2,1,"1030","639E"

Working through the 4 returned values, the "2" reflects the
current "+CREG" setting (2 means "Enables unexpected network
registration and location information messages"), "1" indicates
that the phone is registered with the network, "1030" is the
Location Area Code (LAC) in hex (4144 decimal), and "639E" is the
CellID (CI) in hex (25502 decimal).


text:
Connecting a Arduino to FT232
I found this wonderful breakout board based on FT232. I wonder if I can use this board for connecting my arduino to a USB dongle for 3g/GPRS connection ?
From what I understand this board can be connected to the serial data pins of the arduino board. And if I connect the USB dongle to the FT232 board, I should be able to run AT commands from the arduino board.

How exactly do you imagine connecting two USB devices to work?

Many don't realize that USB has distinct host and device roles; it's a common confusion, but yes, the answer is that it doesn't work.

Unfortunately, no, as the FT232 would have to act as a USB host device. A USB host shield might work if someone has written driver code to support 3G modems.


text:
Attiny84A and IR Sensor
I have a GP2Y0A21YK0F Sharp IR Analog Distance Sensor 10-80cm + Cable, Arduino Compatible and its is connected to my Arduino. All works well and I can read the analog data with the following code:
#include <SoftwareSerial.h>
#define RX 2 // receive
#define TX 3 // transmit
#define SEN1 4
SoftwareSerial mySerial =  SoftwareSerial(RX, TX);

void setup()
{

  mySerial.begin(4800);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{

   int reading = analogRead(SEN1);
   mySerial.println(reading);
   delay(500);
}

When the code runs on the Attiny with the GP2Y0A21YK0F IR Sensor connected, the Attiny84 resets over and over. The Attiny84 and GP2Y0A21YK0F are part of the same circuit e.g. Attiny and GP2Y0A21YK0F share the power and ground rail.
When I disconnect the GP2Y0A21YK0F, the program runs and stops resetting. I was able to reproduce this on an Attiny85 and ATMega328.
The strange thing is, it works fine on the Arduino. Any help is greatly appreciated.

Start by adding 100nF capacitors with short leads as close as possible to the the power pins. One near the ATtiny, one near the IR sensor.

+1 Thanks after some trial and error, placing a 100uf at the source and at the GP2Y0A21YK0F seems to work. Awesome :)!

You really want to use caps in the order of 100nF, that is nano Farad's. The 100uF, micro Farad's, may work now but may not keep up with age. It is fine to use them in parallel. The smaller 100nF caps have a much lower impedance for high frequencies than the 100uF caps and they don't age.

It sounds like the microcontroller is browning out.
IR sensors are notorious for taking a lot of power when they operate; often they will tax a small power supply and cause the voltage to droop low enough to reset/brownout the microcontroller.
Try either putting a fairly beefy capacitor on the power bus, or getting a larger power supply.
Hope this helps!
(edit: I reverted another user's edit to this answer; "droop" is in fact the correct term for what is going on: http://en.wikipedia.org/wiki/Voltage_droop)


text:
Which Arduino-compatible microcontroller for 2 continuous analog audio recording and 2 digital pin snapshots every second?
Apologies if the title is not very well worded. I'm new to electronics and trying to learn more about embedded systems too. I have a small project that requires recording an analog audio input at 8-bit at 40kHz and saving it every second in a SD card.
Although I know that I can do that with an ATmega328P chipset, I'm not sure if the processing power of ATmega328P will be good enough for further extension of the project.
Ideally I would like to be able to record two sound sources at the same time at around 40kHz -- 16 or 24-bit would be perfect, and capture two sensory data also every second.
This device should be able to run on a reasonably sized battery for at least two hours, but ideally up to eight hours.
I do like the idea of working on a AT91SAM3X8E chipset, but I'm afraid this might be an overkill for such a small project and the current draw of a Cortext-M3 series might be too much for this project too.
My question therefore is would a ATmega328P or ATmega2560 be suitable for such requirements -- in terms of processing power, or do I have to upgrade to something like the AT91SAM3X8E?

My question therefore is would a ATmega328P or ATmega2560 be suitable for such requirements

No. Not in the slightest.
Your primary requirement of sampling audio at, basically, CD quality (or better) requires the use of a proper CODEC chip - and to drive that you require a microcontroller that has I2S. None of the 8-bit AVR chips have that.
On top of that you will need a LOT of memory. Far far more than an 8 bit Arduino has.  Two channels of 16 bit audio at 44100Hz (CD quality) requires 176400 bytes per second.
You will need double that.
To both continuously record and save the data you will require DMA to do the recording.  The DMA reads the incoming data from I2S and stores it in one buffer. When that buffer is full you generate an interrupt and switch to a second buffer. You can then save the first buffer to SD - assuming that it can be done in under a second.  Note that SD cards, when controlled by SPI as they generally are on microcontrollers, are generally quite slow.
So with all that in mind:

I do like the idea of working on a AT91SAM3X8E chipset, but I'm afraid this might be an overkill for such a small project

Overkill? No. Not suitable since it is not up to the task. Yes, it has I2S. Yes, it has DMA. But it doesn't have anywhere near enough memory.  You need for the audio alone 350 kilobytes (the SAM3X8E has up to 100 kilobytes) - not to mention memory required by the SD card's buffers.
So you're looking for a microcontroller that has full I2S support, DMA, and around half a megabyte of memory.  And those aren't small and cheap like the Arduino's 8-bit AVRs.

Great, thanks a lot! Do you think there is a way to write down the samples at the time of interrupt -- say every 20us, in a temporary fast but small RAM and then write that down to the SD card every second. This way the microcontroller itself wouldn't need to have the extra memory embedded inside.

Also the whole idea of buffering the data is to not have the SD card on all the time, just to lower the power consumption. If we ignore that for now, do you think a mega328 can write real-time data to a (high quality, fast) SD card without any delays?

As for the temporary cache, maybe some fast EEPROM would work?

No, and no. You need a more powerful MCU.

"write real-time data to a (high quality, fast) SD card without any delays?" The possible speed of the SD card is not important as long as you use SPI. To reach the high data speeds, you need to use the parallel data interface. And even with that most like the microcontroller (assuming you have one, that is up to the task in general) will be the bottleneck. So the possible speed of the SD card doesn't really matter


text:
Arduino as ISP without a computer
Has anyone seen or know of a method of preloading (using a computer or whatever) a firmware as data onto one arduino set up to operate as an isp and then using that arduino plug the isp interface into another and upload the firmware.
To be clear - i'm looking for a way to make uploading arduino sketches possible without a direct connection to a full blown computer.
Ideally the steps involved would be:

Write new sketch/firmware
Compile firmware
Write a copy firmware onto Arduino A as data (Arduino A is set up to work as ISP)
Detach Arduino A from the computer
In a seperate location attach Arduino A to Arduino B using ISP headers
Using some method (maybe a pushbutton) trigger Arduino A to upload the preloaded firmware onto Arduino B.

I'm assuming that theoretically it could work because uploading firmware is just an exchange of bytes across the SPI interface but i'm not sure about the reality.
The scenario for which I'm considering is if I were to install an arduino (permanently) in a location that is remote from my computer (I don't have a laptop nor do I want to get one) it would be troublesome to reprogram it.
The other method I have considered is using the DIL packaged ATMEGA which I can then remove from the board and program at the computer and return to the board - however I would much prefer not to risk bending of pins and the hassle of having to remove the chip each time I want to reprogram.

The result would be that you would only be able to program other Arduinos with the exact sketch/firmware that's been loaded into the programmer (Arduino A). So it would only be useful to make copies as in a production line, is that it? If you need to change anything on the sketch you would need to get back to the computer to modify and load it again. Did I get this right?

Isn't it possible to keep the "flash image" to be copied to the target on another support (like a SD card)?

Yea. I suppose it would also be good for a production line. My situation is I have an arduino glued into a enclosure that is difficult to move and it's in a different room to my computer (also difficult to move). So I would be happy to load the sketch onto Arduino A each time I wanted to change it.

It's been done for the limited purpose of programming a bootloader - https://github.com/WestfW/OptiLoader - but should work for any payload smaller than available flash minus the tool's size.  For a larger payload firmware, an external storage device (or simply an Arduino Mega?) should work.

@ChrisStratton that looks perfect for me to adapt. Thanks

Thanks to both the answers, I will get around to marking one as the answer soon. I just want to make it work first.

I think µProg – tiny, fast, portable AVR programmer with SD does what you want. You can store multiple files in the SD card (hex, eep etc) and select from the device menu which one to write to the target MCU without any need for a PC.
The best part is that it's available for free (PCB, schematic, firmware etc).

One of a kind, portable AVR programmer! Helps wherever you need to
update the device firmware, where target device is in a hard-to-reach
location and you can’t (or don’t want to) bring your laptop with a
bunch of wires with you. Trivially easy to use, super cheap to make,
super small, super fast, uses SD cards…
Features:

super small – dimensions 44 x 39 x 5,5 mm
super fast – write up to 12,5kB/s, read up to 14,5kB/s
uses cheap storage medium – small MICRO SD cards
supports FAT16 and FAT32 file systems
can read, write, verify flash and eeprom memory
can read, write, verify fusebits and lockbits
write and read to BIN, HEX, and TXT files
can set default values of fusebits, erase memories
cheap, easy to obtain, LPH7779 graphic display
shows funny animations after every operation
standard programming header – Atmel 6-PIN ISP
has a function of auto-update its own firmware (from SD)
very simple to use, 4 buttons navigation
user-setting menu
programming speed auto-selection (up to 4MHz)
Operates at 3V, programs chips supplied from 3V to 5V

Supported chip list

Looks good. Will investigate at the weekend.

I don't know how I missed this question the other day. I've only been talking to a friend about creating this exact project ourselves. And then I see your answer.

I have no direct solution for what you want, but yes it is possible to do it. You can hack a bootloader firmware so that it reads the firmware flash code and upload it over ISP.
Though you obviously can't upload 32k of firmware on the target AVR if both arduinos have only 32k of total flash in their MCUs, you'll need to have the flasher have more flash than the target if you want to do so (a 1284p or 2560 Mega will be far enough, or a 328/32u4 will be cood to flash a 168 or an attiny).
The only exception would be to have the firmware to be flashed way smaller than the total memory (like for a blink sketch).
In the end, that won't be easy, it's 100% pure AVR code, but you can do it. Have a look at:

The bootloader FAQ ;
The Optiboot Project which goal is to make the smallest bootloader possible and
AVRISP source code

The way I'd implement that would be to either make everything fit in the bootloader of the flasher device, so it reads the firmware (everything from 0x00 to the bootloader start address) and flashes it through ISP by merging AVRISP with Optiboot.
Anyway, that's an interesting project for a workshop about bootloaders and AVRs I may suggest at my local hackerspace! ;-)
HTH

Thanks, the AVRISP source code doesn't look as complex as I expected. I will look a bit deeper into this over the weekend

Where's your local hackerspace? :)

it's in France Le Loop

no problems, that's what voting up is for ;-)


text:
ATmega168a Breadboard - can't load via Arduino IDE
I have ATmega168a on a breadboard. I am programming it via the Arduino IDE and a FT232RL USB adapter. When I select my board for 168 and upload, I get the following error:
stk500_getsync(): not in sync: resp=0x00

Normally this error means that either:

My wiring is not correct
I choose the wrong board

So to double check my wiring, I replace the 168 with a 328p. I am able to program the 328, so I think its the board selection.
I have tried Ardiono Diecimila or Duemilanove w/ ATmega168 and I also have a custom board entry:
atmega168bb.name=ATmega168 breadboard (16 MHz internal clock)
atmega168bb.upload.protocol=stk500
atmega168bb.upload.maximum_size=14336
atmega168bb.upload.speed=57600

atmega168bb.bootloader.low_fuses=0x62
atmega168bb.bootloader.high_fuses=0xDF
atmega168bb.bootloader.extended_fuses=0xF9
atmega168bb.bootloader.path=arduino:atmega
atmega168bb.bootloader.file=ATmegaBOOT_168_atmega328_pro_16MHz.hex
atmega168bb.bootloader.unlock_bits=0x3F
atmega168bb.bootloader.lock_bits=0x0F

atmega168bb.build.mcu=atmega168
atmega168bb.build.f_cpu=16000000L
atmega168bb.build.core=arduino:arduino
atmega168bb.build.variant=arduino:standard

Also, I am able to program the 168 via my AVR Programmer/Debugger. If you are wondering why I should just use the AVR Dragon, there reason is that I a sometimes don't want to remove the chip from the bread board while developing and programming.
Any suggestions I can try?

Did you program an Arduino bootloader into the chip? Also, jumper wires.

Yes - with ATmegaBOOT_168.hex - And by jumper wires, what do you mean?

The internal oscillator is 8mHz, not 16mHz. That means serial runs at half the speed. So you could try atmega168bb.upload.speed=28800

@Gerben Thanks but that didnt work either. I'll continue to work on it. I can use the SPI/ISP programmer, but this is killing me why it won't work!

Have you burned a bootloader?
The standard Arduino IDE upload requires that you have a bootloader on the chip.
You can burn a bootloader with the Arduino IDE and your AVR dragon

There is another possibility, which I have had in the past.
My AVR was brand new, and it was set to use the internal resonator, at 1/8th speed, for a total of 1mhz. This was too slow to program using the default settings.
I had an USBASP, and it very conveniently had "SLOW SCK" jumper option, to slow down the programming. This was enough to program it, and if I'd wanted to use an external crystal clock (which I didn't, and 1mhz was fast enough for the specific project), I could have changed the fuses Check out http://www.engbedded.com/fusecalc/ to calculate new fuse settings. Be careful, I managed to set one chip to the wrong fuses, and am no longer able to change it.
P.S. - I used AVRDUDE to program the fuses. You should be able to read the current values, before you start - again, at slow speed. AVRDUDE has the '-B' option to slow down the programming, if you do not have the "SLOW SCK" jumper option, option -B10 should be plenty (default = -B1 I think).
When checking what the current fuse settings are, I think the main ones that slow down the clock are: CKSEL and SUT (the top dropdown list on the calculator website), and CKDIV8 - divide clock by 8; the second tickbox on the list. The defaults for these for AtMega 168 should be: Internal RC Oscillator: 8mhz, and the "Divide clock by 8" option selected.

This is indeed a possibility in other settings, but keep in mind that the question here concerns programming via serial communication with a bootloader, not ISP, and that the poster has reported that ISP is working.

. If you are wondering why I should just use the AVR Dragon, there reason is that I a sometimes don't want to remove the chip from the bread board while developing and programming.

Your dragon is an ISP so you don't have to unplug and replug it for programming.
I would check if your ftdi board an indeed function as a stk500.
Another alternative is to burn the bootloader and go down the regular Arduino route.

Try adding a 1k resistor on the TxD and RxD pins to your chip. And a 100nF capacitor like the schematic below. And a 10k Pull-up resistor to the reset pin.
Target processor                                 USB to Serial converter
(Atmega 168)
GND   ------------------------------------------ GND

5V    <----------------------------------------- 5V
RX    <--- 1K ---------------------------------- TX
TX    ---- 1K ---------------------------------> RX
RESET <----||----------------------------------- DTR_PIN
  |       100nF
 10K
  |
 5V

This will help stabalizing the signals.

This will not "stabalize" things.  What you are showing is a mix of ideas - some resistors for pin sharing or lazy level conversion, and an auto reset circuit.  The auto reset might be useful, but unless the ATmega and USB serial solution are running at different voltages, the resistors will not help.

I see. If I wasn't wrong I had some like the same problem as the person who asked this question and fixed it using my answer. Found that on the arduino website back then. Can't really remember it clearly though....

you should be selecting the Arduino NANO board as the original Arduino Nano board is equipped with the FT232RL, rest all have either atmega chip for usb to ttl conversion or CP2302 chip. So select Arduino Nano and try.

Which serial converter is in use does not matter.  It is appropriate to select a proper board configuration, but not for that reason.  In fact historically and even today for the boards concerned here, the boards.txt doesn't even contain any information about the USB serial solution in use.  A few entries such as for the Uno do now contain USB/VID information but that is probably only to help the user find the right serial port - it wouldn't change behavior in how avrdude talks on that port.


text:
Hardware interrupts for buttons not directly assigned to pins
The Adafruit LCD shield offers an LCD and access to 4 button, using only a two wire connection with the Arduino.
This is achieved with the MCP23017 I2C port expander IC.
These buttons are not directly assigned to pins, since only two pins are required for the whole communication, via the I2C protocol.
Can i use a hardware interrupt with any of the 4 buttons?
If not, is there any workaround to trigger an interrupt when one of these buttons is pressed?
PS: I am using Arduino Due

The MCP23017 has two interrupt outputs. The Adafruit shield however doesn't bring out either of those two pins. You could solder a wire between one of these pins and one of the unused arduino-header pins.

No, you can not while keeping the shield intact but it's possible I think.
https://learn.adafruit.com/rgb-lcd-shield/downloads
Here if you see the schematic and fabrication print, you will see that buttons are connected to MCP23017 I/O port. Now if you can connect to the MCP23017 pin corresponding to button you may detect the voltage change. This can be used to trigger interrupt.


text:
Time to read/write memory on the DUE
I am onto a project where a need more memory. I saw the 23LC1024 chips are very popular with the Arduino DUE.
A very helpful person told me he did some timing tests on the 23LC1024 and a page read/write of 32 bytes costs about 100 μs.
I am interested in real time audio manipulation application (using the Arduino Due's ADCs and DACs).
This time of 100μs per 32 bytes seems a lot for the application, though i am not sure.
Are there benchmarking tests of the Arduino DUE for the time it takes to read/write to its memory, so i can compare with this chip and decide what to do?

You really don't want to use an external SPI memory for that.  Switch instead to either a processor with more on-chip RAM (maybe another SAM series part, or maybe the top end Teensy), or even more appropriately for such a task, switch to an SoC which uses a variety of external parallel DRAM and likely has on-chip caches to further speed access to it.  These don't necessarily cost any more today, though they do add some system complexity.

Personally I use the PIC32MZ with an external I2S DAC or CODEC chip. 200MHz 512kB RAM, 2MB flash... And programmable in the Arduino IDE...

Besides, using DMA to read from the ADC and write to the DAC leaves plenty of CPU time for shuffling memory around between internal and external RAM blocks.

I didn't know this chip was programmable from the arduino IDE! Does it follows the same code structure (setup, loop)? Also the chip is available in bulk form. I would have to build a circuit and solder components to program it right? Any references on the circuit?

Also, could you please mention the I2C DAC chip you were using?


text:
Sizeof variables and Due's RAM
I set out to see how much space some arrays have. I used this test code
bool state = false;

uint16_t BuffA[46000];
uint16_t BuffB[20000];
uint16_t BuffC[20000];
uint16_t all = 0;

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

void loop(){
if (state==false){
Serial.println(sizeof(BuffA));
Serial.println(sizeof(BuffB));
Serial.println(sizeof(BuffC));
all = sizeof(BuffA) + sizeof(BuffB) + sizeof(BuffC)
Serial.println(all);
state = true;
  }
}

I got this answer from the serial:
92000
40000
40000
40928

Why are the results doubled from those i initiated? Shouldn't the first one be 46kb and the other two 20kb?
Why is the last value only 40928?
The RAM of Due is 96kb. Does this mean that with the initialization of only three arrays it's almost full? Ifi crossed the RAM limit, would the IDE throw an error?
If i still need more RAM, can i use and external one with Due for high speed RAM acquisition?

sizeof doesn't return the number of elements. It returns the number of bytes. Since they are uint16_t arrays each element is 2 bytes - hence twice the size.
The reason your last number is only 40928 is because of integer wraparound. You only provide a 16-bit unsigned variable to store it in, so all you get is the lower 16 bits of the answer.
92000 + 40000 + 40000 = 172000

172000 in hex is 0x29FE0

0x29FE0 truncated to 16 bits is 0x9FE0

0x9FE0 in decimal is 40928.

The RAM of Due is 96kb. Does this mean that with the initialization of only three arrays it's almost full? Ifi crossed the RAM limit, would the IDE throw an error?

It would, but you aren't actually using the arrays for anything, so the compiler threw them away.

If i still need more RAM, can i use and external one with Due for high speed RAM acquisition?

There are ways of interfacing the SAM3X with external RAM, but I don't thing the Due exposes all the signals you need. I would change to a chip with more RAM, such as the PIC32MZ with 512kB of RAM and 200MHz operation.

OP should be extremely careful with using nearly all RAM for data on embedded systems. One won’t get a nice error when things overflow. Instead, the stack will grow into the data section, overriding data there and getting overwritten by write access’ to the data. One will be seeing erratic misbehaviour, including freezes, NMIs and incorrect data.

Also known as "stack smashing" ;)

The sizeof operator's result is number of bytes, not number of array elements.  Your arrays in the program above have two bytes per element, hence twice as many bytes as elements.
If you want to report the number of elements, divide the total size by the number of bytes per element.  For example:
nElements = sizeof BuffA /  sizeof BuffA[0];

As uint16_t variables have 16 bits, the total all will exceed the maximum (65535) that all can hold.  Consider using uint32_t type for that variable. For example:
uint32_t all = sizeof BuffA/sizeof BuffA[0] + sizeof BuffB/sizeof BuffB[0] + sizeof BuffC/sizeof BuffC[0];

Because the type of sizeof is size_t, a “type able to represent the size of any object in bytes”, one need not cast any of addends to uint32_t for the result to not overflow.

A variable of uint16_t has 16 bits, thus two bytes, so for e.g. BuffA[46000] this means 46000 * 2 = 92000 bytes.
The variable all is also 16 bits and can contain only as max value 65,535.
92000 + 40000 + 40000 = 172000 bytes but that does not fit in 16 bits.
Therefore the value is clipped ... make it a uint32_t variable.
The total is 172.000 bytes, this mean it will not fit in 96KB. What are the value ranges you want to store? If the values are max 255
You can use extra RAM. DRAM is very hard to use, EEPROM is only usable when you don't have to write it too often. Otherwise use SRAM, e.g. the 23LC1024's which can store 128 KB RAM and are only DIP8.

Thanks! About the external SRAM.. I am doing real time audio applications. Will the external RAM introduce delays to the output audio?

I did some timing tests on the 23LC1024 ... a page read/write of 32 byte costs about 100 us. Reading other amount cost relatively more, like 1 byte read or write: 23 us, 8 bytes 30 us, 1024 bytes 4000 us.
I also tested another SRAM, but that was much slower and more DIP pins, but cheaper.

32 byte is pretty small, so maybe the time for read/write is high! To put this into perspective, do you know how much time it would take for 32 byte r/w on the arduino due? Is there some benchmarking info on this?

True, but for 1024 bytes its relatively larger (note that 1024 bytes / 32 * 100 ns = 3200 us. Of course you can read multiple times 32 bytes.
I also am interested about a bench mark for the Arduino (Uno/Mega). But I don't know if it can be found.

I will ask for further info on this and i will answer here if i know something. Thanks for everything!

I'm also curious!

Let us continue this discussion in chat.


text:
Is it ok to declare variables inside timer interrupts?
I am building a real time audio application using the Arduino DUE. This application needs big arrays like:
uint16_t sDelayBuffer0[46000];

The Due has only 96kb of RAM available so this array just ate up most ot its memory.
The problem is i need more arrays like this...
So, i was thinking, instead of declaring all of the arrays as global variables, to declare them inside the timer interrupt functions.
The loop() handles stuff like reading the ADCs. The actual effects are coded inside timer iterrupt funciton that are replayed over and over. So the code constantly loops in loop() and the selected timer interrupt function.
But other timer interrupt fucntions use other arrays. So i was thinking to declare every array that a corresponding timer interrupt function wants inside that fucntion.
So all arrays are not declared at the same time (since when we exit the timer interrupt function we were on and head either to loop or another interrupt function, the grabage collector will destroy the array right?)
The problem with this theory, is that this is a real time audio application. So is it wise to constantly declare a big array like this? Since the timer interrupt ficntion will run very very often. Won't i have delay problems iwth the actual sound? Or variable declarations happen extremely fast inside the CPU, even for big arrays?

Have you considered a simple compression algorithm to allow more samples? 8-bit DPCM (-127..127 and escape for full value) for instance.

What are you planning on doing in the timer interrupt that requires an array of 46000 integers?!?! It certainly can't be anything fast (and thus not suitable for running in an interrupt) if you need to process that much data every time...

The loop() reads the ADCs that contain the information from the guitar. The place to store it is the big array. The effect is applied and then it is sent to the DACs. This is all working by now. But i want more space. So i was considering instead of declaring the arrays as global variavbles - which is not possible. To declare them inside the corresponding timer interrupt function. But i dont know if declaring something this big, something that will be declared over and over again is viable in a real time audio application

@MikaelPatel Haven't thought about compression. But still, since it's a real time audio application, maybe i think its too much to compress/.decompress in real time, all the time

It sounds like you think you can access a variable declared in one function from another function. You can't.

I know! I wasn't suggsting that at all! Each function declares their own stuff. That is destroyed when another function comes into play!

Then I am at a loss as to what it is you are doing. It sounds like you are trying to make some kind of guitar FX pedal: read in through ADC, then send out (modified) through DAC. Perhaps if you actually detailed what you are really trying to achieve we can point you in the correct direction. As it is you have your brain fixated on wanting massive arrays. Chances are you don't want massive arrays at all, but you can't see past that, so you keep getting stuck.,

It does sound very much like a classic X-Y Problem.

The problem is i need more arrays like this...

you probably want to take a look at your processing flow to see if you need all of them at the same time. if you do, well, there is no alternative but to get a bigger chip.

No i do not need them at the same time! This is why i am thinking to declare them inside the functions. So as we move to another, the garbage collector destroys the previous array and space is freed up for the next array to be declared.

If you declare them as local variables, it should be ok, just make sure you have enough space in all cases.

If you don't need them all at the same time then declare a single array as a global and use the same array everywhere. No reason why you can't re-use the same variable for a different use in a different function as long as you can be sure you won't try to use it both ways once. And as others have said, nothing involving creating and pressing 46,000 values should ever be done in an interrupt.

First, I don't think it's a good idea to use 46000 * 2 = 92000 bytes of SRAM. That leaves only around 4K left. I hope you don't use a big stack trace, local variables or other global variables.
I don't know if creating an array costs a lot of space, anyway, constantly creating and removing arrays (in heap space) will make your free memory space a mess. This means, that after some time you cannot allocate arrays anymore, especially big ones which need consecutive memory.
Also, within interrupts the code should be as least as possible.
I suggest you use some arrays and reuse them for different reasons. Keep the name simple (like buffer), and reuse the array when needed, without the need to declare it and destroy it. This keeps your memory clear. Make sure the size is big enough for the maximum/worst case you use it for.
Update:
The above mostly assumes that the arrays are made in heap space, not as local variables. However, using local variables is ok.
But anyway, if you need a 2-byte 46000 array, don't expect to be able to use more arrays. In that case use external SRAM (like 23K256, 23LC1024).

I have already ordered a 23LC1024. But wiating for it to arrive, i am thinking some hacks. Because maybe the time to read/write to an SPI external memory is too big for real time audio applications. Other than that, the code is really small in the timer interrupt functions.

I suggest you do some timing tests (how long it takes to declare/destroy an array). Garbage collection inside interrupts I wouldn't advise. Better to declare them as local variables on the stack (and make sure you have enough memory left). You also can test for current free memory.

Declare them as local variables on the stack? This is the first time i read of theis concept. Can you post a link or something?

@LookAlterno You are right ... just changing the pointer, which is negligible.

Local variables are automatically stored on the stack, you don't have to do anything for this.


text:
Understanding arduino shield schematics
I am researching the schematic of the arduino GSM shield.
Link is this:
https://www.sparkfun.com/datasheets/DevTools/Arduino/cellular%20shield-v12.pdf
What i do not understand is the upper right part, wich says ARDUINO_SHIELDNOHOLES.
What i want to do is understand which pins are used for Rx and which for Tx.
But there are four usable pins on the arduino side and six(?) pins on the other side which says jumper, where are six pins on seeminly two jumpers...
Can anyone understand what is going on here?

"ARDUINO_SHIELDNOHOLES" is a connector in the SparkFun EAGLE libraries which is basically, well, an Arduino shield. It provides the schematic symbol as well as the PCB landing pattern for such.
The pins on the top right of the schematic are two sets of 3, which should have jumpers connecting either 1 and 2, or 2 and 3. To use hardware serial to connect the Arduino to the SM5100B you connect 2 and 3 of the "top" one and 1 and 2 of the bottom one. This connects D0 (RX) and D1 (TX) of the Arduino to TXD0 and RXD0 of the SM5100B. If you want to use software serial instead, connect the other pairs. D2 will then be connected to TXD0 (and will become the software RX), and D3 will be connected to RXD0 (and will become the software TX).
As for "TXD0" and "RXD0" themselves, those are net names, and all wires with the same net name, such as those and the ones connected to pins 19 and 20 of the SM5100B, are considered to be the same wire even if they aren't connected in the schematic.

A lot of good shields will give you the option to use hardware or software serial, and that is what's happening here.
While you think you see four pins on the arduino side and six on the jumper side, what you're actually seeing is (yes) the four pins on the arduino, but those four pins go to four pins on the jumpers.
The other two pins on the jumpers (the ones in the middle) go to the TX and RX of the shield. The shield itself only has one TX (TXD0 pin 2 on JP4) and one RX (RXD0 pin 2 on JP6). So the jumpers form the connection between your arduino and the shield. This is why they are the middle pins, because you put the jumper on the first two, or the last two, depending on what it is you want to achieve.
You will note the net names of pin 2 of JP4 and JP6 relate directly to (and are connected to) pin 19 and 20 respectively of the chip on the shield.
The whole benefit of the jumpers is you connect JP4 and JP6 pins 1 and 2 to which closes the circuit and uses the inbuilt hardware serial (pin 1 of the jumper being arduino hardware and pin 2 being the TXD0 source from the shield). Connecting pins 2 and 3 means you close the circuit between the shields TX and RX to the arduino GPIO pins D2 and D3 which you can assign when initialising your software serial.


text:
SoftwareSerial together with AltSoftSerial and HardwareSerial
The title says it all.
Angone with experience here on this subject?
I want to use all Hardware serial, SoftwareSerial and AltSoftSerial on Arduino Duemilanove with At328.
Is it possible?

in short - Yes. The following compiles and should work
Note the following links detail some subtle issues about HOW to use these various libraries. Some are more optimal depending upon your usage.
http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html#speed
http://forum.arduino.cc/index.php?topic=152122.0;wap2
You might also want to consider just using either Alt or Soft.
Note that NewSoftwareSerial is incorporated in the IDE 1.5.5+
/*
  Software serial multple serial test

 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.

 The circuit:
 * RX is digital pin 10 (connect to TX of other device)
 * TX is digital pin 11 (connect to RX of other device)

 Note:
 Not all pins on the Mega and Mega 2560 support change interrupts,
 so only the following can be used for RX:
 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69

 Not all pins on the Leonardo support change interrupts,
 so only the following can be used for RX:
 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

 created back in the mists of time
 modified 25 May 2012
 by Tom Igoe
 based on Mikal Hart's example

 This example code is in the public domain.

 */
#include <SoftwareSerial.h>
#include <AltSoftSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

AltSoftSerial altSerial;
// AltSoftSerial always uses these pins:
// Board          Transmit  Receive   PWM Unusable
// -----          --------  -------   ------------
// Arduino Uno        9         8         10

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);
  mySerial.println("Hello, world?");
  altSerial.begin(9600);
  altSerial.println("Hello World");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());

  char c;

  if (Serial.available()) {
    c = Serial.read();
    altSerial.print(c);
  }
  if (altSerial.available()) {
    c = altSerial.read();
    Serial.print(c);
  }
}

You should be aware that SoftwareSerial is blocking other interrupts when sending/receiving. I'm not sure exactly how AltSoftSerial behaves, but I believe it was written to deal with that issue. The issue arises if you use a slow baud rate on the SoftwareSerial in combination with a high baud rate on hardware serial. Then you can loose incoming data on the hardware serial. AltSoftSerial will probably be completely blocked during SoftwareSerial activity - hardwareserial can still send / receive one-two bytes in the hardware tx/rx registers. According to https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html you can use AltSoftSerial together with SoftwareSerial, as long as the baud rate for SoftwareSerial is at least 10 times the baud rate of that used for AltSoftSerial.
If you never transmit/receive simultaneously on different interface, you don't really have to worry about any of the above mentioned issues.
When I write SoftwareSerial, I refer to NewSoftSerial, which has been called SoftwareSerial in Arduino for a while now (since 1.0 I believe).


text:
replacing #define with typedefs for bracket scope
I have a project in which basically i have to concatenate existing code.
Each code comes with its own #defines.
But defines are not touched by the compiler, but the preprocessor.
Each snippet of the program will exist in its own fucntion.
Is it possible to include the #defines of each program - now each function, inside this function (and visible only to this function's scope)?
The proper way to do it, would be to replace text reassignment from #define to typedef?
I understand typedef is originally for defining types. But can it be used here? Is there another alternative?

What are these macros used for? You can replace them with different things depending on what they are, but you may lose execution efficiency.

The macros are used for text replacement. For example #define value 255

Then you would use const variables.

#define value 255

Can be replaced with
const int value = 255;

It is possible to use "namespace { ... }" to create local defines for a *.cpp file.
In the Arduino IDE all *.ino files are combined in a single *.cpp file, therefor the "namespace" is not very useful.
When you create new tabs in the Arduino IDE and name them *.cpp, then you have different *.cpp files. Then you can use the "namespace" to create defines that are only valid for that *.cpp file.
More info: Hackaday: Using Modern C++ Techniques with Arduino


text:
Creating a product with arduino bootloader
If you have a prototype with arduino and you wish to create a real product can you do it or the fact that it contains the arduino bootloader prevents you?
BTW, i dont have a product ready. I am thinking options though. Or maybe i will have to go find a job

Getting a programmer means never having to worry about the bootloader. Unless you want it field-upgradeable, in which case you probably want one of the encrypted bootloaders Atmel provides anyways.

A quick google search found this info on the Arduino Forum which a user kindly shows the rules relating to this stuff.
The Optiboot bootloader is not actually an Arduino 'product'. Boards you design and software you write using Arduino IDE and libraries does not need to be disclosed to anybody, other than having the objects available (probably in a hidden part of your product's support website, in a "firmware" sub section) for some reason relating to being able to build the source against newer versions of Arduino.
I am currently making a product which I intend to use Arduino libraries and IDE and bootloader for fast development, but the board, schematics, and essentially the application code except for the libraries from Arduino will be mine. If you copy or build stuff specifically for/from Arduino hardware, you must(?) release certain source/schematics etc.


text:
Is it possible to sample sound with arduino?
I have the arduino duemilanove with atMega328.
The frequency is 16Mhz.
I want to sample and record from the audio jack.
I searched and i found if i want to record "everything - so to speak", i have to sample at 44100Hz.
That means this is unfeasible with my arduino, since my frequency is only 16MHz?

16 MHz is 16000000 Hz. The "M" is relevant.

For the AtMega328's ADC the datasheet says

• Up to 76.9kSPS (Up to 15kSPS at Maximum Resolution)

So, sampling two channels at 10bit resolution and 44.1kHz is not possible.
If 8bit resolution is enough, and if there's only one channel to sample, it should be able to do the job.
Edit:
To answer Connor's comment:
Of course, this does only apply when using the internal ADC. Connecting an external ADC (via SPI or whatever) makes it possible to sample data at the desired speed.
But anyway, the next question is: Is 16MHz fast enough to process the sampled data (which are received every (22.6/channels) microseconds? ;-)

This assumes you're using the ATmega's internal ADC.

Unless one is going after very strong high frequency sounds, it's probably not wise to maximize sample rate at the expense of resolution.