Motor running slowly when connected to digital pins, but fine with 5V pins I am trying to connect a Dagu DG01D motor to my Arduino Uno. First I tried connecting the black wire to GND and the red wire to digital pin 7. My code:

void setup() {
  pinMode(7, OUTPUT);
  digitalWrite(7, HIGH);
}

void loop() {
}

When I connected the motor, it wouldn't turn, but would rotate a little when turned in one direction. However, when I connected the red wire to 3.3V or 5V, the motor turned quickly as expected. Why didn't writing HIGH to pin 7 work?

I already verified that I can connect and run code on the Arduino by turning on the LED by replacing pin 7 with 13. I also tried running the same code on a SparkFun RedBoard, with similar results.

No Load Current: 190mA (250mA MAX)

You're not getting that out of a ATmega328P GPIO. Use a driver instead.


real-time reading of a quadrature encoder at full resolution with only one interrupt on ATmega328 I want to read a quadrature rotary encoders at full resolution with only one interrupt on Arduino Nano (ATmega328). So I found out that we can use XOR to reach a full resolution:

Where pin 3 is interruptable but 4 and 5 are not.

Our requirements are:

Full resolution: for example, the solution offered in this answer works at a half-resolution only, not detecting all the edges.
Real-time: being as fast as possible up to the level that this hardware allows and safe in terms of not missing any of the signal edges.
using only one interrupt. We need the other one for other purposes.

So far, I have developed two different codes, one aiming for safety and the other for performance:

Preamble:

#include "digitalWriteFast.h"

#define pinT 3 // trigger pin comming from XOR

#define pinA 4 // channel A
#define pinB 5 // channel B

volatile long counter = 0;
long counter_ = counter;

where the digitalWriteFast library can be downloaded from here.

Performant:

volatile short int increment = 0;
volatile bool tmpA;
volatile bool tmpB;
volatile bool lastA;

ISR(trigger) {
  tmpA = digitalReadFast(pinA);
  tmpB = digitalReadFast(pinB);
  counter += (1 - 2 * tmpA) * (1 - 2 * tmpB) * (1 - 2 * (lastA != tmpA));
  lastA = tmpA;
}

void setup() {
  pinMode(pinA, INPUT_PULLUP);
  pinMode(pinB, INPUT_PULLUP);
  pinMode(pinT, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(pinT), trigger, CHANGE);
  lastA = digitalReadFast(pinA);
  Serial.begin(9600);
}

void loop() {
  if (counter != counter_) {
    Serial.println(counter);
    counter_ = counter;
  }
}

Safe:

volatile unsigned long error = 0;
unsigned long error_ = 0;

volatile bool inputA;
volatile bool inputB;

volatile short state; // 100 110 101 111
volatile short state_;

void detectState() {
  inputA = digitalReadFast(pinA);
  inputB = digitalReadFast(pinB);

  if (inputA) {
    if (inputB) {
      state = 111;
    } else {
      state = 110;
    }
  } else {
    if (inputB) {
      state = 101;
    } else {
      state = 100;
    }
  }
}

ISR(trigger) {

  detectState();

  if (state_ != state) {
    switch (state_) {
      case 100:
        if (state == 110) {
          counter++;
        } else if (state == 101) {
          counter--;
        } else {
          error++;
        }
        break;
      case 110:
        if (state == 100) {
          counter--;
        } else if (state == 111) {
          counter++;
        } else {
          error++;
        }
        break;
      case 101:
        if (state == 100) {
          counter++;
        } else if (state == 111) {
          counter--;
        } else {
          error++;
        }
        break;
      case 111:
        if (state == 110) {
          counter--;
        } else if (state == 101) {
          counter++;
        } else {
          error++;
        }
        break;
      default:
        error++;
        break;
    }

    state_ = state;
  } else {
    error++;
  }
}

void setup() {
  pinMode(pinT, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(pinT), trigger, CHANGE);

  pinMode(pinA, INPUT_PULLUP);
  pinMode(pinB, INPUT_PULLUP);

  detectState();
  state_ = state;

  Serial.begin(9600);
}

void loop() {
  if (counter != counter_) {
    Serial.print("counter: ");
    Serial.println(counter);
    counter_ = counter;
  }

  if (error != error_) {
    Serial.print(error);
    Serial.println(" errors");
    error_ = error;
  }
}

Now my questions are:

Is there any way to improve the speed/safety of the performant/safe code? Any way to improve this code is appreciated.
Is it possible to have maximum speed and safety together or some trade-off in between?
What is the maximum frequency we can get out of this configuration?

Thanks for your help in advance.

This is just a partial, rushed answer.

You should be able to get a significant speed-up if you define your own
ISR for handling the interrupt, as in:

ISR(INT1_vect) { ... }

The Arduino way of using interrupts is instead

void trigger() { ...}

void setup() {
    attachInterrupt(int_number, trigger, CHANGE);
    ...
}

but this is slow, as it involves the ISR provided by the Arduino core,
which has to locate and call your interrupt handler. The way you wrote
the handler is wrong: either you define a regular function, without the
ISR macro, and go the Arduino way, or you go the plain AVR path and
define the ISR yourself, which should be named INTERRUPT_NAME_vect, in
which case you don't use attachInterrupt(). The way you did it is
probably the slowest you can get, as the compiler will needlessly add an
ISR-type prologue and epilogue to your handler.

As for the maximum frequency, that's hard to assess without testing, but
you may get some idea by reading this answer on interrupt
latency.

Edit: As I stated in my first comment to the question, a pin change
interrupt can be used instead of an external logic gate. Here is how to
do it.

First, one should look at the Arduino Uno pinout and see that:

digital 4 = PD4 = PCINT20
digital 5 = PD5 = PCINT21

Both pins are tied to the pin change interrupt request 2 (PCINT2_vect).
This interrupt can be configured in setup() as follows:

PCMSK2 = _BV(PCINT20)   // enable interrupt on pin PCINT20 = PD4
       | _BV(PCINT21);  // enable interrupt on pin PCINT21 = PD5
PCIFR  = _BV(PCIF2);    // clear interrupt flag
PCICR  = _BV(PCIE2);    // enable pin change interrupt request 2

Now, the interrupt will fire on every change of the logic levels of
inputs 4 and 5.

Then, in the ISR, the whole port D can be read in a single cycle by
just evaluating the corresponding pin input register, i.e. PIND. With
some shifting and masking, one can get a phase between 0 and 3
(the count is in Gray code: 0, 1, 3, 2, 0...). From the previous and the
current phase, one can compute the change that needs to be applied to
the counter:

// Handle pin change interrupt request 2.
ISR(PCINT2_vect) {
    static uint8_t previous_phase;
    uint8_t phase = (PIND >> 4) & 0x03;  // read input pins
    counter += encoder_delta(previous_phase, phase);
    previous_phase = phase;
}

The implementation of encoder_delta() is left as an exercise to the
reader. ;-)


Simon Says Project - Can't go from random lights to user input I'm new to using an Arduino and I am attempting the Simon Says game. Right now, I do not understand why my program will not go from activating the random lights to the user input. Currently it is flashing all the lights three times like I want it to, but then it will flash three random lights and then go straight to flashing every light, right to left (which is the indicator that the wrong button was pushed).

I am working in Tinkercad/circuits.io and have had the physical implementation looked at, and it is good. I just can't figure out the code. Anything will help, thanks!

// Defining LEDs and buttons.
int leds[] = {12, 10, 7, 4};
int buttons[] = {11, 9, 6, 3};

const int max = 40;
int lightArr[max]; // Array with full patterns of LEDs.
int currArr[max];
int gameState = 0;
int level = 1;
int count = 0; // Counter for every sequence of iterating over the
random array of ints (LEDs).
int buttonPressed = -1;
int correct = 1;

void setup() {
  pinMode(leds[0], OUTPUT);
  pinMode(leds[1], OUTPUT);
  pinMode(leds[2], OUTPUT);
  pinMode(leds[3], OUTPUT);
  pinMode(buttons[0], INPUT);
  pinMode(buttons[1], INPUT);
  pinMode(buttons[2], INPUT);
  pinMode(buttons[3], INPUT);
  randomSeed(analogRead(0));
  allOn();
}

void loop() {
  if (gameState == 0) {
    resetGame();
  } else if (gameState == 1) {
    play();
  } else if (gameState == 2) {
    gameOver();
  }
}

void resetGame() {
  if (level == 1) {
  // Setting up a sequence of random lights.
    for (int i = 0; i < 40; i++) {
      lightArr[i] = random(0,4);
    }
  }
  level = 1;
  gameState = 1;
}

void play() {
  while (correct == 1) {
    showPattern();
    int correct = userInput();
  }
}

void showPattern() {
  for (int i = 0; i < level; i++) {
    delay(500);
    digitalWrite(leds[lightArr[i]], 1);
    delay(500);
    digitalWrite(leds[lightArr[i]], 0);
    delay(500);
  }
}

int userInput() {
  for (int i = 0; i < level; i++) {
    int buttonPressed = readOneButton();
    digitalWrite(leds[buttonPressed], 1);
    delay(500);
    digitalWrite(leds[buttonPressed], 0);
    delay(500);
    if (lightArr[i] != buttonPressed) {
      // User button pressed.
      gameState = 2;
      correct = 0;
    }
  }
}

void gameOver() {
  for (int i = 0; i < 3; i++) {
    digitalWrite(leds[0], 1);
    delay(150);
    digitalWrite(leds[0], 0);
    delay(150);
    digitalWrite(leds[1], 1);
    delay(150);
    digitalWrite(leds[1], 0);
    delay(150);
    digitalWrite(leds[2], 1);
    delay(150);
    digitalWrite(leds[2], 0);
    delay(150);
    digitalWrite(leds[3], 1);
    delay(150);
    digitalWrite(leds[3], 0);
    delay(150);
  }
  gameState = 0;
}

int readOneButton() {
  if (digitalRead(buttons[0])) {
    return 0; // Button: Red
  } else if (digitalRead(buttons[1])) {
    return 1; // Button: Green
  } else if (digitalRead(buttons[2])) {
    return 2; // Button: Blue
  } else if (digitalRead(buttons[3])) {
    return 3; // Button: Yellow
  }
}

void allOn() {
  for (int i = 0; i < 3; i++) {
    digitalWrite(leds[0], 1);
    digitalWrite(leds[1], 1);
    digitalWrite(leds[2], 1);
    digitalWrite(leds[3], 1);
    delay(500);
    digitalWrite(leds[0], 0);
    digitalWrite(leds[1], 0);
    digitalWrite(leds[2], 0);
    digitalWrite(leds[3], 0);
    delay(500);
  }
}

void play() {
  while (correct == 1) {
    showPattern();
    int correct = userInput();
  }
}

Why do you create a new variable called correct and put the value form userInput in that?  Why don't you put the return from userInput into the variable named correct that you already have?  Two variables with the same name in the same scope is NEVER a good idea.  The original correct will never be changed here so this becomes an infinite loop.

Next, look at readOneButton.  It will take the Arduino just a few microseconds to run through that for loop and the whole userInput function.  Unless you are super duper fast at getting that button pressed, it is just going to decide that you didn't press any buttons.  You don't have a case in there for no button pressed, so it is going to return 0.  You should probably wait until the user presses a button before you decide whether he is right or wrong.


Relay module and internal pull-up resistors I'm currently assembling a prototype of the lightning infrastructure (based on several MEGAs interconnected via RS485, as described in this other post)

The prototype consists of three MEGAs, a couple of wall-push-button and the two relay modules here below:

250V 2A 8 Channel OMRON SSR G3MB-202P Solid State Relay Module For Arduino
5V 4 CH OMRON SSR G3MB-202P Solid Relay Module with Resistive Fuse For Arduino

Obviously I've:

connected one endpoint of each push-buttons to Arduino INPUT-PIN; the other endpoint to ground;
connected the relay-module control-pins to Arduino OUTPUT-PIN (and ensuring a properly connected ground).
connected lamps to relay-modules power connectors.

My question relates to "pull-up resistor": I've read in lots of places that when involving push-buttons, "pull-up resistors" are needed in order to prevent shorts between ground and input-pin. As such, there are lots of tutorial/videos on the web, showing a nice resistor added in the push-button circuit.

Further investigating, I've also learnt from the official documentation that "...There are 20K pullup resistors built into the Atmega chip that can be accessed from software....", by setting the pinMode() as INPUT_PULLUP or setting it to INPUT and the forcing a digitalWrite(<PIN>,HIGH).

So, I ended:

directly connecting the two relay-modules to MEGAs INPUT-PINs and...
...activating the internal pull-up, with digitalWrite(<INPUT_PIN>,HIGH);

Nothing more.

This is the second evening I'm "testing" my Arduino-luggage-prototype and... lamps are turning on/off like a charm, without any noticeable problem.

The question is: am I doing something nasty toward my MEGAs? Is the approach depicted above, a commonly-safe (as for the Arduino's health) approach?

P.S.: should you wonder about how the prototype looks like, here is a photo (actually, taken right after the first power-up ;-)

Connecting one side of a switch to ground and the other side to an input pin (with its pinmode set to INPUT_PULLUP) is a standard way of connecting control switches to an Arduino installation, and is not a problem.

Note, claims that built-in pull-ups are 20KΩ oversimplifies the situation.  See, for example, Table 28.2, DC Characteristics, in the ATmega48PA/88PA/168PA/328P specs, which shows a min value of 20KΩ for   I/O Pin Pull-up Resistors and a max value of 50KΩ.  I've measured resistances of about 40KΩ, IIRC, whenever I've measured the pull-up values.

Note, built-in pull-ups typically are of too much resistance to work as pull-ups for TWI/SPI/I2C communications.

Note, when you say in the question that you connected the relay-modules to input pins and they worked ok, I suppose that could be the case, but in general it is better to put i/o pins into output mode when you want to drive an output.  When you send LOW to an input pin, its built-in pull-up is turned off, the input impedance becomes high, and then the pin can float to any value between ground and Vcc. It might fail to turn off an attached device if that device also has high impedance.


Sizeof variables and Due's RAM I set out to see how much space some arrays have. I used this test code

bool state = false;

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

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

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

I got this answer from the serial:

92000
40000
40000
40928

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

sizeof doesn't return the number of elements. It returns the number of bytes. Since they are uint16_t arrays each element is 2 bytes - hence twice the size.

The reason your last number is only 40928 is because of integer wraparound. You only provide a 16-bit unsigned variable to store it in, so all you get is the lower 16 bits of the answer.

92000 + 40000 + 40000 = 172000

172000 in hex is 0x29FE0

0x29FE0 truncated to 16 bits is 0x9FE0

0x9FE0 in decimal is 40928.

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

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

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

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


typedef function pointer array declaration problem Thanks for all your feedback. It helped.

I rewrote this yet another time and this time it works perfectly. I included three variations: a simple example using an array of function pointers, a Lambda version and a complex version like what I started with.

#define TASK_COUNT          3

typedef void ( *taskPointer ) ( );

//  Simple Version:
void taskS1 () { Serial.println ( ( char* )"SIMPLE TASK 1" ); }
void taskS2 () { Serial.println ( ( char* )"SIMPLE TASK 2" ); }
void taskS3 () { Serial.println ( ( char* )"SIMPLE TASK 3" ); }

//  Array of pointers to tasks
taskPointer callSimpleTask [ ] = {
taskS1,
taskS2,
taskS3,
};

//  Run the simple test
void showSimpleVersion () {
    Serial.println ( F ( "\nSimple Version:" ) );
    for (uint8_t i = 0; i < TASK_COUNT; i++) {
        callSimpleTask [ i ] ();
    }

}

//  Lambda Version: No separate task definitoins
void ( *callLambdaTask [ ] ) ( ) = {
    [ ] {Serial.println ( ( char* )"LAMBDA TASK 1" ); },
    [ ] {Serial.println ( ( char* )"LAMBDA TASK 2" ); },
    [ ] {Serial.println ( ( char* )"LAMBDA TASK 3" ); },
};

//  Run the Lambda test
void showLambdaVersion () {
    Serial.println ( F ( "\nLambda Version:" ) );
    for (uint8_t i = 0; i < TASK_COUNT; i++) {
        callLambdaTask [ i ] ();
    }

}

//  Complex Version: Each array element is a struct containing a
//  pointer to the corresponding task and related properties
struct complexTaskDefinition {
    taskPointer task;
    bool repeat;                //  Repeat flashing after delay
    int32_t iterations;         //  # times to repeat... -1 = forever
    uint32_t delay;             //  MS to wait before execution
};

//  Create a pointer to a task definition
complexTaskDefinition *task;

//  Prove that called function can call other functions:
void taskC1 () { showTaskC1(); }
void taskC2 () { showTaskC1 (); }
void taskC3 () { showTaskC1 (); }

void showTaskC1 () {
    Serial.println ( ( char* )"COMPLEX TASK 1" );
}
void showTaskC2 () {
    Serial.println ( ( char* )"COMPLEX TASK 2" );
}
void showTaskC3 () {
    Serial.println ( ( char* )"COMPLEX TASK 3" );
}

complexTaskDefinition tasks [ ] [4] = {
    {taskC1, true, -1, 1000 },  //  taskC1 repeats forever every second
    {taskC2, true, 10, 2000 },  //  taskC2 runs 10 times pausing for 2 seconds between iterations
    {taskC3, false, 3, 3000 },  //  taskC3 runs 3 times with 3 second delays between each, then dies
};

void showComplexTaskList () {
    Serial.println ( F ( "\nComplex Task List:" ) );
    for (uint8_t i = 0; i < TASK_COUNT; i++) {
        task = tasks [ i ];
        Serial.print ( '[' );
        Serial.print ( i );
        Serial.print ( F ( "] REPEAT:" ));
        Serial.print ( ( task->repeat ) ? "YES" : "NO" );
        Serial.print ( F ( ", DELAY:" ) );
        Serial.print ( task->delay );
        Serial.print ( F ( ", ITERATIONS:" ) );
        Serial.print ( task->iterations );
        Serial.println ();
    }
}

void showComplexVersion () {
    Serial.println ( F ( "\nComplex Version:" ) );
    for (uint8_t i = 0; i < TASK_COUNT; i++) {
        task = tasks [ i ];
        task->task ();
//      (( *tasks ) [ i ]).task ();
    }
}

void setup () {
    Serial.begin ( 115200 );
    while (!Serial.availableForWrite ()) {}

    showSimpleVersion ();

    showLambdaVersion ();

    showComplexVersion ();

    showComplexTaskList ();
}

void loop () {
}

Here is the output:
Simple Version:

SIMPLE TASK 1
SIMPLE TASK 2
SIMPLE TASK 3

Lambda Version:
LAMBDA TASK 1
LAMBDA TASK 2
LAMBDA TASK 3

Complex Version:
COMPLEX TASK 1
COMPLEX TASK 1
COMPLEX TASK 1

Complex Task List:
[0] REPEAT:YES, DELAY:1000, ITERATIONS:-1
[1] REPEAT:YES, DELAY:2000, ITERATIONS:10
[2] REPEAT:NO, DELAY:3000, ITERATIONS:3

I want to run one more experiment, this time with the complex version as a class.

Try replacing

taskDefinition _tasks [ ] [4] = {

by

taskDefinition _tasks [ ] = {

In short, you have defined _tasks as a 2D array of objects (an array
of arrays of objects) while you intend to use it as a 1D array.

Note that the error message is quite explicit if you take the time to
parse it:

  request for member 'task' in '_tasks[((int)i)]',

You are requesting _tasks[i].task,

  which is of non-class type

but _tasks[i] is not an object.

  type 'taskDefinition [4]'

It is instead an array of four taskDefinition objects.

Edit: Fixing the answer to match the latest version of the question.

Your code works, but not quite as you expect it to work. You wrote:

complexTaskDefinition tasks [ ] [4] = ...;

Here you are defining a 2D array of objects, while your intention was to
define a one-dimensional array (why do I feel like I am repeating
myself?).

complexTaskDefinition tasks [ ] [4] = {
    {taskC1, true, -1, 1000 },
    {taskC2, true, 10, 2000 },
    {taskC3, false, 3, 3000 },
};

This definition, although syntactically correct, is awfully wacky. You
are defining tasks as an array of 3 items. Each item is itself an
array of 4 objects, where the first object of the array is explicitly
initialized, and the three others are implicitly initialized to
all-bits-zero. So basically your definition is equivalent to this
explicit version:

complexTaskDefinition tasks [3] [4] = {
    {{taskC1, true, -1, 1000 }, {nullptr, false, 0, 0},
     {nullptr, false, 0, 0},    {nullptr, false, 0, 0}},
    {{taskC2, true, 10, 2000 }, {nullptr, false, 0, 0},
     {nullptr, false, 0, 0},    {nullptr, false, 0, 0}},
    {{taskC3, false, 3, 3000 }, {nullptr, false, 0, 0},
     {nullptr, false, 0, 0},    {nullptr, false, 0, 0}}
};

Then you wrote:

task = tasks [ i ];

Here, tasks[i] is a row of the 2D array, i.e. a 1D array of 4 objects,
whereas task is a pointer to object. The assignment is legit because
here, like in most contexts, the array “decays” to a pointer to its
first element. The above line is equivalent to the explicit version:

task = &tasks[i][0];

Quite fortunately, this happens to point to one of the elements of the
array that has been explicitly initialized!

As an illustration of the above, here is a modified version of
showComplexTaskList() that loops over all the tasks in the array:

void showComplexTaskList () {
    Serial.println ( F ( "\nComplex Task List:" ) );
    Serial.print(F("number of tasks: "));
    Serial.println(sizeof tasks / sizeof(complexTaskDefinition));
    for (uint8_t i = 0; i < TASK_COUNT; i++) {
        for (uint8_t j = 0; j < 4; j++) {
            task = &tasks[i][j];
            Serial.print ( '[' );
            Serial.print ( i );
            Serial.print ( F ("]["));
            Serial.print ( j );
            Serial.print ( F ( "] REPEAT:" ));
            Serial.print ( ( task->repeat ) ? "YES" : "NO" );
            Serial.print ( F ( ", DELAY:" ) );
            Serial.print ( task->delay );
            Serial.print ( F ( ", ITERATIONS:" ) );
            Serial.print ( task->iterations );
            Serial.println ();
        }
    }
}

Its output is:

Complex Task List:
number of tasks: 12
[0][0] REPEAT:YES, DELAY:1000, ITERATIONS:-1
[0][1] REPEAT:NO, DELAY:0, ITERATIONS:0
[0][2] REPEAT:NO, DELAY:0, ITERATIONS:0
[0][3] REPEAT:NO, DELAY:0, ITERATIONS:0
[1][0] REPEAT:YES, DELAY:2000, ITERATIONS:10
[1][1] REPEAT:NO, DELAY:0, ITERATIONS:0
[1][2] REPEAT:NO, DELAY:0, ITERATIONS:0
[1][3] REPEAT:NO, DELAY:0, ITERATIONS:0
[2][0] REPEAT:NO, DELAY:3000, ITERATIONS:3
[2][1] REPEAT:NO, DELAY:0, ITERATIONS:0
[2][2] REPEAT:NO, DELAY:0, ITERATIONS:0
[2][3] REPEAT:NO, DELAY:0, ITERATIONS:0

So your program works almost by chance: an error in the way you define
the array cancels an error in the way you use it. This kind of cancelled
error method is very bad programming practice. You are wasting memory in
unused complexTaskDefinition objects. More importantly, your code
doesn't express your intent, which makes the program way harder to
understand and to debug.

The fix is to declare a 1D array, as this has always been the intention:

complexTaskDefinition tasks [ ] = {
    {taskC1, true, -1, 1000 },
    {taskC2, true, 10, 2000 },
    {taskC3, false, 3, 3000 },
};

Now, you can check that this array does only have three tasks, as
reported by sizeof tasks / sizeof(complexTaskDefinition). To use the
array, you can use a pointer if you want:

task = &tasks[i];
// ...
Serial.print ( ( task->repeat ) ? "YES" : "NO" );

Or you can directly request a member of tasks[i], as in

void showComplexVersion () {
    Serial.println ( F ( "\nComplex Version:" ) );
    for (uint8_t i = 0; i < TASK_COUNT; i++) {
        tasks[i].task();
    }
}

Now I have a question for you. Since I already explained your 1D vs. 2D
array mistake in the first iteration of my answer, why did you persist
with this in your edited question? If you are going to blatantly ignore
the answers you get, at least say so in the question. This could save
time to those who might consider helping you.


Comparison of Board Shape between Arduino MEGA and Arduino DUE I'm using KiCAD to design boards, and while it has a lot of Arduino templates, it doesn't have one for the Arduino Due. Now, I've did some searching, and it looks like the Arduino MEGA is very similar to the Arduino DUE, not the specifications, but the number of I/O pins and the overall shape of the board. I couldn't find a straight answer, so I decided to ask here: Can the template of the Arduino MEGA be used as a template for the Arduino DUE when designing custom 'shields' and such based on the number of I/O pins and overall layout?

The Due has the same footprint as the Mega 2560.

source


Connect 2 Arduino UNOs via Bluetooth? (HC-05 and HC-06)? So I've researched this topic a lot online, but haven't found what I'm looking for. Before I tell you this, I'll give you guys an idea of what I'm trying to accomplish. Please understand that I'm an extreme beginner to Arduino, and that I've only been at this for a month or so, but plan on doing so much more.

My friend and I are building an RC car. We have an Android phone that has a downloadable application which connects to the Bluetooth HC-06 module that is on the Arduino UNO. We have configured our circuit, and it works fine! I want to go a step above and beyond, though.

My goal is to build a physical, handheld controller or remote (literally plopping everything on a breadboard), and connect that controller or remote to our car using Bluetooth. We have an HC-05 and HC-06 module, and the HC-06 is on the car. Now comes the doubt.

I understand how the android application sends characters through to the RC Car via Bluetooth; that's pretty straightforward as the two pieces are paired (using Android's Bluetooth Settings). What I don't understand is how to pair the two HC-05 and HC-06 Bluetooth modules. There isn't too much help online, I feel. I've looked and people have shown that they connect, but they don't explain the theory, so to speak.

What I want to understand is:

How the two HC-05 and HC-06 modules pair, and
How can I read input from one (remote controller) and execute an action on the other (RC car). From the app-to-Arduino, I was using Serial.available() to see if the Serial had any characters sent over from the application. I can't see how I can do that with HC-05 to HC-06 pairing, however. This concept is hard for me to grasp.

Any help is greatly appreciated. Thank you!

Have a look at this for how to pair them http://www.martyncurrey.com/connecting-2-arduinos-by-bluetooth-using-a-hc-05-and-a-hc-06-pair-bind-and-link basically you need to use the AT mode.
As far as I know you will be using the serial connection to communicate, but if you are using UNOs debugging becomes a bit more difficult, because you can't use serial for debugging.


Connecting ACS 712 30A to my Solar Panel with Arduino I am trying to connect my Solar Panel (array of 2 x 265Wp 24v panels connected in series) to my Arduino UNO R3/Nano so that I can make a current/voltage measurement system that can be connected to the internet for remote data access.

I am not sure if an Allegro ACS712 30Amp chip could handle the voltage/current of my system which is usually over 60v dc and 4-5 amps. I can relate the ACS712 to a simple ammeter which is connected in series of the load where a shunt resistance is used between the two connecting ends of the ammeter.

The confusing part here for me is that the solar panel is connected via an MPPT charge controller to my 1.5 KVA inverter which in turn powers my house equipment, and I am not sure if the two connecting ends of the ACS712 can handle this load (which sometime exceeds to over 450 Wh) if connected in between the wire connecting the panel and charge controller.

Can anyone help me with a suggestion or better with a diagram showing the suggested system.

I am not sure if an Allegro ACS712 30Amp chip could handle the voltage/current of my system which is usually over 60v dc and 4-5 amps.

Easily. It's designed for mains voltages up to 30A. You're using a fraction of that. You could even use the 20A version to get more accuracy and resolution.

  The confusing part here for me is that the solar panel is connected via an MPPT charge controller to my 1.5 KVA inverter which in turn powers my house equipment, and I am not sure if the two connecting ends of the ACS712 can handle this load (which sometime exceeds to over 450 Wh) if connected in between the wire connecting the panel and charge controller.

Why is that confusing? If you're monitoring the feed between the solar panel and the charge controller what comes out of that system at the other end is of no concern. Just because you are drawing a larger current from the output doesn't mean that the solar panels are providing that current - that comes from the batteries. Now if you were monitoring the current to/from the batteries that would be a different matter. You'd need to calculate the peak current that your house would draw at mains voltage then convert that to the current at the battery voltage (converting to watts in between is a good step. Note that Wh is meaningless when you want a peak value - Wh is a total power over a period of time ["area under a curve"], but you don't care about time, only peak ["maximum value of curve"]).


How can I pair a Bluetooth dongle on arduino Yun (openwrt-yun)? On my Arduino Yun (openwrt-yun, updated to latest version), I have a bluetooth dongle in the usb port; I have installed bluez-libs and bluez-utils (and python-bluez).  They show up as version 5.13.  hciconfig and hcitool work properly.  There does not seem to be any utility installed to pair with a device, nor can I figure out how to get pairing to work by editing config files.

I can find the device with hciconfig and hcitool, but rfcomm can't connect without the pin.  If I try the same sequence on my Linux laptop after pairing with the gui, rfcomm is able to connect, so I know the device is working properly (JY-MCU HC-06 on another Arduino).

All the recommendations I can find on the web indicate I should be able to use simple-agent or bluez-simple-agent, but they are not installed with these packages (there is no bluez-tools package for this distro).  If I manually copy the python script for the agent to the device and run it, it fails, saying that org.bluez can't be found with dbus.  There is no bluetoothd running, and no init script for any bluetooth demon.  None of the bt* tools are available.

I also found a description of how to set a pin code in /var/lib/bluetooth/[bt-addr]/pincodes (where bt-addr is my dongle address) containing a line of the form:

[device-addr]  [pincode]

but this seems to have no effect.

I have also tried settings in /etc/bluetooth/main.conf and /etc/bluetooth/rfcomm.conf, but I think they may only be for incoming connections.

Any help would be greatly appreciated.

It takes me some time to make it work :

1) update drivers

opkg update

opkg install kmod-bluetooth bluez-libs bluez-utils

2) add configuration files in directory /etc/bluetooth

root@Arduino:~# cat /etc/bluetooth/hcid.conf

options {
  autoinit yes;
  security auto;
  pairing multi;
  passkey "0000";
   }
device {
  name "OpenWrt";
  class 0x000100;
  lm accept,master;
  lp rswitch,hold,sniff,park;
  }

root@Arduino:~# cat /etc/bluetooth/rfcomm.conf

rfcomm0{
 bind yes;
 device 00:1B:C1:02:B0:F5;
 channel 1;
 comment "Holux M-1000";
 }

3) Reboot the card

4) test if all is OK

hciconfig

5) put the interface up

hciconfig hci0 up

6) Search for devices

hcitool scan

7) Look for Serial Port capability on the devices

sdptool search SP

8) bind the serial dev

rfcomm -i hci0 connect /dev/rfcomm0 00:1B:C1:02:B0:F5

9) see the information comming from the device (bluetooth GPS in my case)

cat /dev/rfcomm0


Scope error in arduino PinChangeInt library #include<PinChangeInt.h>
#define SensorPin 2

int ledPin = 10;
int BuzzerPin = 12;
volatile byte blip = 0;

void blipcount(){
  blip++;
};

void setup() {
   // put your setup code here, to run once:
   pinMode(SensorPin,INPUT);
   pinMode(ledPin,OUTPUT);
   pinMode(BuzzerPin,OUTPUT);
   PCintPort::attachInterrupt(SensorPin,blipCount,FALLING);
   Serial.begin(9600);
}

void loop() {
   // put your main code here, to run repeatedly:
   if(digitalRead(SensorPin)==HIGH){
      digitalWrite(ledPin,HIGH);
      digitalWrite(BuzzerPin,HIGH);
      Serial.print("blipcoun:\t");
      Serial.println(blip,DEC);
   }

   if(digitalRead(SensorPin)==LOW){
      digitalWrite(ledPin,LOW);
      digitalWrite(BuzzerPin,LOW);
   }
}

I am using arduino uno for a project.I need to record when my sensor gives a high value but i need it to read only falls in pulses.The program is giving  error as

Arduino: 1.6.3 (Windows 8.1), Board: "Arduino Uno"

Sense.ino: In function 'void setup()':

Sense.ino:14:38: error: 'blipCount' was not declared in this scope

Error compiling

please tell me what is the problem with the function.

The library link is
https://code.google.com/p/arduino-pinchangeint/downloads/list

tested the code on both 1.72 and 2.19

You have a typo:

PCintPort::attachInterrupt(SensorPin,blipCount,FALLING);

Should be:

PCintPort::attachInterrupt(SensorPin,blipcount,FALLING);
                                         ^

Note the lower-case "c".


teensy as a keybooard throws error as keyboard input I have a program (bash script) I wrote that is for stop motion animation. The script works perfectly, when I use any given keyboard on my laptop, and it works on other computers, as well.  So i wanted to add a controller, using a teensy, and the keyboard library. source here:

The teensy, set up as a keyboard, using one of the example codes, which I modified. The output appears correct: when I press any of the buttons, I get the expected output (asdw). But, the script throws an error, and exits anyhow, which means something else is being sent besides the key presses I desire.

So, WHY?
Here is the keyboard source for the teensy:

 /* Buttons to USB Keyboard Example

   You must select Keyboard from the "Tools > USB Type" menu

   This example code is in the public domain.
*/

#include <Bounce.h>

// Create Bounce objects for each button.  The Bounce object
// automatically deals with contact chatter or "bounce", and
// it makes detecting changes very simple.
Bounce button0 = Bounce(0, 10);
Bounce button1 = Bounce(1, 10);  // 10 = 10 ms debounce time
Bounce button2 = Bounce(2, 10);  // which is appropriate for
Bounce button3 = Bounce(3, 10);  // most mechanical pushbuttons
Bounce button4 = Bounce(4, 10);
Bounce button5 = Bounce(5, 10);  // if a button is too "sensitive"
Bounce button6 = Bounce(6, 10);  // to rapid touch, you can
Bounce button7 = Bounce(7, 10);  // increase this time.
Bounce button8 = Bounce(8, 10);
Bounce button9 = Bounce(9, 10);

void setup() {
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);  // Teensy++ LED, may need 1k resistor pullup
  pinMode(7, INPUT_PULLUP);
  pinMode(8, INPUT_PULLUP);
  pinMode(9, INPUT_PULLUP);
}

void loop() {
  // Update all the buttons.  There should not be any long
  // delays in loop(), so this runs repetitively at a rate
  // faster than the buttons could be pressed and released.
  button0.update();
  button1.update();
  button2.update();
  button3.update();
  button4.update();
  button5.update();
  button6.update();
  button7.update();
  button8.update();
  button9.update();

  // Check each button for "falling" edge.
  // Type a message on the Keyboard when each button presses
  // Update the Joystick buttons only upon changes.
  // falling = high (not pressed - voltage from pullup resistor)
  //           to low (pressed - button connects pin to ground)
  if (button0.fallingEdge()) {
    Keyboard.println("s");
  }
  if (button1.fallingEdge()) {
    Keyboard.println("d");
  }
  if (button2.fallingEdge()) {
    Keyboard.println("w");
  }
  if (button3.fallingEdge()) {
    Keyboard.println("a");
  }
}

What should I do to just get the key presses (asdw) from the teensy as if it were a plain old keyboard.

You are calling Keyboard.println() which sends the character string followed by a new line.  If you want to emulate a keyboard you should only use Keyboard.print() which only sends the character string with no new line.


NRF24 and usb digispark I want to connect NRf24 module with digispark and use USB capabilities at same time.
currently, i use this conexion diagram:
               NC      PB5  1|o   |8  Vcc --- nRF24L01  VCC, pin2 --- LED --- 5V
nRF24L01  CE, pin3 --- PB3  2|    |7  PB2 --- nRF24L01  SCK, pin5
nRF24L01 CSN, pin4 --- PB4  3|    |6  PB1 --- nRF24L01 MOSI, pin6
nRF24L01 GND, pin1 --- GND  4|    |5  PB0 --- nRF24L01 MISO, pin7

Bu my problem is that as you see in this diagram CE and CSN are in the USB + and - pins:

I just want that my module receive data so, i think that if i power up every time CE pin and i change CSN pin to PB5 this may work but, in fact this don't
I can't use 3 pin connexion because i don't have capacitor and my project is for Wednesday
Thanks in advance for your help

it is possible to use digispark with NRF24 and USB keyboard without use system that need capacitors as the tree cable solution? I just want to use the digispark as RX


Is it possible to specify a pin upon which the data sent over i2c can act? A master will send fan speed values to the slave. The slave will then read the fan speed values and change the speed value for the relevant pwm pin. However I am not sure how I can tell the slave which pin the data is for.  Should I send two packets of data in quick sucsession and then have a loop system wherby the first peice of data out of two is always for specifying the pin? Any help in tackling this would be greatly appreciated.

You can use a struct to send multiple things, like this:

#include <Wire.h>

const byte SLAVE_ADDRESS = 42;

struct t_message
{
  byte pin;
  byte speed;
} message;

void setup ()
{
  Wire.begin ();   // initialize master
}  // end of setup

void loop ()
{
  // set desired parameters
  message.pin = 10;
  message.speed = 50;

  // send the message
  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write ((byte *) &message, sizeof message);
  Wire.endTransmission ();
}  // end of loop

More information about I2C - Two-Wire Peripheral Interface - for Arduino

On that page is mentioned how to Send and receive any data type. This includes structs. Using the code there you could send a struct, and receive a struct.


Boolean Logic With Chars For Motor Input Selection Context of the code:

I am trying to control 2 DC motors through an H-gate, this means there are 4 inputs in total:
For DC motor 1: Input 1 (VCC) and Input 2 (GND).
For DC motor 2: Input 3(VCC) and Input 2 (GND).

Summary of the code:

The global variables are motinpN which are the pins connected to the different inputs.

An array, which is where the different PWM for the motor speeds are stored.

Char x, which is the variable used for the boolean logic.

Then comes the actual loop which consists of 4 similar functions, the "input selector" function and then the statements that turn the integers stored in the inpSpeedS[] arrays into motor speeds.

The issue:

The code won't enter the first loop, i.e it won't advance past

Serial.println("X equals:");
  Serial.print(x);"

I would like to know then, what I am doing wrong in order for this not to work?

   int Speed = 0;
const int motinp1 = 2;
const int motinp2 = 3;
const int motinp3 = 4;
const int motinp4 = 5;

char  x = '0';

int inpSpeedS[4]; // An array to determine the speed of each individual input

void setup()
{
  Serial.begin(9600);
  pinMode(motinp1, OUTPUT);
}

void loop() {
  Serial.println("X equals:");
  Serial.print(x);

  if (Serial.available () && (x == '0')) {
    Serial.print("Which input?");
    x = Serial.read();
    Serial.println(x);
  }
  if (Serial.available () && (x == 'a'))
  {
    Serial.println("Input 1 selected");
    inpSpeedS[0] = Serial.parseInt();
    Serial.print("Input 1: ");
    Serial.println(inpSpeedS[0]);
   x = '0'; //reset x, goes back to input selection
  } if (Serial.available () && (x == 'b'))
  {
    Serial.println("Input 2 selected");
    inpSpeedS[1] = Serial.parseInt();
    Serial.print("Input 2: ");
    Serial.println(inpSpeedS[1]);
   x = '0';
  }
  if (Serial.available () && (x == 'c'))
  {
    Serial.println("Input 3 selected");
    inpSpeedS[2] = Serial.parseInt();
    Serial.println("Input 3: ");
    Serial.print(inpSpeedS[2]);
   x = '0';
  }
  if (Serial.available () && (x == 'd'))
  {
    Serial.println("Input 4 selected");
    inpSpeedS[3] = Serial.parseInt();
    Serial.print("Input 4: ");
    Serial.println(inpSpeedS[3]);
   x = '0';
  }
  analogWrite(motinp1, inpSpeedS[0]);
  analogWrite(motinp2, inpSpeedS[1]);
  analogWrite(motinp3, inpSpeedS[2]);
  analogWrite(motinp4, inpSpeedS[3]);
}

EDIT - I have turned the char 0 from a string literal null to an ASCII code for 0, and same for the other chars. It is still stuck outside of the function loops.

It's screaming on you:

sketch_jun13a.ino:7:11: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

 char  x = "0";

           ^~~

sketch_jun13a.ino: In function 'void loop()':

sketch_jun13a.ino:21:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "0")) {

                                    ^~~

sketch_jun13a.ino:21:36: warning: ISO C++ forbids comparison between pointer and integer [-fpermissive]

sketch_jun13a.ino:26:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "a"))

                                    ^~~

sketch_jun13a.ino:33:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0"; //reset x, goes back to input selection

         ^~~

sketch_jun13a.ino:34:38: warning: comparison with string literal results in unspecified behavior [-Waddress]

   } if (Serial.available () && (x == "b"))

                                      ^~~

sketch_jun13a.ino:41:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

sketch_jun13a.ino:43:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "c"))

                                    ^~~

sketch_jun13a.ino:50:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

sketch_jun13a.ino:52:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "d"))

                                    ^~~

sketch_jun13a.ino:52:36: warning: ISO C++ forbids comparison between pointer and integer [-fpermissive]

sketch_jun13a.ino:58:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

Basically this is char variable with assigned character literal: char x = '0';

And this is C string: char str[] = "0"; or its equivalent: char str[] = {'0', '\0'};. Where '\0' is so called NUL Terminal character.

Everything about C strings you need to know

EDIT:

Simple demo for the "parser" - it's not perfect but should be enough:

char  x = '0';

int inpSpeedS[4]; // An array to determine the speed of each individual input

void setup() {
  Serial.begin(9600);
  Serial.println("Select channel [a..d] and speed [0..255]: ");
}

void loop() {

  if (Serial.available() > 1) { // wait for more characters in buffer
    switch (Serial.read()) {
      case 'a': inpSpeedS[0] = Serial.parseInt(); break;
      case 'b': inpSpeedS[1] = Serial.parseInt(); break;
      case 'c': inpSpeedS[2] = Serial.parseInt(); break;
      case 'd': inpSpeedS[3] = Serial.parseInt(); break;
      default : return; // skip invalid characters like line endings
    }

    Serial.print("Speeds: ");
    for (auto spd : inpSpeedS) {
      Serial.print(' ');
      Serial.print(spd);
    }
    Serial.println();
    Serial.println("Select channel [a..d] and speed [0..255]: ");

    /*
      analogWrite(motinp1, inpSpeedS[0]);
      analogWrite(motinp2, inpSpeedS[1]);
      analogWrite(motinp3, inpSpeedS[2]);
      analogWrite(motinp4, inpSpeedS[3]);
    */

  }
}

And the result:

-> Select channel [a..d] and speed [0..255]:
<- a547
-> Speeds:  547 0 0 0
-> Select channel [a..d] and speed [0..255]:


Having trouble with 74HC595 and Uno Just picked up a couple of 74HC595 shift registers to use for my Arduino Uno, and I'm having trouble getting it working 100% of the time. My code is to get a value from the Serial monitor and shift it into the register. The issue is that bits 4 and 5 are always on no matter what I put into the monitor, but when I clock a 0 into the register during setup(), it works as expected, i.e. all LEDs go off

Here is the code:

int dataPin = 2;
int latchPin = 3;
int clockPin = 4;

void setup() {
    Serial.begin(9600);
    pinMode(dataPin, OUTPUT);
    pinMode(latchPin, OUTPUT);
    pinMode(clockPin, OUTPUT);

    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, 0);
    digitalWrite(latchPin, HIGH);
}

void loop() {
    if(Serial.available()) {
        digitalWrite(latchPin, LOW);
        shiftOut(dataPin, clockPin, MSBFIRST, Serial.read());
        digitalWrite(latchPin, HIGH);
    }
}

Is it the code that is wrong? Do i have a busted shift register? Or something else?
Thanks

Serial.read() is going to give you ASCII codes.  So when you send 1 from the serial monitor the Arduino receives 49.  Note that the ASCII code for a digit is the same as the digit plus 48, so that sets bits 4 and 5 high.

You can use Serial.read() - '0' to get the actual number from the ascii code.


Unable to read the Serial Port through Arduino the way Serial Port Monitor softwares read it I have a device feeding Rx Tx data every minute. I connected it to the computer. I downloaded a Serial Port Monitor Software, and here is the data I captured using that software.

Now when I try to capture the same data using Arduino, it captures something else as you can see in the image below. I tried reading it as hex, char, byte, unsigned int, but it just doesn't read the data properly.

Here I have provided my code. Can someone please identify the problem for me? I've been stuck on this for 2 weeks at least, and it is just not a good feeling! Any help will be much appreciated.

  Using Arduino Ethernet with microSD Card Slot

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

static const int baud = 19200;
static const int chipSelect = 4;
static const int rx = 0;
static const int tx = 1;

File dataFile;
//SoftwareSerial serialPort = SoftwareSerial(rx, tx);

void setup() {

  Serial.begin(baud);     // opens serial port, sets data rate to 19200 bps
  while (!Serial) {
    ;
  }
  //serialPort.begin(baud);

 // pinMode(rx, INPUT);
 // pinMode(tx, OUTPUT);

   Serial.print("Initializing SD card...");

   if (!SD.begin(chipSelect)) {
       Serial.println("initialization failed!");
       return;
   }
   Serial.println("initialization done.");

   dataFile = SD.open("data.txt", FILE_WRITE);
   Serial.println("Data file created!");
   dataFile.close();
}

unsigned int incomingByte = 0;
void loop()
{
  if (Serial.available() > 0) {
                // read the incoming byte:
     incomingByte = Serial.read();
     Serial.print(incomingByte, HEX);
    }

  dataFile = SD.open("data.txt", FILE_WRITE);
  dataFile.println(incomingByte, HEX);
  dataFile.close();
}

  You can build the Serial Port Monitor software using C# Console App, here is the code for that:

using System;
using System.IO.Ports;
using System.Text;

class PortDataReceived
{
    public static void Main()
    {

        SerialPort mySerialPort = new SerialPort("COM3");

        mySerialPort.BaudRate = 19200;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;
        mySerialPort.RtsEnable = true;

        mySerialPort.Open();
        while (true)
        {
            string data = ReadData(mySerialPort);

            if (!string.IsNullOrEmpty(data))
            {
                Console.WriteLine(data);

            }
        }

    }

    public static string ReadData(SerialPort serial)
    {
        byte[] buffer = new byte[serial.BytesToRead];
        serial.Read(buffer, 0, buffer.Length);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buffer.Length; i++)
            sb.AppendFormat("{0:X2} ", buffer[i]);

        return sb.ToString();
    }
}

It's not a good idea to use pins 0 and 1 for SoftwareSerial they are usually connected to Serial


Confusion with storage of declared variables and volatile I read that volatile is used when we want to store variables in SRAM.

But aren't all the variables in a code are stored in SRAM anyway?

And what makes it an advantage sometimes for variables(like volatile) to be stored in SRAM?

That's just plain incorrect.

The volatile keyword tells the compiler that the value of that variable may change at any time, and that therefore it must re-read the value every time you use it in your code.

If you don't use volatile, the compiler may choose to make an optimisation.

Consider this code:

int b = 7;
a = b + b;

The compiler can see that 'b' is always 7 -- it is assigned the value 7 and nobody ever changes it.  The compiler may choose to optimise this to the equivalent of

a = 14;

But if you do this:

volatile int b = 7;
a = b + b;

then the compiler MUST read b twice from memory.

Why would you want to do that?  Perhaps you have an interrupt which might change the value of b.  Perhaps your interrupt changes the value of 'b' every time you press a button.  You need the code to really check the value of b every time it calculates a, and not rely on it always being 7.

Here is a fuller explanation.


Delay on multiple NRF24L01+ (RF24.h) and Arduino nodes I have set up a system using 4 arduino clones, each wired to an NRF24L01+ radio. I am using the RF24 library by maniacbug (https://github.com/maniacbug/RF24) and have set-up the nodes with 1 base node as a receiver and 3 child nodes that transmits continuously to the receiver.

What I want to do is to send the read and analog value wirelessly from the child nodes to the base node as fast as possible. I used the starping example as a guide and it looks almost realtime when only 1 child node is active. When I turn on another child node, most of the time the update stops for a while then continue on, with randomly updating either child 1 or child 2.

I'm guessing there's a collision that's causing the delays. How do I lessen these delays? I'm thinking of having some sort of scheduling system for the children to send their messages (like, child2 will send only after child1, etc.) I also tried radio.setAutoAck(false) in an attempt to lessen the delays but that made all my readings stop altogether.

base node:

    #include "Timer.h"
    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include "printf.h"

    RF24 radio(9,10);
    Timer t;

    const uint64_t pipes[5] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL, 0xF0F0F0F0B4LL, 0xF0F0F0F0A5LL, 0xF0F0F0F096LL };
    unsigned int values[3] = {0,0,0};
    void setup(void)
    {

      Serial.begin(115200);
      printf_begin();
      //printf("Receiver Node Active\n\r");

      radio.begin();

        radio.openReadingPipe(1,pipes[0]);
        radio.openReadingPipe(2,pipes[1]);
        radio.openReadingPipe(3,pipes[2]);
        radio.openReadingPipe(4,pipes[3]);
        radio.openReadingPipe(5,pipes[4]);

      radio.startListening();
      radio.printDetails();
      t.every(1, print_values); //call print_values() every 1ms

    }

    void loop(void)
    {
        int sender_id;
        uint8_t pipe_num;
        if ( radio.available(&pipe_num) )
        {
          unsigned int message;
          bool done = false;
            while (!done)
            {
                done = radio.read( &message, sizeof(message) );
            }
          sender_id = pipe_num - 1;
          values[sender_id-1] = message;
        }
        delay(1);
        t.update();

     }

     void print_values(){
       //formatted for arduinoscope
       printf("%d %d %d 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n", values[0], values[1], values[2]);
     }
    // vim:ai:ci sts=2 sw=2 ft=cpp

child node:

    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"

    RF24 radio(0,1);

    const int SW01 = 18;
    const int SW02 = 19;

    const uint64_t pipes[5] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL, 0xF0F0F0F0B4LL, 0xF0F0F0F0A5LL, 0xF0F0F0F096LL };
    int node_id;

    void setup(void)
    {
      node_id=3; //hard coded id
      radio.begin();
      radio.openWritingPipe(pipes[node_id]);
    }

    void loop(void)
    {
        unsigned int val = analogRead(A0);
        radio.write( &val, sizeof(val) );
        //delay(1);
    }

I am too building a RF24 based network there were two issues I encountered:

1) Update your libraries, use TMRh20 fork of RF24 (to make your life easier, use RF24Mesh too)

2) Add a decoupling cap to the NRF24L01+ power pins.


Controlling 4 LED strips I have 4 single color LED strips which I would like to control individually with one remote controller - turn them on/off an dim them. So far I only have my LED strips (They are about 3.5 meters of length combined), an 80W power supply and an Arduino Uno. I'm new to this kind of stuff. Could you help me with the setup. What parts do I need?

EDIT:
So I decided to go with an Arduino Nano. First, I'll try to power up only one strip. My question now is, how to power up the Nano. All the setups I found, have an USB cable connected to the nano to power it up. Can I connect my 12V+ to the VIN?

EDIT2:
Take a look at my setup. Is that OK?

Thanks

You will need several things.

First I assume that the power supply is a 12V power supply. If it isn't, better to get one (3.5m of leds can be 4.2A, so even a 12V 5A supply is fine). Note: you didn't specify the led size, so the current can vary a lot. But a standard one is a 60 leds/m 5050 leds, which means 60mA/5cm, or 4.2A for a 3.5m strip.

Anyway you will need a 12V power supply to power both the strips and the arduino (through the Vin pin).

You will then need a way to control the leds from the arduino. Since the required current is too high for the arduino, you will need to put a transistor. I tend to prefer nMOS over NPN, but just because of the way I learned them. Anyway just get a low-side transistor (either an nMOS or an NPN) capable of handling the required amount of current (at least a couple amperes, better if they are >5A) and the proper circuit to turn them on. Usually you will just need one or two resistors. You will need to connect the +12V to the plus terminal of the leds, the drain (or collector) of the transistor to the ground pin of the led you want to control, the source (or emitter) of the transistor to ground and the gate (or base) of the transistor to the arduino through the proper circuit.

Then the remote controller. You did not specify what kind of remote controller you want to use, but usually you can cope with a IR receiver (e.g. the TSOP382 or any other) and the proper decoding. A lot of remote controllers are already mapped in the library IRremote; you just have to read the value it provides; inside the arduino you will need to save the codes for the commands (you will have to train it first) and then simply compare.

This is a generic answer, because you did not provide any details. If, implementing this, you encounter any problem open a specific question with what you did up to that point.


Keyboard.print() skips keys I'm playing with the Arduino Leonardo Keyboard.print() command, but I'm facing a annoying problem:

When I print a double quote, it will not appear and also will make to disappear the next character (i.e.):

Keyboard.print("echo \"This is a demo\"");

Output:

echo his is a demo

And when I use this line:

Keyboard.print("echo -This is \"a demo-");

Output (note the umlaut over the a instead of getting "a):

echo 'This is ä demo'

I suspect that the problem is that my computer is configured to use Spanish layout.

What source code file can I change to fix this? I can't find the defines used by Keyboard.print()

The Arduino assumes a US keyboard layout.  The thing with keyboards is they don't actually send the letters or symbols that are printed on the keys.  Instead the send a scan code that defines where on the keyboard the key is.  It is then up to the computer to convert those scan codes into actual letters and symbols, and that is performed by the keyboard mapping selected in the operating system.

Some special keys are known as dead keys.  These don't actually print a character on their own - instead they are used to modify the next key pressed - for instance the key which occupies the space a " would be on a US keyboard, on a Spanish keyboard, is a dead key which modifies the next key by adding an umlaut to it.

Since the Arduino doesn't know that you have a Spanish mapping, when you send a " it just sends what it believes is the location of that character on a keyboard, and of course it gets that wrong since it assumes the wrong keyboard layout.

So there are two things you can do to "fix" it:

Change your keyboard layout to US, but that will mean your normal keyboard will stop working properly.
Change how the Arduino thinks the keyboard is laid out, but that means lots of work to find the right scan codes.

The Arduino's keyboard layout is stored in the file HID.cpp in the Arduino core (hardware\avr\cores\arduino or somewhere like that - I forget off hand) and is the _asciimap array.  It is a list of the first 128 ASCII characters and the keyboard scancode mappings for them, including modifier keys like Shift.  You will have to find the scan codes for the keys you want to map on your keyboard layout and change the codes in that list.  For instance, the character " is listed as:

0x34|SHIFT,    // "

Which is scan code 0x34 (52 decimal) coupled with the SHIFT modifier.  You will have to discover (maybe Google can help) what the 0x34 should be changed to so that it moves the " to wherever it is on a Spanish keyboard.


Problems with Dallas temperature sensor code I have connected up my temperature sensor and I am trying to run the one wire address finder to find the address of the sensor.

The problem is that when I run the code it gives me the error: 'OneWire' does not have a type.

I have imported by the temperature and the onewire libraries but it still does not work.

#include <OneWire.h>

OneWire ds(6);  // This is where the error is

I presume the exact error you get is

  error: 'OneWire' does not name a type

This error is typical when the OneWire library (or any other library for that matter) is not located under the  libraries folder, which should be at the root of the Arduino installation folder.

Also, make sure that the OneWire.h and OneWire.cpp files are 1 folder down the hierarchy, as follows:

[Arduino Installation Folder]\libraries\OneWire\OneWire.h

If they are nested deeper inside the folder hierarchy, the Arduino IDE will not find these files in its initial scan, and you will get the same error.

Make sure to close all Arduino IDE windows and re-open it after fixing the folder path.


Why does this code show me a lot of space? I want to make a 4hz reading of GSR and temperature, in the following format for every second:

697,20.8744
696,20.86521
695,20.8653
699,20.8777

The print, in python, would be print(GSR+","+Temp)
The tries in C are giving problem, here's my actual code:

#include <OneWire.h>

const int GSR=A0;
int threshold=0;
int sensorValue;
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
OneWire  ds(3);

void setup(){
  long sum=0;
  Serial.begin(115200);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
  }

void loop()
{
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius;
    if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        // Do your job, such as
        sensorValue=analogRead(GSR);
        Serial.print(sensorValue);
        Serial.print(",");
        if ( !ds.search(addr)) {
    ds.reset_search();
    return;
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
      return;
  }
  // the first ROM byte indicates which chip

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

   // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
  }

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  Serial.print(celsius);

    }
    Serial.println("\n");

}

How can I reach the upper format?

From the point of view of what you print, your loop boils down to:

if (millis() - startTime >= MEASURE_PERIOD) {
    startTime += MEASURE_PERIOD;
    sensorValue = ...;
    celcius = ...;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.print(celsius);
}
Serial.println("\n");

You are printing two newlines on every loop iteration. One is written
as "\n", the other is the “ln” of Serial.println (“println” means
“print some stuff followed by a new line character sequence”). Instead,
you probably want to print a single newline, and only when there is
actual data being printed:

if (millis() - startTime >= MEASURE_PERIOD) {
    startTime += MEASURE_PERIOD;
    sensorValue = ...;
    celcius = ...;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.println(celsius);  // notice the ln in println
}

But since you are doing nothing else in loop(), you could simplify a
bit and avoid having everything inside a big if statement:

if (millis() - startTime < MEASURE_PERIOD)
    return;

startTime += MEASURE_PERIOD;
sensorValue = ...;
celcius = ...;
Serial.print(sensorValue);
Serial.print(",");
Serial.println(celsius);

Edit: Here is a simple test demonstrating this logic. In both the
second and the third case, it generates an output in the requested
format.

const uint32_t MEASURE_PERIOD = 250;

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

void loop()
{
    static uint32_t startTime;
#ifdef SECOND_CASE
    if (millis() - startTime >= MEASURE_PERIOD) {
        startTime += MEASURE_PERIOD;
        int sensorValue = random(695, 699);
        float celsius = map(sensorValue, 695, 699, 208653, 208777) / 1e4;
        Serial.print(sensorValue);
        Serial.print(",");
        Serial.println(celsius, 3);  // notice the ln in println
    }
#else  // third case
    if (millis() - startTime < MEASURE_PERIOD)
        return;

    startTime += MEASURE_PERIOD;
    int sensorValue = random(695, 699);
    float celsius = map(sensorValue, 695, 699, 208653, 208777) / 1e4;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.println(celsius, 3);  // notice the ln in println
#endif
}


Beat 1 LED light is always on - should turn off /**************************************/
const int lowestPin = 1;//the lowest one attach to
const int speaker = 13;
int ts = 4;//how many beats you want
int count = 1;
const int keyPin = 11;
const int keyPinR = 10;
int buttonState = LOW;
int buttonState2 = LOW;
int bpm = 120;
int rthm = 1;
/**************************************/
void setup()
{
  Serial.begin(9600);
   for(int thisPin = 1;thisPin <= ts;thisPin++)
   {
 pinMode(thisPin,OUTPUT); //initialize thisPin as an output
 pinMode(8, INPUT);

 pinMode(keyPin, INPUT);
 pinMode(keyPinR, INPUT);
 digitalWrite(keyPin, HIGH);
 digitalWrite(keyPinR, HIGH);
 }

}

/****************************************/
void loop()
{
 buttonState = digitalRead(keyPin);
 buttonState2 = digitalRead(keyPinR);
 if(buttonState==LOW){
 ts++;
  if(ts==6)
   {
    ts = 2;
   }
  }
 if(buttonState2==LOW){
  rthm++;
    Serial.println(rthm);
  if(rthm==5)
  rthm = 1;

  }
  for(int thisPin = 1;thisPin <= ts;thisPin++)
  {

  for(int r = 1; r<=rthm; r++){
   bpm = pulseIn(6, HIGH);
    digitalWrite(thisPin,HIGH);

    pinMode(13,OUTPUT);

    if(count == 1&&r==1)
    tone(13,1500,40);
    else if(r==1)
    tone(13,1000,40);
    else
    tone(13,500,40);
    delay((bpm-52)/rthm);

    digitalWrite(thisPin,LOW);
    pinMode(13,INPUT);

   }
    count++;
    if(count >ts)
    count = 1;
    }

   }

This is a metronome project. Each LED represents a beat. However, The LED for beat 1 is always on. It should turn off when it's on a different beat other than one. Is there anything wrong with the code?

You are using PIN1 as an output pin and you are writing data to the Serial interface.  The serial interface uses pin 1 and 0.
Change lowestPin to 2 and ts to 5 and it will work.


How to use ESP8266-12E with PCF8574 as an I/O extender I am using ESP8266-12E with a PCF8574 as an I/O Pins Extender.
There are videos on youtube to use the PCF8574 with an ESP8266-01, but my problem is that I'm unable to analyze the pin connections with an ESP8266-12E.
In the youtube tutorial it is said that the GPIO0 AND GPIO2 will go to the SDA and SLC pins of the PCF8574, but then, in the case of ESP8266-12E, the pins will go to the PCF8547.

Thanks in advance.

Found the answer .
The data sheet of ESP8266-12E explains everything.
The pin diagram has the given tags which shows which pins we can use.


strcat appending multiple times when called in loop The strcat function is working fine when called for the first time but when the broker goes down and it's attempting to reconnect it is appending the value twice. I am not able to figure out the problem as i am writing C code for the first time.

void reconnect() {

  while (!client.connected()) {
    const char* cid = clientID.c_str();
    if (client.connect(cid)) {
       const char* sTopic = strcat("clm/",cid);
       client.publish(outTopic, sTopic);
       client.subscribe(sTopic);
    } else {
    // Wait 5 seconds before retrying
    for(int i = 0; i<5000; i++){
      delay(1);
    }
  }
}

}

It is called in the loop method

void loop() {
  if (!client.connected()) {
    reconnect();
  }
}

The value of sTopic for the first time is clm/5C:CF:7F:3D:5B:F6 but when the broker restarts and the client connects again it is clm/5C:CF:7F:3D:5B:F65C:CF:7F:3D:5B:F6

What could be the reason for the same ?

Appends a copy of the source string to the destination string.

source

Congratulations, you've broken your string literal. Either stick to using String or make sure you allocate a string properly and then concatenate into that.


Timer 1 Arduino - Create 2 Timers I’m trying to output 2 separate frequencies using 2 output pins from an Arduino using the Timer 1 library. A snippet of the code is show below.

void setup()
{
 Serial.begin(9600);
 pinMode(button,INPUT_PULLUP);
 pinMode(button2,INPUT_PULLUP);
 pinMode(sig_out, OUTPUT);
 pinMode(sig_out2, OUTPUT);
Timer1.initialize(1000);
Timer1.pwm(sig_out,512,period);
Timer1.pwm(sig_out2,512,period2);
}

The issue is the way I’ve wrote this makes sense as I’ve initialised 2 outputs and 2 inputs but the ‘period’ is getting overwritten as there’s 1 timer and I’m not sure how to stop this. I was thinking about storing them in variables (like 'T1=' 'T2=') but it would still use the same timer.

I just wanted to know if there’s a way to use 2 timers so the Arduino outputs the frequencies separately.

The Timer1 library only supports... Timer 1! So you only have one
hardware timer available. If you are using an Arduino Uno or anything
similar, you have a couple of other timers. However, unlike
Timer 1, which is a 16-bit timer, the others are 8-bit only. This
means they are very limited in the range and precision of the
frequencies they can generate. If you have an Arduino Mega, then you
have a few other 16-bit timers available. You may want to search for a
library called Timer3, which should work just like Timer1, while using
the 16-bit Timer 3.

If you don't find any suitable library, you may still be able to
generate your two signals using only Timer 1. Here is the trick:

set both PWM outputs to “toggle on compare match”
enable both compare match interrupts
in each of these ISRs, advance the compare match register by half a
period of the corresponding signal.

For doing this you will need to dig into the low-level details of how a
timer actually works. I recommend you start by reading the
Timers and counters tutorial by Nick Gammon.
Take the time to read and
study this. It's not a topic you will be able to master in just a
couple of hours.


Advice on setting up a real-time audio equaliser First time Arduino user here.
We have a microphone set-up which feeds back loudly on particular frequencies and need an equalizer to (preferably automatically) detect spikes in particular frequency bands and attenuate them before sending them on to the speakers. The dB level that has been cut from that frequency channel would then be displayed on an LED matrix such as this one:

Does the Arduino have the processing capabilities to keep up with the audio without noticeable lag? As the LEDs will only be a visual indication of the affect the attenuation is having on the frequencies, it is not particularly important that these be fast. Unfortunately, as the audio stream will be vocals, even a slight delay will render the thing useless. What delay might I expect with a single mono channel going through the arduino?
I expect that I will eventually have to revert to the less-interesting project of an RTA which takes a split of the audio sends to the speakers and simply displays the frequency band intensities rather than altering them.
I'd appreciate any thoughts.

Somewhat possible if you accept that the Arduino won't be doing most of the work:

Yes, the Arduino can sample audio and perform FFT on it, though not fast and not at high frequencies
Yes, the Arduino can decide what to do depending on the power of different buckets
Yes, the Arduino can display the results
No, the Arduino cannot do realtime audio filtering.

If you accept that the filtering will have to be done with a bank of analogue band-cut filters that the Arduino turns on and off as needed then it may be possible.

The Arduino Due might be a more suitable candidate since it will be able to sample and do the FFT much faster so you'll be able to respond to the peaks much quicker, and the displaying won't get in the way so much, but actively filtering inside the chip really requires a DSP.


How can I program RFduinos and how can I connect them with Bluetooth? My RFduino dev kit just arrived, and for my project I have to connect a few RFduinos via Bluetooth and light up certain LEDs attached to the RFduinos. If anyone could point me in the right direction as to where I can program them/how I can connect them, it would be GREATLY appreciated.

I am starting on a similar project (without the Dev Kit).  Hooking the Bluetooth module to the RFduino is pretty straight forward, PWR to PWR, GND to GND, remember to cross the transmission wires: TX to RX & RX to TX.

In your void setup(), you need to start the connection:

Serial.begin(9600); // check your documentation to see the baud rate

In your void loop(), read or write to/from the bluetooth connection with serial write/read. Serial.read() or Serial.write()

Remember that Bluetooth is a communication protocol, not a controller.  You don't mention WHAT you are connecting your RFduinos to using Bluetooth. You still need a controller capable of sending a signal to light up the LEDs using Bluetooth.


Arduino SoftwareSerial - can't get data from NEO 6M-GPS module I am using Mikael Hart's TinyGPS (v.13) library and example code to talk to my module. The LED on the GPS module is lit and flashing which I assume means it is receiving data from the GPS satellites. The module seller claims that the module has a default baud of 38400.
I'm pretty sure it's wired up correctly:

And my sketch says:
SoftwareSerial ss(4, 3);

So I read this as Orange (Rx) to pin 4 and Brown (Tx) to pin 3.
Any help appreciated

RX of the Arduino (pin 4, according to the SoftwareSerial statement) goes to the TX of the GPS.  Arduino pin 3 (ss TX) goes to the GPS RX.

And you should use pins 8 & 9 instead.  That would let you use AltSoftSerial, the best choice when you can't use HardwareSerial (i.e., Serial).

If you can't use pins 8 & 9, then NeoSWSerial is a better choice than SoftwareSerial.

And while I'm promoting NeoSWSerial, I'll mention a library I wrote, NeoGPS...  It's faster and smaller than all other GPS libraries, and very configurable.  It also has several diagnostic programs and a Troubleshooting section in the docs.


8 bit arduinos: What happens to the data in registers during a function call? During an interupt? If I have one function that uses registers heavily calling another that does the same thing, what happens?  Does the data get destroyed?  What, then, would happen on return to the first function?  Is this different for interrupt handlers?

The compiler is capable of analyzing which registers are used by the function or ISR, so it generates prologue and epilogue code that saves the registers on the stack on entry and restores them on exit.


Can the DHT11 give reasonable readings? I bought a batch of ESP8266-01 and DHT11 on ebay.

The sensors give data, but the datasheet say +/- 2 degrees. Who can live with that? Well, they claim the repeatability is 0.2 degrees, so I guess they could be calibrated.

But thet are not stable. They start a few degrees over room temperature, but gradually the reading is up to 33 degrees, more than 10 degrees too high.

Could it be the proximity of the ESP8266 giving off heat? Or are the sensors themselves heating up when reading at one read every two seconds?

It could be the ESP8266, try physically separating the DHT11, but I'm guessing that that will only help slightly.

Do you have some way of reliably calibrating the sensors? If not, then even if you are getting consistent readings, you'll have a hard time knowing how accurate your readings are.

While they're typically more expensive, it might be prudent to buy an infrared temperature sensor. If you have the budget, replacing the DHT11s with IR temperature sensors might just be a better solution, I saw that Sparkfun's MLX90614 was accurate within +/- 0.5 degrees Celsius. If you don't have the budget to replace your DHT11s, or don't want to be wasteful, perhaps you just buy one IR temperature sensor to use as a sanity check. These should be more reliable than DHT11s and you could even write a sketch to calibrate them based on the IR temperature sensor's readings.


How to convert 0-5v inverted serial to 0-3.3v non-inverted serial This weather stations has a 0-5v serial output.  I'm trying to read the serial output with the Adafruit 32u4 feather board and I get nonsense data out of it.  When I hook the Ultimeter up to my serial->usb cable I get the normal data output.  When I hook up the Ultimeter to a 5v arduino via SoftwareSerial in inverted mode I get proper data.  But I need to connect this weather station to a 3.3v Feather board's hardware uart which doesn't seem to be able to operate in inverted mode.  Is there a 5v -> 3.3 level converter that also will invert the serial signal ?

I think you're looking for an inverting amplifier. This can be done with either a BJT or a MOSFET (assuming your input is enough to turn the MOSFET on). Here's an example with a BJT:

simulate this circuit – Schematic created using CircuitLab

The output range is independent of the input and is defined by the supply voltage.


How can an Arduino-Quadcopter be stabilized? I have built an arduino quad-copter and I am using an MPU6050 to read the rotational position and velocity of the aircraft. The problem is that I cannot get the thing to stabilize. Watch this video here to get an idea of what I mean.

So as you can see from the footage (and you did watch it, right?), I'm not even getting steady oscillations, it's just random. What I don't understand is how people get their quad-copters to oscillate very quickly (maybe 10 times per second) and then trim up their PID gains to smooth it out, whereas if I raise my p-gain high enough for it to adjust that quickly, the quad-copter just goes berserk and tries to kill me.

And, speaking of p-gains, here's the PID I wrote:

float KrP = 0.002000;
float KrI = 0.000001;
float KrD = 0.200000;

void adjustRoll(float currentRoll, int newRoll) {
  if (thrust <= 1200){
    inAutoRoll = false;
    NWPower = thrust;
    NEPower = thrust;        //PID not ready to turn on yet? Just set motor powers
    SWPower = thrust;        //equal to the throttle.
    SEPower = thrust;

    I_roll = 0;              // Reset the integral.
    return;                  // Don't do anything else
  }

  float newRate = 2 * (newRoll - currentRoll); // How fast should the drone try to
                                                                       // adjust, based on the error.

  if (newRate > 50)newRate = 50;        // Don't adjust too fast!
  else if (newRate < -50)newRate = -50;

  float offset = newRate - rollRate;

  I_roll += KrI * offset;

  if(!inAutoRoll) {        // Is the PID just now turning on? (Throttle requirement met).
    lastRollRateOffset = offset;  //Smooth transition.
    inAutoRoll = true;
  }

  float adjust = (KrP * offset) + (KrI * I_roll) + (KrD * (offset - lastRollRateOffset));

  NWPower += adjust;
  NEPower -= adjust;
  SWPower += adjust;
  SEPower -= adjust;

  if (NWPower > maxOut) NWPower = maxOut;
   else if (NWPower < minOut) NWPower = minOut;

  if (NEPower > maxOut) NEPower = maxOut;
   else if (NEPower < minOut) NEPower = minOut;

  if (SWPower > maxOut) SWPower = maxOut;
   else if (SWPower < minOut) SWPower = minOut;

  if (SEPower > maxOut) SEPower = maxOut;
   else if (SEPower < minOut) SEPower = minOut;

  lastRollRateOffset = offset;
}

And in case you were wondering... yes, I do know about integral windup. The reason I have not dealt with that in my code is because the quadcopter is no where near stable, so I'm not worrying about perfection just yet. Also, I have my I-gain set to 0.000001, so it doesn't matter. The reason I have done this is because (as far as I know) a quadcopter can fly with only P and D, and with the way mine is behaving, I think a larger I-gain would only make things worse.

More detail about my PID: The PID corrects for the rotational velocity of the quad-copter, which, as I understand it, is the best way to control a quadcopter. The correction-rotation-rate is determined by multiplying the error (in degrees) by two. Why two? I dunno. I experimented with some other multipliers and two seems to be okay. Its also a prime number, so, yeah...

So anyways! What do I need to do to make the quad-copter stable? I have seen amazingly perfect quad-copters using the same arduino and the same MPU6050, but mine just tilts all over the place.

Some possible problems off the top of my head:

Bad algorithm for calculating the needed rotational velocity based on error.
Bad PID algorithm.
Bad PID gains.
I didn't balance my props, but seriously, would a couple of pieces of electrical tape stuck to the props really fix this? It doesn't seem like it would.

Thanks for any help you have to offer!

For stability and tuning you need to make the adjustment cycle time compatible with the physical system.  How fast does this adjustment code get called relative to how fast the physical system oscillates?  Without that under control, tuning the gains will be difficult, particularly for krI and krD.

For instance, if you are updating every millisecond, and it takes a 1/10th of a second to physically flop over from -90 to 0 at the current roll_thrust setting, there's only enough kP to adjust the roll_thrust kP*(RollDelta/2)*DT/dt=0.002*(90/2)*0.1/0.001=9  Is that a sane adjustment for a thrust/motorPower of 1200+?  If you sample fast enough to make it capable of a full-throttle (+/-800?) adjustment with this particular kP, you might need to sample 88x faster (1ms/(800/9)=0.01125ms).  From the other direction, I'd figure out how fast you can sample, then choose a krP that could get you a full-bias adjustment in reasonable time.

Maybe think of adjust as roll_thrust state variable measured in units of ESC_microseconds, and krP is the conversion factor from whatever error you are measuring.  Is it roll angle error? roll rate error? Absolute roll rate error?  It looks like this bit:

float newRate = 2 * (newRoll - currentRoll); // How fast should the drone try to
if (newRoll - currentRoll < 0) {             // adjust, based on the error.
   newRate = 0 - newRate;
}

is essentially:

float newRate = 2 * abs(newRoll - currentRoll);

which might make control discontinuous.  If currentRoll is a positional roll angle setpoint, it won't be able to tell if it is on one side or the other.

If you want a roll angle of -90deg to make full throttle one way and 90deg to full throttle the other, then krP should be on the order of 900us/90deg=10us/degree.   And krI=krD=0 to start with.

I'd code up separate PIDs for thrust, roll_thrust, pitch_thrust, yaw_thrust control variables and then sum them together to get the  {NE,NW,SE,SW}Power outputs.  Then you could monitor and control in {thrust,roll_angle,pitch_angle,yaw_rate} space and the coding will be more straightforward and interpretable.


Power ESP01 in forest I want to do WiFi GeoChaching box. I'll use cheap ESP01, but problem is it will work in forest 24/7 in cycle of 1 min of work 5 in deep sleep and waiting for those who will find that.
How I can get power?

I think that in this case you will need multiple solutions for generating the power.

You need to know how much power you need.  This depends on you solution, I can't help there.
You need a backup battery, ideally one that doesn't mind constant trickle charge and deep discharge.  Sealed lead acid are probably the best.
Your battery must have enough power over a long enough time.
You need a power generator, wind, solar, water, chemical. And they should all have a common interface so you GeoCache is modular, so the GeoCaches can be plugged into any of the power sources, maybe even more than one source.

The problem with the power source is it is going to be a visual clue to where the cache is, probably also an audio clue.
The battery, if SLA, is going to be a great big lump that could be dangerous if damaged.
The caches are not going to be cheap, just because of the power source and battery, so I hope you have deep pockets.

Rather than looking for a ESP01+BT4 module look for any microprocessor with BT built in, it maybe a better way to go.


How to prevent Arduino compiler from merging changing of port pin outputs into a single operation I want to set one pin's output value, and then set a different pin's output value so that the two pins change value one after the other.
However, the compiler optimises the two calls to change both pins in one go.

PORTD |= _BV(0);    //set pd0 to high
PORTD |= _BV(1);    //set pd1 to high
PORTD &= ~(_BV(1)); //set pd1 to low

The two pins go high simultaneously. I tried inserting a NOP between these but it doesn't change behaviour.

(I originally intended to include an oscilloscope screengrab to show what was happening - that's how I knew (or got the wrong impression) that the two pins were changing at the same time. But the photo wasn't shifting from my Nexus 7 for me to access it from my laptop.)

I certainly can't duplicate what you are saying.  The small code snippet:

void setup() {
    PORTD |= _BV(0);
    PORTD |= _BV(1);
    PORTD &= ~(_BV(1));
}

void loop() {
}

compiles into:

000000a6 <setup>:
  a6:   58 9a           sbi 0x0b, 0 ; 11
  a8:   59 9a           sbi 0x0b, 1 ; 11
  aa:   59 98           cbi 0x0b, 1 ; 11
  ac:   08 95           ret

000000ae <loop>:
  ae:   08 95           ret

That is clearly two separate bit sets followed by a bit clear.

I am using UECIDE that is set to use GCC 4.3.2

If I switch to GCC 4.8.1 instead, the code generated is identical.

Even turning on full -O3 optimization I still get the same results.

So how are you determining that it's happening at the same time?


Stuck on uploading sketch via USB 6 pin I'm just got a Galileo Gen2 and wanted to try a simple blinking-led. The firmware have been updated to 1.0.4. My problem is whenever I try to upload the code I get this error:

Sketch uses 83,775 bytes (0%) of program storage space. Maximum is 10,000,000 bytes.
...
echo "Sending Command String to move to download if not already in download mode"
echo "~sketch downloadGalileo" > $tty_port_id

Deleting existing sketch on target
#Move the existing sketch on target.
echo "Deleting existing sketch on target"
"$fixed_path/lsz.exe" --escape -c "mv -f /sketch/sketch.elf /sketch/sketch.elf.old" <> $tty_port_id 1>&0
Login timed out after 60 secondsPoky 9.0.2 (Yocto Project 1.4 Reference Distro) 1.4.2 clanton /dev/ttyS1clanton login:`

The answer was simply that 6-pin are not designed for uploading sketches. Instead use the micro-USB port to upload sketches.


Unsure how to connect the anode in this circuit I am making a game of X and O’s and ran out of pins on the Arduino. After searching on the internet I found out about connecting it in a grid connecting all the anodes in columns and the different colours in rows but I don't know how to connect the anodes so it only turns on only one of the LEDs rather than the other 2 in the grid if they are all connected to ground. The wires I am unsure to connect are the orange ones in the diagram below (bottom left corner). Note the Red on the RGBs are not used so don't need to be connected

Firstly, you have made the classic rookie mistake with your circuit regarding your LED current limiting resistors.  You have one per LED group instead of one per LED within a group.  The arrangement you have at the moment means that at best some LEDs will be dim or not light at all, and at worst will result in LEDs burning out.

There should be a resistor in every red, green and blue wire in your diagram.

As for what to do with the three orange wires (once you have re-arranged the resistors) they connect to three spare IO pins on the Arduino - you then turn each column on or off as you need - only one column is on at a time.  If you need more than 20mA for a column (which is highly likely with up to 9 LEDs on at a time) then those lines should be connected to either +5V or GND (depending on if you are common anode or common cathode) via transistors and the transistors should be switched by the IO pins.


Utilizing Array with RGB I am trying to create a sketch that utilizes two arrays, one array to hold five buttons as input, assigned to pins, and another array to hold five musical notes.  I have attached a RGB LEDs with pull-down resistors and attached a 8 ohms resistor speaker.

The code is as followed:

 //Pentatonic Piano
 // C D E G A

 #define NOTE_C   262 //HZ
 #define NOTE_D   294 //HZ
 #define NOTE_E   330 //HZ
 #define NOTE_G   392 //HZ
 #define NOTE_A   440 //HZ

 const int SPEAKER = 9;   //speaker on pin 10
 const int BLED = 10;      //Blue LED on pin 9
 const int GLED = 6;      //Green LED on pin 6
 const int RLED = 5;      //Red LED on pin 3

 int buttonState = 0;

 //Button Array
 int Buttons[]= {11, 8, 7, 4, 3};

 //Tone Note Array
 int Notes[] = {NOTE_C, NOTE_D, NOTE_E, NOTE_G, NOTE_A};

 void setup()
 {
 pinMode(BLED, OUTPUT);
 pinMode(GLED, OUTPUT);
 pinMode(RLED, OUTPUT);
 pinMode(Buttons, INPUT);
 }

 void loop()
 {

   buttonState = digitalRead(Buttons);

   if (buttonState = Buttons[0])
   { tone(SPEAKER, Notes[0]);
    digitalWrite(BLED, LOW);
    digitalWrite(GLED, LOW);
    digitalWrite(RLED, HIGH);

   }
   else if (buttonState = Buttons[1])
   {tone(SPEAKER, Notes[1]);
    digitalWrite(BLED, LOW);
    digitalWrite(GLED, HIGH);
    digitalWrite(RLED, LOW);
   }
   else if (buttonState = Buttons[2])
   {tone(SPEAKER, Notes[2]);
    digitalWrite(BLED, HIGH);
    digitalWrite(GLED, LOW);
    digitalWrite(RLED, LOW);

   }
   else if (buttonState = Buttons[3])
   {tone(SPEAKER, Notes[3]);
    analogWrite(BLED, 127);
    analogWrite(GLED, 0);
    analogWrite(RLED, 127);

   }
   else if (buttonState = Buttons[4])
   {tone(SPEAKER, Notes[4]);
    analogWrite(BLED, 0);
    analogWrite(GLED, 127);
    analogWrite(RLED, 127);

   }

   else
   {
    digitalWrite(BLED, LOW);
    digitalWrite(GLED, LOW);
    digitalWrite(RLED, LOW);
    noTone(SPEAKER);
   }
 }

The problem is no matter what button I press, the RGB only emits a green light and there is absolutely no sound coming from the speaker.  I am truly stumped.

First, these statements:

if (buttonState = Buttons[0])

are doing an assignment, not a test for equality. You want:

if (buttonState == Buttons[0])
//               ^Notice

Next, pinMode takes two integers, but you are passing an array. You can use a loop to call pinMode multiple times:

for (int i = 0; i < sizeof(Buttons) / sizeof(Buttons[0]); i++) {
     pinMode(Buttons[i], INPUT);
}

Same goes for digitalRead(). You need to read the state for each button:

buttonState = digitalRead(Buttons[0]);
if (buttonState == HIGH) {
   ....
}
buttonState = digitalRead(Buttons[1]);
if (buttonState == HIGH) {
   ....
}
//etc


Using an Arduino as an input device I had an idea to create a control panel using an arduino and some buttons. How would I go about making the arduino emulate an input device so that when I press a button connected to the arduino, it would cause the same effect as when a keyboard key was pressed? (I'm using arduino UNO, if it helps.)

Thanks in advance.

I have successfully reprogrammed the UNO's R3 8U2 to support keyboard emulation, as to just this. Making dedicated user inputs for kiosks to Computers. I recommend NicoHood's GitHub as it allows simultaneous Arduino Bootloader and Keyboard functionality, making it easy to reprogram the Arduino.

This along with using Capacitive Touch Sensor connected to Copper tap under clear acrylic protecting printed graphics of buttons is very quick and easy to make. Very little machining.

Example of such code is found at artemis-firmwares it was initially created with a different 8U2 method. Where next time we will use NicoHood's.

Note the stock keyboard send key command for the Arduino is limited. Where the above methods allows the code to send complete virtual keys supporting full emulation.


NodeMCU: Wiegand not working for one device, while working for another I'm using a NodeMCU, and a working code for reading Wiegand data, with this library.

I managed to successfully read the Wiegand signal from this device.

However, I also have this new AR-721H device, and I can't get the Wiegand to work. This is the manual for the device.

There is absolutely nothing coming to the mcu. Everything is wired identically as the working device.

According to the manual, everything should be working, but I am at a loss.

Can someone please tell me what I might be doing wrong?

The store clerk told me something about needing a controller that converts RS485 to RS232, but I have no idea what that means. I already made it work with another device...

It's quite cryptic from the little information in that (somewhat chaotic) "manual", but I interpret it that the Wiegand interface is an input port, not an output port.  It is intended to connect that port to an external card reader or keypad as a remote interface (typically the other side of the door to this unit).

For communication with your Arduino you should use the RS-485 interface. For that you need an MAX485 breakout board.


How should I use an optocoupler to control a 12Vcc load with Arduino? I am developing a project to operate a load of about 12Vdc.  I considered the use of an optocoupler to avoid mechanical wear of a relay.  The design I have tried is this:

This configuration seems to work OK, but I am a biologist and this is my first attempt with an opto of any kind!!!!  I had a lot of trouble with the transistor until I changed to a PNP.  Is this right?  Can it be done with an NPN or even without any transistor at all?

If your load draws a small amount of current (less than about 30 mA current), your 4N35 optocoupler could drive the load directly on 12 volts.

Ignore my use of 4N28 (similar to 4N35). It is the symbol that I had.

It appears that your PNP transistor circuit is something like this :

The PNP transistor circuit can work well depending upon your load current.  The PNP circuit has some problems with the transistor not turning on fully (and won't be described here).  You may not get the full 12 volts to your Load. But, if it works for your load, then be happy with the PNP circuit.

The circuit below is for a NPN transistor circuit  :

Using the NPN circuit allows (in this case) for the transistor to turn on fully, leaving almost the full 12 volts for your Load.

Important Note :  The NPN transistor circuit produces an output that is the LOGIC opposite of the PNP circuit.   Notice that for the PNP circuit, a logic 1 to the input of the optocoupler (LED on) turns on power to your Load.

On the NPN circuit, a logic zero (0) to the optocoupler LED is required to turn on your Load.

Another variation of the circuit is below, and does NOT have the reverse logic situation.  In other words, it will behave like the PNP circuit. When LED is on, the Load will be on  :

You can experiment with the value of R1 in the NPN circuits. You could experiment with lower value, down to 1K (1000 ohms) if you are using a power transistor to drive high current loads.


Communication over I2C protocol with more than one A/D device According to datasheet of MCP3021 A/D converter (Microchip, page 16) the MCP3021 can be accessed by proper address bits in control byte. In case of MCP3021 5AT the address is 101, in case of MCP3021 4AT the address is 100. Does than mean that to interface two MCP3021 diveces in one circuit one have to purchase two devices with different serial number, e.g. MCP3021 5AT and 4AT?

Yes, you need different devices for different addresses. Up to 8 addresses are possible:

  The first part
  of the control byte consists of a 4-bit device code, which
  is set to 1001 for the MCP3021. The device code is fol-
  lowed by three address bits: A2, A1 and A0. The default
  address bits are 101 (contact the Microchip factory for
  additional address bit options).The address bits allow
  up to eight MCP3021 devices on the same bus and are
  used to determine which device is accessed

The number after the A in the part number indicates the address:

Off the shelf you get address 5. If you want other addresses you have to order them specially from Microchip.

The device sacrifices flexibility in favour of size. If you want multiple devices on the same bus and not have to order different parts specially then you generally end up with a bigger chip with more pins to allow you to manually configure the sub-address.


3D printer firmware version Is there a way to determine which version of a Marlin firmware I would have installed onto my printer? I am trying to modify the existing arduino sketch rather than starting all over with a wrong, earlier version. Thanks.

First, check to see if the printer itself yields this information, either on LCD display if present, or by reporting it to a host computer upon connection (ie, try enabling verbose output in your printing software).

While it's not guaranteed to be supported, in practice many Arduino Mega based 3d printers have bootloaders capable of readback of the flashed contents, and the chips themselves are unlocked.  Even if the bootloader does not support this, an ISP connection might.

If you are able to read out the contents, you can have avrdude write them to a flat binary file, and examine it with the strings program or a hex editor.  If you end up with a hex file instead, there are tools for converting this to a flat binary.

Your goal would be to look through the file for version strings, and other messages which might indicate specifics, especially on which side of various points of change or configuration options it falls.

Making such a backup is a good idea before loading a new firmware anyway.  Ideally after verifying that you obtained meaningful contents, you would also readback a few distinct copies of the file and use something like diff to verify that they are all the same.  You can grab the EEPROM contents too, if your firmware may be storing things there.