text:
Distance and Serial or SPI
I'm setting up a grid of 200+ slave modules which will be about 12 inches apart and the master will be anywhere from 5 to 10 meters away from the closest module. Each slave module will have a ATtiny85 to manage the sensor reading, LEDs and the network protocol.
The communication packets will be small and will probably be at 115200 baud if using ATTiny85's TTL serial or 1MHz if using SPI. In either case, the modules will be connected in a daisy chain to each other.
Each module will have a resistive touch sensor and be driving about 12 - 16 RGB LEDs (I'm making a step responsive disco dance floor). There will be 12v+ running to each module to drive the LEDs and regulated down to 5V for the ATtiny.
Which brings me to my question. With these constraints, do you think the ATtiny85's built-in serial or SPI would still work well over the 5 to 10 meters from the closest module to the master.
I know some people push towards RS422 or RS485 transceivers for distance applications, but I'd like to keep the total part count down, if possible.

I'm not sure SPI can work at all, since you would need 200 Chip-Select wires running from the master.

I would daisy chained the SPI connection between modules: http://www.maximintegrated.com/en/app-notes/index.mvp/id/3947

Just to be annoying... 115200 is about 10k bytes / sec. Divided by 200 is 50 bytes per second assuming your master is loading up the serial buffer and nothing else. If you have to wait for acks, etc that slows down things again. With daisy chain SPI there will be some delay getting to the 200th node, and getting a reply back. Why not try a tree topology, with routers that control a certain number of nodes. The routers can then communicate back to the master. Or instead of one ATtiny per tile, have one control multiple tiles with a led driver chip with lots of outputs, and multiplexed analog

inputs for the sensors. Sorry for the unsolicited opinion, I may have misinterpreted your design. :P

I have a few years working with DMX, SPI (and other serial) & LEDs. I have worked with DMX and a video dance floor for 10+ years previously. I would offer that "some people" are correct. You will get a reliable system with differential pair signalling (such as DMX).
I have found from experience that over 5m of unbalanced serial starts chancing it. Over 10m and you are likely to come up with at least reliability issues, but more likely garbage.
I have used the TI SN75176B driver a fair bit and is cheap and works.
Depends on your audience. You can afford to chance it for your bedroom, but not paid business.

Sounds like a fascinating project.
It sounds like the majority of signals are driven by one ATTiny85 and received by a neighboring ATTiny85 about 12 inches away, with a good ground connection between them.
Those signals can be directly connected.
If I were you, I would go ahead and get differential transceivers for the 10 meter distance.
If you use daisy-chain SPI, then you need 3 differential line drivers at one end of the cable and 1 differential line driver at the other (and the corresponding line receivers to match); plus GND and +12VDC.
If you use a SN75176BP as a line driver and another one as a line receiver for each SPI signal, that's a total of less than $8 for those 8 interface chips.
(You need fewer line driver chips if you somehow daisy-chain TTL UART serial, since it uses fewer pins, but requires each chip to have more precise baud clock).
The software should not even be able to detect the difference between a simple wire from the output pin of one chip to the input pin of the next chip, vs. a line driver, some twisted pair cable, and a line receiver between those same two chips running the same software.
Many people use the rule of thumb that if a bit time is less than 10 times the time it takes for something traveling at the speed of light to make a round trip from the transmitter to the receiver and back, then you must use differential signaling with line termination.
At 1 MHz, that gives a (1-way) cable length of 15 meters before you must use differential signaling with line termination.
So using the differential line drivers is probably overkill, but I'd rather have the first prototype work rather than cut corners on 100 things that I'm 99% sure probably won't matter, and then spend a lot of time debugging trying to figure out which one or two of those 100 things turns out that it does matter.
In addition to distance, loading might also be an issue.
In particular, the "CLK" and "/CS" pins from the SPI master apparently need to drive every SPI slave.
You can't really expect a single MCU output pin or even a single RS485 line receiver to be able to drive 200+ other chips.
A line driver or other buffer every 10 or so chips is more than adequate.
Related:
"What if the SPI signal lines are very long?"
(this experiment completely neglects the effects of interference from other noisy devices).
AN10364 "Transmitting the I2C signals as differential signals using RS-485 hardware"
(Like SPI, I2C signals were never intended to be transmitted long distances over wire cables.)
"Maximum Unterminated Network Speed Calculator"

Keep in mind that termination and differential signaling are two different issues.  Granted differential signals tend to be conceptually easier to terminate as it is obvious where the return path is, but the concept is applicable and advantageous with single-ended signals too.

@ChrisStratton: Yes. Termination helps prevent a signal from interfering with itself (round-trip bounce). Differential signaling helps prevent other stuff (including "ground noise") from interfering with the signal. Is there a better rule of thumb for deciding whether to use termination or differential signaling or both or neither?


text:
User callback functions
I want to write a class that allows the user to attach his own function to a member function that listens for messages coming from a wireless module, so that the user's function can be called depending on the message.
I am thinking about using function pointers but I don't know how it will work since I don't know the user's function parameters, return type and number of functions that will be added.
//sketch.ino

<unknown> (*funcPtr)(<unknown>)[<unknown>];

void receive() {
  message.type = 'o';
  if (message.available()) {
    message.receive();
  }
  switch (message.type) {
    case 'p': {
      Serial.println(p);
      break;
    }
    case 'f': {
      funcPtr[message.funcID](message.parameter1, message.parameter2);
      break;
    }
    default: break;
}

void userFunction1() {
  Serial.println("User function 1");
}

int userFunction2(int x) {
  return x * 2;
}

funcPtr[0] = &userFunction1;
funcPtr[1] = &userFunction2;

void setup() {}

void loop() {
  receive();
}

Is this kind of thing possible?

I don't know the user's function parameters,

A common way for dealing with this issue is to pass a generic pointer to
arbitrary data. See below.

return type

It makes little sense to allow for arbitrary return types, as your
library would have no way of knowing what to do with the returned value.

and number of functions that will be added.

Either you allocate the callback array statically with a fixed size, or
you use dynamic allocation. In the first case, the array size could be
decided by the user if it is a template parameter. In the second case,
you risk memory fragmentation unless all the callbacks are registered
once and for all at program startup, which is a common scenario anyway.

About the generic pointer technique
This is a very common way of defining callbacks in C: a callback
contains both a function and a void * pointer to arbitrary data, which
will be given as a parameter to the function. It is up to the user to
decide if and how he will use this pointer: he could completely ignore
it, like he could make it point to the root of a complex data tree.
Here is a simple example:
// A callback contains both a function and a pointer to arbitrary data
// that will be passed as argument to the function.
struct Callback {
    Callback(void (*f)(void *) = 0, void *d = 0)
        : function(f), data(d) {}
    void (*function)(void *);
    void *data;
};

Callback callbacks[3];

// This callback expects an int.
void print_int(void *data)
{
    int parameter = * (int *) data;
    Serial.println(parameter);
}

// This one expects a C string.
void print_string(void *data)
{
    char * parameter = (char *) data;
    Serial.println(parameter);
}

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

    // Register callbacks.
    static int seventeen = 17;
    static int forty_two = 42;
    static char hello[] = "Hello, World!";
    callbacks[0] = Callback(print_int, &seventeen);
    callbacks[1] = Callback(print_int, &forty_two);
    callbacks[2] = Callback(print_string, hello);
}

void loop()
{
    // Test all the callbacks.
    for (size_t i = 0; i < 3; i++)
        callbacks[i].function(callbacks[i].data);
    delay(500);
}

Notice that the two callback functions take different types of
parameters, only disguised into the same generic pointer. Notice also
that print_int is used in two different callbacks with different data.
In this example, the data does not change, but this need not be the
case: both the callbacks and the rest of the user code could change the
data pointed to by the generic pointers. Again, it is up to the user to
decide how he will use this facility to communicate between his
callbacks and the rest of his code.

Thank you for your answer and sorry for the delay. I modified it to take the address of the function, send it to the server (without saving it on the Arduino), then sending the address back from the server to the Arduino with information about how to recast it into function pointer.

You are a life saver my man!!!

You can't call arbitrary functions (with random return types, and any number of arguments) but you can specify a callback function that takes a certain number of specific arguments, and returns a certain thing (or nothing).
See http://www.gammon.com.au/callbacks
Example code:
typedef void (*GeneralMessageFunction) ();

void sayHello ()
  {
  Serial.println ("Hello!");
  }  // end of sayHello

void sayGoodbye ()
  {
  Serial.println ("Goodbye!");
  }  // end of sayGoodbye

void checkPin (const int pin, GeneralMessageFunction response); // prototype

void checkPin (const int pin, GeneralMessageFunction response)
  {
  if (digitalRead (pin) == LOW)
     {
     response ();  // call the callback function
     delay (500);  // debounce
     }
  }  // end of checkPin

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (8, INPUT_PULLUP);
  pinMode (9, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  checkPin (8, sayHello);
  checkPin (9, sayGoodbye);
  }  // end of loop

I don't know how it will work since I don't know the user's function parameters, return type and number of functions that will be added.

You will need to tell the user what sort of function to write. For example, a function that takes a string (ie. the message) and returns a boolean (whether it was handled or not).

Thank you for the answer, I went with the other method, because it was closer to what I needed.

source: Stack Exchange

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

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

sort: votes


text:
Defining object
I am trying to hide libraries behind another, for simplicity. But I can't deal with the objects required by the libraries. Basically I want to use the objects both in my .cpp and .ino file, but I am getting errors about double definition, or not declared in this scope.
test.ino
#include "lib.h"
#include "obj.cpp"

void setup() {
  mesh.setNodeID(40);
  mesh.begin();
}

void loop() {
  mesh.update();
}

lib.cpp
#include "Arduino.h"
#include "lib.h"

#include "obj.cpp"

int message = 1;

void send() {

  if (!mesh.write(&message, 'C', sizeof(message))) {

    // If a write fails, check connectivity to the mesh network
    if ( ! mesh.checkConnection() ) {
      //refresh the network address
      Serial.println("Renewing Address");
      mesh.renewAddress();
    } else {
      Serial.println("Sending failed, Test OK");
    }
  } else {
    Serial.print("Sent OK");
  }
}

lib.h
#ifndef lib_h
#define lib_h

void send();

#endif

obj.cpp
#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>
#include <EEPROM.h>

RF24 radio(7, 8);
RF24Network network(radio);
RF24Mesh mesh(radio, network);

#include "obj.cpp"

Don't include .cpp files. That gets them compiled twice (or more) and then you get duplicate definitions. Include .h files only.
What you are calling obj.cpp should probably be obj.h, however I haven't actually tried to compile it.

it says that I have multiple definitions of the three objects

I tried compiling but I don't have the RF24 library. Anyway, this is wrong:
obj.h
#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>
#include <EEPROM.h>

RF24 radio(7, 8);
RF24Network network(radio);
RF24Mesh mesh(radio, network);

You can't define things there (like radio) which get included in multiple files. obj.h or obj.cpp it will be the same thing.
These lines need to be in one .cpp file:
RF24 radio(7, 8);
RF24Network network(radio);
RF24Mesh mesh(radio, network);

Thus you cannot include that file in another file. However you can refer to them by making them extern in a header file, eg.
extern RF24 radio;
extern RF24Network network;
extern RF24Mesh mesh;

I changed obj.cpp to obj.h but it says that I have multiple definitions of the three objects: sketch\test.ino.cpp.o:(.bss.mesh+0x0): multiple definition of mesh' sketch\lib.cpp.o:(.bss.mesh+0x0): first defined here sketch\test.ino.cpp.o: In function setup':
D:\test/test.ino:4: multiple definition of radio' sketch\lib.cpp.o:(.bss.radio+0x0): first defined here sketch\test.ino.cpp.o: In function setup':
D:\test/test.ino:4: multiple definition of `network'
sketch\lib.cpp.o:(.bss.network+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1

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


text:
Compiling source with Arduino.h with avr-g++
How should I include the Arduino libraries when I'm compiling from the the command line? I tried to do it like this:
avr-g++ -g -Os -Wall -mcall-prologues -mmcu=atmega328p -fno-exceptions -o blink.obj blink.cpp -L. -lutil -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" -I"D:\Projects\Arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores"

but it returns undefined reference to the function that I am trying to use.
Arduino version: 1.8.2

You need to do a whole lot more than just run the one command.
You need to compile each individual source file for the libraries you want (using -c to just compile and not link), then (ideally) archive them into a library file. Do the same for the core. Then you need to add paths to your sketch compilation command pointing to where the header files are for those libraries, and compile the sketch to an object file (again with -c). Finally you need to link everything together into an ELF file, and convert that to a HEX file.
TBH you're best off using an already-existing Makefile project, or arduino-builder.


text:
How can I handle micros() double rollover?
I know that I can handle a single rollover with subtraction:
if (micros() - lastTime > period) {
  lastTime = micros();
  ...
}

But how it can be handled if this is not true or it is not checked for more than 70 minutes (without using uint64_t)?

What is the objection to using millis() if you are timing rather long periods?

I'm using my implementation of micros() and I don't want to implement millis() because it makes the ISR bigger. Also the precision.

So just to be clear, this is your version of micros you are asking us about? How about posting the code to it?

It's the same as Arduino's version except that in ISR(TIMER0_OVF_vect) there is a single variable increment. The code needs to run with as little interruptions as possible and I want to be able to run something with irregular long intervals.

It's the same as the Arduino version, except it's completely different, is that it? I gather this is top-secret code.

It is the same, and it has nothing to do with the question: `
#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )
volatile uint32_t timer0OverflowCount = 0;
ISR(TIMER0_OVF_vect) {
++timer0OverflowCount;
}
uint32_t us() {
uint32_t m;
uint8_t t;
uint8_t oldSREG = SREG;
cli();
m = timer0OverflowCount;
t = TCNT0;
if (((TIFR0 & (1 << TOV0)) && (t < 255))) ++m;
SREG = oldSREG;
return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
} `

What exactly is the problem? Do you want period to be more than 70 minutes?

If you want to measure times longer than 70 minutes with
micros(), you will have to use uint64_t, and there is nothing
wrong with that.

The code needs to run with as little interruptions as possible [...]

You don't need to do the 64-bit arithmetic within the ISR. You could
very well implement an interrupt-driven 32-bit version, and then extend
it to 64 bits in non-interrupt context. Example:
// Your ISR-based implementation.
uint32_t micros32();

// Extend to 64 bits.
uint64_t micros64() {
    static uint64_t time64;
    time64 += micros() - (uint32_t) time64;
    return time64;
}

This should work as long as you call micros64() often enough.
Presumably, you will have something like
if (micros64() - lastTime > period) { ... }
within your loop, so this should be no issue as long as you never block
your loop.
Actually, you can push this idea even further. If you can guarantee that
micros64() will be called at least once every 65.5 ms, then you
could have your ISR increment only a 16-bit counter.

Thank you, this will solve the issue. The last part will be a nice further optimization for my case.


text:
Using PROGMEM in constructor
Is it safe to use PROGMEM variable like dynamically allocated memory (a pointer to PROGMEM variable which is out of scope).
I need this so I can generate a variable size (before compilation), constant values, lookup array stored in flash.
Working example:
class Ex_class {
  public:
    Ex_class(int table_size, int value_range) {
      int flash_table[table_size + 1] PROGMEM;
      _ex_table = flash_table;
      for (int i = 0; i <= table_size; i++) {
        _ex_table[i] = random(value_range);
      }
    }

    int get_value(int index) const { return _ex_table[index]; }

  private:
    int* _ex_table;
};

void setup() {
  randomSeed(analogRead(0));
  Serial.begin(9600);
  Ex_class ex_object(5, 50);
  for (int i = 0; i <= 5; i++) {
    Serial.print(i); Serial.print(": "); Serial.println(ex_object.get_value(i));
  }
}

void loop() {}

I am amazed this even compiles... You cannot assign a value to a PROGMEM variable, the only thing you can do with PROGMEM is store compile-time constants. And you cannot dereference a pointer to PROGMEM with * nor [], you need one of the pgm_read_*() macros.

The compiler cannot run "Ex_class ex_object(5, 50);" at compile time.

I am surprised too, but it actually works.

It's probably getting the data from RAM that was allocated (and deallocated) in the stack.

You are right, it stored a new variable in the same address.

The closest I could get to what you are trying to do is this:
template <size_t table_size> struct Ex_class {
  int get_value(int index) const {
    return pgm_read_word(&_ex_table[index]);
  }
  int _ex_table[table_size];
};

void setup() {
  Serial.begin(9600);
  static PROGMEM const Ex_class<5> ex_object = {1, 2, 3, 4, 5};
  for (int i = 0; i < 5; i++) {
    Serial.print(i);
    Serial.print(": ");
    Serial.println(ex_object.get_value(i));
  }
}

void loop() {}

avr-nm and avr-objdump confirmed that the object lives indeed in the
text section of the program. Please note that:

The object is PROGMEM const. It would make no sense to try to put in
PROGMEM anything that is not constant.
The object is allocated statically. It can be either a global or a
static local, but not an automatic local like in your example.
I am using aggregate initialization here. I know no other way to
statically initialize an array of variable length. If you have an
idea, I would be interested to know though.

Thanks. The only thing I can think of is initializing the flash variables separately (because they need to be calculated) and then putting the pointers to them in an array. It shouldn't be a problem since the flash is read-only.


text:
Set the timeout - Ethernet Shield library
Does anyone know if you can set the time for the timeout Ethernet Shield library? Let me explain:
I created a very simple function (below) that attempts to connect to an address if it is not accessible returns 0 if it is available returns 1. Problem is that when the site is not available, the microcontroller is waiting for an answer for a long time, wanted to reduce it.
uint8_t ping(const char* address)
{
    EthernetClient http;

    if(http.connect(address, 80)) {
        http.stop();
        return 1;
    }
    else
        return 0;
}

In the stream class there is a setTimeout(ms) function. e.g.
String str;
Serial.setTimeout(5000) ;
str = Serial.readStringUntil('\r');

Where this does timeout the initial connection attempt in http.connect(). Whereas I found it also important to timeout each line, as a web page may not disconnect at the end or not send anything.
int httpGetHeaders() {
  String request, response;
  int result = 0;
  long startOfHttpResponseTime;

  client.setTimeout(1000) ;
  response = "";
  inHeaders = true;
  startOfHttpResponseTime = millis();
  while((client.connected()) && inHeaders && ((long)(millis() - startOfHttpResponseTime) < HTTP_RESPONSE_TIMEOUT)) {
    String header = client.readStringUntil('\n');
    header.trim(); // trim off white spaces including CR and LF at end.
    Serial.print(F("head["));
    Serial.print(header.length());
    Serial.print(F("]:\""));
    Serial.print(header);
    Serial.println(F("\""));
    if (!header.length()) { // first blank line indicates end of headers
      inHeaders = false;
      Serial.println(F("No longer in Headers"));
    }
    else {
      if (header.startsWith("HTTP")) {
        Serial.println(F("HTTP Found"));
        int firstspace = header.indexOf(" ");
        result = header.substring(firstspace + 1, header.indexOf(" ", firstspace + 1)).toInt();
        Serial.print(F("result = "));
        Serial.println(result);
      }
    }
  }

  Serial.print(F("Result code = "));
  Serial.println(result);
  return result;
}

You may want to review the whole code at https://github.com/lansing-makers-network/StatusBotArduino/blob/master/StatusBotArduino.ino I have reduced the connection to a sequence of commands that can be used consectutively in the desired order to meet different needs. The above is just to read a headers response.


text:
Error while saving data in text file
I created a function that saves the timestamp in a text file, but it saves unreadable. Full of invalid characters, example: Ÿ@Â   O   ƒº!¥ Ÿ@Â   O   ƒº!¥ Ÿ@Â   O   ƒº!¥ Ÿ
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include "RTClib.h"

RTC_Millis rtc;
File txt;
const char * getCurrentTimestamp()
{
    char dateBuffer[40];
    DateTime now = rtc.now();
    sprintf(dateBuffer,"%02u-%02u-%04u %02u:%02u:%02u", now.day(), now.month(), now.year(), now.hour(), now.minute(), now.second());
    return dateBuffer;
}

void saveLog()
{
  txt = SD.open("dados.txt", FILE_WRITE);
  txt.print(getCurrentTimestamp());
  txt.close();
}

void setup() {
  pinMode(53, OUTPUT);
  SD.begin(4);
  Serial.begin(9600);
  rtc.begin(DateTime(F(__DATE__), F(__TIME__)));
}

void loop() {
  Serial.println(getCurrentTimestamp());
  saveLog();
  delay(1000);
}

My code is very simple, do not understand where I went wrong. if I copy the following code snippet for saveData() function and save the dateBuffer variable, everything works normally.
char dateBuffer[40];
DateTime now = rtc.now();
sprintf(dateBuffer,"%02u-%02u-%04u %02u:%02u:%02u", now.day(), now.month(), now.year(), now.hour(), now.minute(), now.second());

how to save the timestamp correctly in the file through the function getCurrentTimestamp() ?

Your function, getCurrentTimestamp() saves the date string in an automatic variable - it is on the function's stack frame which gets freed as soon as that function returns. Either Serial.println() or savelog() is overwriting it.
The proper way to do what you're trying to do is to make the buffer live for the duration of both function calls. One way is to use a global buffer. Another is to declare the buffer in loop() and pass it to both functions.

As far as I know you should use
text.write(getCurrentTime());

That because (if I'm not wrong) you need to send it as ASCII characters so the text editor will be able to read them in the right way.


text:
Set dynamically hour - DS1307
I want keep my RTC1307 always updated with my server, so I created this code to first search the time on the server then passes to getServerTime() function to divide it and set in the RTC. I use the rtc.adjust() to adjust my watch.
Problem: My watch is getting wrong, this is set 2165/165/165 165:165:85. I think the problem is in defining the time in rtc.adjust(), I'm going as follows:
//tempDate -> May 19 2015
//tempHour -> 09:25:14
rtc.adjust(DateTime(tempDate, tempHour));

Does anyone know the cause of this error?
#include <Ethernet.h>
#include <SPI.h>
#include <Wire.h>
#include <RTClib.h>
RTC_DS1307 rtc;

byte server[] = { 192, 168, 0, 8 };
byte ip[] = { 192, 168, 0, 237 };
byte mac[] = { 0xDE, 0xAD, 0xAD, 0xEF, 0xFE, 0xED };

void setup() {
    Ethernet.begin(mac, ip);
    Serial.begin(9600);
}

void loop() {
    getServerTime(getSiteData());
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    Serial.println();
    delay(5000);

}

char * getSiteData()
{
    EthernetClient http;
    unsigned char startRead = 0, i = 0;
    char inString[50];

    if (http.connect(server, 80)) {
        http.println("GET /util/date.php HTTP/1.1");
        http.println("Host: ");
        http.println("Connection: close");
        http.println();

        while (http.connected()) {
            while (http.available()) {
                char c = http.read();

                if (c == '<' )
                    startRead = 1;

                else if (startRead) {

                    if (c != '>') {
                        inString[i] = c;
                        i++;
                        inString[i] = '\0';
                    } else {
                        startRead = 0;
                        http.stop();
                        http.flush();
                        return inString;
                    }
                }
            }
        }
        Serial.println(inString);
        http.stop();
        http.flush();
    }
    else
        Serial.println("Tentativa de conexão falhou. Sem internet ou servidor inacessivel");
}

//May 19 2015-09:17:24
void getServerTime(char* siteData)
{
    char *tempDate, //May 19 2015
        *tempHour; //09:17:24

    tempDate = strtok(siteData, "-");
    tempHour =  strtok(NULL, "-");

    rtc.adjust(DateTime(tempDate, tempHour));

}

As long as the string you are getting is exactly what you think it is, then that should be working.  I suspect that tempDate and tempHour don't contain exactly the right data.  Print it to serial surrounded by some markers (maybe "[" and "]") to ensure that it is exactly what you expect it to be.

Do you get the difference between  binary-coded decimal (BCD) and regular decimal values?

The numbers reported are typical of the time coming out as -1 or something like that.

I performed a debug and the string no contains  LF+CR, LFCR, CR+LF or CRLF

How about rogue spaces?

The numbers you are reporting are very familiar to me.  They are telling me that it is not possible to obtain the time from the RTC chip.
You are getting the time from your server, and as long as the string is actually what you think it is, then the values should be fine.  This snippet works perfecty:
#include <RTClib.h>

char siteData[] = "May 19 2015-09:17:24";

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

    char *tempDate = strtok(siteData, "-");
    char *tempHour =  strtok(NULL, "-");
    DateTime now(tempDate, tempHour);

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    Serial.println();
}

void loop() {
}

So it must be in the passing of the data through the RTC chip that is failing.
Check that the chip is actually wired up properly, is running, and is responding normally before you try adding in the code to set the time from the server.

I forgot -> Wire.begin();   RTC.begin();

That'll do it ;)


text:
Will a magnetometer give distorted values if there is a magnet near?
I am not entirely sure how a magnetometer works in IMU units, so I was wondering how a magnet near the sensor affects readings?

Will a magnetometer give distorted values if there is a magnet near?

Yes, effectively.
In fact no, as the reading it gives WILL BE the field at that point BUT the field will be distorted compared to what you would see when the magnet is absent.
The effect of magnets at a distance is a somewhat complex subject - especially when there are several presnt and/or where ther are "magnetic materials" present but, as a guide.

At a distance large compared with magnet dimensions the field falls as the cube (not square) of the distance.
Very rough but useful rule of thumb: A top-end rare earth magnet will produce a field of about 1 Tesla at a distance of  1/2 it's thickness from the centre of its pole face. So eg a 20mm thick circular magnet will produce ABOUT 1 T at 10mm from the centre of its pole face. This is more useful in motor or alternator applications than when using magnetometers.

So are you saying if the magnet stays in the same place in relation to the magnetometer, the reading with be quantitatively different, but qualitatively usable, as it always reflects a relative change? If this is so, presumably moving the magnet's position would then change the magnet field distortion and consequently distort the readings entirely?

@Kontur I wasn't specifically saying that but it may be true. I do not know what magnetometer you are referring to or the application or general environment - but as you note - you may be able to make use of the vector sum of magnet + desired field. Whether this is usable may depend on relative strength and field directions. If the desired field is the earth's field then relative  X Y Z angles will probably be affected equally. If it was from a low power local source then the x y z vector sums may now be at new and different angles and interpretation my be difficult.

As MAC notes -  saturation MAY occur.

The IMU magnetometer is made to measure the magnetic filed of the earth, which magnitude is a few 10 - 60 uT (micro-Tesla). You cannot measure it near to a large magnet that may generate 1 T or more: the magnetometer will saturate.


text:
I2C hookup - sketch just crashes
I am encountering problems with I2C when trying to attach a 9DoF Sensor to my Arduino Uno. Following these instructions (the hardware setup I have is like in the schematic) I noticed the basic example not working. I've since debugged different aspects and when I use the "I2C Scanner" example from this page it seems something basic with I2C must be wrong. The code from there I am using is:
// I2C Scanner
// Written by Nick Gammon
// Date: 20th April 2011

#include <Wire.h>

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

  // Leonardo: wait for serial port to connect
  while (!Serial)
    {
    }

  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;

  Wire.begin();
  for (byte i = 8; i < 120; i++)
  {
    Wire.beginTransmission (i);
    if (Wire.endTransmission () == 0)
      {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");
      count++;
      delay (1);  // maybe unneeded?
      } // end of good response
  } // end of for loop
  Serial.println ("Done.");
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");
}  // end of setup

void loop() {}

Instead of this suggested sample output:
I2C scanner. Scanning ...
Found address: 42 (0x2A)
Done.
Found 1 device(s).

The output I am getting is in Serial monitor on the correct baud rate is:
ù
I2C s

With other examples I have tried I have similar results. As soon as something calls Wire.endTransmission() things start to crash and burn.
Any ideas what this could be or how to debug it?

Have you tried using a slower serial comms rate - ie: 9600 baud? That looks like lots serial bits. I would also add an LED heartbeat and boot indicator (flash pin 13 5 times quickly first thing in setup()) so you can detect resets or hangs easily)

Wire.endTransmission() is where the action is. Nothing is actually sent until that point. Wire.beginTransmission just gets ready for sending and Wire.write (if used) adds stuff to an internal buffer.
If it hangs at that point you probably have dodgy hardware. Check the connections are correct (ie. SDA/SCL the right way around, and that it is powered, and that you have a common ground).
Then try a pull-up resistor between SDA and +5V, and SCL and +5V. A typical value resistor (for both resistors) would be 4.7k.
I see from the linked page that the board already has 10k resistors. Hopefully you did not cut the jumper links. Whether or not you did you might want to augment them with 4.7k resistors. Also keep the cable runs short.


text:
Capacitive sensor touch detection on wearable
I have a wearable wristband project where I'd like to detect a touch to the outside of the wristband, like a button. However, all my attempts to get this to work with capacitive sensing fail.
The problems accumulate from these aspects:

Without grounding, the behaviour seems totally arbitrary at times
I need high response times (12 fps so < 100ms), so some resistor values keep hitting the timeout limit
Testing is really hard, as behaviour changes after unplugging the USB connection to the computer. I have a bluetooth connection in the Arduino and debug via bluetooth connection to get a "actual scenario" type of reading
I've also tried things like setting very short timeouts as well as low sample sizes as well as experimented with different resistors

However, I am not trying to really get any sort of gradual "capacitive sensing" here at all, I merely would need to detect a threshold for "is touching". In fact, the area that the user is touching could even be made out of metal (which it was in my tests so far) and touched directly (so nothing in between finger and metal).
This seems like such an obvious thing to try to achieve, I believe there must be some way to get this done. Any ideas?

Could you put some metal on the inner side of the wristband? This would allow you to use the user's body as a ground.

@EdgarBonet It should be possible. You reckon this would help? How would this work without resulting in a "full" contact being detected all the time?

This still would need testing. But for sure having a closed circuit is
needed. C.f. my answer below.

Expanding on my previous comment:
You can think of capacitive sensing as a form of impedance measurement,
even though it's more a threshold detection than an actual measurement.
In order to perform an impedance measurement, you have to build a
circuit like this:
┌─────────┐           ┌───────────┐
│         ├───────────┤           │
│  meter  │           │ impedance │
│         ├───────────┤           │
└─────────┘           └───────────┘

The important thing in this figure is that you need two electrical
contacts in order to close the circuit. The lower contact is often
provided by a common ground, but since your wristband is not properly
grounded, you will have to provide it by some other means.
My suggestion is to have two electrodes on the wristband: a lower
electrode in permanent contact with the user, and an upper electrode
that will be the touch button. If both electrodes are exposed metal,
then you have a full DC path all around, and this is not “capacitive”
sensing any more. Depending on how your sensing is done, this may not be
a problem, and it may be detected just like an infinite capacity.
If you want to avoid a full DC path, you can have one of the electrodes
covered by a thin layer of dielectric. Or even both, but then you have
two capacitors in series and need twice the sensitivity.


text:
RS-232 is a protocol or a cable?
RS-485 and RS-232 are a type of communication protocol or a type and cable?
I studying these serial communication protocols and each place refers to the RS-232 / RS-485 in different ways. Some articles mention that it is a cable, the other a protocol, so I was in doubt.

RS-232 etc mean different things in different contexts.  More specifically it is called TIA/EIA-232.
It refers to both the electrical characteristics of an NRZ signalling system, and at the same time it refers to the packet format for the transmission of data through such a system.
It also refers to the connectors that are used with such a system and, by extension, the cables that have those connectors on them.

The standard defines the electrical characteristics and timing of signals, the meaning of signals, and the physical size and pinout of connectors. The current version of the standard is TIA-232-F Interface Between Data Terminal Equipment and Data Circuit-Terminating Equipment Employing Serial Binary Data Interchange, issued in 1997.

RS-485, or TIA/EIA-485, in contrast only specifies the electrical characteristics and not the data that is sent down the line. It doesn't specify any connectors to use, nor what format the data should take. For instance you can use RS-232 formatted packets, or you could use a MODBUS-RTU format that uses completely different packets. It only refers to the drivers and voltages used.

TIA-485-A, also known as ANSI/TIA/EIA-485, TIA/EIA-485, EIA-485 or RS-485, is a standard defining the electrical characteristics of drivers and receivers for use in balanced digital multipoint systems.


text:
create a interruption-proof power
I need to create a interruption-proof power for a project of mine, very similar to the design of this link.
My problem is that I need to adjust the current delivered of the solar panel (21V, 1.2A) to 5V and simultaneously charge a battery 12V, 18Ah. If the solar panel does not supply power, the battery takes its place.
Does anyone know any circuit to do something? Or can someone give me a light as do something?

See @Jon's recommended Sparkfun charger - this can be adapted to 12V operation (set to 13.7V) by changing  R7 in Sparkfin's circuit diagram. Some other changes will be needed but the IC is made to work with both LiIon and Lead Acid batteries. **LT3652 data sheet here

Rough block diagrams below show two ways this can be achieved - "Easiest" costs least but is inefficient. "Better" uses PV panel output more efficiently. Details of either can be discussed if of interest.
'Schottky diodes' should be used to minimise losses.
(1) "Easiest"
Connect PV panel to battery with diode.
Panel is clamped to battery voltage (+ diode drop).
This will not hurt the PV panel but wastes some of the available power.
[What is the formal PV panel specification. Is it 21V O/C or loaded or .... Do you have a datasheet link for it?].
Use 12V (nominal) to 5V converter to power load.
This could be

A linear regulator - only about 40% efficient - very wasteful.
A buck converter (build or buy from eg ebay)

(2) "Better"
Use a buck regulator to charge the battery - ideally an MPPT (maximum power point transfer) controller. Details can be discussed if you are interested.
Use a second buck regulator to power the load. This must be capable of (at least) 11V to 22V input. Power this from a Schottky diode from the PV panel AND a Schottky diode from the battery. When the panel voltage is > battery voltage the panel will power the load.

As a supplement, there are pre-made buck regulators specifically designed for all of your requirements; i.e. micro-power (solar/wind/vib), charge the battery when it's able, use the battery at night, etc.   An example MPPT (for a single-cell lipo) https://www.sparkfun.com/products/12885

@Jon The LT3652 that Sparkfun use is quite a good match to this application. It is able to be adapted to a 12V SLA battery by a resistor change and Vin of 32V is high enough. | The MPPT method used is proxy one - they hold V_PV at some fraction of V_PV_OC BUT they claim to get within 2% o true MPPT. (I've meant to try these for some while but not yet done so).

I wish Sparkfun would give me free samples like Linear does :)


text:
Arduino running at 8MHz with external crystal
I want to use my Atmega328P in 8MHz, but I noticed that the internal clock is not as accurate and cause problems in my application. To add an external crystal 8MHz I do like the image below or 22pF capacitors are only necessary when I use a 16MHz crystal?

You need to use the capacitors as this helps the signal generated by the crystal to be stable. If you do not use them, it will be worse than the internal clock basically.

You need to use the correct capacitors. The capacitors to choose depend on the crystal. Read the datasheet.

If you want to keep your componenet count down- then you may want to consider a resonator instead of using crystals and capacitors

@qwerty10 Resonators aren't that much better than the internal RC clock source. Yes, they can be faster, but no more accurate. Personally I don't use either. I use MEMS clock chips now - usually the ASEMB range from ABRACON.

@Majenko My interpretation of the question is  seemed to  impliy that the OP wanted to use as few components as possible so I suggested using a resonator. In my experience Ive found resonators to be accurate. But it would depends on the situation of course how accurate the clock pulse is to be required which only the OP really knows. Yes you can use a clock chip too-sometimes found in old epson printers-which is what you seem to be referring to.

@qwerty10 I highly doubt that old Epson printers used MEMS® clock chips. They are a very recent invention.

@Majenko Thats why I said seem to be referring to. Maybe its more accurate if I said the following. You can get clock chips or subcircuits in Epson usb printers (that can be reused)  and maybe there made by ABRACON. It a long time since I looked inside epson printer to fix it so Im not totally  sure.

This is a board I am at the prototyping stage with now. The MEMS® clock chip is the small one immediately south-west of the main chip. I think you are referring to the old crystal oscillator modules - the big metal 4-pin cans.

What you trying to make overall? I recall there was a small clock chip in the printers-it had maybe up to 12 pins. It had its own battery supply in the printer control circuit. I dont recall if it used an external  crystal. If I can remember all the details I'll let you know. Basically it was a way to save money by reusing that part of the printer circuit.

That sounds like either a clock generator chip (needs a crystal with it) or a clock management chip (takes a clock from elsewhere and creates other clocks from it). Still, 12 pins is 8 too many...

It was a self contained clock circuit (if you cut it out from the PCB) yes the number of pins was up to 12, so could have been less-simply dont recall now as it was so long ago. What are the other chip names in your circuit?

I could understand your circuit design if you explained it all. Part names and so on.

Yes, you require the capacitors, and the capacitors have to be the right value for your crystal.
The datasheet will specify a load capacitance which you use in the following formula:
C1 = C2 = 2(CL - C_STRAY)

That is, the load capacitance of the crystal, minus the stray capacitance from your circuit (as long as your traces are short that is negligible and can be largely ignored unless you have very very tight timing requirements) multiplied by 2.
So for 22pF capacitors it is safe to assume that the crystal that is with them has a load capacitance of 11pF.
So check the datasheet for the load capacitance (it should be very prominent) and select the correct capacitors accordingly.
If you want to do away with the capacitors and your timing requirements aren't that precise you may get away with a ceramic resonator which doesn't require capacitors.
Another option is to use a MEMS® clock chip which generates a stable clock signal at a pre-set frequency. While this doesn't require capacitors for the clock signal it does still require a decoupling capacitor on the power supply for it, but of course that doesn't affect the timing of the clock signal, so precise selection of a specific value isn't needed.

When would stray capacitance or stray inductance be significant if the 22pf capacitance was made from a number of capicitors connected in a combination of series and parallel to make up a 22pf capacitance? E.g. use two 44pf capacitors in series to make 22pf-and two 11pf capacitors for another 22pf-but it could be a lot more complicated than that-such as using lower values e.g. 1pf capacitors.

This crystal here has 18pF capacitance, then I need two 36pF capacitors. Is correct? http://br.mouser.com/ProductDetail/ABRACON/ABLS-8000MHZ-B2-T/?qs=sGAEpiMZZMsBj6bBr9Q9aUe%252bp9Tek3UMgyOb46u0oQg%3d

Yep, that is correct.

it would be interesting to know a good answer to the question I made in the comment above.

I am sorry, I do not understand the question.

I would guess it to be yes there is a threshold where it becomes significant for my question in the comment. I got the idea for the question when trying to make a value for a capacitance from other capacitors.

It all depends what you are doing and how important the timing is to whatever it is you are doing.

And my question in the comment was referring to values such as - C_STRAY

I am sorry, you have completely lost me now. Go back to shining lasers at each other to try and make a yellow dot in mid air.

That's a Majenko style, end of this conversation then.


text:
using seek() in Arduino to go to the end of a variable-sized file
Anyone know how to use the seek() function of Arduino SD Library to position pointer at the end of a file?
If programming in Windows do something like:
void fileInsert(char *file, void *data, size_t len) {

    FILE *filePtr;

    if ((filePtr = fopen(file, "rb+")) == NULL) {
        printf("Arquivo %s não pode ser aberto.", file);
        exit(EPERM);

    } else {

        fseek(filePtr, 0L, SEEK_END);
        fwrite(data, len, 1, filePtr);
        fclose(filePtr);
    }
}

But the Arduino does not have the SEEK_END

You can only seek to an absolute position from the start of the file.  Fortunately there is the size() method that can tell you where the end is, though.
file.seek(file.size());


text:
FastLED and Neopixel Help
I'm in the process of trying to create a "Aurora Glow" effect using a Particle Photon and a Neopixel ring.
I have the code fully working using a single Breadboard-friendly NeoPixel however when upgrading this to a NeoPixel Ring (16 LED) the code does not run as expected
The current working code for a single NeoPixel can be found here: http://pastebin.com/Yj1cywpx
It was my assumption that i could change Line 33 from one LED to Sixteen e.g.:
FastLED.addLeds<NEOPIXEL, 6>(&led, 1);

to
FastLED.addLeds<NEOPIXEL, 6>(&led, 16);

However when I run this code rather than all NeoPixels cycling through the Aurora Colours, only the very Top LED does and rest are either off or a static colour (e.g. https://i.sstatic.net/6rY38.jpg)
Could someone please advise what i missing? Apologies if this is a "Noob" question but this is my 2nd Arduino project and I cannot understand why this would not work.
Thanks

Never used neoPixels in arduino before so this is a complete guess based on reading the code but it looks like you are only setting the colour of the first LED.
Try creating 16 LED colours:
CRGB led[16];

and then setting them all:
for (int i = 0;i<15; i++) {
  int colourIndex = index + i;
  if (colourIndex > 15)
    colourIndex -= 15;
  led[i] = ColorFromPalette(auroraPalette, colourIndex , 255, LINEARBLEND);
}

edit - as @rDg indicates in his answer
FastLED.addLeds<NEOPIXEL, 6>(&led, 16);

becomes
FastLED.addLeds<NEOPIXEL, 6>(led, 16);

since led is now an array not a single value
Finally I think paletteSize should only be 16 not 5*16, you only have 16 colours in there.

Thanks Andrew for a swift response i will make the changes and let you know! Thanks again

Hi Andrew,
When editing the void loop() to use the for loop i get:
ringtest.cpp:41:6: error: 'i' was not declared in this scope
do i need to declare this at the top of the script?
http://pastebin.com/8FaDdzLW
Thankyou again for your help

You need to declare it somewhere for (int i=0;... would work fine. I'll update the original answer...

In addition to the above, you need to tweak your addLeds line:
FastLED.addLeds<NEOPIXEL, 6>(led, 16);

That's confusing.  I'm not sure why stackexchange is currently ordering your answer first.   But, if I may, I think it would be clearer to say  "In addition to @Andrew's answer, you need to tweak your addLeds line".  Yes, I agree, it is no longer a variable but an array and no longer needs the ampersand.

@rDg Thankyou for your comment i have since removed the ampersand.
Taking yours and Andrews comments into account i have modified my script. Changing the if statemnet to use Andrews For loop. Getting errors compiling but working on the issues: http://pastebin.com/8FaDdzLW
Thanks for your help

@4dogsofwar You seem to have removed most of the code from your loop() code. The for loop in my changes only replaced the single line that was setting the value of led, with code that set all 16 values. You still needed the other lines that were in your loop(). Something like this http://pastebin.com/5N1dEYTv

@Andrew. Apologies this was my mistake i wasnt 100% sure. I have edited the code (http://pastebin.com/nGgUXw9B) and it complies successfully :D I Will test and run the code when I'm home.
I would like to thank you for bearing with me and your hard work, its been a very good learning exercise!


text:
ATmega328PB Sleep Mode Current Consumption
I am using an ATmega328PB to run an RF module. When testing sleep mode current consumption, I noticed it was much higher than I expected. I took off all unnecessary components. The only things in the circuit are: ATmega328PB chip, a Pull-Up resistor between VCC and RESET pin, 10uF and 0.1uF capacitors between VCC and GND; the circuit boils down to the schematic below.

I'm running the chip at 8MHz internal and 3.3V. I have tried using the power_all_disable() function, setting all my pins up to be input pull-ups, setting the clock prescalar to clock_div_4, calling sleep_bod_disable() and I'm setting sleep mode to be Power Down mode. The datasheet(sec 33.3 page 352) says that the chip should use 3.2uA in this mode, but I'm measuring 110uA. Since my clock frequency is higher than the suggested 4MHz at 3.3V, I expect current consumption to be larger but not by this much. Here is all the code that I'm running.
void setup(){
    delay(2000) //just so i can compare current levels (4.8mA before sleep)
    power_all_disable();
    power_adc_disable();
    power_spi1_disable();
    power_spi_disable();
    power_timer0_disable();
    power_timer1_disable();
    power_timer2_disable();
    power_twi_disable();
    power_usart0_disable();
    for(uint8_t i = 0; i < 27; i++){
      pinMode(i, INPUT_PULLUP);
    }

    ADCSRA &= ~(1 << ADEN);
    ADCSRB &= ~(1 << ADEN);
    clock_prescale_set(clock_div_4);
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_enable();
    sleep_bod_disable();
    sleep_mode();

    while(true);
}

loop(){

}

I'm measuring by hooking up a multimeter in series between my power source and my circuit. I know this may add a load to the circuit and therefore drive the current up, but the circuit I'm using as a reference is a different version of this module using an ATmega324P chip, which measures around 40uA in sleep mode through the same multimeter setup. If I could reduce my current consumption to about ~50uA through this setup it would be enough.
EDIT:
I compiled that same code above for an ATmega324PB and uploaded it onto the board I was using as a reference. It draws the same as the ATmega328PB (110uA). When I upload the old code that was present on it it drops down to 14uA. This very strongly suggests it is a software issue instead of hardware. Unfortunately the code is long and old, and not organized very well. Plus it's written in Atmel Studio which means I can't just move it all over to arduino, or move my arduino sketch to Atmel.
When trying to slowly deconstruct the code to figure out the difference, I found that commenting out a specific line:
//enable SPI, set as Master, set clock rate fck/8 = 500kHz
SPCR1 = (1 << SPE) | (1 << MSTR) | (1 << SPR0);

The device seemingly no longer sleeps. However in this case the current draw remains around 2.8mA and not the 110uA that my program produces.
Another thing I've noticed that I now believe could be the issue, is that while the chip is active (i.e. not asleep), my program has it running at 2.9mA vs the older code running it at 2.8mA. this 0.1mA difference is the same difference in sleep modes, which to me suggests that my code for some reason has something that is always on, where the older code does not / disables it, but I have no clue what.

Note that the ADEN bit belongs to ADCSRA, not to ADCSRB. 2. Could you try the recommended practice for sleeping with BOD disabled?

@EdgarBonet 1. I changed it to ACME although it made no difference.  2. The only difference is mine included an extra call to sleep_enable() after sleep_bod_disable()which shouldn't matter, but I did it anyway (no change in current)

This isn't the code you are running because it doesn't compile. There should be a semicolon on the sleep line, and void before loop.

Where did you purchase the ATMEGA328PB ? There are tales of "clone" ATMEGA328P devices which have higher than normal power consumption in sleep modes. These are sometimes fitted to boards such as the Pro Mini. Maybe there are also "clones" of the "PB" variant in circulation.

Running your code as a benchmark on my Atmega328P I got the following:
15 mA, then dropped to 141 µA.
However the following code:
#include <avr/sleep.h>
void setup() {
  delay(2000); //just so i can compare current levels (4.8mA before sleep)

  for (uint8_t i = 0; i < 27; i++) {
    pinMode (i, OUTPUT);
    digitalWrite(i, LOW);
  }

  // disable ADC
  ADCSRA = 0;

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  noInterrupts ();           // timed sequence follows
  sleep_enable();
  // turn off brown-out enable in software
  MCUCR = bit (BODS) | bit (BODSE);
  MCUCR = bit (BODS);
  interrupts ();
  sleep_cpu();

  while (true);
}

void loop() {

}

.. gave me 15.6 mA, then dropped to 0.128 µA (128 nA).

Turns out power_all_disable() and power_adc_disable() don't actually turn off the ADC, because as soon as I turned it off myself via register (I did ADCSRA &= ~(1<<ADEN); instead) the power dropped all the way down!

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


text:
Loop buzzer through 12khz too 20kz and show on LCD 1602 display with breadboard button and serial cmd
Well the title is the summary of my setup and its to see if it cancels out my tinnitus lol it actually does :)
well I made progress with what you said, I can turn on my LED and loop through the Hz on the buzzer and LCD with the use of a serial command like "on 15000 200 20 255". The breadboard button also turns off and on if it gets too loud. It still doesnt like the python script for DOS cmd line though.
please help.
This is my updated code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

const int ledPin = 13;  // Pin connected to the LED (built-in LED)
const int buttonPin = 2;
const int buzzerPin = 9;
unsigned long previousMillis = 0;
long interval = 100;
int frequency = 12000;
int duration = 10;
int volume = 128;
bool buttonPressed = false;
bool buzzerActive = false;  // Initialized only once

void setup() {
  pinMode(ledPin, OUTPUT);  // Set the LED pin as an output
  Serial.begin(9600);  // Start serial communication at 9600 baud rate
  Serial.println("Enter 'on' followed by parameters (frequency, interval, duration, volume) to turn the LED, LCD, and buzzer on, and 'off' to turn them off.");
  Serial.println("Example: on 15000 200 20 255");

  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Hz: OFF");
  lcd.setCursor(0, 1);
  lcd.print("Ear pop MH help");

  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buzzerPin, OUTPUT);
}

void led_lcd_buzzer_change(String command) {
  Serial.println("Received command: " + command);  // Echo the received command

  command.trim();  // Remove any trailing whitespace
  if (command.startsWith("on")) {
    // Parse additional parameters if present
    int firstSpace = command.indexOf(' ');
    if (firstSpace != -1) {
      String params = command.substring(firstSpace + 1);
      int secondSpace = params.indexOf(' ');
      if (secondSpace != -1) {
        frequency = params.substring(0, secondSpace).toInt();
        params = params.substring(secondSpace + 1);
        int thirdSpace = params.indexOf(' ');
        if (thirdSpace != -1) {
          interval = params.substring(0, thirdSpace).toInt();
          params = params.substring(thirdSpace + 1);
          int fourthSpace = params.indexOf(' ');
          if (fourthSpace != -1) {
            duration = params.substring(0, fourthSpace).toInt();
            volume = params.substring(fourthSpace + 1).toInt();
          } else {
            duration = params.toInt();
          }
        } else {
          interval = params.toInt();
        }
      } else {
        frequency = params.toInt();
      }
    }

    digitalWrite(ledPin, HIGH);  // Turn the LED on
    lcd.setCursor(0, 0);
    lcd.print("                ");
    lcd.setCursor(0, 0);
    lcd.print("Hz: ON");
    Serial.println("Hz is ON");

    buzzerActive = true;
    tone(buzzerPin, frequency, duration);  // Start the buzzer with current settings
    lcd.setCursor(4, 0);
    lcd.print(frequency);
    lcd.print("Hz  ");
    Serial.println("Buzzer started with frequency: " + String(frequency) + ", interval: " + String(interval) + ", duration: " + String(duration) + ", volume: " + String(volume));

  } else if (command == "off") {
    digitalWrite(ledPin, LOW);  // Turn the LED off
    lcd.setCursor(0, 0);
    lcd.print("                ");
    lcd.setCursor(0, 0);
    lcd.print("Hz: OFF");
    Serial.println("Hz: is OFF");

    buzzerActive = false;
    noTone(buzzerPin);
    lcd.setCursor(4, 0);
    lcd.print("Off       ");
    Serial.println("Buzzer Off");
  } else {
    Serial.println("Invalid command. Please enter 'on' with parameters or 'off'.");
  }
}

void loop() {
  if (Serial.available() > 0) {  // Check if there's any data available from the serial port
    String command = Serial.readStringUntil('\n');  // Read the incoming string until a newline character
    command.trim();  // Remove any trailing whitespace
    led_lcd_buzzer_change(command);  // Call the function and pass the command
  }

  // Handle button press
  if (digitalRead(buttonPin) == HIGH) {
    buttonPressed = false;
  } else if (digitalRead(buttonPin) == LOW && !buttonPressed) {
    delay(50); // Debounce the button press
    buttonPressed = true;
    if (digitalRead(buttonPin) == LOW) {
      if (digitalRead(ledPin) == HIGH) {
        led_lcd_buzzer_change("off");
      } else {
        led_lcd_buzzer_change("on");
      }
      delay(250); // Prevent rapid toggling
    }
  }

  // Handle the buzzer frequency update if it is active
  if (buzzerActive) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      tone(buzzerPin, frequency, duration);
      lcd.setCursor(4, 0);
      lcd.print(frequency);
      lcd.print("Hz  ");
      frequency += 100;
      if (frequency > 20000) {
        frequency = 12000;
      }
    }
  }
}

DOS just exits.
Python script:
import serial
import time
import argparse

# Set up the serial port (adjust the port name as necessary)
ser = serial.Serial('COM4', 9600)  # Use the correct COM port for your system

def send_command(command):
    print(f"Sending command: {command}")
    ser.write((command + '\n').encode())  # Ensure command ends with newline
    time.sleep(0.1)  # Small delay to ensure the command is processed

def main():
    parser = argparse.ArgumentParser(description="Control Arduino via serial commands.")
    parser.add_argument("action", choices=["on", "off"], help="Action to perform: on or off")
    parser.add_argument("--frequency", type=int, default=12000, help="Frequency in Hz")
    parser.add_argument("--interval", type=int, default=100, help="Interval in ms")
    parser.add_argument("--duration", type=int, default=10, help="Duration in ms")
    parser.add_argument("--volume", type=int, default=128, help="Volume (0-255)")

    args = parser.parse_args()

    if args.action == "on":
        command = f"{args.action} {args.frequency} {args.interval} {args.duration} {args.volume}"
    else:
        command = args.action

    send_command(command)

if __name__ == "__main__":
    main()

reduce your code to simply turn on an LED when the serial command is received

that was a good idea, just done that, now building up from that :)

well I made progress with what you said, I can turn on my LED and loop through the Hz on the buzzer and LCD with the use of a serial command like "on 15000 200 20 255". The breadboard button also turns off and on if it gets too loud. It still doesnt like the python script for DOS cmd line start though.

its okay, got it working :)


text:
Training Commands with easyVR
I am using the EasyVR Arduino Shield with Uno.
What i am trying to do is train a custom phrase like a name.
I want to be able to train the phrase directly with arduino whilst it is not connected a pc.  I have noticed in the documentation there are some references to commands like it, but i'm not sure how to go around writing code for such a thing.
thank you

Hi a bit late but I thought it could be useful to someone, I successed to train SD  commands without pc easyvr commander with this code:
// ARDUINO 1.6.6
// EasyVR Shield 2.0
// EasyVR library v1.7

#include "Arduino.h"
#if !defined(SERIAL_PORT_MONITOR)
#error "Arduino version not supported. Please update your IDE to the latest version."
#endif

#define pcSerial SERIAL_PORT_MONITOR

#include "SoftwareSerial.h"
SoftwareSerial port(12, 13);

#include "EasyVR.h"
EasyVR easyvr(port);

//

char label[33];
uint8_t data;

bool train = false;
bool recog = false;

int8_t group = EasyVR::PASSWORD;
int8_t index = 0;

void setup()
{
  pcSerial.begin(9600);
  port.begin(9600);

  while (!easyvr.detect())
  {
    pcSerial.println(F("EasyVR not detected!"));
    delay(1000);
  }

  //

  easyvr.setPinOutput(EasyVR::IO1, LOW);
  pcSerial.print(F("EasyVR detected, version "));
  pcSerial.println(easyvr.getID());
  easyvr.setTimeout(5);
  //  easyvr.setLevel(EasyVR::HARD);

  //

  printCommands();
}

void printCommands()
{
  pcSerial.print(F("Password: "));
  int16_t count = easyvr.getCommandCount(group);
  pcSerial.print(count);
  pcSerial.println(F(" command(s)"));
  for (int8_t idx = 0; idx < count; ++idx) {
    if (easyvr.dumpCommand(group, idx, label, data)) {
      pcSerial.print(idx);
      pcSerial.print(F(" = "));
      pcSerial.print(label);
      pcSerial.print(F(", Trained "));
      pcSerial.print(data, DEC);
      if (!easyvr.isConflict()) pcSerial.println(F(" times, OK"));
    }
  }
}

bool checkMonitorInput()
{
  if (pcSerial.available() <= 0) return false;

  int16_t rx = pcSerial.read();
  //  pcSerial.print(rx);

  if (rx == 's')
  {
    easyvr.removeCommand(group, index);
    easyvr.addCommand(group, index);
    easyvr.setCommandLabel(group, index, "cuss");

    printCommands();
  }

  if (rx == 't')
  {
    recog = false;
    pcSerial.print("say something");
    train = true;
  }

  if (rx == 'r')
  {
    train = false;
    pcSerial.print("start recognition");
    recog = true;
  }

  //

  if (rx >= 0)
  {
    easyvr.stop();
    pcSerial.flush();
    return true;
  }
  return false;
}

void loop()
{
  checkMonitorInput();

  if (train) {
    pcSerial.println("Train a word");
    easyvr.trainCommand(group, index);
  }

  if (recog) {
    pcSerial.println("Say the word");
    easyvr.recognizeCommand(group);
  }

  //

  do {
    if (checkMonitorInput()) return;
  }
  while (!easyvr.hasFinished());

  //

  int16_t idx = easyvr.getCommand();
  if (idx >= 0) {
    if (easyvr.dumpCommand(EasyVR::PASSWORD, idx, label, data)) {
      pcSerial.print("recognized = ");
      pcSerial.println(label);
    }
    easyvr.playSound(0, EasyVR::VOL_FULL);

  } else {
    if (easyvr.isTimeout()) pcSerial.println("Timed out, try again...");
    int16_t err = easyvr.getError();
    if (err >= 0) {
      pcSerial.print("Error 0x");
      pcSerial.println(err, HEX);
    }
  }
}


text:
Arduino Yun USB host - reading usb MIDI data and passing forward to another device
I am starting simple, but for some reason I cannot find any examples online and I stuck with my task.
I have a usb midi keyboard, Arduino Yun, and a synthesiser that can accept midi via usb. The problem is that the synth doesn't send a voltage through its usb and the keyboard has only one usb that is used to send midi data and it's powered via it at the same time.
My idea is to use my Yun's USB host (which sends voltage too) to power my midi keyboard and grab all incoming midi data from the keyboard, then simply pass it unchanged through to my synth.
Where do I start? Do I need some python code for it or everything can be done with sketch code? I've done few arduino projects but I am new to usb host functionality  . This is my first step, later I would like to also convert usb-midi to 5-din-midi (old school connection), but that's different story.
Can you guys help me and point into the right direction? Anyone done something similar on Yun? I've seen some examples done on different boards, but it's all overcomplicated, I need simple read/pass usb solution. Thanks!

If the problem is simply power, you are far better off making a power injection cable than trying to proxy things through software.  Only resort to that if there are other things you need to do as well.

If you are going to try and sniff USB, don't even start. It's not ever going to happen at your skill level. USB is a very very complicated software stack to even get "hello world" working. If you are dealing with pure midi signals, this is a different story. MIDI is very simple and there are tons of guides

You need the USB Audio kernel driver and the aconnect utility:
$ opkg update
$ opkg install kmod-usb-audio
$ opkg install alsa-utils-aconnect

Then just connect the ports:
$ aconnect -lio
client 0: 'System' [type=kernel]
    0 'Timer           '
    1 'Announce        '
client 14: 'Midi Through' [type=kernel]
    0 'Midi Through Port-0'
client 40: 'SC-8820' [type=kernel]
    0 'SC-8820 Part A  '
    1 'SC-8820 Part B  '
    2 'SC-8820 MIDI    '
client 44: 'My Little Keyboard' [type=kernel]
    0 'My Little Keyboard MIDI 1'
$ aconnect "My Little Keyboard" SC-8820
$

(This is plain Linux and does not need to run anything on the ATmega.)

Thanks for you answer, but I need to do it with Arduino, not Linux computer, I will be later extending that project to convert to 5-din midi socket. Also, I won't have the laptop next to the keyboard and synth when using that set-up so it has to go through Arduino I am afraid.

The Yun runs a Linux on the AR9331's CPU. And that is where the USB host ports are.

I got confused by your comment it doesn't need Arduino ; ) Ok I will need to test this solution then!


text:
Tools > Board settings: how are they captured?
In the Arduino IDE, the Tools menu can be used to make some board-specific settings like this:

... such as Processor Version = "Atmega168P", Processor Speed = "16MHz Crystal Resonator" and so on. These end up choosing fuses when burning a bootloader.  They may or may not also set constants that influence library behavior, I'm not sure.
What I'd like to know is how such settings stored, as they don't seem to be stored in any file associated with the sketch. And that being the case, they seem to be lost when using different boards or settings for subsequent projects.
So what files store these settings, at least temporarily, and how might one associate those settings more permanently with the project/sketch, so that they are repeatable later?

The board settings from Tools menu are stored in the IDE preferences file.
You can open the file from the Preference dialog of the Arduino IDE. The path to the file is shown at the bottom of the dialog and it is clickable.

Thanks for that good clue! And do you know of a way to associate those settings permanently with the project/sketch to which they pertain, so they can be repeated later?

@gwideman https://arduino.stackexchange.com/questions/91305/is-it-possible-to-save-and-restore-the-arduino-ide-tools-settings-somehow

the link to preferences file is missing in IDE 2.0.3


text:
Arduino Start en Stop
Is there a way to set a time for instance 8.00 PM to make the arduino-uno start or stop at that time?

Power it through one of these: http://www.dealec.co.uk/acatalog/Timeguard-TS800B-24-Hour-Mechanical-Plug-In-Timeswitch-6519.html#SID=2

What are you trying to accomplish? Why do you need it stopped? Is it to save power or to quit doing its function? The suggestions would be different in each case.

@Majenko: mechanical? Really? :-)

Really stop Arduino is possible, it's called sleep mode, but the UNO is designed so badly with respect to power consumption that you may as well keep it running.
To have it done something at a specific time you could connect a real time clock (RTC) breakout board (SparkFun has a couple). Use a 1 second timer interrupt to read the clock and compare it with (a table of) times where you want things done. A table could hold the time, an output (e.g. for a relay) and the new status (on or off). If you have just a couple of those you can store them in the RTC's battery-backed up RAM.
edit
You can use your PC's time, all the hardware you need is the USB cable. On the PC you run a program that sends the current time to the Arduino. (There are Processing examples of how to communicate with the Arduino on the Net.)
Note that without an RTC your PC will have to be on all the time and connected to the Arduino. You could use the PC just to sync the Arduino's clock and keep time yourself, but the clock of the Arduino is not very accurate.
Getting the time from the Internet is also possible, but then you'll need a Wifi or Ethernet shield to make the connection.

thanks for the answer, but I want to use the time of my pc or internet. Is it still possible?

See the edit of my answer.


text:
Running a servo and tone() won't compile? "multiple definition of `__vector_32'"?
Im using Spark fun pro micro:https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro
I am controlling a servo motor which reads its data from a pot connected to A0, and then writes to the servo on D9.
A speaker is connected to A5. Im using tone()
If I comment out the servo part of it, the tone() works out just fine and vise versa..
The error message I get is "multiple definition of `__vector_32'"
Got a clue??!
Thanks!

What version of the Arduino software are you using?

The link you provided shows a board built around the ATmega32U4.
On this chip, “__vector_32” is the low-level name of an ISR
(Interrupt Service Routine) named “TIMER3_COMPA_vect”. Your problem
comes from having two libraries trying to define an ISR for the same
interrupt, which is generated by the timer 3 of the chip. Merging
the ISRs is actually unlikely to work, because since each library
configures the timer in its own way, the timing of the interrupts will
be wrong for at least one of the libraries. You really have to use
different timers.
On my copy of Tone.cpp I can read:
#elif defined(__AVR_ATmega32U4__)

#define AVAILABLE_TONE_PINS 1
#define USE_TIMER3

const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 3 /*, 1 */ };
static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255 */ };

which shows that the code is configured to use timer 3 on this
particular chip. In Servo.h I have:
#elif defined(__AVR_ATmega32U4__)
#define _useTimer1
typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t ;

which shows it should use timer 1, and not conflict with Tone.cpp.
It seems we have different versions of Servo.h. Mine is from Arduino
1.0.5. You may try to fix the problem by modifying the relevant section
of either file (just after #elif defined(__AVR_ATmega32U4__)) and
have them use different timers.
Edit: It appears this issue has already been fixed... on June 2012!
See this diff: Avoid TIMER3 conflict with Servo and
tone()
on the Arduino GitHub repository. The simplest fix in your case may be
to just upgrade your Arduino software. You could also manually apply
that (really small) diff to your current copy.

@downvoter: care to comment?

An upgrade did the job! Thanks a lot!!
But a new problem occurred, I had a timer interrupt connected as well which now is conflicting with the servo... gaaaah!! =) Guess I´ll have to modify or change the timer which interrupts

The problem you're seeing arises when two codes (e.g. libraries) try to use the same interrupt.
If you look at the source code of the two libraries, you'll find that they both make use of a number of ISRs (interrupt service routines): Tone.cpp uses
ISR(TIMERn_COMPA_vect) {...}

for n = 0..5, while Servo.cpp uses
ISR(TIMERn_COMPA_vect) {...}

for n = 1, 3, 4, 5.
Now what happens when you compile this code is that they both libraries generate identical symbols (the __vector_32 part) which then clash when the compiled code is linked to give the final binary you'd upload to your Arduino.
There is no simple way around this because the interrupt handlers need to be  registered at certain fixed positions in flash memory and there can only be exactly one interrupt handler for each of these slots (these slots are simply entries in a look-up table with the addresses of the interrupt handlers in flash, cf. Table 9-1 in the datasheet).
Now to solve this problem you would need to find a way to either merge the interrupt handlers of the two libraries (not so easy I guess), or make them use different interrupts (without looking further into what options the pro micro offers, the code suggests that there are several TIMER interrupts which could be assigned one to the Servo, one to the Tone, if that is supported by the hardware).
In any case you'll not get around modifying the libraries (or writing your own code for one functionality or the other).

Why the downvote?


text:
Passing VAL(0-179) to OLED
I´m using Spark Fun Micro Pro board 5V: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro
and to that i´ve hooked a true color OLED from digole: http://www.digole.com/index.php?productID=859
I manage to get my VAL from my potentiometer on screen. But when I exceeds val "10", and then go back to lets say "9", the zero from "10" is still there. It looks like:  "90" instead of "9". The problem is of course that the second (and third) number don't go away.. Im sure there is a simple way of doing this but I can't get my head around it..
I´ve tried using clearScreen but that function makes the OLED blink in a unpleasant way every time it clears... Hope you get my question, english isn't my native language, as u maybe can tell =)
Thanks
void loop()
{
  val = analogRead(potpin);        // reads the value of the     potentiometer (value between 0 and 1023)
  val = map(val, 0, 1023, 0, 179);  // scale it to use it with the servo (value between 0 and 180)
  myservo.write(val)  sets the servo position according to the scaled     value
  mydisp.clearScreen();
  mydisp.setPrintPos(9, 6);
  mydisp.print(val);

  delay(200);  // waits for the servo to get there
 // mydisp.clearScreen();

}

Instead of printing "10" or "9" etc, print "10 " or "9 ".  Add an extra space at the end of what you print which overwrites the character that was there before.
mydisp.print(val);
mydisp.print("  ");

I used 2 spaces there, in case you go from 3 digits straight to 1.
Another method is to "format" the number using sprintf:
char temp[4];
sprintf(temp, "%3d", val);
mydisp.print(temp);

Ok, but the problem is that I print (val). So what should I write to add a " "(space) after the (val)?

Just print spaces to the display. See my edit.


text:
Can someone explain how to program i2C communications without using the library?
I am starting to get into i2C, SPI, and other forms of communication. I have read about them and have a fuzzy idea of how they work electrically, but can someone explain how I would turn the electronic portion into the coding/controlling portion? I really want to get a great understanding of it.

If you have Arduino Uno, you can try my free I2C terminal. I2C communication is quite complex. Check out https://iobtoolkit.com/s/i2c/
and https://www.youtube.com/watch?v=4x3NNWLgtTU .
The idea is that you hook up I2C device and you can chat with the device using a console, exploring the protocol and device functions, without writing a single line of C.

I really want to get a great understanding of it. - reading the existing library would help (Wire.cpp and twi.c amongst other files).

The AVR microcontrollers that Arduino uses have built-in hardware support for the said protocols.
That means that you don't have to write program to control the transmission/reception process but you only need to configure the appropriate registers and the hardware will initiate transfer and inform you when it's done.  I suggest you carefully read the datasheet of the microcontroller you are using with your Arduino and you should find all the information there.  It even has code examples, so you can actually copy-paste functions and use them in your program, here is one of the examples:
void SPI_MasterInit(void)
{
    /* Set MOSI and SCK output, all others input */
    DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);
    /* Enable SPI, Master, set clock rate fck/16 */
    SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
}

void SPI_MasterTransmit(char cData)
{
    /* Start transmission */
    SPDR = cData;
    /* Wait for transmission complete */
    while(!(SPSR & (1<<SPIF)));
}

The keywords with the capital letters are usually register and bit names: you can look them up in the datasheet.

Would that work for I2C?

Can someone explain how to program i2C communications without using the library?

The AVR has hardware support for this but you can implement it with the pin functions. I2C is a lot about timing the signals and detecting the reply signal from the slave.
The hardware support for I2C requires understanding of a complex state-machine. If you have implemented the I2C protocol it becomes easy to understand the hardware support and how this help remove a lot of work from the processor core. The state machine, control and status registers and interrupts, are described in the AVR product specification. There are also lots of excellent descriptions on the web. Do not miss the AVR application notes for the I2C. Most of the code in the Arduino core originated from them.
Cheers!

So its based all on timing, and hardware application? Sounds like it has to almost be like clockwork

I2C hardware is present in almost any modern microcontroller. It's all about writing a driver for it. Hardware interface will take care of low-level details, such as clock generation and timing.

A good way to learn how to code for these interfaces is to look at the source code for the libraries themselves. In the PC world, these will be in the directory
Program files (x86)\Arduino\hardware\arduino\avr\libraries


text:
Working with long strings
So I need some tips on working with long strings with the arduino. I have a barcode scanner working. This barcode scanner reads a persons driver license. the result is a lengthy character string of varying length that's 300+. Using substring doesn't work when looking for a certain section of the string and indexOf results in a -1 in most spots. Is there anyway getting around this? Right now I have the data just stored in a string variable.
Thanks.

Don't use String. It's slow, inefficient, and makes swiss cheese of your memory. Use the standard C string.h library routines (already included and available in your sketch).

This doesn't really sound like a task to which an Arduino is well suited.  You can probably make it work, but it's likely not the best choice.

Since the Arduino Uno only has a few KB, 300 bytes is a considerable amount.
My advice:

Define a fixed char[300] array, where 300 is the max amount of characters you want to support.
Use the C (string.h) library as Majenko already suggests.

The last thing you want is that the string will be copied somehow, using up double the amount of data, or triple. It's hard to see what's going on under water, by casting or even by implicit casting a copy can be made, so 600/900 bytes are used.
For the default library, searching should work for strings longer than 256 characters. You can even write them yourself, for example if you can make it more efficient if you know something about the characters (e.g. if you can skip some because you know some patterns exist or don't exist).
Update after your comment below.
What you can try:

Try (if existing) an example sample for the barcode scanner to see if the hardware is ok. If not possible try to make a minimal sketch.
Double check the wiring (although it seems easy).
Try different wires (maybe a jumper wire is malfunctioning).
Try another sketch using serial, but without the barcode scanner (to verify RX/TX is not broken on the Arduino).

Searching substrings, with strstr() or strcasestr() works, of course, with strings of any length. And note that, if the program is light enough, it would make sense to allocate 1 KiB to the string.

@EdgarBonet True ... I rephrased my answer slightly, thanks!

The barcode scanner is the heaviest part of this build. I have a few I2C devices, and maybe 5 digital outputs at most. The physical aspect with outputs is really light.

I updated my answer.

In response to your answer, I'm pretty sure the hardware is fine. I WISH it was serial but all I was given to work with is a USB scanner and USB shield. When scanned in and stored in the string variable, I can Serial.print the data just fine. My issue only comes when searching the string. For drivers license, there are delimiters like "dbb" to indicate date of birth. I'm essentially trying to search for the occurrence of this delimiter and extract the date of birth, turn it to a julian date, compare with an RTC module, and make sure the person is over 21.

Can you put in your question the exact code you use for searching? (including a Serial.print of the values before and after your search).

I don't have the code with me currently, but I was just using Serial.println(DL.indexOf("dbb")); and I received a -1 for the output. I'm using indexOf to get the index, add 3 to bypass the delimiter, and then I was going to get the next 8 digits for the date. When I am able to, I am going to put it into a character array and use strstr() as suggested. If I do Serial.println(DL); I get the data displayed just fine.

my answer posted

So when printing my string variable, I get the full, uninterrupted string displayed to me. I decided to index through my string with a for loop and come to find out, I had many null characters included in the string itself. I did a check to make sure that the character isn't a NULL character before appending it to my string upon creation, and that seemed to do the trick. indexOf is working now.
Reason I decided to index through my string is because I tried to string.toCharArray(buff, DL.length()); and despite the length, I would only get one character pushed into buff.
Thanks for all the tips guys!

Functions of the “str” family, like strstr(), expect NUL-terminated strings, and thus they can't handle character arrays with embedded NULs. Arbitrary character arrays, however, are handled just fine with functions from the “mem” family, like memmem(), which is the equivalent of strstr() for arbitrary arrays.