Use ATtiny85 to perform initial config on a Cisco router using its USB console port We have 200+ brand new Cisco routers that have USB console ports (but not the old RJ45 serial console ports). This is quite frustrating because the routers didn't ship with console cables and Cisco wants to charge $60 for their proprietary USB->RJ45 serial adapters.

When I plug the router in to a computer using a standard USB cable (mini USBb on one end and USB on the other end), it shows up as a virtual com port and allows me to configure the router if I have a VCP driver installed. More specifically it shows up as a "CP2105 Dual USB to UART Bridge Controller". Here's the full lsusb -v output for the router:

Bus 001 Device 005: ID 10c4:ea70 Cygnal Integrated Products, Inc. CP210x UART Bridge
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               2.00
  bDeviceClass            0 (Defined at Interface level)
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0        64
  idVendor           0x10c4 Cygnal Integrated Products, Inc.
  idProduct          0xea70 CP210x UART Bridge
  bcdDevice            1.01
  iManufacturer           1 Silicon Labs
  iProduct                2 CP2105 Dual USB to UART Bridge Controller
  iSerial                 5 12345678
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           55
    bNumInterfaces          2
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0x80
      (Bus Powered)
    MaxPower              100mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           2
      bInterfaceClass       255 Vendor Specific Class
      bInterfaceSubClass      0
      bInterfaceProtocol      0
      iInterface              3 Enhanced Com Port
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0040  1x 64 bytes
        bInterval               0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x01  EP 1 OUT
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0040  1x 64 bytes
        bInterval               0
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        1
      bAlternateSetting       0
      bNumEndpoints           2
      bInterfaceClass       255 Vendor Specific Class
      bInterfaceSubClass      0
      bInterfaceProtocol      0
      iInterface              4 Standard Com Port
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x82  EP 2 IN
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0020  1x 32 bytes
        bInterval               0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x02  EP 2 OUT
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0020  1x 32 bytes
        bInterval               0
Device Status:     0x0000
  (Bus Powered)

Is it possible to have an ATtiny85 board (eg Digispark) interface with the router via its USB console port to send several commands over the link to perform a perform basic initial config?

It's been a couple of decades since I was programming Cisco routers, firewalls and switches but I appreciate you pain. Like @Gerben says, you need a bigger processor, an ATtiny85 isn't going to be able to hold a lot of config and even the basic configs I used were about 4 to 6KB.

If there is anything in the configs that is different, you idea is going to hit problems.  Are the device names and passwords all the same? In which case you probably want the engineer to be able to set some configuration data in you "programmer", could they set this specialisation data using their mobile phone?

I doubt you will have any problem connecting an "Arduino" via serial (RS232) to a Cisco router. However you now have to encapsulate the serial in "USB", which I don't think will be straight forward for an "Arduino".

I can't think of an option that doesn't require power, but as an alternative to your idea what about using a Raspberry Pi to connect to the router via USB. Stick a touch screen on it and a battery pack to power it.


Change Arduino Clock Speed I want to run an arduino board at a slower - but more accurate - clock speed. What (if anything) needs to be changed in the arduino code/libraries in order to achieve this? Normally the boards I use run at 16MHz, but I wish to derive a 10MHz clock from a GPS timing module and run the ATMEL processor off the 10MHz timing clock.

You have to change F_CPU only - You can add new board into the boards.txt with correct clock speed.
EDIT: Aparently millis counter will be drifting much more then expected due to "rounding" errors.

The bootloader on the other side needs to be recompiled with correct F_CPU and  reflashed, if you want it working at the same baud rate (plus it's possible to change fuses to use external clock source instead of crystal). Otherwise you have to try reduced speed (also configured in board config).

You can use MCUdude/MiniCore as inspiration. It supports many clock speeds (but 10MHz doesn't)


How to use strtok() and strstr() with arduino? Can anyone explain how things like strtok() and strstr() can be used to provide a numeric value for a substring location position within the mainstring array.

I've tried to understand from the C++ examples, but their 'position' locations of the substring within the mainstring (which I need) are returned in C++ as %d variables, whereas all I can get returned by the arduino 'char * pointer=' is the actual substring chars if they exist, rather than a number for their start position locations within the mainstring.

The C++ examples show that it is possible to discover the position values from %d,  but how can I get that equivalent position value in arduino?

I want to be able to parse a char header[30] array for occurances of things like "s=123" and "d=789" in order to extract and assign the specified values to any appropriate variables (source or destination etc).

You have to define a format for the header you will be parsing and stick to that format. Say this is a sample header terminated by null:

s=123 d=789 e=463

A common property of each assignment in the string is the '=' symbol. You can use that to locate each variable and the value assigned to it. strchr is the function to use to locate a single character. Once you locate the = character, you move back and then forward along the array to obtain the variable and its value.

I will make some assumptions here: that your variable names will be single character, that numbers assigned will be no bigger than ints, and a space character is used to separate assignments.

char header[] = "s=123 d=789 e=463";

int d, s, e;   //your variables to be assigned to
char * ptr = header;
char * eq = NULL; //locate assmts
int * num = NULL; //just for starters
while (1){
  eq = strchr(ptr, '=');
  ptr = eq; // update the pointer
  if (ptr == NULL) // found no = chars
    break;
  switch (*(ptr - 1)){
    case 'd':    //all the possible variables
      num = &d; break;
    case 's':
      num = &s; break;
    case 'e':
      num = &e; break;
    default:   //unknown variable
      num = NULL;
  }
  ptr++;
  if (num == NULL) //unrecognized var
    continue;   // locate next = char
  *num = 0;
  while (*ptr && (*ptr != ' ')){  // while space or end of string not yet reached
    *num *= 10;  // extract each int
    *num += *ptr - '0';
    ptr++;
  }
}

Serial.println(d);  //now contains the numbers in the header
Serial.println(s);
Serial.println(e);

Untested but it should work for the header sample I gave.


Efficiently using a serial inteface So at my school we are preapering for a competition. They asked me to do the technical side of it. And I accepted... I was thinking of using an arduino as a usb device for the buttons. I am going to use the serial port for this. But I can't think of a way to do it in the way I want. I want to recieve the button presses fair and well. But I also want to control the lights for the buttons, from my computer. I am using Serial.printLn() to send the serial data to the computer. But how can I send serial data to the arduino without delaying other things (What happens when someone presses a button while I am sending a command?)? Thanks in advance!

The nastiest part in what you describe is likely to be the debouncing on the button, rather than the serial communication.

One easy way out is to use some form of bounceless implementation, like an optical coupler. Another is to use HW debouncing, like the MAX 6816 family.

Then you can use a loop where you alternate between serial communications and checks for the status of the buttons.

Or you can rely on interrupts for the buttons, but it's more complex and might be overkill.


Matlab too many input arguments using csvread I have files called t1_25, t1_45, t1_65, t2_25, t2_45 and so on till t5_65.

I wrote this piece of code:

MaxForce =[0,0,0;0,0,0;0,0,0;0,0,0;0,0,0;0,0,0];

MaxForce(1,1) = 25;

MaxForce(1,2) = 45;

MaxForce(1,3) = 65;

HeightNo = 3;

NoOfRepeats = 5;

for x = 1:HeightNo
    for y =1:NoOfRepeats

        if x == 1

        MaxForce(y+1,x)= ((max(csvread('t', y, '_25.csv',1,1)))-0.392)/0.000267;
        if x ==2
            MaxForce(y+1,x)= ((max(csvread('t', y, '_45.csv',1,1)))-0.392)/0.000267;
            if x ==3
                MaxForce(y+1,x)= ((max(csvread('t', y, '_65.csv',1,1)))-0.392)/0.000267;
            end
        end
        end
    end
end

MaxForce(:,:)

It says Error in Project (line 10)
        MaxForce(y+1,x)= (max(csvread('t', y, '_25.csv',1,1))-0.392)/0.000267;

Why?

You should improve your question and it seems not being related with arduino at all. However, what I think you are trying to do is to auto generate the name of the file you use in cvsread accordingly to the value of y. This can be done using sprintf, in your case for the first expression csvread(sprintf('t%d_25.csv',y),1,1).
Although, the structure of your code seems really messy take a look at your end instructions.


Port register not working I am trying to read my ultrasonic sensor. It sends a pulse in the trigger pin and the echo pin receives the pulse. Using pulseIn I can know exactly the time it took to the pulse go and back. But I need to use port register which is much faster and I need it to be fast in this specific case.

My code is very simple:

void setup() {

    Serial.begin(9600);
    //pin 12 as output
    DDRB = B00010000;
    //pin 12 as low
    PORTB = B00000000;

}

void loop() {

    //pin 12 as high
    PORTB = B00010000;
    delayMicroseconds(10);
    //pin 12 as low
    PORTB = B00000000;

    long start_time = micros();

    //While reading high in pin 13 keep running the loop
    while (PINB & B00100000)) {

    }

    Serial.println(micros() - start_time);

    delay(1000);

}

The problem is that it does not work, I mean, the while loop is not being processed so the serial is always printing a very small number. It doesnt matter if I move the ultrasonic sensor to distant walls the while loop still does not work. What am I doing wrong?

According to anything I could find, the Echo output is normally low and then goes high for a duration equal to the range. Your initial while condition is inverted, and you need to check for both edges.

unsigned long up, down;

// trigger pulse
while (!(PINB & _BV(PB5)))
  ; // wait for leading edge
up = millis();
while (PINB & _BV(PB5))
  ; // wait for trailing edge
down = millis();
Serial.println(down - up);


If the USB gives 5v, how can the Arduino supply 5v to the 5v pin? (And another question) I must not of understood something. Online, I've heard that the Arduino uses 9v typically (average), and that USB's in general supply 5v@500mA. If this is true:

How can the Arduino even POWER ITSELF with the 5v USB? I've heard the minimum is 7v.
How can there be a 5v pin if the USB supplies 5v... that leaves no room for the Arduino!

My understanding is very bad currently, any explanation would be great. Thanks!

Actually, Arduino is powered at 5V (the 5V pin and the ATmega328p are connected to the +5V rail in the board). The point here is where do those 5V come from. Basically, from 2 possible sources:

USB. The 5V line from USB is (or should be) already regulated, so it's feed directly (in fact it goes through a polyfuse) into the +5V rail of the board. The maximum current draw operating this way is 500 mA, limited by the polyfuse so you don't blow up your PC.
Barrel connector (wall adapter). It accepts 7-12V and brings it down to 5V using a linear regulator whose output goes to the +5V rail of the board. The maximum current draw operating this way is 1,000 mA, limited by the regulator capability.

If both sources are present at the same time, preference is given to the wall adapter. The UNO board has circuitry that detects voltage from the adapter and disconnects (using a MOSFET switch) the USB 5V line from the +5V rail of the board.

This is done not only for convenience purposes (so you have more current available), but also for protection. Otherwise, you'd be connecting two power sources (+5V from the regulator and +5V from USB) which is a dangerous situation.

I have commented the UNO R3 schematics so you can see for yourself how it's done (both input sources, adapter voltage detection circuitry, etc.), see below.


Unable to use analog pins as digital inputs I want to use the analog pin A7 as a digital input pin. As stated in the Arduino docs the analog pins can be configured in the same way like any other digital pin.
However, when trying to configure an analog pin as a digital input pin, I get unexpected behaviour:

Using a digital pin (e.g. D2) works as expected.
When using an analog pin (e.g. A7) the LED is lit after start-up without pressing the button and does not change/react to any button press.
Since the docs state, that analog pins can be configured as digital pins and used in the same way, this behavior seems to be kind of confusing.

See my attached snippet to reproduce/examine the issue:
// using pin 2 (D2) works as expected (LED is lit on button press only)
// const int buttonPin = 2;

// using analog pin 7 (A7 / pin 21) as a digital input is not working,
// LED is lit directly after start-up & does not react to button press,
// analog pins are generally usabable as digital inputs
// see https://www.arduino.cc/en/Tutorial/Foundations/AnalogInputPins
const int buttonPin = A7;

const int ledPin = 13;

int buttonState = 0;

void setup() {
  // button is connected to GND, so enable internal pull-up resistors
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
};

void loop() {
  // as we use internal pull-up resistors, logic HIGH & LOW are inverted
  buttonState = !digitalRead(buttonPin);
  if (buttonState) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
};

A6 and A7 are special on the nano. They are the only pins that can't be used for digital.  They are only analog inputs.


Stepper motor control I'm using Arduino to control a stepper motor. I need it to make one revolution and then stop. I'm new to this and haven't ran it yet. Will this do for me?

#include <Stepper.h>

const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  myStepper.setSpeed(60);
}

void loop() {
  myStepper.step(stepsPerRevolution);
}

No, that will not do what you want. That will continuously rotate the stepper round and round and round.

The clue as to why is in the name of the function you put the myStepper.step call: "loop". That function repeatedly loops around over and over again, so your step function will be called over and over again.

There is one piece of information lacking from your thinking at the moment, and that is when do you want the stepper to rotate? If it's just once when you turn the power on then it's as simple as doing everything (including calling myStepper.step) in setup() and leaving loop() empty. If not, then you will need to add appropriate logic to only run the step function when the required conditions are met.


How do I write an Arduino program to an AVR chip without the Arduino bootloader? Is it possible to write an Arduino program to an AVR chip that does not have teh Arduino bootloader installed?  What is the process to do so?

Step 1: Get yourself a programmer.
This can be anything from a USBasp to an Arduino programmed for ISP all the way to an AVR ONE!. Some can be used from the IDE, and some cannot.
Step 2: Set up the chip as expected from the entry in boards.txt and from the datasheet.
Add a crystal, decoupling caps, whatever. Don't connect power yet.
Step 3: Connect the programmer.
If using ISP, connect the ISP pins. If using JTAG, connect the JTAG pins. If using something else, see the programmer and chip documentation for connection details. You may want to connect power at this point for the next step.
Step 4: Program fuses.
Program the oscillator, BOR, CKDIV8, EESAVE fuses as desired/required. Fuse calculator.
Step 5: Compile the program and write it to the chip.
If using the IDE, select the programmer in Tools | Programmer and then hold shift when clicking the Upload button (or press Ctrl-Shift-U). If your programmer is not supported by the IDE then compile the program (Sketch | Verify/Compile or Ctrl-R), locate the temporary directory it has been built in, and use avrdude or your JTAG program to upload it to the programmer.
Step 6: There is no step 6. You're done.
I just wanted to see if you would read this far.


Is it better to use #define or const int for constants? Arduino is an odd hybrid, where some C++ functionality is used in the embedded world—traditionally a C environment. Indeed, a lot of Arduino code is very C like though.

C has traditionally used #defines for constants. There are a number of reasons for this:

You can't set array sizes using const int.
You can't use const int as case statement labels (though this does work in some compilers)
You can't initialize a const with another const.

You can check this question on StackOverflow for more reasoning.

So, what should we use for Arduino? I tend towards #define, but I see some code using const and some using a blend.

It's important to note that const int does not behave identically in C and in C++, so in fact several of the objections against it that have been alluded to in the original question and in Peter Bloomfields's extensive answer are not valid:

In C++, const int constants are compile time values and can be used to set array limits, as case labels, etc.
const int constants do not necessarily occupy any storage. Unless you take their address or declare them extern, they will generally just have a compile time existence.

However, for integer constants, it might often be preferable to use a (named or anonymous) enum. I often like this because:

It's backward compatible with C.
It's nearly as type safe as const int (every bit as type safe in C++11).
It provides a natural way of grouping related constants.
You can even use them for some amount of namespace control.

So in an idiomatic C++ program, there is no reason whatsoever to use #define to define an integer constant. Even if you want to remain C compatible (because of technical requirements, because you're kickin' it old school, or because people you work with prefer it that way), you can still use enum and should do so, rather than use #define.


Can not initialize ESP module in Arduino SoftwareSerial Can not initialize ESP module in Arduino SoftwareSerial's example sketch in configuring WiFi module.

In the sketch it tells:

#include "WiFiEsp.h"
// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(11,12); // RX, TX
#endif

I plugged jumper wires in from esp8266 RX to Digital 11 of mega which is RX and TX of esp8266 to Digital 12 of mega, and I compile the code and looked at the Serial Monitor, but it says:

[WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Cannot initialize ESP module

Advise is greatly appreciated.

#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(11,12); // RX, TX
#endif

Because your Mega has a Hardware Serial1 port, HAVE_HWSERIAL1 is defined. Thus the lines inside that preprocessor conditional will not be compiled. This means you should connect the ESP8266 to the Serial1 lines on your Mega:

Mega | ESP8266
--------------
19   | TX
18   | RX


nRF24L01+ Unable to set address I'm trying to communicate between Arduino Nano and Arduino Uno using nRF24L01+.

I tried using RF24 by ManiacBug and TMRH20, but when I open the serial monitor after uploading the Example Programs Getting Started from ManiacBug and pingpair Program from TMRH20, it does not change its address.

The addresses for reading and writing I'm using are 0xF0F0F0F0E1LL and 0xF0F0F0F0D2LL, but the response I'm receiving is as follows:

I check all the connection and tried different examples available on the internet, but nothing worked at all.

You can set addresses using SPI commands.  For example a 5-byte transmitter address could be written as (MSB first):

  digitalWrite(CSN_pin, LOW);
  SPI.transfer(0x30); // write TX_ADDR register
  SPI.transfer(tx_addr[0]);
  SPI.transfer(tx_addr[1]);
  SPI.transfer(tx_addr[2]);
  SPI.transfer(tx_addr[3]);
  SPI.transfer(tx_addr[4]);
  digitalWrite(CSN_pin, HIGH);

where tx_addr is an array of 5 bytes.  Similarly you can write to the RX_ADDR registers, see the nRF24L01+ datasheet, section 9 for the register map.

Furthermore, the following code allows you to read the TX_ADDR register:

  digitalWrite(CSN_pin, LOW);
  SPI.transfer(0x10); // read TX_ADDR register
  data_out[0] = SPI.transfer(0x0);
  data_out[1] = SPI.transfer(0x0);
  data_out[2] = SPI.transfer(0x0);
  data_out[3] = SPI.transfer(0x0);
  data_out[4] = SPI.transfer(0x0);
  digitalWrite(CSN_pin, HIGH);

  Serial.print("TX_ADDR=");
  Serial.print(data_out[0]);
  Serial.print(data_out[1]);
  Serial.print(data_out[2]);
  Serial.print(data_out[3]);
  Serial.println(data_out[4]);


Binary reader with arduino blinking 8 leds I´m trying to insert a binary raw sequence (01010100, 01101000, 01100001) into Arduino. I would like to make 8-led group blink in a loop, showing with light each 8-group binary sequence when: 0=light off and 1=light on.

It´s possible to do this operation with Arduino-uno ?

You just prepend the number in binary with B e.g. B01100100 which is 100 in decimal

byte sequence[] = {
    B10000000,
    B01000000,
    B00100000,
    B00010000,
    B00001000,
    B00000100,
    B00000010,
    B00000001
}

And to check the n-th bit from the right in a number you do

boolean bit_set = number & (1 << (n - 1)) != 0;


Weird Arduino Code Problem I'm currently getting started with Arduino, so I do not have very much knowledge.
In this project I have a receiver and a transmitter with 2 buttons.
So, I'd like to switch something to on, when I press the A button. If A is pressed longer I'd like something else to happen.
Same thing goes on with the B button, but for some reasons, when I long press A, then B gets triggered and I have no clue why...

Btw. this code is not purely made by me, but copied and edited for my use.
If anyone could help me I'd be very happy :)

code:

//ButtonAEvents

long prevA = 0;
long prevB = 0;
int buttonStateA = 0; // 0 = not pressed   --- 1 = long pressed --- 2 short pressed
int buttonStateB = 0; // 0 = not pressed   --- 1 = long pressed --- 2 short pressed
int ButtonAPin = 2;
int ButtonBPin = 3;
int DURATION_A_IN_MILLIS = 1000;
int DURATION_B_IN_MILLIS = 1000;

//ONE TIME SETUP

void setup()
{
    pinMode(ButtonAPin, INPUT);
    pinMode(ButtonBPin, INPUT);
    Serial.begin(9600);
}

//LOOP BEGIN

void loop()
{

    //BUTTON A CHECK
    buttonStateA = 0;
    if (digitalRead(ButtonAPin)) {
        prevA = millis();
        buttonStateA = 1;
        while ((millis() - prevA) <= DURATION_A_IN_MILLIS) {
            if (!(digitalRead(ButtonAPin))) {
                buttonStateA = 2;
                break;
            }
        }
    }

    if (!buttonStateA) {
        // Nothin pressed
    }
    else if (buttonStateA == 1) {
        //LONG PRESS

        Serial.println("LongpressA");
        digitalWrite(A1, HIGH);
        delay(100);
    }
    else if (buttonStateA == 2) {
        //SHORT PRESS
        digitalWrite(A1, HIGH);
        Serial.println("ShortpressA");
        delay(100);
    }

    //BUTTON B CHECK
    buttonStateB = 0;
    if (digitalRead(ButtonBPin)) {
        prevB = millis();
        buttonStateB = 1;
        while ((millis() - prevB) <= DURATION_B_IN_MILLIS) {
            if (!(digitalRead(ButtonBPin))) {
                buttonStateB = 2;
                break;
            }
        }
    }

    if (!buttonStateB) {
        // Nothin pressed
    }
    else if (buttonStateB == 1) {
        //SHORT PRESS

        Serial.println("LongpressB");
        delay(100);
    }
    else if (buttonStateB == 2) {
        //LONG PRESS
        digitalWrite(A1, LOW);
        Serial.println("ShortpressB");
        delay(100);
    }
}

Not sure if this is just an academic exercise on your part to learn (which is totally cool), but if you're just trying to move forward and get something working you may consider one of the many excellent button libraries out there for Arduino.

I recently used a library called ButtonKing that allowed me to do some very sophisticated menu interactions on a MKR1010 with a display and single button interface.  There are several other libraries out there as well that take care of debouncing, long clicks, double clicks, etc.


5V pin output on arduino Sorry for the newbie question (just started learning electronics).

I just saw a tutorial that says that the 5V output pin on the Arduino delivers more amps (if needed) when connecting more voltage to the board (connecting to the 9 - 12V instead of 5V).
Does that mean that the 5V pin then delivers more than 5V as well?

Time for a crash course in electronics and power:

The 5V pin only ever provides 5V. That's why it's the "5V" pin. (assuming, of course, that you give the board more than 5V).

In simple linear electronics you have three values:

The voltage
The current
The load

Generally two of the three are either "fixed" or "known" and the third changes depending on the other two. For simple resistive circuits (where the load is a simple resistor) this relationship is Ohm's Law.

If the voltage is fixed, and
If the load changes, then
The current will also change to keep the relationship stable.

A "power supply" (any device which provides power to some other device) generally has two parameters: Voltage and Current.  One of those is always fixed. The other is always variable, and quoted as a maximum that the supply can give.

For the Arduino's 5V pin the parameters are:

Voltage: 5V
Current: 800mA Maximum

That means that the 5V pin has a fixed voltage of 5V, but the current is free to change depending on the load up to a maximum of 800mA (or a lower limit if you are providing the input power from a source with a lower current. There is also heat to consider with the Arduino - see below).

The two values, voltage and current, combine together to give the "power" of the power supply, through simple multiplication. So the Arduino's 5V pin is 5V × 0.8A = 4 watts maximum.

When you provide power to the Arduino through the barrel jack it first goes through a linear voltage regulator.  This is the device which takes the incoming voltage and reduces it to 5V. Since energy can neither be created nor destroyed it does that reduction in energy by converting some of it to heat.

Say you connect something up that needs 100mA and you plug in a 9V power supply to the board. Let's also assume that the Arduino itself needs 50mA (I like nice round numbers).

That's 150mA in total for the "load".
The incoming voltage is 9V
The outgoing voltage is 5V

The power of the input is thus 9V × 0.15A = 1.35W
The power of the output is then 5V × 0.15A = 0.75W

The power difference is 0.6W

That 0.6W is converted from electrical energy to heat energy by the voltage regulator and "thrown away".

So the "heavier" your load (the more current you demand from the 5V pin) the greater the heat that is generated by the voltage regulator.

When the regulator gets too hot one of two things happen:

A good quality regulator will shut down and you will lose power to the board
A cheap Chinese regulator will likely "fail short" and feed your 9V direct into the Arduino causing components to release their Magic Smoke™ and stop working


ESP8266 Soft Access Point: Timeout of request of resource when not responded to in set undocumented time I'm experimenting with the ESP8266 chip on a Wemos D1 R2 board. I'm trying to write some code which will allow the user to input a username and password in an HTML form then get a response as to what happened with trying to connect to the WiFi as either they connected or the password was wrong. After I've turned setup Access Point and Station mode on the device using:

    // The field here would be global so other functions can access it
    ESP8266WebServer server(80);
    server.on("/connect", handleConnect);
    server.begin();

In my handleConnect function, I check the body of the request and attempt to login:

    if(!server.hasArg("ssid") || !server.hasArg("password")) {
        server.send(200, "text/html", "You didn't submit a ssid and password");
        return;
    }

    auto ssid = server.arg("ssid");
    auto password = server.arg("password");

    WiFi.begin(ssid, password);

    auto status = WiFi.waitForConnectionResult();

    server.send(200, "text/html", String(status));

When the user inputs the correct password, the function returns the request in time and the request responds with 3 (the connection was successful). However, if the password is wrong, the request times out. I've also tried several approaches to either work-around or fix the problem such as:

Using a while loop and calling WiFi.status() and checking it and responding accordingly. This approach ends with the same request timeout if the password is wrong. An example of this would be:

while(true) {
  delay(1000);
  auto status = WiFi.status();

  if(status == WL_CONNECTED) {
    server.send(200, "text/html", "You're connected!");
  }

  if(status == WL_CONNECT_FAILED) {
        server.send(200, "text/html", "You inputted the wrong password! Try again!");
  }
}

Registering another resource to specifically only return what state the WiFi is in and in the original connect function to send back HTML with some javascript in it which calls this other resource and do the decision making of what text to display client-side but this approach always returns 0 (when the WiFi is in process of changing between statuses, quoted from the docs)

server.on("/checkConnection", checkConnection);

// other code

void checkConnection() {
  server.send(WiFi.status());
}

And finally, I have experimented with using a public field to save the state once it has finished in the main function where the original connection tried to be established and then use the checkConnection function to return this state and this SOMEWHAT works, however, the code is messy, hacky and there must be a better way of doing this otherwise this will have to be my solution until the libraries are updated to fix this or something like that:

// public field for the status

      int status = 0;

      // other code

      void handleConnect() {

        // checking ssid and password

        WiFi.begin(ssid, password);

        // use an interval with AJAX or this to get the connection state
        server.send(200, "text/html", "Go to to check the connection");

        while(true) {
          delay(1000);
          auto s = WiFi.status();
          status = s;
          if(s = WL_CONNECTED) break;
        }

      }

      void checkConnection() {
        server.send(200, "text/html", status);
      }

Has anyone encountered this problem and if so, is there a better way of solving it apart from using a public variable which just makes it a pain in the bum to work with? Thank you.

WifiMulti wifiMulti;//declare global.
wifiMulti.addAP(ssid,pass);//instead of WiFi.begin();
int i = 0;
//add below to wait for connection.
while (i < 20)
  {
    if (wifiMulti.run() == WL_CONNECTED)
    {
      return (20);
    }
    delay(500);
    Serial.println(WiFi.status());
    i++;
  }


How to connect 5V sensors to 3.3V digital input (Due)? I'm completely new with Arduino and microcontrollers in general.

I have several 5V sensors, and need 3.3V because that's the max for the Due. Is it possible to use a resistor to connect it to the Arduino? Do I have to measure the current from the sensor and calculate the needed resistor like this?

$$\frac{5.0 - 3.3}{\text{Measured current}}$$
(5.0 - 3.3)/(Measured current)

Well if you're not sure of what you're doing, you can always go with level-converters for your sensors (that does not apply to shields though)

Level-converters (sometimes called level-shifters) come in different flavors:

breakout board (the easiest to work with)
IC
DIY circuits with a few components

Some are "one-way": they have pin-pairs with converters 3.3V -> 5V, and other pin-pairs with 5V -> 3.3V conversion; others are bi-directional, i.e. you can use the same pair of pins in 2 directions 3.3V <-> 5V.

There are plenty of these converters, and they are rather cheap; here are just a few examples:

one-way breakout usable with 4 pairs of pins
bi-directional breakout usable with 4 pairs of pins
74HC4050 IC discussed here


Using esp8266 instead of xbee I want to ask a question. I am using my project xbee pro s2c to get data from arduino(temp,pressure etc.) and i am sending data another xbee module and read these data from serial port. Question is that i want to use esp8266 instead of xbee. is it possible ? can i communicate 2 esp module like xbee ?

I want to ask a question.

You don't need to tell us.

  Can i communicate 2 esp module like xbee ?

You can make two ESP8266 modules talk together, yes. It's not "simple" like an XBee, since you have a generic WiFi network interface, so there's many many different ways of doing it. Typically one would be running as a WiFi Access Point (SoftAP) and the other would connect to it. Then you'd run some "server" code on one module (typically the SoftAP one) and the other acts as a client and connects to it (or sends data to it).


Why do I have to open Serial Monitor to display what is in loop function? Why do I have to open Serial Monitor to display non-NaN values retrieved from DHT22,
what am I doing wrong in the code below?

#include <DHT.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
// OLED display TWI address
#define OLED_ADDR   0x3C
// reset pin not used on 4-pin OLED module
Adafruit_SSD1306 display(-1);  // -1 = no reset pin
// 128 x 64 pixel display
#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif
#define DHTPIN D3
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup() {

Serial.begin(115200);
delay(100);
  dht.begin();
  pinMode (DHTPIN, OUTPUT);
  /// initialize and clear display
  display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR);
  display.clearDisplay();
  //  display.drawRect(1, 1, display.width()-1, display.height()-1, WHITE);   // draws the outer rectangular boundary on the screen
  display.display();
  // display a pixel in each corner of the screen
  display.drawPixel(0, 0, WHITE);
  display.drawPixel(127, 0, WHITE);
  display.drawPixel(0, 63, WHITE);
  display.drawPixel(127, 63, WHITE);
  // display a line of text
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(20, 18);
  display.print("Welcome");
  display.setCursor(25, 40);
  display.print("San");

  // update display with all of the above graphics
  display.display();
}
void loop() {
  // put your main code here, to run repeatedly:
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0, 1);
  display.print("Showing Temperature");
  // display Temperature
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(1, 18);
  display.print("T : ");
  display.print(t);
  display.setTextSize(1);
  display.print((char)247);
  display.setTextSize(2);
  display.print("C");
  display.setCursor(1, 40);
  display.print("H : ");
  display.print(h);
  display.print(" %");
  // update display with all of the above graphics
  display.display();
}

After uploading code it does will display NaN but when I open serial monitor it works fine displaying actual values from DHT22  :o

below is the fritzing of the hookup, I do not have witty cloud in fritzing, so I have used wemos D1Mini instead. on wemos d1 mini 3v3 is VCC on witty cloud dev board.

It looks like loop function doesn't execute by itself unless I open the serial monitor, why is it so? please help

Hard to tell from your fritzing which actual ESP8266 pin you are using, but you require a pull up resistor on the data line of the DHT22.

My guess is that you are using one of the serial UART pins for the data connection, and opening the serial monitor activates the output of the onboard UART chip which then acts as your missing pullup resistor.


Add -D option via boards.txt I'm trying to find a way to set a -D compiler option from within the boards.txt file. Basically set a #define for use in code. There are already some special ones like board.vid but is there a generic way to do it?

Somehow the Teensy add-on adds a little magic that allows the IDE to recognize options like:
.board.define0=-DHELLOWORLD
.board.option0=-DHELLOWORLD

In other words, add the -DHELLOWORD (#define HELLOWORLD) to the command line for GCC.

BUT, I can't get this to work without the Teensy add-on installed.

Is there a way to do this with the stock IDE?

Yes, it is possible in the 1.5.+ IDE. while not possible in the 1.0.+ and earlier.

Hardware-specification refers to both the boards.txt and platform.txt files.

in short the boards.txt file specifies...

uno.build.f_cpu=16000000L

and the platform.txt uses in the compile commands such as ...

 -DF_CPU={build.f_cpu}

You can your own. There is already a "build.extra_flags=" that some of the USB devices use to add their own FLAGs conditionally on the board type.


How to embed a 5V-range Arduino-based controller in a 12V-range DC circuit? We have an installation that provides:

a common line (C), which divides into two wires;
an input line (I), which carries the signal from a button (between I and C there's normally 0V, and 12V when the button is pressed);
an output line (O), which carries a signal to a bell (between O and C there's always 12V).

simulate this circuit – Schematic created using CircuitLab

A controller is to close the OC circuit every time a given temporal pattern shows in I (say, a concrete Morse-like -short/long- sequence of pulses), so the bell will ring if the concrete word is recognized at the input. Such a controller has been implemented in C++ and uploaded to an Arduino Nano, and it works fine on a protoboard, with a button as input and led as output, all in the same electrical range.

Since both the IC and the OC are 12V circuits, and the controller is in the 5V range, what is the minimal circuit to embed the controller between the IC and the OC circuits?

Just use a transistor that can handle 12V with the base connected to the Arduino and that's it...

Maybe I didn't get what you were trying to say, but anyway, I think that's what you are looking for.


MMA7660 accelerometer with ATTiny85 I'm trying to make the ATTiny85 work with the MMA7660 accelerometer, so far, without any success. Google search for "ATTiny85 MMA7660" gives poor results, and I'm not sure it has been done at all, at least publicly, so I thought I'll try my luck here.

What I've tried is using the TinyWireM library, in different combinations. The last one is based on the MMA7660 Arduino library, specially adjusted to the TinyWireM, and taken from this post in Arduino forums (direct link to download).

The SCL is connected to PB0 and SDA to PB2, with 5k ohm pull-ups (I know that the recommended is 4.7k but this is what I have available, and I assumed it shouldn't make much difference).

I am using the Arduino IDE v1.5.6, which works successfully with other non-I2C attiny projects I have.

As for the final code I am using the .pde example that comes with the MMA7660, altered to use SoftwareSerial:

#include <TinyWireM.h>
#include <MMA7660.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(-1,4);

void setup()
{
  mySerial.begin(9600);
  MMA7660.init();
}

void loop()
{
  int x,y,z;
  delay(100); // There will be new values every 100ms
  MMA7660.getValues(&x,&y,&z);
  mySerial.print("x: ");
  mySerial.print(x);
  mySerial.print(" y: ");
  mySerial.print(y);
  mySerial.print(" z: ");
  mySerial.println(z);

}

The current problem with the above code is that the pointers just dump some memory without making any sense. If I try to see what TinyWireM.receive() command returns, values are 216 for all three variables. This is true even when I disconnect the MMA7660 from the prototyping board...! so I assume the problem is with the I2C itself, not working properly. The actual I2C address for the MMA (0x4C) and other relevant code is in MMA7660.cpp.

Any ideas?... Unfortunately I don't currently have another I2C device to examine the health of this protocol with my ATTiny85, so any experience you might have with this sort of configuration will be blessed.

EDIT: I marked dvlabsllc's answer as accepted answer since it gave me the right direction to pinpoint the issue further down the library path. I have opened a new question regarding TinyWireM library here.

I have run into similar frustrations using standard libraries and I2C.  I would have to look into the code and try it out on my own before confirming anything about this particular code; however, in the meantime you might want to try a tool such as I2cScanner that simply scans the I2C bus for all possible addresses and reports addresses that are "alive".  This (or something similar as I am not sure if you are using Arduino API) might be a good start to just see if the I2C is working and that you have the correct address.


Use external power - nodemcu 0.9 I'd like to deploy my project so I'm looking for a way to power the nodemcu.
I'd like to know if there's a way to power it with a 9V battery without any other external circuit.

Until now I've found information for the nodemcu 1.0 and it supports up to 20V on the VIN port. Here's the article I read:
http://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/

I'd like to use the two port: 5V and GND but I'm not sure, here there is no VIN port and I'd prefer to not burn my board.
Are there any better way to power my project?

It looks like the 0.9 uses the SPX3819 regulator. That can run with up to 16V on the input, so 9V on the 5V pin (as long as USB never gets connected) should work fine.

Except: 9V PP3 batteries are useless. If it can even provide enough power to run the board (which is doubtful) it won't last more than a few hours.  You would have to ensure that you use very very deep sleep mode to get any semblence of longevity out of it.

The 3.3V regulator will be throwing away half to two-thirds of the power as heat. So wasteful. You would be better off investing in a 3.3V switch-mode ("buck") regulator circuit (cheap on eBay) to directly power the 3.3V pin of the board instead of 9V into the on-board regulator.


Connecting a Arduino to FT232 I found this wonderful breakout board based on FT232. I wonder if I can use this board for connecting my arduino to a USB dongle for 3g/GPRS connection ?

From what I understand this board can be connected to the serial data pins of the arduino board. And if I connect the USB dongle to the FT232 board, I should be able to run AT commands from the arduino board.

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


code for line following robot not working perfectly I have made a line following robot using 2 IR sensor. My line following robot was working successfully with this code.

#define LS 2      // left sensor
#define RS 3      // right sensor

/*-------definning Outputs------*/
int LM1= 5;       // left motor
int LM2= 6;     // left motor
int RM1= 9;       // right motor
int RM2= 10;

void setup()
{
  pinMode(LS, INPUT);
  pinMode(RS, INPUT);
  pinMode(LM1, OUTPUT);
  pinMode(LM2, OUTPUT);
  pinMode(RM1, OUTPUT);
  pinMode(RM2, OUTPUT);
}

void loop()
{
  if(digitalRead(LS) && digitalRead(RS))     // Move Forward
  {
    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, HIGH);
    digitalWrite(RM2, LOW);
  }
 else if(!(digitalRead(LS)) && digitalRead(RS))     // Turn right
  {
    digitalWrite(LM1,HIGH);
    digitalWrite(LM2, LOW);
    analogWrite(RM1,70);
    digitalWrite(RM2,LOW);
  }
  else if(digitalRead(LS) && !(digitalRead(RS)))     // turn left
  {
    analogWrite(LM1,70);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1,HIGH);
    digitalWrite(RM2,LOW);
  }else{
    digitalWrite(LM1, LOW);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1,LOW);
    digitalWrite(RM2, LOW);
  }
}

As I used only two sensor,sometimes it goes out of the line. So I have tried to make an advanced line following robot which could get back to track automatically when it goes out of the line.But the code is taking only the 1st value of tmp.(tmp=1) even when left sensor touches the line after white sensor and the robot goes out of the line.The value of tmp should be 2 when the robot goes out of the line and the left sensor touches the line after the white sensor.  Here is the code:

/*-------definning Inputs------*/
#define LS 2      // left sensor
#define RS 3      // right sensor

/*-------definning Outputs------*/
int LM1= 5;       // left motor
int LM2= 6;      // left motor
int RM1= 9;       // right motor
int RM2= 10;  //right motor
int tmp;

void setup()
{
  pinMode(LS, INPUT);
  pinMode(RS, INPUT);
  pinMode(LM1, OUTPUT);
  pinMode(LM2, OUTPUT);
  pinMode(RM1, OUTPUT);
  pinMode(RM2, OUTPUT);
}

void loop()
{
  if(digitalRead(LS) && digitalRead(RS))     // Move Forward
  {
    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, HIGH);
    digitalWrite(RM2, LOW);
  }
 else if(!(digitalRead(LS)) && digitalRead(RS))     // Turn right
  {
    digitalWrite(LM1,HIGH);
    digitalWrite(LM2, LOW);
    analogWrite(RM1,70);
    digitalWrite(RM2,LOW);
    tmp=1;
  }
  else if(digitalRead(LS) && !(digitalRead(RS)))     // turn left
  {
    analogWrite(LM1,70);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1,HIGH);
    digitalWrite(RM2,LOW);
    tmp=2;
  }
  else//out of the line
  {
    if(tmp=1){
      analogWrite(LM1,70);
      digitalWrite(LM2, LOW);
      digitalWrite(RM1,LOW);
      analogWrite(RM2,70);
    }else if(tmp=2){
      digitalWrite(LM1,LOW);
      analogWrite(LM2, 70);
      analogWrite(RM1,70);
      digitalWrite(RM2,LOW);
    }
  }
}

This test:

if (tmp = 1)

is always true. You are assigning 1 to tmp and that value (1), when
interpreted in a boolean context (i.e. as a truth value), is true.

You probably mean

if (tmp == 1)

and similarly for the next test.


can homemade arduino be powered up with battery? I am new to arduino. It is costly for me to buy an arduino uno board. Therefore I am going to make a Arduino with breadboard at my home. I also want to make my Arduino portable. Arduino Uno boards can be powered up with battery. But can I do so with my homemade Arduino? If it is possible, what things need to be included in my homemade Arduino?

First, of course, you'll need a battery with enough capacity, and voltage enough greater than 5v (assuming you want to run your home-built at 5v - typical, but you could run it lower, say 3.3v) to give enough run-time before the battery discharges to where it can no longer supply the system. Note that the 9v, so-called "Transistor battery" is not capable of supplying much current. A battery pack of off-the-shelf alkaline batteries or rechargables, or a Lithium Polymer rechargable battery will do much better.

You'll need a low dropout voltage regulator to reduce the battery voltage to your chosen Arduino supply voltage. National Semiconductor's LM1117 would be a good choice. The diagram below from NS's datasheet shows a simple-to-make voltage regulator. Its input is your battery; its output will be the supply voltage to the chip and any accessory circuitry.


RGB LED color control with a single value Apps like Photoshop have a single slider to select color: .

I'd like to achieve the same using variable resistance knob as a slider to control color of RGB LED. Can anyone put me on the right track how to linearly map color values?

What you are controlling there is one out of three values from the HSV (aka HSB) colour space.

Colour can be represented in a number of different ways, called "spaces".  You computer monitor displays colour in the RGB colour space - red, green and blue. An RGB LED of course also displays in the RGB colour space.  Your colour printer works in the CMYK colour space.

Different colour spaces represent the colour using different values and combinations of values, and which colour space you use may be imposed by technical limitations (such as in the printer it is dictated by the combination of the colours of the inks).

HSV is a convenient way of visually manipulating colour since it gives you easy to understand "Hue" (the colour), "Saturation" (how much colour) and "Value" (or "Brightness" - how light the colour is) values that are easy for a human to understand.

However physical devices don't generally work with that colour space, so you need to be able to translate between them.

You can think of HSV as the "Human" colour space, and RGB as the "Digital" colour space.

Fortunately it's relatively simple to convert from one to another and there are a number of code snippets online that give examples of how to do it.

I'm going to include one here that I use in my chipKIT TFT display library "Cariad".  Given three 8 bit values (0-255) of "hue" "sat" and "val" it will calculate the red, green and blue values. "hue" would be the one you change with your pot - the others can be static values (or you could add more pots to control those too).

    unsigned int H_accent = hue/43;
    unsigned int bottom = ((255 - sat) * val)>>8;
    unsigned int top = val;
    unsigned char rising  = ((top-bottom)  *(hue%43   )  )  /  43  +  bottom;
    unsigned char falling = ((top-bottom)  *(43-hue%43)  )  /  43  +  bottom;

    int r = 0;
    int g = 0;
    int b = 0;

    switch(H_accent) {
        case 0:
                r = top;
                g = rising;
                b = bottom;
        break;

        case 1:
                r = falling;
                g = top;
                b = bottom;
        break;

        case 2:
                r = bottom;
                g = top;
                b = rising;
        break;

        case 3:
                r = bottom;
                g = falling;
                b = top;
        break;

        case 4:
                r = rising;
                g = bottom;
                b = top;
        break;

        case 5:
                r = top;
                g = bottom;
                b = falling;
        break;
    }
    if (r > 255) r = 255;
    if (g > 255) g = 255;
    if (b > 255) b = 255;
    if (r < 0) r = 0;
    if (g < 0) g = 0;
    if (b < 0) b = 0;


ESP 01 - reset settings to default values I set up communication between Arduino UNO and ESP 01 module. ESP replied to AT commands, but sometimes I got result from ESP uncompleted or with wrong characters, so I tried to set AT+IPR=9600, I didnt receive any output to this command and after reboot I only can see random characters on every baudrate, blue diode on ESP shines all the time. Is there any way how I can reset ESP 01 to default settings? Tried to set RESET pin to GND, but it didnt help.

I use remote power supply 3,3V/1A

Pins connected:

Vcc = external power supply 3,3V
GND = GND (interconnected bot Arduino and power supply GND)
Tx = Arduino Rx(changed pin to 11 by SoftwareSerial)
Rx = Arduino Tx(changed pin to 10 by SoftwareSerial)
CH_PD - 3,3V

Current ESP-01 firmware versions do not have an AT+IPR command. If you're trying to change the ESP's baud rate to use it with SoftwareSerial, the command to do so (in recent versions of the firmware) is: AT+UART=9600,8,1,0,0 for 9600 baud, 1 stop bit, no parity, no flow control.

The full syntax is: AT+UART=<baudrate>, <databits>, <stopbits>, <parity>, <flow control>, where <databits> is the number of data bits per frame, 5,6,7,or 8; <stopbits> is 1, 2, or 3 for 1, 1.5, or 2 stopbits (respectively); <parity> is 0, 1, or 2 for None, Odd, Even (respectively); and <flow control> is 0, 1, 2, or 3 for None, RTS, CTS, RTS and CTS (respectively). Most serial communication and devices that most of us will ever see will be 8 data bits, no parity, and 1 stop bit, abbreviated as "8N1". Flow control is sometimes used, but often it is contained in the data stream itself, such as sending Ctl-S and Ctl-Q from the keyboard to manually stop and resume incoming data transmission.


Extend battery life with a power-controlling microcontroller? This article describes a method to extend the battery life: use a low-power controller to switch on the Arduino only when needed. The author states that this method uses considerably less power than using Arduino's sleep mode.

Are there downsides to this approach? Which variant should I build?(The TPS61240 variant seems to use something from Circuits@Home that's not available anymore.) I'd appreciate schematics or links to detailed instructions.

Background: I'm building a sensor device that's in an environment with no mains power supply. The sensor should wake up eg. hourly, read eg. a temperature sensor, possibly send an SMS and then go back to sleep.

Switching off power to the board only makes sense if you're using a full Arduino. Once you strip the Arduino down to the bare MCU and decoupling capacitors (or start with a basic breakout board instead), disabling unused peripherals and sleeping the CPU has much more of an effect since you no longer need to supply power to an external monitor chip.

Naturally this may involve creating your own board for the MCU. Fortunately Atmel has the basics of that covered.


IRRemote send and receive same Arduino I am an Arduino (and C/C++) newbie so apologies if I am missing something obvious.

I am using IRremote (github link) as my IR library.

I can get the simple send and receive demos working  individually.

However, I cannot get send AND receive working in the same Arduino at the same time.

I do not wish to do something like the "IRrecord" example but what I do want to do is have Arduino send and receive at all times and then trigger alarm/LED once the "beam" is broken.

I am using a TSOP 22 series as my IR receiver. I have tried to use protothreads but no luck. Any tips appreciated.

My current code snippet:

#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);
IRsend irsend;

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  Serial.println("IR Receiver... Started");
}

void loop() {
  //single threaded nature seems to break below

  // i want to start receiver here
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
  //delay(5000);

  //trying to send here
  for (int i = 0; i < 3; i++) {
    irsend.sendSony(0xa90, 12);
    Serial.println("Sent Sony......");
    delay(40);
  }
  //delay(5000); //5 second delay between each signal burst
}

I managed to do this using solution from Ken Sheriff's Blog. Ken provides a simple example and documents it perfectly. Due to the nature of my IR Receiver (rejecting continuous beam) I used the sample code provided by Stephane Deniaud in the comments section. Thanks to both...

#include <IRremote.h>

#define PIN_DETECT 2
IRsend irsend;

void setup()
{
    pinMode(PIN_DETECT, INPUT);

    Serial.begin(115200);
    Serial.println("READY");

    attachInterrupt(digitalPinToInterrupt(PIN_DETECT), checkIRBeamBreak, RISING);

    // Note : the IR emitter is on PIN #3
    irsend.enableIROut(38);
    IREmitterOn();
}

// Use this function instead of delay() as delay() does not work in interrupt callbacks
void pause(int ms) {
    // We need a loop as the largest value for delayMicroseconds that will produce an accurate delay is 16383
    for (int i = 0; i < ms; i++) {
        delayMicroseconds(1000);
    }
}

void IREmitterOff() {
    irsend.space(0);
    pause(60); // 60 ms is OK for my TSOP but should be tuned
}

void IREmitterOn() {
    irsend.mark(0);
    pause(10);
}

void switchOffOnIREmitter() {
    IREmitterOff();
    IREmitterOn();
}

void checkIRBeamBreak() {
    int val = digitalRead(PIN_DETECT);
    // LOW : no beam break
    // HIGH : beam break
    if (val == LOW)
        return;

    detachInterrupt(digitalPinToInterrupt(PIN_DETECT));
    switchOffOnIREmitter();
    if (digitalRead(PIN_DETECT) == HIGH) {
        Serial.println("IR BEAM BREAK !!!!");
    }
    attachInterrupt(digitalPinToInterrupt(PIN_DETECT), checkIRBeamBreak, RISING);
}

void loop() {

}


Integrating an analog signal using Arduino Due I have an 2 analog signal, and I want to calculate the difference between 2 signals (A0 and A1), then integrate an analog, but it doesn't work (I just started studying Arduino).

Please could you show me how to deal with this problem?

Thanks a lot

float analogInPin = A0;
float analogInPin1 = A1;
float analogOutPin = DAC1;
float FeqIn, FeqIn1, FeqIn2, FeqIn3, FeqOut, w, Triarea, Recarea, area, n, y, t;

void setup() {
  Serial.begin(9600); // use the serial port
}

void loop() {
  FeqIn1 = analogRead(analogInPin);
  FeqIn2 = analogRead(analogInPin1);
  FeqIn3 = FeqIn1 - FeqIn2
  // integration
  area(1) = 0;
  y(1) = 0;
  for (n = 1; n = t; t++) {
    Triarea(n+1) = (0.5*t(2))*(FeqIn3(n+1) - FeqIn3(n));
    Recarea(n+1) = t(2)*(FeqIn3(n));
    area(n+1) = (Triarea(n+1) + Recarea(n+1)) + area(n);
  }
}

The error message is:

Arduino: 1.6.5 (Windows 8.1), Board: "Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

_02.ino:3: error: 'DAC1' was not declared in this scope
_02.ino.ino: In function 'void loop()':
_02.ino:20: error: expected ';' before 'area'
_02.ino:21: error: 'y' cannot be used as a function
_02.ino:24: error: 'Triarea' cannot be used as a function
_02.ino:24: error: 't' cannot be used as a function
_02.ino:24: error: 'FeqIn3' cannot be used as a function
_02.ino:24: error: 'FeqIn3' cannot be used as a function
_02.ino:25: error: 'Recarea' cannot be used as a function
_02.ino:25: error: 't' cannot be used as a function
_02.ino:25: error: 'FeqIn3' cannot be used as a function
_02.ino:26: error: 'area' cannot be used as a function
_02.ino:26: error: 'Triarea' cannot be used as a function
_02.ino:26: error: 'Recarea' cannot be used as a function
_02.ino:26: error: 'area' cannot be used as a function
'DAC1' was not declared in this scope

I think your main problem here is a fundamental lack of understanding about C++.  There's numerous basic errors in your code.  Let's take a look at them:

FeqIn3 = FeqIn1 - FeqIn2

All C++ statements must be terminated by a ; otherwise it doesn't know where one statement finishes and the next one begins.

area(1) = 0;
(and many others)

You have declared a bunch of float variables in the global scope.  You are then trying to use those float variables as functions, and on top of that you are then trying to assign a value to the return value of that function.  That makes absolutely no logical sense whatsoever.

I think you meant to be using arrays of float values.  Arrays are denoted by [ and ] not ( and ).  Further, they have to be defined as arrays, including the size of the array, not a single value.  Also in C++ arrays are zero based (i.e., they start at index 0 not index 1).

For example, area could be defined as:

float area[1024]; // 1024 floating point values in an array
// ...
area[0] = 0;

Next:

Recarea(n+1) = t(2)*(FeqIn3(n));

I don't even know what to make of this bit...  If I assume you should replace (...) with [...] for indices to arrays, it still makes no sense.  You're calculating a single value (FreqIn3 = FreqIn1 - FreqIn2) then using that as an array (FreqIn3[n]) which makes absolutely no sense to me at all.  Then you're using another value t which you are incrementing (incorrectly, more on that later), which again you are then trying to use as an array (t[2]).  Which is it - arrays or single values? And how do you increment an entire array?

Now the incrementing:

for (n = 1; n = t; t++)

n starts at the value 1.  While n is assigned the value t, increment t.  Now, does that sound logical?  And what is t? when that loop starts?  It has no defined value, so it could be anything at all.  And when does the loop end?  Well, since you're using float values for your counters (which is idiotic at best) you won't ever get any integer wraparound, so t will never equal 0 and consequently the result of assigning t to n will never be 0, so the loop will never end.

I think you need to go back to absolute basics and learn a bit more about syntax of C++, arrays, functions, loops, etc, before embarking on something complex like signal integration.


Text send via HC-05 is broken up by first character on the receiving end? On the receiving end, I have an mit app inventor app which acts like a client.

In arduino, I check for connection status and do a serial write to send the text. The code for that is below:

#include <SoftwareSerial.h>

#define D2 2
#define D3 3
#define BT_STATE_PIN 4

SoftwareSerial BTSerial(D3, D2);
long lastMark;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(38400);
  BTSerial.begin(9600);
  pinMode(BT_STATE_PIN, INPUT);

  int counter = 0;
  lastMark = millis();
}

bool isBTConnected() {
  return (digitalRead(BT_STATE_PIN) == HIGH);
}

void sendText(char* message) {
  Serial.println("SEND: " + String(message));
  if(isBTConnected()) {
    BTSerial.write(message);
  }
  else {
    Serial.println("did not send");
  }
}

int msgCount = 0;
void loop() {
  long now = millis();

  if(now - lastMark > 2500) {
    msgCount++;
    String msg = "This is a really really long MSG" + String(msgCount);
    sendText(msg.c_str());
    if(msgCount == 5) {
      msgCount = 0;
    }
    lastMark = millis();
  }
}

This is how the device is wired currently:

simulate this circuit – Schematic created using CircuitLab

On the app inventor side of things, I have a very simple app that connects to the bluetooth module; it listens for anything received, and then just receives the text.

aia file

Here is a pic showing the issue I am facing currently:

Sometimes the breaking up happens randomly at some other place. Hoping someone can help sort this issue.

I did something similar (multiBT) using HC-05 and PC BT, with the same App.
Results: all the incoming data from the PC_BT to the phone are right, but with the HC-05 sometimes is chunked as @deostrol show. I think is a bug with the HC-05 firmware.
To correct this, I've implemented StartBegin and StopFinish character in the received string before use.


Detecting pulsed LED I am trying to use an Uno to detect if an LED is on or not. Sounds simple, but I am tearing my hair out on this one, here is why.... This is a model railway application and I want to detect an LED being lit on the control panel showing how a route (points/turnouts) is set. The LED is lit by a point position indicator (www.blocksignalling.co.uk/index.php/points-position-indicator-ppi4-dc) which works perfectly but the LEDs are not permanently on when lit, even though they appear so, they are pulsed at around 8khz. I tried using opto isolators triggering an digital input on the Uno. They all happily detect 'no light' and the pin goes HIGH, but when the led is lit, the pin flucuates between 0 and 1 so not a true or stable LOW. I also made my own opto using a TCRT5000 with the leds pointing at eachother encased in shrinkwrap, using standard breadboard set-up which worked perfectly when powering the transmitter from the Uno, but same result when powered from the LED. Anyone out there got any ideas please?

Count HIGH values read for example in 2 ms. It should be zero if the LED is not lit and more then zero if it is lit.


Which component is described as a "jumper" (NOT jumper wire) when working with a motor shield? In this video I'm watching then instructor talks about using "jumpers". He's got a motor controller shield and at first he says that "during the making of this video we only had 1 jumper, thus only Pin 4 is working", and that as a result he could only move a motor/wheel in 1 direction.

He proceeds to find another jumper, uses it to make Pin 5 work, and then he can reverse polarity and change the direction the the wheel spins.

At first I thought that he must mean header pins, but when he holds the tiny component up, it looks like it's something else:

I read about a "power jumper" on an Adafruit page, but it only applied to one version of the Arduino and sounded like it was to do with Power joining (using the same power source for the motor and controller), so I really don't know if that's the same thing.

It's one of these (or similar). It connects two adjacent male header pins.


Wiring for Arduino Mega and multiple MPU 6050/Gy 521? I have an Arduino Mega 2560 that I need to connect 4 MPU 6050/Gy 521's to.

I found some resources on the Mega and Uno, however I'm having trouble piecing them together.

This resource gives great detail for connecting a single MPU to a mega.
http://dummyscodes.blogspot.com/2014/07/mpu6050-gy-521-breakout-arduino-mega.html

This resource gives a trick for connecting multiple to an UNO.
https://playground.arduino.cc/Main/MPU-6050

My problem is that the wiring for the Uno and Mega are different. The resource I have for the UNO describes using the MPU AD0 (output) connecting it to different output pins for each MPU. The resource talking about the MEGA doesn't even use the AD0, and uses INT but I'm not sure if I can use the same concept.

Plus, I still don't actually understand how to connect/what other pins to use for the other 4.

I'm pretty new to Arduino, definitely new to anything with wiring.

Please help! I'm really confused about using multiple together, and about how to properly wire them.

MPU-6050 uses I2C for comm's, yes?
Connect all the SCLs in parallel to the Mega with a 4.7K, or 3.3K, pullup resistor. Same for the SDAs. I2C is D20, D21 (or D21, D22) on the Mega.

The MPU-6050 has an A0 pin to select from one of two addresses, let's call them Add0 and Add1 for simplicilty.
Connect each MPU-6050 A0 pin to a unique Mega pin.  When none are being addressed, have each Mega output high. When one MPU-6050 is to be accessed, take that device's A0 pin low and communicate with it using Add0. The other's will be looking for communications at Add1 and thus will not respond.

If the MPU6050 is a 3.3V device, then you should also remove the pullup resistor network package on the Mega that pulls SCL/SDA to 5V.  There are 2 pullups in a very little 8-pin package, the other 2 are not used. Connect the 3.3K or 4.7K pullup resistors discussed above to 3.3V.

This is the part, RN1, on the Mega R3 board. It may not be marked as such on the board. Remove it, or cut the traces next to the pad legs, one on the left side (connects to pin 3), one on the top (connects to pin 2).


Should millis() be stored in a variable once each loop, or called for every reference? When comparing the value of millis() numerous times per loop(), are there reasons for/against storing it in a variable once at the top of loop(), v.s.  calling millis() each time?

The most basic example code "Blink Without Delay" is written as such:

void loop() {
  //...
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // Do stuff
  }
}

I don't really she why the example code above bothers storing millis() in a variable "currentMillis" at all. (I realize that in such a simple program, there would be no noticeable difference.)

I imagine that if I use a variable, the longer the duration of loop(), and the further down my use of the "currentMillis" variable, the more deviated the stored value will be.
I'm wondering the other ramifications of either method as well.

Does calling millis() directly hog resources of any sort? If not, I imagine it would be better to not use a variable, so as to get a more accurate time value and save a bit of memory.

The primary downside to calling a function each time is that it may take more CPU cycles to complete the overall loop. The difference in CPU cycles, if any, depends on the actual implementation of the function and how the compiler optimises the call. For low-CPU sketches, this difference is probably unnoticeable.

Generally speaking, it is good programming practice to avoid calling a function more times than is necessary. Really the function should be called directly only if you have reasons to believe, based on desired timing and procedure order, that using the same return value in multiple places could create problems. In the example sketch given, there would be almost no functional difference between using a variable or calling the function inline.

Another advantage to using a variable is that you can give it a name that makes the code clearer to understand. In the example given, the relationship between currentMillis and previousMillis is very clear. In the case where a function returns a more complex object, such as a class or structure instance, using a variable (of the appropriate type) can be really useful since this would allow multiple members of the returned data to be accessed without calling the function multiple times. In fact, even in the given example, the function would have to be called twice since currentMillis appears twice in the loop.

As far as memory goes, an unsigned long uses very little.


How can I power a NeoPixel ring and strip through Arduino MKR1000? I currently have a MKR1000 which is connected to 1 ring with 8 neopixels, 1 strip with 20 neopixels, 1 microwave sensor, 1 speaker, 1 rotary encoder. I am running the NeoPixel positive and negatives through a 220 µF capacitor, and the data pins through 220 Ω resistor.

I am soldering these components onto a board, but currently, when I plug the MKR1000 into my USB it says it's drawing too much power, the Arduino also smokes and I can smell burning, so disconnected straight away.

What am I doing wrong?

The on-board regulator of an Arduino can supply a maximum of 500 mA when connected to USB, and up to 1000 mA when connected to an external power supply (see Maximum current from Arduino 5V power pins).

If your components are drawing more current than that, then you will need to use an additional separate power supply for the NeoPixel ring - ensuring that the ground lines of the Arduino's supply and the NeoPixel's supply  are connected.

If the Arduino has been smoking then it may already be damaged. Did you see which part was smoking? If it was a capacitor as shown in Is my Arduino dead?, then this answer may help.


sending room temp data from multiple esp8266's to Mega 2560 to control CH gas boiler My existing Arduino Mega set up has been in use for about 4 years controlling my gas CH system & heat pump HW system using an Arduino mega & 13 'wired' DS18B20 sensors; 2 of these sensors monitor the main room (lounge) temperature & 1 sensor monitors the outside temp. These 3 sensors control the CH by gas boiler using an algorithm that constantly adjusts the room temp setting as the outside temp changes. The others monitor HW tank temps, heat pump inlet & outlet temps.

I want to change this 'single zone' CH control to a 'multi zone' control using many more temp sensors (DS18B20 or ESP8266?) but laying in hidden wiring would be a real pain.

I've been looking at using ESP8266-07 as a wireless temp sensor for each 'zone', sending its data to the Mega for processing by the above refered to algorithm, so that the Mega can control the CH system better but I can't find any reference to receiving this wireless data at the Mega for processing within the IDE sketch.

I've tried testing the nRF24L01 & nRF24L01+ but my house has many 'black' reception areas & transmission is unreliable.
My 2.4GHz wireless LAN has 3 extenders around the house so this would be my prefered wireless solution.

Could a wireless 'master' be used at the Mega to process data coming in from the 'slave' sensors or am I misunderstanding this?

My programming skill is limited to 'basic IDE' & I find 'wireless' a bit of a black art (I'm a retired mechanical engineer!)

I am also in the middle of converting the control of my heating, multi-zone, but using Ciseco / Wirelessthings units as temperature sensors both inside and out. See https://www.wirelessthings.net

Simple serial interface is all you need from the Arduino to run these on a network. The coin cell battery lasts for over 1 year running 1 sample / 10min - the sample rate is configured but obviously the more samples you send the more the battery drains. Range seems to be OK and gets through 3 floors in the house and from the outside. I do use external antenna on the Arduino wireless unit to ensure I get all of the sensor readings.

However sounds like your house is BIG if running 3x WIFI extensions where as a single WIFI base station does me fine.


How to stop loop in the serial monitor? I want to make a serial program with input from the serial monitor and show each character with its binary and ASCII codes.

At the end of the program, I want to show the whole message sent from the serial monitor but I don't know how to stop the loop. Can someone help me please?

Here's my program:

String dataST;

void setup() {
  Serial.begin(9600);
  Serial.println("Message sent by serial monitor : ");
}

void loop() {
  for (int i = 0; i < 400 ; i++) {
    if (Serial.available()) {
      char dataOK = Serial.read();
      dataST += dataOK;
      Serial.print(dataOK);
      Serial.print(" = ");
      delay(200);
      for (int i = 7; i >= 0; i--) {
        byte bytes = bitRead(dataOK, i);
        Serial.print(bytes, BIN);
      }
      Serial.print(" = ");
      int dataAS = dataOK;
      Serial.print(dataAS);
      Serial.println(" ");
      Serial.println(" ");
    }
  }
  Serial.println("Message : ");
  Serial.print(dataST);
  dataST = "";
}

The result from the program above is:

Message sent by serial monitor :
Message :
Message :
Message :

And the result I want is:

Message sent by serial monitor:
H = 01001000 = 72

e = 01100101 = 101

y = 01111001 = 121

Message :
Hey

Please help me.

Please take a look at the documentation of SerialEvent.

This might be exactly what you are looking for (after several small tweaks)

Code from the example:

/*
  Serial Event example

  When new serial data arrives, this sketch adds it to a String.
  When a newline is received, the loop prints the string and clears it.

  A good test for this is to try it with a GPS receiver that sends out
  NMEA 0183 sentences.

  NOTE: The serialEvent() feature is not available on the Leonardo, Micro, or
  other ATmega32U4 based boards.

  created 9 May 2011
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/SerialEvent
*/

String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}

void loop() {
  // print the string when a newline arrives:
  if (stringComplete) {
    Serial.println(inputString);
    // clear the string:
    inputString = "";
    stringComplete = false;
  }
}

/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}


How can I initialize an array of objects in setup? How can I declare an empty global array, to be initialized in setup?

What I would like to do is this:

#include <ResponsiveAnalogRead.h>

const size_t ANALOG_SIZE = 3;
const int ANALOG_PINS[ANALOG_SIZE] = {A0,A1,A2};
ResponsiveAnalogRead analog_reads[ANALOG_SIZE];

void setup() {
  for(size_t i=0; i<ANALOG_SIZE; i++){
    analog_reads[i]=ResponsiveAnalogRead(ANALOG_PINS[i], true, 0.01);
  }
}

But the error I get is:

sketch_may29c:5: error: no matching function for call to 'ResponsiveAnalogRead::ResponsiveAnalogRead()'
 ResponsiveAnalogRead analog_reads[ANALOG_SIZE];

                                              ^

Is it impossible to declare an empty array of a given size?

As Craig wrote, the declaration of an class typed array will call the default constructor of the class, which is the one without any arguments. The class, that you use, does not provide a default constructor, since it needs it's parameters. You cannot do it this way.

But you can use dynamic allocation. In global scope only declare an array of pointers to ResponsiveAnalogRead objects:

ResponsiveAnalogRead *analog_reads[ANALOG_SIZE];

This array only holds pointers, that can point to ResponsiveAnalogRead objects. The objects themselves are not created yet. In setup() you can then create the objects dynamically with the new statement:

analog_reads[0] = new ResonsiveAnalogRead( input_parameters);

(Of course you have to replace input_parameters with all parameters, that the constructor needs). To call a member of the object, you can dereference it like this:

analog_reads[0]->member_function();

If you don't know about pointers yet, you should google for a tutorial (there are plenty), so that you understand the principle behind them.

Important note: Dynamic allocations of memory geht written to the heap in RAM. Since the Arduino (especially the Atmega based ones) has only very limited RAM, dynamic allocations have to be handled with great care. You should not create and delete data often in your program, since this would make swiss cheese out of your heap. But allocating the memory only once in your program and never deleting it, will not be a problem, as long as you don't try to allocate too much memory.


Record video with CMOS camera using Arduino Is it possible to use this with Arduino to record and store videos on memory card?

Additionally, if someone has already done it, a tutorial link would be appreciated.

Arduinos have two major drawbacks:

Not enough memory.
Way too slow.

There's a shield to help you do that:

http://nootropicdesign.com/ve/
http://blog.arduino.cc/2011/03/24/arduino-computer-vision-with-video-experimenter-shield/


No Information obtained when using 2 x SoftwareSerial ports on Arduino Nano I have a LoRa Click Module and Adafruit Ultimate GPS which both use Serial Communication.

I wish to just check the initial tests with all the components in on the Serial Console. Hence I have declared :

SoftwareSerial GPSSerial(10,11);
SoftwareSerial LoRaSerial(5,6);

Apparently when I declare them and upload the code on the board I do not obtain any information.

observations

However when I comment out the LoRaSerial declaration I obtain the GPS coordinates.
When I set the SoftwareSerial LoRaSerial(10,11) I retrieve the information.
I thought 5,6 pins won't be the right choice and hence went on the set SoftwareSerial(8,9) but I retreive no information.

inference

Nano cannot take into consideration more than 1 SoftwareSerial Component. However the Official Documentation states that all Digital pins can be used for Software Serial.

Is it too much for a Nano to have overall 3 Serial ports (including Serial itself)?

sketch

#include <SoftwareSerial.h>
#include <TheThingsNetwork.h>

SoftwareSerial GPSSerial(10, 11); //RX , TX
SoftwareSerial LoRaSerial(8,9); // RX, TX (tried with 5,6 too)
#define freqPlan TTN_FP_EU868

 TheThingsNetwork ttn(LoRaSerial, Serial, freqPlan);
void setup() {
  Serial.begin(115200);
  GPSSerial.begin(9600);
  LoRaSerial.begin(57600);
}
void loop() {
  delay(2000);
  while (GPSSerial.available()) {
    char c = GPSSerial.read();
    Serial.write(c);
  }
  delay(2000);
  while (LoRaSerial.available()) {
    ttn.showStatus();
  }
  delay(2000);
}

You cannot use two SoftwareSerial instances at the same time - or not for receiving anyway.

SoftwareSerial is a "last resort" system - only to be used if there is absolutely no other option. And then you need to be aware of certain information and rules:

Only one device can listen at any time, switchable using the SoftwareSerial::listen() method
When a byte is being received nothing else can happen - it takes over the entire CPU for the duration of reception
When a byte is being transmitted nothing else can happen - it takes over the entire CPU for the duration of transmission
There is a minimum required time between successive bytes when receiving that causes problems at higher baud rates

These limitations mean that, when using multiple devices, you have to know before hand which device will be sending you data so you can be ready to receive it. It also means that SoftwareSerial is effectively half duplex - it only really works properly when you are either only receiving, only transmitting, or using a "call-response" scenario like sending "AT" commands and looking for a response afterwards.

So the general recommendation is: use hardware UARTs whenever possible (and if you don't have enough, then consider using a different, more suitable, board with multiple UARTs), and if you must use SoftwareSerial then limit yourself to only one instance of it.

As a last resort you can always use multiple boards and connect them using a different system, such as I2C.


Sparkfun Can-Bus Shield example not working I recently bought a Sparkfun Can-Bus Shield, and tried the SparkFun_CAN_Demo from here but the program only prints "CAN-Bus Demo" and then does nothing, even when I have it connected into my vehicle's OBD-II port and the key is turned to ON (I can't run the engine because I am in my garage). Any help will be appreciated.

SPI pins are located on different pins in Arduino Mega. You have to wire it correctly with your shield. Some shields uses ICSP (6-pin header) for better compatibility but this one doesn't.

See Arduino SPI Reference for more details (section: Connections)


Number of digits setting for serial printing the sensor output value I am getting fan motor rpm as 3200. But if I get the data as 50, I should get the value like 0050. How can I do this?

I can do it like checking the value for single digit(0-9), double digit (10-99), and triple digit (100-999) and four digit(1000-9999). I need to fix digit size and send it through serial. Is there any other way for this?

You can use the C function sprintf:

char text[5];
sprintf(text, "%04d", number);
Serial.println(text);

The leading 0 in 04d will add zero's for the length (4) is met, so 1 will become 0001, 10 will become 0010, 100 will become 0100 and 1000 will stay 1000.


Smooth out digital signal from SW-420 vibration sensor in order to record duration? I'm attempting to make a sensor that will record the duration and frequency of a pump going off. It always fires for at least 4 seconds, but the duration can be up to 7 days.  The vibration sensor I have is a SW-420, which I think will work. I'm fairly new at this, and I don't mind figuring out the actual code myself, but I'm running into newb problems.

Should I approach this as an interrupt that uses a callback while loop, or would it be better to look at it as a typical debounce sub? Is there a better solution?
Since the duration can (very rarely) exceed running for more than a few minutes, I'm wondering if I need an RTC module. The time is not very important, it just needs to be "close".
The duration info will be fed to node-red via MQTT. I can count frequency in that system... I'm trying to decide if I should do remote frequency calculations, or try and wrap it into the firmware on the Arduino. Any suggestions for this?

Bonus points if I can accomplish this without any additional libraries. I'd love to put this on an ESP8266.

Thanks for your help, I appreciate it.

Should I approach this as an interrupt that uses a callback while loop, or would it be better to look at it as a typical debounce sub?

No. If you want to use interrupts then just record the start time on one edge of the signal and subtract it from the current time on the other edge (not sure which edge is which on that sensor).

  Since the duration can (very rarely) exceed running for more than a few minutes, I'm wondering if I need an RTC module. The time is not very important, it just needs to be "close".

It depends how you define "close".  An RTC can give you better accuracy over long periods, yes, and the Arduino struggles with > 49 days by itself.

  The duration info will be fed to node-red via MQTT. I can count frequency in that system... I'm trying to decide if I should do remote frequency calculations, or try and wrap it into the firmware on the Arduino. Any suggestions for this?

What kind of frequency are you wanting? The frequency of the vibration itself, or the frequency at which some vibration occurs?  If the former the sensor you have won't do the job - that just tells you when there is vibration above a certain threshold.

To sense the actual frequency of vibration you need a more hands-on approach by the MCU. Either use the raw HDX-2 vibration sensor as used on the SW-420 (that's the blue tube at one end), or do it properly and use an accelerometer which you sample over time and perform an FFT on the sampled signal to isolate the different frequencies.


Arduino Xbee AT command mode I have 2 Xbee Series 2 modules.
One of it is connected to arduino via an adapter. And Ground 5V, as well as Rx>>Tx and Tx>>Rx.

The xbee is configured AT mode Coordinator.

I want to use the serial monitor in arduino to change the parameters of the xbee, such as DH or DL or PAN ID things like this.

Is there a way for the xbee to display its "OK" response after entering command mode on the serial monitor?

Because you have an Arduino Mega, you can set it up to use it like a USB-to-UART adapter by using the following code (source):

void setup() {
  // initialize both serial ports:
  Serial.begin(9600);
  Serial1.begin(9600);
}

void loop() {
  // read from port 1, send to port 0:
  if (Serial1.available()) {
    int inByte = Serial1.read();
    Serial.write(inByte);
  }

  // read from port 0, send to port 1:
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial1.write(inByte);
  }
}

Basically what this does is it takes the data it receives from the USB port via Serial and transmits it to Serial1 and then also reads from the UART port via Serial1 and transmits it back to the computer via Serial. With this code running you should be able to hook up the XBee to RX1 and TX1 and communicate to it using the Serial Monitor.


Motor Shield StepMotor What the two yellow cables as you can see in the picture do not know?

There are two types of stepper motors: unipolar and bipolar. Bipolars usually have four wires and unipolars have six.

  --http://hobbymilling.com/wp-content/uploads/2011/05/Unipolar-stepper-motor-windings.png

  --https://www.codeproject.com/KB/system/steppermotorcontrol/pic6.jpg

The motor shield is designed to drive a bipolar motor (4 wires) but the motor is unipolar (6 wires). As you can see in the pictures, if you ignore the middle wire of the unipolar motor, it is the exact same as a bipolar stepper motor.


What are the other IDEs for Arduino? The basic Arduino IDE lacks a lot of the sophistication present in other IDEs such as code completion, code collapsing, folder organisation, etc. Are there other IDEs that allow programming in C or C++ and improve on these aspects?

There is an Arduino Eclipse plugin named sloeber! And Eclipse is an awesome cross-platform open-source IDE!

Stino is good. It requires Sublime Text 2 which has an indefinite free trial.

Visual Micro provides a full build system with debugger for Arduino in Microsoft Visual Studio. For advanced users it also allows the underlying Arduino source code to be viewed or modified, enabled projects and/or libraries to be edited from any location and shared in multiple projects alongside true cross-platform intellisense.

For more go to The Official Arduino Site

For development on Windows, there is a special edition from Arduino official IDE called arduino-erw, This edition much better the last one because it fixed a lot of lagging and stability issues!


analogRead DC Motor - Negative value I was trying to play with Arduino this weekend and connected a DC motor to A0 and GND to measure the voltage it provides when I rotate it.

However,
when I rotate the DC motor with my fingers to test out the readings I see that when rotated clockwise it generates voltage that can be read in Arduino. But when I rotate it counter-clockwise the values I get are 0 - this is probably because DC motor generates negative voltage (?).

How do I fix this so that no matter the direction of the turn I get always positive value?

I am trying to build a simple anemometer, just for fun for kids and plot the values, however can't do much when I get 0 on analogRead when wind blows from the other direction..

thanks for any input into this.

You can use full wave rectifier, but there is a significant voltage drop on it.

Another way is using Voltage divider to provide 1/2 Vcc to one of the motor terminals. But then you can measure just 1/2 Vcc in both directions (without another Voltage divider)

Something like:


How to drive a strip of 12 V no-addressable LEDs? I recently bought this LED Strip. I got the 5M 3528 300LEDs SMD RGB Non-waterproof ones. However, I am not sure how to use them. On the strip there is four wires. I have tried supplying power to the wire that says it needs power and then I put ground to each of the other wires, but that only turns on a colour. How do I make it so I can choose what colour to use (Wiring, Code, etc.)?

EDIT: I'm sorry, I misunderstood! I assumed your LEDs were the 4pin serial version, whereas it makes more sense to me that they are the 6pin analog version. I must've brushed over the part where you said you grounded the colored wires and got that corresponding color.

You will provide 12V to the Power wire. To light the strip Red, you'd ground the Red wire, ground Blue for Blue, etc. Ground Red and Blue to light Purple, mixing colors etc etc.

So what if you wanted teal? or maybe a different shade of green? You'll need a way to generate PWM on the R, G, and B pins. Basically if you have an 80% duty cycle on Blue, that means it's only grounded 80% of the time. This corresponds to 80% brightness of the blue LEDs, then you could mix that with say 60% red and 10% green, or whatever you wanted to get a full 16 million colors. This is most easily accomplished with a microcontroller, and so I'll provide schematic and code tips for the simplest solution: an Arduino.

Schematic

simulate this circuit – Schematic created using CircuitLab

I chose Pins 9, 10, and 11 of the Arduino because they are all PWM; you can choose any PWM pins you want (denoted by ~ or # usually). Just reflect those changes in the sketch.

Arduino pins are also only capable of sinking about 40mA if I remember correctly, so you'll need to control some MOSFETs with the PWM. I find you can't go wrong with the IRFZ44N, but that's just what I've had available to me.

Arduino Sketch

How you control it is up to you; sensors, potentiometers, networked, bluetooth, constant fade pattern, there's a slew of options. So this code will tell you the necessary functions, but from there it's a matter of programming and integration of whatever else you want.

void setup(){
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
}

void loop(){
  //255 -> 100%   ;   0 -> 0%
  analogWrite(9, 255); // turn red to 100%
  analogWrite(10, 0); // turn green to 0%
  analogWrite(11, 128); // turn blue to 50%
}

If this doesn't work, please let me know and I'll fix it. I forget if analogWrite is okay with being called in a simple, unrestrained loop over and over, and I also forget if Arduino pins have internal pull-downs


Class TKPotentiometer has no member named 'read' I am testing a set-up using the TinkerKit shield for Arduino Uno, and a few TinkerKit inputs and outputs. I have an issue with the code provided on the TinkerKit website for the potentiometer component:

#include <TinkerKit.h>

// creating the object 'pot' that belongs to the 'TKPotentiometer' class
TKPotentiometer pot(I0);

// creating the object 'led' that belongs to the 'TKLed' class
TKLed led(O0);

int brightnessVal = 0;  // value read from the pot

void setup() {
  // initialize serial communications at 9600 bps
  Serial.begin(9600);
}

void loop() {
  // read the potentiometer's value:
  brightnessVal = pot.read();

  // set the led brightness
  led.brightness(brightnessVal);

  // print the results to the serial monitor:
  Serial.print("brightness = " );
  Serial.println(brightnessVal);

  // wait 10 milliseconds before the next loop
  delay(10);
}

I get an error message when compiling:

Class TKPotentiometer has no member named 'read'

According to this webpage, though, read should be a member of the class. Why am I receiving this message?

As soon as I finished writing the question, it came to my mind that perhaps I misspelled something, so I looked for a file in the Menu's sketchbook that I could load.

With my surprise, I found the same exact code as I posted, with a little difference:

pot.read() was substituted with pot.get()


I am making an easy game but something in my code is wrong I am making a game where you need to push the button when the LED lights up but it is not registering the push at the right time. I need to push the button when LED is about to go off.

My code:

randNumber = random(2);

if(randNumber == 0){
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
}

if (btnAddFirst.pressed() && randNumber == 0){
  Serial.println("You did it");
}
else {
  Serial.println("u failed");
}

Don't use delay(), since nothing can happen (not even reading a button) while that delay is running.

Instead use millis() as in the BlinkWithoutDelay example sketch.


Interrupt driven serial in Arduino Mega This is the multi serial example from Arduino IDE

void setup() {
  // initialize both serial ports:
  Serial.begin(9600);
  Serial1.begin(9600);
}

void loop() {
  // read from port 1, send to port 0:
  if (Serial1.available()) {
  // plus do some operations
    int inByte = Serial1.read();
    Serial.write(inByte);
  }

  // read from port 0, send to port 1:
  if (Serial.available()) {
    // plus do some operations
    int inByte = Serial.read();
    Serial1.write(inByte);
  }
}

As you can see, the loop is running multiple times doing almost nothing at most of cycles, this will eat up battery life (if it has one).

Is it possible to read when data is available without looping, just like with an interrupt.

Also, is it a good practice to run a loop all the time? Is there any way to sleep? I have seen examples like this one http://playground.arduino.cc/Learning/ArduinoSleepCode which uses some other pin to wake up. I don't want that.

Why do you not want to sleep the processor? If it's running at all, it doesn't matter whether it is polling the UARTs or executing something else; it will still be using power.

The first several paragraphs of the article you linked to describe putting the processor into low-power mode and reducing the power consumption further by disabling some internal hardware modules. When the UART receives a byte, the processor will wake up and continue execution from where it slept. Isn't that what you are asking for?


Does millis() conflict with the PWM pins associated with timer 0? I've read that the millis() function uses the same timer as a couple of PWM pins.

If you're using those PWM pins, will millis() still return the correct value?

They do not conflict as millis() strictly reads the immediate value in TCNT0 whereas PWM via timer 0 uses the hardware's ability to compare the value of TCNT0 with the values in OCR0x without affecting the value of any of them.