body:
I have an SPI 128x64 OLED display. Is it safe to power this display's VCC from a digital I/O pin? I would like to do this so I can connect it flush to my arduino's header, and so I can control the power going to the display for a "low power" sleep mode.

Thanks for any responses.

title: Powering via an I/O Line

Answers: 2

body: Unlikely. An IO pin can only provide 25mA sustained, and 40mA peak. A display is likely to require more than that. However check the datasheet for the display. If by chance it should not need more than 25mA maximum (all pixels white) then yes it may be possible.

body:
Adafruit model. monochrome 1.3" 128x64 OLED display (similar to yours, I assume):

> Display current draw is completely dependent on your usage: each OLED
> LED draws current when on so the more pixels you have lit, the more
> current is used. They tend to draw ~25mA or so in practice but for
> precise numbers you must measure the current in your usage circuit

To be safe, you can use one pin to control a power switch for the display.


body:
I'm new to the operation and applications of the arduino and have a question. I would like to run 6 x 4 bit seven segment displays from an arduino controller. How do I connect an external supply to the displays to ensure I don't overload the arduino please?

Regards

title: Using a separate power supply?

Answers: 1

body:
Here's a [tutorial from Sparkfun][1] that shows how to drive an LED using a transistor to switch the LED. Where the transistor is connected to +5v, that should be to your _external_ 5v supply. The pin labeled "Control" is connected to one of your Arduino pins. Connect the external supply's ground to the Arduino's ground.

Done this way, the Arduino's pin driver only needs to supply enough current to switch the transistor; the current to power the LED is provided by your external power supply.

  [1]: https://learn.sparkfun.com/tutorials/transistors/applications-i-switches


body:
I use the Wire Library and need to have multi-master setting. I see multi-master examples, where the masters have their own ID's -- which make sense.

Now I have just connected three devices on the bus with the same ID (for example `0x05`) and they can communicate! Every node can listen to all traffic, which is not common but this was exactly what I want.

The question is: Will I have trouble in the future? Is my setup something like "multi-slave"?

title: Multimaster I2C with same address

Answers: 1

body:
    const byte MY_ADDRESS = x;  // where x is whatever unique address you like

    byte RxByte[32]  //32 byte buffer

    void setup() {
      //insert unique ddress
      Wire.begin(MY_ADDRESS);

    // this line allows the arduino to listen for i2c broadcast at address 0

    TWAR = (MY_ADDRESS << 1) | 1;
    //set up a receive handler
     Wire.onReceive(receive_data);

    then call
    Wire.beginTransmission (0)  //transmit broadcast so all devices will receive

    Wire.write( address of destination) // make the first byte the destination

    Wire.endTransmission ();

    then you need a receive handler

    void receive_data() {
    //use a buffer to temporarily store the data

    for ( int d = 0; Wire.available() > 0 ;d++){

    RxByte[d] = Wire.read();} // READ WIRE BUFFER UPTO 32BYTES, INTO AN ARRAY
    datareceived = 1;

    //then test if it was for this device
    if (RxByte[0] == MYADDRESS){ do somthing with RxBytes[1-31];}
    else {}

I use this extensively its very handy and works well I have a complex transmission table which has a 4 byte header and the rest of the bytes can be used as data send

destination, myaddress, a command, and how many data bytes to follow
***************************************************************************
Addendum to Original answer. below is a complete working example.

//so the basics of the tranmission table are the first 4 bytes (ie Rx or Tx byte 0-3 depending on if we are talking about the sender or recipient)
    //are used as a header 0= recipient (0 for broadcast. or address) 1= senders address 2= is the command (ie tells the recipient what to do)
    //and 4= the number of data bytes which follow in the packet
    //not all of these need to be specified at any time but its usefull to have a structure to follow at each end which never changes
    //copy and past this upload to 2 arduinos connected by i2c change the 2 addresses and it should work.
its a n example of how data can be moved around in a multi master situation
that should hopefully give you some ideas. it looks complicated but half of it is just generating some example data and triggering method and the transmit part is repeated 3 times to send out different data.. you should be able to create a more general purpose transmit block for your application

to send data just attach a button or wire to pin 2 directly to ground

watch the 2 serial windows

    #include <Wire.h>
    //device address  MAKE DIFFERENT FOR EACH

    const byte MY_ADDRESS = 20;
    const byte PARTNER_DEVICE = 25;

    // transmission table stuff
    byte RxByte[32]; //setup a receive buffer to hold data
    byte TxByte[32]; //setup a transmit buffer to hold data
    byte datareceived;

    // stuff to generate some data
    const int Sensor1 = A0;
    byte SensorVal1 = 0;

    //stuff to debounce pin 2
    const byte digitalpin = 2;
    byte pinstate = 0;
    byte lastpinstate = 0;
    unsigned long checktime = 0;
    const byte debouncetime = 50;

    // timer
    unsigned long timing_loop = 5000;

    void setup() {
      Wire.begin (MY_ADDRESS);
      TWAR = (MY_ADDRESS << 1) | 1;                                                      // ENABLE BROADCASTS TO BE RECEIVED
      Wire.onReceive(ReceiveData);     // INTERUPT ON I2C DATA RECEIVE
      Serial.begin(9600);
      pinMode (  digitalpin  , INPUT_PULLUP );// set the pin to input pullup so we can trigger the code by connecting directly to ground
      Serial.println( "READY" );
    }

    void loop() {
      // generate some random data

      GenRandData();
      //Serial.print(  pinstate);Serial.print( " " );Serial.println( lastpinstate );
      // debounces pin 2 so we can trigger a data broadcast
      pinstate = digitalRead (digitalpin);
      if ( pinstate != lastpinstate && millis() >= checktime) {
        if ( pinstate == 0 && lastpinstate == 1 ) {
          checktime = millis() + debouncetime;
          Serial.println( " button working" );
          REQUEST();
        }
        lastpinstate = pinstate ;
      }

      // this triggers the process data method after receive of data
      if (datareceived == 1  ) {
        datareceived = 0 ;
        ProcessData();
      }

      // 10 second timer triggers transmission of some data
      if ( millis() >= timing_loop ) {
        BROADCAST();
      }
    }
    void GenRandData() {
      // this just reads analog0 and maps it to a byte then sequentially shifts the transmit buffer
      SensorVal1 = random(255);
      TxByte[7] = TxByte[6];
      TxByte[6] = TxByte[5];
      TxByte[5] = TxByte[4];
      TxByte[4] = SensorVal1;
    }

    void ReceiveData() {
      // READ AVAILABLE BYTES INTO 32BYTE BUFFER (while data is available)
      for ( byte d = 0; Wire.available() > 0 ; d++) {
        RxByte[d] = Wire.read();
      }
      //set a trigger event
      datareceived = 1;
      Serial.println( "receive" );
    }

    void ProcessData() {
      Serial.println( "process" );
      // check what the data is an who its for then do something with it (RECEIVE TABLE)
      if (RxByte[0] == MY_ADDRESS) { // for this device
        switch (RxByte[2]) {
          case 1:       Serial.print("RECEIVED DATA FOR THIS DEVICE, = "); Serial.println( RxByte[4] ); break;
          case 255:       Serial.println("RECEIVED A REQUEST FOR DATA, SENDING READ FROM  > Sensor1"  ); ActAsMaster();              break;
          default:      Serial.print("D-Type byte = error"); Serial.println(RxByte[2]);                   break;
        }
      }

      else if (RxByte[0] == 0) {       //handle broardcast
        Serial.print( "RECEIVED BROADCAST FROM DEVICE = " ); Serial.println( RxByte[1] );
        Serial.print( "DATASIZE = " ); Serial.print( RxByte[3] ); Serial.println( " Bytes" );
        Serial.print( "DATABYTE 1 = " ); Serial.println( RxByte[4] );
        Serial.print( "DATABYTE 2 = " ); Serial.println( RxByte[5] );
        Serial.print( "DATABYTE 3 = " ); Serial.println( RxByte[6] );
        Serial.print( "DATABYTE 4 = " ); Serial.println( RxByte[7] );
        Serial.println( "DONE" );
      }
      Serial.println(  );
    }

    void BROADCAST() {
      // this is transmission table to send data to everyone
      Serial.println("Sending broadcast");
      byte count = 0;
      byte errorcode;
    Tx:
      Wire.beginTransmission (0);                       // broadcast
      Wire.write(0);                                    // ADDRESS =0 BROARDCAST
      Wire.write(MY_ADDRESS);                           // SEND my address
      Wire.write(0);                                    // DATA TYPE CODE
      Wire.write(4);                                    //number of bytes being sent
      Wire.write(TxByte[4]);                            //data
      Wire.write(TxByte[5]);                            //data
      Wire.write(TxByte[6]);                            //data
      Wire.write(TxByte[7]);                            //data
      errorcode = Wire.endTransmission ();
      if (errorcode != 0 && count <= 2) {
        count++;
        Serial.println( "fail" );
        goto Tx;
      }
      //reset timer to run this again
      timing_loop = millis() + 10000 ;
      Serial.println(  );
    }

    void ActAsMaster() {
      //this is transmission table to send data to specific device OR return a result of a task
      Serial.println("Sending data");
      byte count = 0;
      byte errorcode;
    Tx:
      Wire.beginTransmission (RxByte[1]);               //the return address
      Wire.write(RxByte[1]);                            //recipient address (return)
      Wire.write(MY_ADDRESS);                           // SEND MASTER ADDRESS
      Wire.write(1);                                  // DATA TYPE CODE
      Wire.write(1);
      Wire.write(SensorVal1);
      errorcode = Wire.endTransmission ();
      if (errorcode != 0 && count <= 2) {
        count++;  // if fail and not exceed count try again
        Serial.println( "fail" );
        goto Tx;
      }
      Serial.println(  );

    }
    void REQUEST() {
      //this is transmission table to send data request of partner device
      Serial.println("Sending request");
      byte count = 0;
      byte errorcode;
    Tx:
      Wire.beginTransmission (PARTNER_DEVICE);               //the return address
      Wire.write(PARTNER_DEVICE);                            //recipient address (return)
      Wire.write(MY_ADDRESS);                           // SEND MASTER ADDRESS
      Wire.write(255);                                  // DATA TYPE CODE (MASTER ADDRESS)
      Wire.write(0);
      errorcode = Wire.endTransmission ();
      if (errorcode != 0 && count <= 2) {
        count++;  // if fail and not exceed count try again
        Serial.println( "fail" );
        goto Tx;
      }
      Serial.println(  );
    }


body:
I chose the correct COM port but it won't upload.

Arduino: 1.8.3 (Windows 10), Board: "Arduino Leonardo"

    Sketch uses 5252 bytes (18%) of program storage space. Maximum is 28672 bytes.
    Global variables use 228 bytes (8%) of dynamic memory, leaving 2332 bytes for local variables. Maximum is 2560 bytes.
    processing.app.debug.RunnerException
     at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:160)
     at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
     at processing.app.SketchController.upload(SketchController.java:713)
     at processing.app.SketchController.exportApplet(SketchController.java:686)
     at processing.app.Editor$DefaultExportHandler.run(Editor.java:2149)
     at java.lang.Thread.run(Thread.java:745)
    Caused by: processing.app.SerialException: Error touching serial port 'COM4'.
     at processing.app.Serial.touchForCDCReset(Serial.java:99)
     at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:144)
     ... 5 more
    Caused by: jssc.SerialPortException: Port name - COM4; Method name - openPort(); Exception type - Port busy.
     at jssc.SerialPort.openPort(SerialPort.java:164)
     at processing.app.Serial.touchForCDCReset(Serial.java:93)
     ... 6 more
    An error occurred while uploading the sketch
    Exception in thread "Thread-124" java.util.ConcurrentModificationException
     at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
     at java.util.ArrayList$Itr.next(ArrayList.java:851)
     at cc.arduino.contributions.libraries.LibrariesIndexer.rescanLibraries(LibrariesIndexer.java:123)
     at cc.arduino.contributions.libraries.LibrariesIndexer.setLibrariesFolders(LibrariesIndexer.java:106)
     at processing.app.BaseNoGui.onBoardOrPortChange(BaseNoGui.java:682)
     at processing.app.Base.onBoardOrPortChange(Base.java:1297)
     at processing.app.Editor$DefaultExportHandler.run(Editor.java:2179)
     at java.lang.Thread.run(Thread.java:745)

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

title: Problem with uploading my sketch to my Arduino

Answers: 2

body:
I don't see any trivial solution from the error log, but you can try one or more of the following items:

- Unplug and replug the USB cable (to check if the connection is ok)
- Change your USB cable in another USB port from your computer
- Restart computer
- Change USB cable
- Try another Arduino (if you have two megas, or change to Uno if possible), just to check for uploading
- Reinstall Arduino

body:
This is the relevant bit in your error output:

    Caused by: jssc.SerialPortException: Port name - COM4; Method name - openPort(); Exception type - Port busy.

Is your Leonardo on COM4, or some other port? Does some other program have that port open?


body:
I try to build an automatic roof with rain sensor input, when it's rain the roof then closed pulled by DC motor on the tracks and activate a buzzer. When it reach the end (limit switch pressed) then the motor stopped and buzzer off. And when the rain stopped, motor will turning again to open the roof until the second limit switch pressed to stop the DC motor.

I have try to make my own program but it have an error, when it's has no rain detected the motor spin to close the roof and stop when limit switch pressed (LOW logic), but when rain detected the buzzer turned on but the motor doesn't spin at all. Here is my code, I'm using L293D for motor driver and using its enable pin.

    void setup() {
      digitalWrite(enable_motor, HIGH);
      digitalWrite(motor_open, LOW);
      digitalWrite(motor_close, LOW);
      digitalWrite(alarm, LOW);
    }

    void loop() {
      if (analogRead(rainSensor) < 650){
        digitalWrite(alarm, HIGH);
        digitalWrite(motor_close, HIGH);
        digitalWrite(motor_open, LOW);
      }
      else if (digitalRead(stop_close) == LOW){
        digitalWrite(alarm, LOW);
        digitalWrite(enable_motor, LOW);
      }
      else if (analogRead(rainSensor) > 850){
        digitalWrite(alarm, LOW);
        digitalWrite(motor_close, LOW);
        digitalWrite(motor_open, HIGH);
      }
      else if (digitalRead(stop_open) == LOW){
        digitalWrite(alarm, LOW);
        digitalWrite(enable_motor, LOW);
      }
      else {
        digitalWrite(enable_motor, HIGH);
        digitalWrite(alarm, LOW);
      }
    }

Can I use If-Else logic? Or I make a mistake?

title: Stopping motor DC with 2 limit switches

Answers: 1

body:
Your logic is a bit off. For example, when it is raining and `rainSensor < 650`, only that part of the `if` gets executed and the `else if` parts never happen.

You could just wait for the roof to open/close in a loop. Also, you will find it helpful to break your code into smaller functions. (I'm not sure what the `enable_motor` pin is for, so that part may need fixing).

    // This function determines the current status of the roof
    enum {OPEN, CLOSED, OPENING, CLOSING, UNKNOWN};
    byte get_roof_status()
    {
        if (digitalRead(stop_close) == LOW) return CLOSED;
        else if (digitalRead(stop_open) == LOW) return OPEN; // Fixed typo
        else if (digitalRead(motor_open) == HIGH) return OPENING;
        else if (digitalRead(motor_close) == HIGH) return CLOSING;
        return UNKNOWN;
    }

    // Helper functions
    void open_roof() {
        digitalWrite(alarm, HIGH);
        digitalWrite(enable_motor, HIGH);
        digitalWrite(motor_close, LOW);
        digitalWrite(motor_open, HIGH);
        // Loop until roof is open
        while (OPEN != get_roof_status()) /* NULL */;
        stop();
    }
    void close_roof() {
        digitalWrite(alarm, HIGH);
        digitalWrite(enable_motor, HIGH);
        digitalWrite(motor_open, LOW);
        digitalWrite(motor_close, HIGH);
        // Loop until roof is closed
        while (CLOSED != get_roof_status()) /* NULL */;
        stop();
    }
    void stop() {
        digitalWrite(alarm, LOW);
        digitalWrite(enable_motor, LOW);
        digitalWrite(motor_open, LOW);
        digitalWrite(motor_close, LOW);
    }

    void setup() {
      // Set the pinmodes
      pinMode(enable_motor, OUTPUT);
      pinMode(motor_open, OUTPUT);
      pinMode(motor_close, OUTPUT);
      pinMode(stop_close, INPUT_PULLUP);
      pinMode(stop_open, INPUT_PULLUP);
      pinMode(alarm, OUTPUT);

      digitalWrite(enable_motor, HIGH);
      digitalWrite(motor_open, LOW);
      digitalWrite(motor_close, LOW);
      digitalWrite(alarm, LOW);
    }

    void loop() {
      // This function is much simpler now
      if (analogRead(rainSensor) < 650) {
        close_roof();
      }
      else if (analogRead(rainSensor) > 850){
        open_roof();
      }
    }


body:
I m trying to give ext ref. To Arduino using lm317 1.25 ref.
I  tried to do it. Iswt this voltage in programme too
But when I run it it was just displaying 1.25
And der was no variation as I varie the resistance of potentiometer which is connected to A0
So plz help me.....
My Arduino chip is Atmega 8A

title: can we use Lm317 1.25 ref for ext. reference of arduino

Answers: 1

body:
yes but you have to use the analogReference(EXTERNAL); command otherwise it will short the default VCCref volatage with the external (i assume this will cause damage.. dunno never done that. yet...)
also if you use a 1.25v reference just remember that that will be the maximum voltage you can measure up to.
theres a couple of things you can do

1 use a voltage devider circuit to drop the max voltage out of your sensor(potentiometer) down to about 1.25v

2 put a series resistor betweent vcc and the positive terminal of your potentiometer (creating a voltage devider between the resistor and the full resistance of the potentiometer)

3 and probably the easiest connect the positive of the potentiometer to the lm317 /reference pin so that its output will be between Aref and GND this is the best option as it will be the most stable as its output will be in propotion to any fluctuation of the lm317

as in 3. the same can be done if using the internal Vref conect the pot to Aref (but remember that it has a limited current output so be carefull not to draw too much by using low resistance pots or many in parallel)


body:
I have written simple code to enable toggling of `serial.print` debug data.

      #define DEBUG
      #ifdef  DEBUG
        #define DEBUG3(x,y,z) Serial.print(x);Serial.print(" ");Serial.print(y);
         Serial.print(" "); Serial.println (z)
        #define DEBUG2(y,z) Serial.print(y);Serial.print(" ");Serial.println
         (z)
        #define DEBUG(z) Serial.println(z)
        #define DEBUGln  Serial.println("");
      #else
        #define DEBUG3(x,y,z)
        #define DEBUG2(x,y)
        #define DEBUG(x)
        #define DEBUGln
      #endif

Then I can just call `DEBUG3("words",value,"words");` anywhere in the sketch and it will automatically print out the text, int, strings, etc with a single space between and automatically go to next line etc etc.

Just define the correct number of fields to print and separate using commas.

If I want to turn off debug then I just comment out `#define DEBUG` at the top.

Now the issue is I don't want to copy in this code every time I want to use it, so it makes sense to make it a library so that I can just call something like:

    #include <SERIAL_DEBUG.h>
    #define DEBUG     (or //#define DEBUG) //to enable or disable

The reason being that sometimes I might want to print up to 10 things on a single line (not very often but it could happen).

This is my first library attempt and I'm having a hard time finding any information on how I would go about setting up the .h and .cpp files for this type of `#define DEBUG(x) Serial.println(x)` and the `#define DEBUG (from sketch)` parts.

title: How to use #define in a library I'm trying to write?

Answers: 2

body:
Not a direct answer to your question, but I would suggest a different
approach based on streaming output, as described in the Arduino
Playground: [Adding Streaming (insertion-style) Output][playground]. In
a nutshell, you define the `<<` operator for `Serial` (and any other
object that inherits from `Print`) in a way that allows you to write
things like:

    Serial << "My name is " << name << " and I am " << age << " years old.";

Now you can define a `Debug` object which would be, depending on whether
you want debugging output or not:

* an alias to Serial
* a dummy object that just discards its input.

Example:

    #define DEBUG_ON

    // From https://playground.arduino.cc/Main/StreamingOutput
    template<class T> inline Print& operator<<(Print &obj, T arg)
    { obj.print(arg); return obj; }

    #ifdef DEBUG_ON
    # define Debug Serial
    #else
    class DummyStream {
    public:
        template<class T> DummyStream& operator<<(T arg)
        { (void) arg; return *this; }
    } Debug;
    #endif

    void setup()
    {
        const unsigned long BAUDRATE = 9600;
        Serial.begin(BAUDRATE);
        Debug << "Serial port open at " << BAUDRATE << " bps\r\n";
    }

[playground]: https://playground.arduino.cc/Main/StreamingOutput

body:
Anything in a header file that is included with `#include` is literally pasted into the file at the point of the `#include`.

So anything in your sketch you want to place into a header file you can just place it in a header file and include that file *at the same location where the original code was*.

So you can have a header file `debug.h`:

      #ifdef  DEBUG
        #define DEBUG3(x,y,z) Serial.print(x);Serial.print(" ");Serial.print(y);
         Serial.print(" "); Serial.println (z)
        #define DEBUG2(y,z) Serial.print(y);Serial.print(" ");Serial.println
         (z)
        #define DEBUG(z) Serial.println(z)
        #define DEBUGln  Serial.println("");
      #else
        #define DEBUG3(x,y,z)
        #define DEBUG2(x,y)
        #define DEBUG(x)
        #define DEBUGln
      #endif

And include that in your sketch at the right location:

    #define DEBUG
    #include "debug.h"

Note that the `#define DEBUG` *must* come before the `#include`. Remember: the `#include` is replaced by the content of the included file, so after preprocessing you end up with exactly what you had before in your sketch:

      #define DEBUG
      #ifdef  DEBUG
        #define DEBUG3(x,y,z) Serial.print(x);Serial.print(" ");Serial.print(y);
         Serial.print(" "); Serial.println (z)
        #define DEBUG2(y,z) Serial.print(y);Serial.print(" ");Serial.println
         (z)
        #define DEBUG(z) Serial.println(z)
        #define DEBUGln  Serial.println("");
      #else
        #define DEBUG3(x,y,z)
        #define DEBUG2(x,y)
        #define DEBUG(x)
        #define DEBUGln
      #endif

The file can be in the same location as the sketch (in which case you should use `#include "debug.h"` or in a library folder (`Arduino/libraries/debug/debug.h`) in which case you should include it with `#include <debug.h>`. In the Arduino IDE it actually makes little or no difference which type of `#include` you use, but it does serve as a visual reminder that this is either a header included with the sketch (`""`) or an external library or system header (`<>`).


body:
This is a simple usart program in avr c which just transmits a character.

    #include <avr/io.h>
    #include <util/delay.h>
    #define F_CPU 16000000UL
    #define BAUD 9600
    #define BAUD_PRESCALLER ((F_CPU / (BAUD * 16UL)) - 1)
    void send_val(unsigned char);
    int main() {

    UBRR0H = (uint8_t)(BAUD_PRESCALLER>>8);
    UBRR0L = (uint8_t)(BAUD_PRESCALLER);
    UCSR0B = (1<<TXEN0);
    unsigned char x = 'B';
    while(1) {

     send_val(x);
     _delay_ms(1000);
    }

    return 0;
    }

    void send_val(unsigned char v) {
 while(!(UCSR0A & (1<<UDRE0)));
 UDR0 = v;

    }
when I upload this code via the Arduino IDE, everything is fine and the code works as expected.The LED labeled "L" on the PCB is still.

but, when I upload the code using the following Makefile, the code uploads successfully but the outcome is unexpected. I see a weird character(see EDIT) and the LED "L" blinks a couple of times in that 1 sec delay.

    CC=avr-gcc
    OBJCOPY=avr-objcopy

    CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
    PORT=/dev/ttyACM0

    led.hex: led.elf
     ${OBJCOPY} -O ihex -R .eeprom led.elf led.hex

    led.elf: led.o
     ${CC} -o led.elf led.o

    install: led.hex
     avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:led.hex

I referred the Schematics and the led is connected to SCK but I don't understand why the makefile is causing it to trigger.
that blinking of LED is what I think is causing the issue. Does the IDE have some other specific flags while uploading the code or am I committing some silly mistake?

EDIT: I wrote a small program to see the values in the device node /dev/ttyACM0. the ASCII value of the weired character(looks like a question mark) is actually 255.

another issue I noticed is that when I touch the solder beneath the pin 13 (only pin 13) the led L goes off!

As led L is connected to pin 13 I thought this is some hardware issue with my board but then I uploaded the blink led example code, touched the solder and everything is fine.

what could be the actual issue? this is getting mysterious.

title: usart sketch uploaded using makefile gives unusual behaviour

Answers: 1

body:
The `-mmcu=atmega328p` compiler flag is needed not only for the compile
phase, but also for the link phase. Otherwise the linker will not know
which CRT (C run time) to link with your program, and it will link none.
The CRT is responsible for things like initializing the stack pointer,
clearing `r1` (as required by the AVR calling convention) and calling
your `main()`.

**Edit**: the following simplified Makefile should work if you have a
modern version of avrdude that understands ELF files:

<!-- language: lang-make -->

    CC     = avr-gcc
    MCU    = atmega328p
    CFLAGS = -Os -DF_CPU=16000000UL -mmcu=${MCU}
    PORT   = /dev/ttyACM0

    led.elf: led.c
        ${CC} ${CFLAGS} $< -o $@

    install: led.elf
        avrdude -c arduino -p ${MCU} -P ${PORT} -b 115200 -U $<

Otherwise you can keep your rules for led.elf → led.hex → install.


body:
So basically, I'm trying to make a digital wall clock and using digital numbers, I have 7 sections of LED's per number, 4 numbers and one section for the colon in between them. A total of 30 sections. The colon will toggle every second so the the most possible simultaneously glowing sections is 27. That's because of the time 08:08.
Is there any way to make this work with an arduino? Possibly by Charlieplexing the arduino into 30 sections, using 6 pins. Or is there something out there that has 30 pins!?

The problem of course with charlieplexing, is that you need it to become rapid pulses. I'm sure I'm going to need some help with this, and also with laying out a schematic.

To be clear, this is how the led sections are going to be laid out. I also know I'm going to need an npn transistor for every single one of them. the biggest section uses 20 LEDs.
[![enter image description here][1]][1]

Thanks!

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

title: Charlieplexing 30 LED sections with a max of 27 LEDs at the same time?

Answers: 1

body:
I would consider 74HC595N's. These are shift registers, which can control 8 'outputs' using less pins on your Arduino.

These are very cheap (buy them per 10) and you can daisy chain 4 of them, having 32 outputs, using only 5 pins of your Arduino. This would fit perfectly with your 30 sections.

Each of the 30 outputs can be used to control a transistors to control one LED sections.

See for an example for using shift registers with the Arduino: [ShiftOut][1]

  [1]: https://www.arduino.cc/en/Tutorial/ShiftOut

Also you might need this: ULN2803 darlington drivers for each output (4 total).


body:
I am trying to burn bootloaders to Atmega2560V and when I hit burn bootloaders it shows me this error

> avrdude: Device signature = 0x1e9803
avrdude: Expected signature for ATmega2560 is 1E 98 01

I know this device should have 0x1e9801, But I don't know why it's showing me this error.

I tried my luck by starting threads at [AVRFREAKS][1] but no joy.

One of my friend told to try changing the device signature in the avrdude from 0x1e9801 to 0x1e9803 for a temporary try.

How can I do that.? please please please anyone help.

Thanks

  [1]: http://www.avrfreaks.net/forum/factory-reset-mega2560-and-mega2560v#comment-2241211

title: changing device signature in avrdude

Answers: 1

body:
You should have, somewhere in your hard drive, a file named
avrdude.conf. My copy of the file has the following lines:

    #------------------------------------------------------------
    # ATmega2560
    #------------------------------------------------------------

    part
        id               = "m2560";
        desc             = "ATmega2560";
        signature        = 0x1e 0x98 0x01;
        ...

Try changing the line with `signature`. Alternatively, you could make a
new entry for your MCU like this:

    #------------------------------------------------------------
    # ATmega2560V
    #------------------------------------------------------------
    # Identical to  ATmega2560 but for the signature

    part parent "m2560"
        id        = "m2560v";
        desc      = "ATmega2560V";
        signature = 0x1e 0x98 0x03;


body:
The `AT+CENG=2,0` command is giving me this result:

>+CENG: 0,"0794,48,00,510,10,53,7944,10,00,36e3,255"

My LAC is `36e3` but what is the type? (Int, Double, byte, string)?

I get this code to translate cell ID and LAC into lat long:

    class GMM {
      public static byte[] PostData(int MCC, int MNC, int LAC, int CID) {
        /* The shortCID parameter follows heuristic experiences:
         * Sometimes UMTS CIDs are build up from the original GSM CID (lower 4 hex digits)
         * and the RNC-ID left shifted into the upper 4 digits.
        */
        byte[] pd = new byte[] {
          0x00, 0x0e,
          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
          0x00, 0x00,
          0x00, 0x00,
          0x00, 0x00,
          0x1b,
          0x00, 0x00, 0x00, 0x00, // Offset 0x11
          0x00, 0x00, 0x00, 0x00, // Offset 0x15
          0x00, 0x00, 0x00, 0x00, // Offset 0x19
          0x00, 0x00,
          0x00, 0x00, 0x00, 0x00, // Offset 0x1f
          0x00, 0x00, 0x00, 0x00, // Offset 0x23
          0x00, 0x00, 0x00, 0x00, // Offset 0x27
          0x00, 0x00, 0x00, 0x00, // Offset 0x2b
          0xff, 0xff, 0xff, 0xff,
          0x00, 0x00, 0x00, 0x00
        };
        Console.WriteLine(pd.Length);
        bool isUMTSCell = ((Int64)CID > 65535);
        if ((Int64)CID > 65536) /* GSM: 4 hex digits, UTMS: 6 hex digits */
          pd[0x1c] = 5;
        else
          pd[0x1c] = 3;
        pd[0x11] = (byte)((MNC >> 24) & 0xFF);
        pd[0x12] = (byte)((MNC >> 16) & 0xFF);
        pd[0x13] = (byte)((MNC >> 8) & 0xFF);
        pd[0x14] = (byte)((MNC >> 0) & 0xFF);
        pd[0x15] = (byte)((MCC >> 24) & 0xFF);
        pd[0x16] = (byte)((MCC >> 16) & 0xFF);
        pd[0x17] = (byte)((MCC >> 8) & 0xFF);
        pd[0x18] = (byte)((MCC >> 0) & 0xFF);
        pd[0x27] = (byte)((MNC >> 24) & 0xFF);
        pd[0x28] = (byte)((MNC >> 16) & 0xFF);
        pd[0x29] = (byte)((MNC >> 8) & 0xFF);
        pd[0x2a] = (byte)((MNC >> 0) & 0xFF);
        pd[0x2b] = (byte)((MCC >> 24) & 0xFF);
        pd[0x2c] = (byte)((MCC >> 16) & 0xFF);
        pd[0x2d] = (byte)((MCC >> 8) & 0xFF);
        pd[0x2e] = (byte)((MCC >> 0) & 0xFF);
        pd[0x1f] = (byte)((CID >> 24) & 0xFF);
        pd[0x20] = (byte)((CID >> 16) & 0xFF);
        pd[0x21] = (byte)((CID >> 8) & 0xFF);
        pd[0x22] = (byte)((CID >> 0) & 0xFF);
        pd[0x23] = (byte)((LAC >> 24) & 0xFF);
        pd[0x24] = (byte)((LAC >> 16) & 0xFF);
        pd[0x25] = (byte)((LAC >> 8) & 0xFF);
        pd[0x26] = (byte)((LAC >> 0) & 0xFF);
        return pd;
      }

      public static string[] GetLatLng() {
        string[] result = new string[2];
        try {
          String url = "http://www.google.com/glm/mmap";
          HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(url));
          req.Method = "POST";
          int MCC = Convert.ToInt32(510); //actual data
          int MNC = Convert.ToInt32(10); //actual data
          int LAC = Convert.ToInt32(36e3); //actual data - gives error here
          int CID = Convert.ToInt32(7945); //actual data
          byte[] pd = PostData(MCC, MNC, LAC, CID);
          req.ContentLength = pd.Length;
          req.ContentType = "application/binary";
          Stream outputStream = req.GetRequestStream();
          outputStream.Write(pd, 0, pd.Length);
          outputStream.Close();
          HttpWebResponse res = (HttpWebResponse)req.GetResponse();
          byte[] ps = new byte[res.ContentLength];
          int totalBytesRead = 0;
          while (totalBytesRead < ps.Length) {
            totalBytesRead += res.GetResponseStream().Read(
            ps, totalBytesRead, ps.Length - totalBytesRead);
          }
          string r = System.Text.Encoding.UTF8.GetString(ps);
          Console.WriteLine(r);
          if (res.StatusCode == HttpStatusCode.OK) {
            short opcode1 = (short)(ps[0] << 8 | ps[1]);
            byte opcode2 = ps[2];
            int ret_code = (int)((ps[3] << 24) | (ps[4] << 16) | (ps[5] << 8) | (ps[6]));
            if (ret_code == 0) {
              double lat = ((double)((ps[7] << 24) | (ps[8] << 16) | (ps[9] << 8) | (ps[10]))) / 1000000;
              double lon = ((double)((ps[11] << 24) | (ps[12] << 16) | (ps[13] << 8) | (ps[14]))) / 1000000;
              result[0] = lat.ToString();
              result[1] = lon.ToString();
              return result;
            } else {
              return result;
            }
          } else return result;
        }
        catch (Exception ex) {
          result[0] = ex.Message;
          return result;
        }
      }
    }

title: AT+CENG=2,0 What type is the returning LAC?

Answers: 1

body:
LAC is "[Location Area Code](https://en.wikipedia.org/wiki/Mobility_management#Location_area)" - the code assigned by the operator to a group of cells that operate as one single broadcast unit.

It is returned to you as a hexadecimal representation of an unsigned 16 bit integer.

To know where the LAC is physically located on the planet you need to look it up in a table. I believe only the operator can give you that information. OS providers like Apple and Google most likely also have access to that data through agreements with operators.


body:
I connected the SD card to Arduino as it's explained [here](http://www.toptechboy.com/arduino/arduino-lesson-21-log-sensor-data-to-an-sd-card/). The problem is that the Arduino writes only once to the SD card and I don't understand the reason.

    #include <SD.h>
    #include <SPI.h>

    int CS_PIN = 4;

    File file;

    void setup() {
      Serial.begin(9600);
      pinMode(10, OUTPUT);
      digitalWrite(10, HIGH);
      Serial.print("Initializing SD card...");
      if (!SD.begin(CS_PIN)) {
        Serial.println("Card failed, or not present");
        return;
      }
      Serial.println("card initialized.");
    }

    void loop() {
      String dataString = "TEST";
      File dataFile = SD.open("datalog.txt");
      if (dataFile) {
        dataFile.println(dataString);
        dataFile.close();
        Serial.println(dataString);
      } else {
        Serial.println("error opening datalog.txt");
      }
      delay(1000);
    }

The output on Serial Monitor:

> Arduino write only one time on SD card error opening datalog.txt error
> opening datalog.txt error opening datalog.txt error opening
> datalog.txt error opening datalog.txt error opening datalog.txt error
> opening datalog.txt error opening datalog.txt error opening
> datalog.txt error opening datalog.txt error opening datalog.txt error
> opening datalog.txt error opening datalog.txt

I also tried to use:

    SD.open("file.txt", O_RDWR | O_APPEND);
    SD.open("file.txt", O_RDWR | O_CREAT);

As I saw https://arduino.stackexchange.com/questions/37288/adding-data-to-an-sd-card-file, but it doesn't work.

title: Arduino writes only one time on SD card - Data log

Answers: 3

body:
You are opening the file in read mode but should be opening it in write mode. Change `File dataFile = SD.open("datalog.txt");` to `File dataFile = SD.open("datalog.txt", FILE_WRITE);`.

You can remove this line of code: `digitalWrite(10, HIGH);`.

The [arduino.cc website][1] is also an excellent source of information regarding the SD library.

  [1]: https://www.arduino.cc/en/Reference/SD

body:
> File dataFile = SD.open("datalog.txt");

Repeatedly opening the same file is probably not a good practice, if you want to retain previously written contents.

body: For people having the same problem. I had the same problem where the SD Card would only run the if statement once and then not read it anymore. For some reason, after I ran the CardInfo, DumpFile, and ReadWrite example scripts in the SD Library (changing the title of the SD.open() command to the one that I was using), my code began to work and it started running the if statement each time. I would recommend trying this if you're experiencing the same problem.


body:
Good evening, I'm trying to establish serial communication between an Arduino UNO/Nano (ATMega328P) and a SP1ML-868 RF radio module (http://www.st.com/en/wireless-connectivity/sp1ml.html). I can talk to the radio with an FTDI breakout board, connected directly to my PC, but I can't do it with the Arduino.

As the radio is 3.3V and the Arduino is 5V, I tried to use the logic level converter from Sparkfun in the RX/TX lines, but that didn't work as well.

Any idea as to what I might be doing wrong? Thanks!

**EDIT**
I was able to talk to the radio by uploading a blank sketch to my Arduino and using only the RX/TX pins and the FTDI chip on the board. When I configure the Serial port (i.e. Serial.begin), this no longer works, which leads me to believe the problem is in the ATmega USART configuration. For some weird reason, this only works when the Arduino RX is connected to the module RX, and TX with TX.

As requested, below is the simple serial echo code I'm using, and an image with the wiring. This assumes the normal RX->TX and vice-versa connection. The module is powered through wires underneath its breakout board (3.3v).

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

void loop(){
  while(Serial.available() > 0){
    Serial.print((char)Serial.read());
  }
}

[![enter image description here][1]][1]
  [1]: https://i.stack.imgur.com/RxZfy.jpg

title: Arduino UNO/Nano communication with SP1ML-868 module

Answers: 2

body:
>For some weird reason, this only works when the Arduino RX is connected to the module RX, and TX with TX.

This works because in that configuration you are actually using your Arduino as a USB-serial adapter. When you make the RX-RX, TX-TX connection you cannot communicate between the ATmega328P on your Uno but you are also making a RX-TX, TX-RX connection with the ATmega16U2 chip on your Uno that is used as the USB-serial adapter on the board.

I feel that it's problematic to try to use Serial (pins 0 and 1) for communication both with the computer and the module. Instead I would recommend using the [SoftwareSerial library](https://www.arduino.cc/en/Reference/SoftwareSerial) for communication between the Uno and the module.

SoftwareSerial doesn't work reliably at 115200 so you should first use the current working wiring to configure the module to communicate at a lower baud rate. 9600 is quite safe but if communications speed is a bottleneck for your application you can probably use a higher baud rate.

Next, wire the module to any unused pins on your Uno other than 0 and 1.

Finally, upload the following code to the Uno:

<!-- language: lang-cpp -->

    #include <SoftwareSerial.h>

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

    void setup() {
      Serial.begin(115200);  // set this to the baud rate of the Serial Monitor
      SP1MLserial.begin(9600);  // set this to the baud rate of the module
    }

    void loop() {
      if (SP1MLserial.available()) {
        Serial.write(SP1MLserial.read());
      }
      if (Serial.available()) {
        SP1MLserial.write(Serial.read());
      }
    }

This is the equivalent of the simple echo code you posted above and can be used to verify that everything is working before moving on to more complex code. I have arbitrarily chosen pin 10 for the Uno software serial RX pin 11 for the TX pin but you can modify the code to any pins that are convenient for you. You should make the connections with the module as RX-TX, TX-RX.

body:
Not an answer to my question per-se, but I was able to solve my problem.
As mentioned on my comment on the last answer, the SP1ML module's serial communication is handled through an ARM microcontroller. So I got my hands on an Arduino Due, which has an ARM Cortex M3 MCU, and uploaded a serial echo code similar to the one on my question, only now using Serial3 to talk to the module:

void setup(){
  Serial.begin(9600);    // Connected to PC
  Serial3.begin(115200); // Connected to SP1ML, Rx-Tx connection
}
void loop(){
  if (Serial.available() > 0){
    Serial3.write(Serial.read()); // Echo to SP1ML
  }
  if (Serial3.available() > 0){
    Serial.write(Serial3.read()); // Echo to serial monitor
  }
}

I tried the exact same code on an Arduino Mega (same pins, ATmega2560 MCU) and it didn't work.
Obviously the MCUs are very different, but I have no idea one works and the other doesn't. A wild guess would be that the word sizes are different. In the Atmega, the word size is 16-bits, and in the ARM, the word size is 32-bits.


body:
I want to get data from ESP to my Arduino. I added firmware v2 to my ESP and it works correctly in my serial USB to TTL and shows the JSON data that I send to it.

But when I connect to my Uno serial it shows some unknown chars.

    #include <SoftwareSerial.h> //Including the software serial library
    #define DEBUG true
    SoftwareSerial esp8266(2, 3); // This will make the Arduino pin 2 as the RX pin and Arduino pin 3 as the TX. Software UART
    /* So you have to connect the TX of the esp8266 to the pin 2 of the Arduino and the TX of the esp8266 to the pin 3 of the Arduino. This means that you need to connect the TX line from the esp to the Arduino's pin 2 */

    void setup() {
      Serial.begin(115200); // Setting the baudrate to 9600
      esp8266.begin(115200); // Set it according to your esp’s baudrate. Different esp’s have different baud rates.
      pinMode(11, OUTPUT); // Setting the pin 11 as the output pin.
      digitalWrite(11, LOW); // Making it low.
      pinMode(12, OUTPUT); // Setting the pin 12 as the output pin..
      digitalWrite(12, LOW); // Making pin 12 low.
      pinMode(13, OUTPUT); // Setting the pin 13 as the output pin.
      digitalWrite(13, LOW); // Making pin 13 low.
      sendData("AT+RST\r\n", 2000, DEBUG); //This command will reset module to default
      sendData("AT+CWMODE=2\r\n", 1000, DEBUG); // This will configure the mode as access point
      sendData("AT+CIFSR\r\n", 1000, DEBUG); // This will get ip address and will show it
      sendData("AT+CIPMUX=1\r\n", 1000, DEBUG); // This will configure the ESP8266 for multiple connections
      sendData("AT+CIPSERVER=1,80\r\n", 1000, DEBUG); // This will set the server on port 80
    }

    void loop() {
      if (esp8266.available()) {
        // Checking that whether the esp8266 is sending a message or not (Software UART Data)
        while (esp8266.available()) {
          // Checking whether ESP8266 has received the data or not
          char c = esp8266.read(); // Read the next character.
          Serial.print(c);
          // Storing the response from the ESP8266
        }
      }
    }

    String sendData(String command, const int timeout, boolean debug) {
      // Function to send the data to the esp8266
      String response = "";
      esp8266.print(command); // Send the command to the ESP8266
      long int time = millis();
      while ((time + timeout) > millis()) {
        // ESP8266 will wait for some time for the data to receive
        while (esp8266.available()) {
          // Checking whether ESP8266 has received the data or not
          char c = esp8266.read(); // Read the next character.
          response += c; // Storing the response from the ESP8266
        }
      }
      if (debug) {
        Serial.print(response);
       // Printing the response of the ESP8266 on the serial monitor.
      }
      return response;
    }

Prints this for me:

    ???AR)?WS?TZ?eO?C?AJ+CIFSR
    +CIFSR:APHP,"192.168.4.1"
    +CIFSQ:APMAC,"62:01:94:22:96:7e"

    OK
    AZ??R????jC?u?H?AT+CIPSERVDR=1,80

    OK
    0,CONNECT

    +IPD,0,385:POST / HTTP/1.1
    cache-control: no-cache
    Postman-Token; 45494ff7-b3e1-400f-8afc-fcda26514705
    Content,Type: application/jsonUser-Agent: PostmanRunthme/6.1.6
    @ccept: */*Host: 192.178.4.1
    accept-encoding: gzip, defl`te
    content,length: 14Connection: keep-alive
    {"name":"`li"}0,CLOSED

My correct JSON is: `{"name":"ali"}`. But it shows incorrectly. And I set the mt serial library to `#define _SS_MAX_RX_BUFF 1024`.

How can I fix this?

My connection is:

[![my connection][1]][1]

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

title: Connecting ESP8266 to Arduino Uno

Answers: 3

body:
Try connecting arduino's TX and RX pins (0 and 1) with esp8266's RX and TX and see if it works. Upload a blank sketch. Whatever you type in serial box will be sent to esp.
Instead of using voltage divider you should use logic level converters with LM2596.

body:
Software serial doesn't work reliably at 115200. You need to use a lower baud rate:

1. Connect the ESP8266 back to your serial USB to TTL setup.
2. Send the following command to reconfigure the ESP8266 to do AT communication at 9600 baud: `AT+UART_DEF=9600,8,1,0,3`
3. Change line 9 of your sketch to `esp8266.begin(9600);`. This will cause the Uno to communicate with the ESP8266 at 9600 baud.
4. Upload the revised sketch to your Uno and connect it back up to the ESP8266.

body: i used AT+UART_DEF=9600,8,1,0,0 and it works correctly now


body:
Im a very beginner with Arduino. Recently started with the blink code. Thats my only experience with these. Ive got an ultrasonic sensor (As in this tutorial http://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/). So I setup the connections as trigger to Pin3 , Echo to 4, Vcc to 5v marked pin, GND to gnd next to 5v. Im using Arduino nano clone. When I run the program same as in the above example Im getting the following error. Other than that Im not getting any information.

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

Im sharing the same program I tried.

    // defines pins numbers
    const int trigPin = 3;
    const int echoPin = 4;
    // defines variables
    long duration;
    int distance;
    void setup() {
    pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
    pinMode(echoPin, INPUT); // Sets the echoPin as an Input
    Serial.begin(9600); // Starts the serial communication
    }
    void loop() {
    // Clears the trigPin
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    // Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    // Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);
    // Calculating the distance
    distance= duration*0.034/2;
    // Prints the distance on the Serial Monitor
    Serial.print("Distance: ");
    Serial.println(distance);
    }

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

title: Ultrasonic Sensor returns com3 false

Answers: 0


body:
I've connected a real time clock ZS-042 to my Arduino Uno. I tried to set the time, using an example from DS1307RTC library. Here is my code:

    #include <DS1307RTC.h>
    #include <Time.h>
    #include <Wire.h>

    *const* char *monthName[12] = {
      "Jan", "Feb", "Mar", "Apr", "May", "Jun",
      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    };

      tmElements_t tm;//it says that problem is in here

    void setup() {

      bool parse=false;
      bool config=false;

      // get the date and time the compiler was run
      if (getDate(__DATE__) && getTime(__TIME__)) {
        parse = true;
        // and configure the RTC with this info
        if (RTC.write(tm)) {
          config = true;
        }
      }

      Serial.begin(9600);
      while (!Serial) ; // wait for Arduino Serial Monitor
      delay(200);
      if (parse && config) {
        Serial.print("DS1307 configured Time=");
        Serial.print(__TIME__);
        Serial.print(", Date=");
        Serial.println(__DATE__);
      } else if (parse) {
        Serial.println("DS1307 Communication Error :-{");
        Serial.println("Please check your circuitry");
      } else {
        Serial.print("Could not parse info from the compiler, Time=\"");
        Serial.print(__TIME__);
        Serial.print("\", Date=\"");
        Serial.print(__DATE__);
        Serial.println("\"");
      }
    }

    void loop() {
    }

    bool getTime(const char *str)
    {
      int Hour, Min, Sec;

      if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
      tm.Hour = Hour;
      tm.Minute = Min;
      tm.Second = Sec;
      return true;
    }

    bool getDate(const char *str)
    {
      char Month[12];
      int Day, Year;
      uint8_t monthIndex;

      if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false;
      for (monthIndex = 0; monthIndex < 12; monthIndex++) {
        if (strcmp(Month, monthName[monthIndex]) == 0) break;
      }
      if (monthIndex >= 12) return false;
      tm.Day = Day;
      tm.Month = monthIndex + 1;
      tm.Year = CalendarYrToTm(Year);
      return true;
    }
and this is my output:

    Arduino: 1.6.12 (Windows 10), Плата:"Arduino/Genuino Uno"

    In file included from C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino:1:0:

    C:\Users\папа\Documents\Arduino\libraries\DS1307RTC/DS1307RTC.h:19:22: error: 'tmElements_t' has not been declared

         static bool read(tmElements_t &tm);

                          ^

    C:\Users\папа\Documents\Arduino\libraries\DS1307RTC/DS1307RTC.h:20:23: error: 'tmElements_t' has not been declared

         static bool write(tmElements_t &tm);

                           ^

    SetTime:10: error: 'tmElements_t' does not name a type

       tmElements_t tm;

       ^

    C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'void setup()':

    SetTime:21: error: expected primary-expression before ')' token

         if (RTC.write(tm)) {

                         ^

    C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'bool getTime(const char*)':

    SetTime:54: error: expected unqualified-id before '.' token

       tm.Hour = Hour;

         ^

    SetTime:55: error: expected unqualified-id before '.' token

       tm.Minute = Min;

         ^

    SetTime:56: error: expected unqualified-id before '.' token

       tm.Second = Sec;

         ^

    C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'bool getDate(const char*)':

    SetTime:71: error: expected unqualified-id before '.' token

       tm.Day = Day;

         ^

    SetTime:72: error: expected unqualified-id before '.' token

       tm.Month = monthIndex + 1;

         ^

    SetTime:73: error: expected unqualified-id before '.' token

       tm.Year = CalendarYrToTm(Year);

         ^

    exit status 1
    'tmElements_t' does not name a type

title: 'tmElements_t' does not name a type

Answers: 1

body:
Clearly the compiler does not know what tmElements_t means.

It is defined in TimeLib.h

In your program you reference Time.h instead, where it is not defined.

So:  Change

    include <Time.h>

to

    include <TimeLib.h>

and it should clear that error.


body:
I'm controlling some devices through a relay and a NodeMCU, it works fine and reconnects without problem in the meantime I'm testing it, but after I leave it like for 3 or more hours, it stops responding. I need this system to always be working without sleeping or anything. Here is my code:
<!-- language-all: lang-cpp -->

    #include <ESP8266WiFi.h>

    const char* ssid = "wifi_Guerrero ";
    const char* password = "3245968530";

    int ledPin = 13; // GPIO13
    int ledPin2 = 12; // GPIO13
    int desconectado = 5;
    int conectado = 4;
    WiFiServer server(80);
    WiFiClient client;

    int counter = 0;

    void setup() {
      Serial.begin(9600);
      delay(10);

      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, LOW);

      pinMode(ledPin2, OUTPUT);
      digitalWrite(ledPin2, LOW);

      pinMode(conectado, OUTPUT);
      pinMode(desconectado, OUTPUT);
      digitalWrite(desconectado, HIGH);

      connectWifi();

      Serial.print(F("Setting static ip to : "));
      Serial.println(WiFi.localIP());

      // Start the server
      server.begin();
      Serial.println("Server started");

    }

    void loop() {

      delay(200);

      if (WiFi.status() != WL_CONNECTED) {
        delay(100);
        digitalWrite(conectado, LOW);
        digitalWrite(desconectado, HIGH);
       connectWifi();
      }

      // Check if a client has connected
      client = server.available();
      if (!client) {
        return;
      }

      // Wait until the client sends some data
      Serial.println("new client");
      int t = millis();
      while(!client.available()){
      delay(1);
      if (millis()-t>130) return;
      }

      // Read the first line of the request
      String request = client.readStringUntil('\r');
      Serial.println(request);
      client.flush();

      // Match the request
      if (request.indexOf("/switch") != -1)  {
        digitalWrite(ledPin, !digitalRead(ledPin));
        digitalWrite(ledPin2, !digitalRead(ledPin2));
        printSwitch();
      }else if (request.indexOf("/uno") != -1) {
        client.print("Canal 1 apagagado | Canal 2 encendido");
        digitalWrite(ledPin, HIGH);
        digitalWrite(ledPin2, LOW);
      }else if (request.indexOf("/dos") != -1){
        client.print("Canal 1 encendido | Canal 2 apagado");
        digitalWrite(ledPin, LOW);
        digitalWrite(ledPin2, HIGH);
      }else if (request.indexOf("/tres") != -1){
        client.print("Canal 1 apagado | Canal 2 apagado");
        digitalWrite(ledPin, HIGH);
        digitalWrite(ledPin2, HIGH);
      }else if (request.indexOf("/cuatro") != -1){
        client.print("Canal 1 encendido | Canal 2 encendido");
        digitalWrite(ledPin, LOW);
        digitalWrite(ledPin2, LOW);
      }else if (request.indexOf("/cinco") != -1){
        printIP();
      }else if (request.indexOf("/apagaruno") != -1){
        client.print("Canal 1 apagado");
        digitalWrite(ledPin, HIGH);
      }else if (request.indexOf("/apagardos") != -1){
        client.print("Canal 2 apagado");
        digitalWrite(ledPin2, HIGH);
      }else if (request.indexOf("/prenderuno") != -1){
        client.print("Canal 1 encendido");
        digitalWrite(ledPin, LOW);
      }else if (request.indexOf("/prenderdos") != -1){
        client.print("Canal 2 encendido");
        digitalWrite(ledPin2, LOW);
      }else if (request.indexOf("/canaluno") != -1){

        if(digitalRead(ledPin) == HIGH) {
          client.print("Off");
      } else {
        client.print("On");
      }

      }else if (request.indexOf("/canaldos") != -1){

        if(digitalRead(ledPin2) == HIGH) {
        client.print("Off");
      } else {
        client.print("On");
      }

      }

    // Set ledPin according to the request
    //digitalWrite(ledPin, value);

      // Return the response

      delay(1);
      Serial.println("Client disonnected");
      Serial.println("");

    }

    void printSwitch(){
      if(digitalRead(ledPin) == LOW) {
        client.print("Canal 1 Encendido");
      } else {
        client.print("Canal 1 Apagado");
      }
      Serial.println("");
      if(digitalRead(ledPin2) == LOW) {
        client.print("Canal 2 Encendido");
      } else {
        client.print("Canal 2 Apagado");
      }
    }

    void printIP(){
      delay(100);
      client.print(WiFi.localIP());
    }

    void connectWifi()
    {
      Serial.print("Connecting to "+*ssid);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
      }

      // config static IP
      IPAddress ip(192, 168, 0, 8);
      IPAddress gateway(192, 168, 0, 1);
      IPAddress subnet(255, 255, 255, 0);
      WiFi.config(ip, gateway, subnet);
      digitalWrite(conectado, HIGH);
      digitalWrite(desconectado, LOW);
      Serial.println("");
      Serial.println("Connected");
      Serial.println("");

      // Print the IP address
      Serial.print("Use this URL to connect: ");
      Serial.print("http://");
      Serial.print(WiFi.localIP());
      Serial.println("/");
    }//end connect

title: NodeMCU stops responding after several hours

Answers: 1

body:
I think thatthe problem lies with this definition

    String request = client.readStringUntil('\r');

which you define dynamically in loop this leads possibly to heap fragmentation, causing resets after sometime

Define a global char array

    char request [256] ={'\0'};
    char c;
    uint cc = 0;

and work instead the String functions with

    while(client.available()){
    c = client.read();
    if (c != '\r'){
      request[cc] = c;
       cc++;
     }
     else return;
    }

then handle the filled request buffer like

    if (strcmp(request,"/switch") != 0)  {
      ....
     }

This should keep you esp running


body:
My project is to control a dual motor model boat via bluetooth hand-held device. I am using an Adafruit feather 32u4 bluefruit LE and Adafruit DC Motor + Stepper FeatherWing Add-on. I am using the Apple IOS Adafruit Bluefreuit BLE app as the controller. I have this part of the design nearly done.  I plan to use this in a swimming pool.

How can I have the boat automatically avoid the sides of the pool or any other obstruction?  Also how can I have the boat steer toward a buoy in the water?

I would like to have any solutions as low-cost.

Thanks in advance

title: Boat project - object detection

Answers: 0


body:
In the C file in [simplesample_mqtt.c][1], which connects Arduino to the Azure IoT hub, I need to use the IRsend and IrRemoteESP8266 libraries to send an infrared signal with Azure IoT hub.

<!-- language: lang-cpp -->

     #include <IRremoteESP8266.h>
     #include <IRsend.h>
     IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

I don't have any problem when I use this code in my main Arduino file. But when I use these includes in a C file (simplesample_mqtt.c), I get this error from line 3: "unknown type name 'IRsend'".

[![enter image description here][2]][2]

error full info :

    Arduino: 1.8.2 (Windows 10), Board: "NodeMCU 0.9 (ESP-12 Module), 80 MHz, 115200, 4M (3M SPIFFS)"

    In file included from sketch\simplesample_mqtt.c:29:0:

    C:\Program Files (x86)\Arduino\libraries\IRremoteESP8266\src/IRsend.h:29:1: error: unknown type name 'class'

    class IRsend {

    C:\Program Files (x86)\Arduino\libraries\IRremoteESP8266\src/IRsend.h:29:14: error: expected '=', ',', ';', 'asm' or 'attribute' before '{' token

    class IRsend {

    simplesample_mqtt.c:31: error: unknown type name 'IRsend'

    IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

    simplesample_mqtt.c:31: error: expected declaration specifiers or '...' before numeric constant

    IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

    exit status 1
    unknown type name 'IRsend'

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

  [1]: https://github.com/Azure/azure-iot-arduino/tree/master/examples/simplesample_http
  [2]: https://i.stack.imgur.com/NOX39.jpg

title: Unknown type name 'IRsend'

Answers: 1

body:
I solved this problem. The reason for this is because main Arduino is c++ and simplesample_mqtt.c is c code and we have to use c++ code in c code:

In main Arduino file you have to declare function like this :

    extern "C" void TurnOn();
    void TurnOn()
    {
        digitalWrite(RELAY_SONOFF, HIGH);
        digitalWrite(LED_SONOFF, HIGH);
    }

and use this function in c code:

    void TurnOn();
    EXECUTE_COMMAND_RESULT TurnOn(ContosoAnemometer* device)
    {
        (void)device;
        TurnOn();
        (void)printf("Turning fan on.\r\n");
        return EXECUTE_COMMAND_SUCCESS;
    }


body:
the aim of the project I'm working on is to water my bonsai automatically, depending on numerous sensor inputs. So basically I have Arduino Nano with huminity and light sensor, a relay to switch the water pump and ESP8266 wifi module, which I use to check the data from the sensors in the Blynk app on my phone. I use two isolated circuits. The first one is used only by the DC motor (water pump) and is supplied by a 5V 600 mA power source. The second takes care of the rest (arduino, ESP, sensors, relay) while it's supplied by a 5V 1A power source. I'm using this with the ESP8266 board.

Once I run the program, it connects to the Blynk server and I can read data from the sensors on my phone. The problem comes when I want to switch the relay from the Blynk app. Than the ESP8266 disconnects (nearly immediately, or after few seconds). I tried a different DC motor (not a water pump) and it worked fine. I also tried to switch the pump without using EPS8266, that worked as well (so the code should be ok). I think this has something to do with the current draw caused by the water pump, but that makes no sense - I'm using two independent circuits, the pump draws maximally 300 mA from the 600 mA source, while the rest of the electronics draws no more than 200 mA from the 1 A power supply. Neither different power supplies, nor another relay worked.

Here's my code:

    #define BLYNK_PRINT Serial
    #define BLYNK_DEBUG

    #include <ESP8266_Lib.h>
    #include <BlynkSimpleShieldEsp8266.h>

    #include <BH1750.h>
    #include <Time.h>
    #include <SoftwareSerial.h>

    #define PUMP  10
    #define SENSOR A0
    #define BUTTON 2

    char ssid[] = "XXXXX";
    char pass[] = "XXXXXXXXXXXXXXXXXX";

    SoftwareSerial EspSerial(11, 12);
    ESP8266 wifi(&EspSerial);

    BlynkTimer timer;
    BH1750 lightMeter;
    int humidity;
    int light;
    bool pressed = 0  ;
    bool pump=1;
    char auth[] = "XXXXXXXXXXXXXXXXXXXXXXXXXX";

    void sendData(){
          humidity=analogRead(SENSOR);
          light=lightMeter.readLightLevel();
          Blynk.virtualWrite(V0,humidity);
          Blynk.virtualWrite(V1,light);
    //      Serial.print("humidity: ");
    //      Serial.println(humidity);
    //      Serial.print("light: ");
    //      Serial.println(light);
    }
    void checkConnection(){
      if(!Blynk.connected()){
        digitalWrite(PUMP,1);
        Blynk.begin(auth, wifi, ssid, pass);
      }
     }
    void checkButton(){
      if(digitalRead(BUTTON) && pressed){
         Blynk.virtualWrite(V3,digitalRead(BUTTON));
         pump=!pump;
    //      Serial.println("pump from button");
         }
      else if(digitalRead(BUTTON) && !pressed){
        pressed=1;
        }
      else{
        pressed=0;
        }
    }
    BLYNK_WRITE(V2)
    {
        Serial.println("switching pump");
        pump=!param.asInt();
        digitalWrite(PUMP,pump);
    }
    void setup() {
      Serial.begin(9600);
      delay(10);
      EspSerial.begin(9600);
      delay(10);
      lightMeter.begin();
      pinMode(PUMP, OUTPUT);
      pinMode(BUTTON, INPUT);
      digitalWrite(PUMP, pump);
      Blynk.begin(auth, wifi, ssid, pass);
      timer.setInterval(5000L, sendData);
      //timer.setInterval(5L, checkButton);
    //  timer.setInterval(2000L, checkConnection);
      }

    void loop() {
      if (Blynk.connected()) {
          Blynk.run();
          timer.run();
        }
    }
and the Blynk log:

    [2631095] <[06|05|14|00|00]
    [2631389] >[00|05|14|00|C8]
    [2632112] <[14|05|15|00|08]vw[00]0[00]632
    [2632280] <[14|05|16|00|07]vw[00]1[00]28
    [2637109] <[14|05|17|00|08]vw[00]0[00]630
    [2637214] <[14|05|18|00|07]vw[00]1[00]28
    [2641393] <[06|05|19|00|00]
    [2651445] Cmd error
    [2656470] Cmd skipped:20
    [2656471] Cmd skipped:20

[EDIT] and the circuit:
[![circuit][1]][1]

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

title: ESP8266 disconnects after relay switch

Answers: 1

body:
The problem was hidden in a wrong relay wiring. Once I'm using only COM and NO PIN as it is showed in [this article][1], not only that the whole system is stable and the ESP8266 is not disconnecting any more, but I can also power the circuit using only one 5V 2A power supply.

Here's my updated schematics [![enter image description here][2]][2]

  [1]: https://bocoup.com/blog/javascript-relay-with-johnny-five/
  [2]: https://i.stack.imgur.com/wupDW.png


body: I used to be able to use my Elegoo Uno R3, just fine. It worked with my computer no problem. Except I used the USB cable on a power bank and now the Uno isn't being recognized on any computer. I tried uninstalling and re-installing the IDE and drivers. But nothing works. I don't even get the serial 2.0 USB in the device manager. the Uno itself works. The orange and green lights stay on continuously when plugged in and It's still outputting the code I put in it before it stopped connecting to my computer. Any help to be able to fix my Uno. The button on the UNO doesn't seem to do anything either.

title: Elegoo "Uno R3" not being recognized in any computer anymore

Answers: 0


body:
I would really appreciate any help, my home project has been put on hold for weeks as I haven't been able to figure this out. In a nutshell, I'm connecting to my wifi network, measuring temperature from a sensor, and sending that temperature data to a server via a HTTP Request. All of that stuff works.

I have it in a loop, and on the 3rd HTTP request I get 'Connection Failed' when it's trying to `client.connect(server, 80)` - I don't understand why it fails. I've tried adding `client.stop()` and `client.flush()` after each HTTP request, but nothing fixes it. Below is my sketch file with some of the temperature code removed to make it easier to read

    #include <SPI.h>
    #include <WiFi101.h>
    #include <string.h>
    #include <stdlib.h>
    #include <OneWire.h>
    #include <DallasTemperature.h>

    //WiFi Client Setup
    char ssid[] = "HIDDEN";    //  your network SSID (name)
    char pass[] = "HIDDEN";       // your network password
    int status = WL_IDLE_STATUS;    // the WiFi radio's status
    char server[] = "HIDDEN";
    WiFiClient client;

    // Setup for temperature sensor
    #define ONE_WIRE_BUS A5
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);
    DeviceAddress insideThermometer;

    void setup() {
      Serial.begin(9600);
      WiFi.setPins(8,2,A3,-1);
      while (!Serial) {
        Serial.println("Waiting for serial");
      }

      //Connect to wifi shield
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");
        while (true);
      }
      wifiConnect();
      sensors.begin();
    }

    void loop() {
      while (client.available()) {
        char c = client.read();
        Serial.write(c);
      }
      /*
      Code to get temperature here
      */
      httpRequest(temp);
      delay(10000); // 5min
    }

    void httpRequest(String temp) {
      String request = "POST /api/webhooks/temp?temperature=" + temp + " HTTP/1.1";

      // if there's a successful connection:
      if (client.connect(server, 80)) {
        Serial.println("connected to server");
        client.println(request);
        client.println("Authorization: Token HIDDEN");
        client.println("Host: HIDDEN");
        client.println("Connection: close");
        client.println();
      }
      else {
        Serial.println("Connection failed");
      }
    }

    void wifiConnect() {
      //Attempt to connect to WiFi network:
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        status = WiFi.begin(ssid, pass);
        delay(1000);
      }

      Serial.println("You're connected to the network");
    }

title: WiFi101 Client HTTP POST fails after 3rd request

Answers: 1

body:
I tried changing the strings to char's, that didn't work.
Verified that it was closing connections with the server, check.

Was reading around and saw someone who tried a soft reset of the wifi client [here][1]. I added the following to the end of my `httpRequest()` method

    client.stop();
    WiFi.end();
    delay(10);
    WiFi.begin(ssid, pass);

And now it's working just fine. I'm going to have it run all night and see if there are any issues, but it's definitely an improvement as I can make more than 3 requests :|

This seems like a terrible work around. Clearly something isn't getting reset after each HTTP request on the wifi client, and this (right now) is the only way to solve it. I'd really love any other feedback on a better ways to solve it. Seems like some issues with the WiFi101 Library.

  [1]: https://github.com/arduino-libraries/WiFi101/issues/118#issuecomment-269799115]here


body:
I am pretty new to NodeMCU (ESP8266) and Arduino IDE in general. I followed various documentation / blogs to set up 2 Channel Relay with NodeMCU chip.

Below is sketch code for it.

<!-- language: lang-cpp -->

    #include<CayenneMQTTESP8266.h>
    #define CAYENNE_DEBUG
    #define CAYENNE_PRINT Serial

    #define LEFT_GARAGE 4
    #define RIGHT_GARAGE 5

    char ssid[] = "XXXXXXXXXXXXXXXXXXXXXXXX";
    char password[] = "XXXXXXXXXXXXXXXXXXXXXX";

    char username[] = ""XXXXXXXXXXXXXXXXXXXXXX";";
    char mqtt_password[] = ""XXXXXXXXXXXXXXXXXXXXXX";";
    char client_id[] = ""XXXXXXXXXXXXXXXXXXXXXX";";

    void setup() {
      Cayenne.begin(username, mqtt_password, client_id, ssid, password);
      pinMode(LEFT_GARAGE, OUTPUT);
      digitalWrite(LEFT_GARAGE, HIGH);
      pinMode(RIGHT_GARAGE, OUTPUT);
      digitalWrite(RIGHT_GARAGE, HIGH);
    }

    void loop() {
      Cayenne.loop();
    }

    // Left Garage Door
    CAYENNE_IN(0){
      int currentValue = getValue.asInt();
      digitalWrite(LEFT_GARAGE,!currentValue);
    }

    //Right Garage Door
    CAYENNE_IN(1){
      digitalWrite(RIGHT_GARAGE,!getValue.asInt());
    }

On relay board I tried to connect wire in 2 different configuration.

1st Config:

    vcc -> 3.3v from NodeMCU
    in1 -> D1/GPIO 04 from NodeMCU
    in2 -> D2/GPIO 5 from NodeMCU
    GND -> GRD from NodeMCU

2nd Config:

    vcc -> 5v USB from NodeMCU
    in1 -> D1/GPIO 04 from NodeMCU
    in2 -> D2/GPIO 5 from NodeMCU
    GND -> GRD from NodeMCU

In 1st config, On relay board respective LED's are turning on when Cayenne buttons are pressed but when I check for continuity on multi meter I don't get anything.

In 2nd config, no LED and no continuity.

am I missing something here? Any feedback/comments are highly appreciated.
[![2 Channel Relay][1]][1]
[![NodeMCU Setup][2]][2]

  [1]: https://i.stack.imgur.com/OvJGG.jpg
  [2]: https://i.stack.imgur.com/Qi4KV.jpg

title: 2 Channel Relay normal open is not working with NodeMCU but led on board light up

Answers: 1

body:
Your second configuration is right because from picture of relay module it clear that it requires 5V supply.

<h2> relay working principal is:

- when the signal port(in1/in2) is at low level, the signal light will light up and the optocoupler (it transforms electrical signals by light and can isolate input and output electrical signals) will conduct, and then the transistor will conduct, the relay coil will be electrified, and the normally open contact of the relay will be closed.
- When the signal port(in1/in2) is at high level, the normally closed contact of the relay will be closed. So you can connect and disconnect the load by controlling the level of the control signal port.

As you mentioned that in second configuration there is no LED glow. For find out solution of your problem, you have do one test. Test voltage level of D1/D2. Just make connection on breadboard as mentioned in image.[![enter image description here][1]][1]

If voltage level is correct that it might be problem with your relay module.

Also I have attached here relay connection reference for your directness.[![enter image description here][2]][2]
  [1]: https://i.stack.imgur.com/WgyKW.jpg
  [2]: https://i.stack.imgur.com/EyP5b.jpg


body:
I'm trying to build a datalogger using Arduino UNO, I'll use RS232 for the communication between PC and Arduino, the problem I'm facing now is that I'm using delay(10000) : 10 seconds as a timestep for data acquisition. however, I can't find any solution to receive a string from the serial input to Arduino while delay is executing. Here is the code :

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

    void loop() {
      serialRoutine();
      dataLoggingEvery10Second(); // That's a function to receive data from the sensor and store it in SD card.
      delay(10000);
    }

      // A function to handle all the serial in out
      void serialRoutine(){
      // print the string when a newline arrives:
      while(Serial.readString() == ""){
        String serstr = Serial.readString();
          /*
          *  Getters
          */
          if(serstr == "GETDATA"){
            Serial.println("Here is my data");
          }
          serstr = "";
      }
    }

Any help would be highly appreciated !

title: How to listen for an incoming serial string inside loop with long delay?

Answers: 2

body:
    void loop() {
      static unsigned long prev = 0;
      unsigned long now = millis();

      if (now - prev >= 10000L) {
        serialRoutine();
        dataLoggingEvery10Second();
        prev = now;
      }
    }

This will executed at time 10s, 20s, etc. I

body:
If your PC is sending GETDATA, then it can send it every 10 seconds (or every 15 or 30 minutes) so you don't need any delays at the Arduino end at all.

I have [a page about getting serial data without blocking](http://www.gammon.com.au/serial) which illustrates how you can be doing other things (like reading sensors) without blocking.

An example sketch is:

    /*
    Example of processing incoming serial data without blocking.

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

    Released for public use.
    */

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

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

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

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

      switch (inByte)
        {

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

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

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

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

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

        }  // end of switch

      } // end of processIncomingByte

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

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

      }  // end of loop


body:
Hej there,

I have a small project at home and I'm curious if people have some advice/idea for me. Because I'm not sure if the communication between the different devices is the way to go.

This is my current setup:

I have a Android application running on an Android device (tablet). This Android device can communicate with a MySQL server with a json/PHP. The Android device is receiving data from the database but also writing data to it. The MyQL/web server is running on a Raspberry.

The second device is an atmega328p microcontroller(http://www.ebay.com/itm/2-x-ATMEGA328P-PU-ATMEGA328-MICROCONTROLLER-IC-Free-Shipping-/280994585126) that is sending temperature/humidity to the MySQL server on the Raspberry. The ATmega is communicating through a 433 MHz chipRF(MX-05V). The Raspberry also has a 433 MHz chip RF(MX-05V) that is receiving this data and writing it to the MySQL server.

So actually the ATmega is communicating with the Raspberry and the Raspberry is communicating with the MySQL server.

It is working properly but I'm not sure if this is the way to go. So my question, what are you thoughts of this setup, what would you do different and why?

Thanks, Matthijs

title: Android, Raspberry, Atmega, SQL communication

Answers: 1

body:
If I understand correctly:

 - You have a Pi hosting MySQL and a web server.
 - A Mega writes temp/humidity data to the server.
 - An android device reads data from the web server.
 - The Pi and the Mega talk over a 433(MHz) radio?

Is it the write way to go?
What you have is a tried an tested design, a central server responsible for collating at serving the data.  My one concern is the 433 radios, I think you might be limiting the scalability of your design by using that.  What happens if you want to add a second Mega to report a different sensor?  You PI needs a second receiver and a second app to read, although the PI will handle 2, easily, there will be a point where it can't handle any more.  I'd suggest that you look at technology that allows multiple nodes on the same network, WiFi.

You could use WIFI by either getting adding a WiFi device to you Mega or ditching the expensive Mega and buying a $2 Wemos D1.

But that's just my opinion, and unfortunately that's the reason this question will get closed, because asking for people's opinions is taboo.


body:
I'm using the ESP8266WiFi library on a NodeMCU, running the arduino bootloader in the arduino software (Windows 10 app version).

I'm trying to load the SSID and password from SD-card (this part is successfull).

My problem this far is when i use the Wifi library it looks like this:

     Wifi.begin(const char*, const char*);

Since it takes 2 const parameters i cannot change it later. Is there anyway i can add SSID and PASSWORD to my sketch without having to recompile it. (I have to send it to people who does not know how to compile and flash an arduino)

I'm not attached to the ESP8266WiFi library, i'm not attached to SD-card, other solutions are welcome.

SD-reader works as planned, WiFi works as planned with a static password and SSID.

title: Dynamic SSID + Password from ESP8266WiFi

Answers: 2

body:
The `const` keyword there does not force the data you call it to be constant, it only forbids certain assignments with the parameters inside that function but it's just superfluous in most cases. Meaning you can call it with input you got from serial or some other source (for ex. setup page accessible from hotspot->Store in EEPROM->Next boot connect to set WiFi AP). There's also a nice StackOverflow thread about this [here][1] and why it's not actually a good idea in many cases.

  [1]: https://stackoverflow.com/questions/117293/use-of-const-for-function-parameters

body:
The problem was not const char*, but bad conversion from string to char*.

Thing that lead me to believe it was the const char* was an unclear compiler message, and poor understanding of C++ data types.

but the correct answer was:

     ssid.toCharArray(ssidc, ssid.length());


body:
I want to play a file that I have in my USB device through a yx5300 mp3 module.

I have a file in my USB device at path `Music/hello.mp3`. I want to play this file using the yx5300 module or some other module, if available.

I have already read this file using a shield. I want to pass the data to the yx5300.

title: Can we use yx5300 to play audio from a file in Arduino?

Answers: 1

body: No. That chip can only play files on an SD card that is directly attached to it.


body:
I'm a very beginner with electronics and of course with Arduino. Actually I've been in the software field (.NET) for the past 12 years. I am trying to develop a simple system to run for longer using Arduino Nano. Longer means roughly it could be for years continuously, expecting normal wear and tear.

So what I understood is Arduino loop always executes based on any values from sensors while in the loop. And also Arduino has some interrupt mechanism too.

But since the looping system feels pretty awkward for some situations, I tried to stop the loop using `exit(0);` inside the loop. So loop will stop  after the first execution.

I am trying to build an external simple interrupt hardware system (like any timer object in software) which interrupts Arduino in a specified interval, say 20 sec. So when that interrupt on that particular pin occurred we can call some function there to do the job and that's all from Arduino side and it can go back to sleep.

So I believe this will reduce the load on Arduino and of course since no looping it will not get heated at all. How can we make such a system (external timer) to interrupt Arduino in specific intervals? This is just a theory in mine, not an idea how to implement it in electronics.

How can I achieve this above scenario?

title: Solution to interrupt Arduino every n seconds

Answers: 3

body:
So, since you're coming from the application domain there are some things you might want to consider:

  - Make sure to always stay inside the super loop. With an Arduino or any other Microcontroller (not using a RTOS) you do not have anything defined that's going to happen after the superloop. Everything that happens after this loop is basically undefined (it typically is a reboot or jump to a default interrupt handler but may also be a lockup). Simply telling the processor to "exit" will .. well, exit - but you have no idea where it's going after that. To allow for interrupts and further execution of your main code, you need to have your processor in a defined state (and that basically is the super-loop). as a comparison with your PC, after you exit a thread, the operating system will take over. On your Arduino there is no such concept. The super-loop IS your OS (well, at least it's some minimum implementation of a non-preemptive scheduler).
  - If you want to have only interrupt actions active while the processor is using only little power, you will need to use the processors sleep modes. These are modes, where special functionality is disabled but which keeps the processor alive or in some idle mode where it's actually just waiting. Whilst the Arduino may have various sleep modes, none of them are what can be achieved with other architectures, such as the MSP430 platform or some SAMxL platform. Those are dedicated as low power processor and provide the necessary deep sleep modes.
  - When using a deep sleep mode, it depends on the actual sleep mode which interrupts can wake the processor. Typically for the deepest sleep modes, only few interrupt sources will actually wake the processor up as all other peripherals are inactive either because their clock was gated or power was turned off for that function block.
  - You will always have some power drain for the processor but keep in mind that it's not only the processor which will require power. At some point, you have leakage currents through your capacitors/resistors and other ICs on your board which require power as well. When you're talking about "years", you will also need to account for the battery discharge as well. No battery is perfect.
  - [Jack Ganssle][1] is probably well known for his insight into anything related embedded, but [he explicitly wrote some articles for ultra-low-power systems][2]. You must read those if you want to start somewhere. While having the software side covered using low power techniques you will also need to tackle the hardware side, yet as I said - the Arduino wasn't made for such tasks even if it provides some basic sleep modes.

  [1]: http://www.ganssle.com
  [2]: http://www.ganssle.com/reports/ultra-low-power-design.html

body:
You can refer below links once for understanding sleep concept on Arduino.

1) http://playground.arduino.cc/Learning/ArduinoSleepCode

2) http://www.gammon.com.au/power

body:
You wrote:

> I'm a very beginner with electronics [...] the looping system feels
> pretty awkward

I think these two statements are highly correlated. It feels awkward to
you simply because you are not used to it.

> So what I understood is Arduino loop always executes based on any
> values from sensors while in the loop.

This sounds like a misunderstanding. The Arduino `loop()` is a function
_you_ write, and whether its behavior is “based on any values from
sensors” or not is up to you. The `main()` function provided by the
Arduino core library will just call your `loop()` repeatedly.

> I tried to stop the loop using exit(0);

As explained by Tom L. in his answer, there is nowhere to exit to. In
this kind of embedded system, `exit()` essentially means “stop doing any
useful work”. On AVR microcontrollers (like in the Nano), `exit()` is
implemented as an empty infinite loop running with interrupts disabled.

> I believe [sleeping] will reduce the load on Arduino and of course
> since no looping it will not get heated at all.

Heat? What heat? The CPU core of the Arduino does not generate heat. Not
at any significant level. Think about this: it's clocked at 16 MHz.
Yes, those are **mega**hertz: snail pace! The MCU _can_ get hot if you
have it source or sink too much current, but this is completely
unrelated to CPU load.

> I am trying to build an external simple interrupt hardware system
> [...] which interrupts Arduino in a specified interval, say 20 sec.

Since you come from the software world, you probably know about
“premature optimization”: this is exactly what you are doing here. I
recommend you stop right now. Do not build into your system complexity
that may not be useful. Instead, start simple: read the [Blink without
delay][] Arduino tutorial, and apply this technique to solve your
problem. In a nutshell, you will put, inside your `loop()`, something
like:

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

    if (millis() - previousMillis >= JOB_PERIOD) {
        do_the_job();
        previousMillis += JOB_PERIOD;
    }

Note that the tutorial I mentioned would instead do something like
`previousMillis = millis();`, which is fine if you want to ensure that
`JOB_PERIOD` is the _minimum_ time between the jobs. The code above,
instead, assumes you want to enforce an _average_ period.

Once you have this working, test it, and see whether you do need to
optimize it. There are two aspects that could be optimized: current
consumption and period accuracy. Either may be useful for your
particular application. Or none. Or both. It all depends on your
specific requirements.

## Current consumption

There is a low hanging fruit here. You can put the CPU to sleep on every
loop iteration, simply by calling `sleep_mode()`:

    #include <avr/sleep.h>

    const uint32_t JOB_PERIOD = 20000;  // 20 seconds

    void do_the_job()
    {
        // The stuff you have to do every 20 seconds.
    }

    void loop()
    {
        static uint32_t previousMillis;
        if (millis() - previousMillis >= JOB_PERIOD) {
            do_the_job();
            previousMillis += JOB_PERIOD;
        }
        sleep_mode();
    }

The Arduino core library has a timer interrupt triggered every
1024 µs. This is the interrupt responsible of updating the variable
that `millis()` returns, and it will wake you up. With the code above,
the Arduino will be awake for only a few CPU cycles per iteration
(update `millis()`, subtract, compare) and spend most of its time
sleeping. In the default sleep mode, only the CPU does sleep. But it is
also the only mode in which the timer does _not_ sleep, and is thus the
appropriate mode here.

The trick above should suppress most of the power consumption of the
CPU. If it's still consuming too much for your liking (i.e. if you want
your Nano to run for years on a couple of AA cells), you should know
there are ways to push the microcontroller into the ultra-low power
realm. But it is not so simple, and you will have to tune not only the
software, but also the hardware. Your journey into microamp hunting
should start by reading [Power saving techniques for
microprocessors][power], by Nick Gammon. The link has already been
mentioned in Chirag Patel's answer.

## Period accuracy

The Arduino Nano being clocked from a [ceramic resonator][], you should
expect its timing accuracy to be pretty poor. The standard solution for
when you need accurate timings is to use an RTC. You could query the RTC
periodically to ask for the current time or, better yet, you can choose
an RTC with “alarm” capability. This is not unlike an alarm clock: you
program it to send you an interrupt signal at a time of your choosing.
Read the manual of your RTC for details.

[Blink without delay]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
[power]: http://www.gammon.com.au/power
[ceramic resonator]: https://en.wikipedia.org/wiki/Ceramic_resonator


body:
I'm trying to communicate between two Arduino Due and Nano. Nano as Master and Due as a slave. As given in the library description [Wire Lib][1]

  [1]: https://www.arduino.cc/en/Tutorial/MasterReader

When the master request for data from the slave, first it goes to Request ISR. `Wire.onRequest(requestEvent)`    But when compile the program for Arduino Due I get following errors.

    In file included from C:\Users\\Slave_Test3.ino:14:0:

    C:\Users\..\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\libraries\Wire\src/Wire.h:59:7: error:   initializing argument 1 of 'void TwoWire::onRequest(void (*)())' [-fpermissive]

     void onRequest(void(*)(void));

           ^

  But If I change from Arduino Due to any other board this error does not come.

Thank you

title: I2C communication between Arduino Due and Nano

Answers: 1

body:
Dead easy !!
(Well only because I had a `-fpermissive` yesterday :) )

You are trying to implicitly cast, and you can't do that with modern GCC versions (quite rightly).

So you need to explicitly cast the first parameter to void*.

Because this is in a "core" library for the Due I would get the latest version of the board package and see if it goes away.  You can turn the check off, but you will need to google on how to do that.


body:
I bought this SAMD21 development board which shows up as an "Arduino/Genuino Zero (Native USB Port)" when plugged in. And I've successfully got a blink sketch running on it all good so far:

[![SAMD21 development board][1]][1]

The reason I picked up this board was to experiment with the built-in capacitive touch sensor on the SAMD21. In [the datasheet for this chip][2] it claims to support a *'Peripheral Touch Controller with 256-Channel capacitive touch and proximity sensing'*.

Does anyone know what this exactly means and how I would access this functionality to detect touches in my Arduino code? Obviously there are not 256 IO pins so how would this work? Is there some kind of internal multiplexer?

The **256 channel capacitive touch controller** is also mentioned in a [Sparkfun video][3] about their SAMD21 board, so it must be possible to access this functionality.

Can someone direct me towards an Arduino library or method and more information on the wiring and pin connections for this. Thanks.

  [1]: https://i.stack.imgur.com/T5BMJ.jpg
  [2]: http://www.atmel.com/Images/Atmel-42181-SAM-D21_Summary.pdf
  [3]: http://youtube.com/watch?v=QY2rOvHIJlI

title: Built-in capacitive touch detection with SAMD21 development board (Arduino Zero Compatible)

Answers: 1

body:
You have three options for the silicon-based PTC (peripheral touch controlller).

 1. [LibrePTC][1] - My own library that targets the SAMD11 but should work with some modifications for other SAMD architectures. The README file has lot of information on how the PTC works and how to specify designs for it.
 2. [Adafruit FreeTouch][2] - Works only with the SAMD21. Given the high quality of the register documentation, I suspect they may have had inside help from Atmel but I haven't been able to reach Ladyada, their primary contributor, to learn more.
 3. QTouch, which is Atmel's library available in closed source only but is extremely feature-rich. Arduino team decided not to allow closed source stuff in their IDE so its been banned from official distributions. However, it is possible to hack it into the Arduino IDE and I've used it successfully that way. However this requires esoteric modification to boards.txt that are beyond the scope of this answer.

The PTC hardware peripheral on the SAMD chips works on self-capacitance using "Y" lines specified in the data sheet. See the README on LibrePTC for details. Some chip variants have more pins broken out. For instance, the SAMD21G has fewer available Y pins than the SAMD21J, although the J series is not as readily available in breakout boards as of the summer of 2017 and it has limited Arduino IDE support. I personally prefer the SAMD11 because it is cheaper ($1.00) and has way more available Y lines in the QFN package.

As of August 2017, I intend to attempt a merge between the Adafruit and LibrePTC libraries but no guarantees when this will happen. I don't have access to insider documentation so my library was 100% reverse engineered through trial and error.

  [1]: https://github.com/jgilbert20/Libre_PTC
  [2]: https://github.com/adafruit/Adafruit_FreeTouch


body:
I live in India, and unfortunately here the unlicensed band ranges only from 865MHz to 867M Hz. The IBM LoRa code for Arduino (as node) for RFM95 module allow you to choose between 915 Mhz and 868 Mhz only. I initially created a gateway using a Pi3 listening at 865.7 (to conform with Indian rules), but it couldn't receive any payloads from my node running at 868 Mhz. Then, eventually, I tried again with my gateway listening at 868 Mhz, and it worked like a charm. No hiccups.

But, obviously, it seems to be against the rules, and I don't fancy prison. So I want to know if I can get the RFM95 module working somewhere in the range of 865 Mhz to 867 Mhz? And if yes, how can I do it? There certainly doesn't seem to be an option to choose a frequency other than 868 Mhz or 915 Mhz in the IBM Lora code. Here is the link to the code library. https://github.com/matthijskooijman/arduino-lmic

title: RFM95 LoRa module frequency options

Answers: 1

body:
The RF networks of the RFM95 board are ideally configured for the general range of frequencies, but the difference between your 865.7 MHz and the 868 MHz tuning of a **European** (vs US) version of the board is likely smaller than the error with which the RF networks can be tuned to begin with, so that is unlikely to be a problem unless there is some hard lockout of your desired frequency in the SX1272 chip.  I've even heard claims that some people have managed to at least somehwat use US vs European tuned versions on the opposite bands, which is far more drastic than what you are trying to accomplish.

So assuming there is no hard lockout of your desired frequencies in the hardware, basically what you will need to do is to change the frequency list in the source of the software you are using to operate the module.

Basically you would edit `src/lmic/lorabase.h` and make a modified version of the EU configuration.  Ideally you'd add that as an additional option and select it, but for an initial test you could just edit the European version to fit your needs.

Do keep in mind the code will probably want to use multiple frequencies - if you have a gateway that receives only on a single frequency, you'll need to modify the code to always use that, after determining if doing so fits with usage-rate rules in your jurisdiction.

It's probably worth doing some online research to see if anyone has already put thoughts into operating LoRa in India - if so, there may already be a modified branch of the LMiC code you can use.