pushing accelerometer data in packets from an arduino due to the pc and unto processing I'm quite a newbie to this and I've been struggling for sometime now with my school project, trying to find a way to send accelerometer data from my MMA7361 in data packets, I understand that I have to send the data in packets, but I'm having problems going about it. One of the requirements of the project is that I have to send the data in array-packets of all the individual axes (e.g. a buffer array to hold the x-axis value, another for the y-axis value and also for the z-axis value). I have read quite a lot of documentation on the internet about this  but putting it together is a challenge. Below is the infamous MMA7361 code sketch, do please help out if you can thankyou.

    #include <AcceleroMMA7361.h>

    AcceleroMMA7361 accelero;
    int x;
    int y;
    int z;

    void setup(){
        Serial.begin(9600);
        accelero.begin(13, 12, 11, 10, A0, A1, A2);
        accelero.setARefVoltage(3.3);     //sets the AREF voltage   to 3.3V
        accelero.setSensitivity(LOW);           //sets the sensitivity to +/-6G
        accelero.calibrate();
    }

    void loop(){
        x = accelero.getXRaw();
        y = accelero.getYRaw();
        z = accelero.getZRaw();
        Serial.print("\nx: ");
        Serial.print(x);
        Serial.print("\ty: ");
        Serial.print(y);
        Serial.print("\tz: ");
        Serial.print(z);
        delay(500);                                     //(make it readable)
    }

It's pretty simple to store the x, y and z co-ordinates in three separate arrays. Instead of storing them in single int variables you can just store them in int arrays. You can make three arrays that are of size 1000 a store the raw values there. In order to iterate through the arrays within loop() you can set up i at global scope and include an if statement that will know when the arrays are filled, for example if (i == 1000) and within this if statement you can set up a for loop that will iterate through the arrays and print their values and after reset i to 0 and then reset the buffer arrays i.e. fill them with zeroes. This last step is not needed since they will be overwritten anyway but it is good to have so you don't accidentally use old values.

Also the for loop that will print the values will take 8 minutes with that delay(500); You can make this delay smaller or print the value before each if statement as the data comes in.

#include <AcceleroMMA7361.h>

AcceleroMMA7361 accelero;
int xAxisBuffer [1000] = {0};
int yAxisBuffer [1000] = {0};
int zAxisBuffer [1000] = {0};

int i = 0;

void setup(){
    Serial.begin(9600);
    accelero.begin(13, 12, 11, 10, A0, A1, A2);
    accelero.setARefVoltage(3.3);     //sets the AREF voltage   to 3.3V
    accelero.setSensitivity(LOW);           //sets the sensitivity to +/-6G
    accelero.calibrate();
}

void loop(){
    // This stores the x, y and z values in their
    // respective arrays
    xAxisBuffer[i] = accelero.getXRaw();
    yAxisBuffer[i] = accelero.getYRaw();
    zAxisBuffer[i] = accelero.getZRaw();
    ++i; // moves to the next position

    if (i == 1000){ // the arrays are full
        // prints the (x, y, z) values
        // because the delay is .5 seconds it will
        // take about 8 minutes to print all 1000
        for (int j = 0; j < 1000; j++){
            Serial.print("\nx: ");
            Serial.print(xAxisBuffer[j]);
            Serial.print("\ty: ");
            Serial.print(yAxisBuffer[j]);
            Serial.print("\tz: ");
            Serial.print(zAxisBuffer[j]);
            delay(500); //(make it readable)
        }
        // restart at beginning of the arrays
        i = 0;
        // reset the arrays
        memset(xAxisBuffer,0,sizeof(xAxisBuffer));
        memset(yAxisBuffer,0,sizeof(yAxisBuffer));
        memset(zAxisBuffer,0,sizeof(zAxisBuffer));
    }
}


Adding music to loop Im newbie. I just wanted to ask how can i put my tmrpcm.play into loop. Im trying to put it in a loop but the problem is it didn't play. I also try adding a method and call the method into the loop but it give me the same problem also. It will just only play in the void setup.

Here's my code.

#include "SD.h"
#define SD_ChipSelectPin 4
#include "TMRpcm.h"
#include "SPI.h"

TMRpcm tmrpcm;

void setup(){
tmrpcm.speakerPin = 9;
Serial.begin(9600);
if (!SD.begin(SD_ChipSelectPin)) {
Serial.println("SD fail");
return;
}

tmrpcm.setVolume(5);
tmrpcm.play("Yeah.wav");
}

void loop(){  }

The library has a built in loop function:

audio.loop(1);             0 or 1. Can be changed during playback
                           for full control of looping.

See WIKI page of the library.

Btw, it is unclear if you mean by 'a loop' a while(true) loop or the void loop() function. Although it should not make a difference.


MPU-9250 compass always returns to zero I am trying to build a 9-DOF IMU using the MPU-9250 chip which contains a gyro, accelerometer and compass. I have successfully realized 6-DOF sensor fusion using the DMP chip and Sparkfun's library, but I still have some yaw drift which is why I want to use its onboard compass for 9-DOF.

The DMP unfortunately can't do that so I tried kriswiner's work on 9-DOF sensor fusion which seemed to work but after I rotate the PCB, the yaw moves in the correct direction but it then slowly returns back to where it started, without me moving the PCB any more. This happens with many different sensor fusion libs, some more some less severe.

I have also tried just reading the raw mx and my values and reading the heading using atan2(my, mx) which made things a little better but still a 360° real-life rotation did not correspond at all to a 360° rotation on the chip.

Is this a known problem with the MPU-9250 and I am missing something completely obvious, or what could be wrong here?

Thank you for any help!

Ok, I have finally found the issue, and I am feeling very, very stupid.

I needed to calibrate the magnetometer with the figure-8 movement
I put a gigantic solid-metal 18650 Li-ion cell right next to the magnetometer chip...

EDIT: after replacing the 18650 with a polymer battery that is far away from the chip, things got a little better but both sensors in both devices still return garbage values.


Should I use a loop instead of an If statement? I have a simple sketch that tests input from 2 touch sensors and outputs to 2 relays (if a sensor is touched, trigger the respective momentary relay).  It has been a bit quirky to say the least.  perhaps I need to adjust delays or adjust sensitivity of the touch sensors, but I feel that maybe the coding could be more efficient.  Would using a WHILE or DOWHILE loop work better than an IF statement for this?  It seems like there is a timing issue between the relay and the sensor.  When I hit the sensor, the relay triggers immediately, but then it doesn't shut off right away.  Also if both sensors are made at the same time, I am seeing only 1 relay trigger or neither.  I am trying to eliminate the code as my failure point. I have the code printing to the serial monitor to show "Sensor 1 touched" or "Sensor 2 touched", and sometimes that triggers once and sometimes it will print multiple times.

int touchPin1 = 2; //Touch sensor 1
int touchPin2 = 4; //Touch sensor 2
int val_1 = 0;
int val_2 = 0;
int relayPin1 = 8; //Relay 1
int relayPin2 = 9; //Relay 2

void setup()
{
  Serial.begin(9600);
  pinMode(touchPin1, INPUT);
  pinMode(touchPin2, INPUT);
  pinMode(relayPin1, OUTPUT);
  pinMode(relayPin2, OUTPUT);

}

void loop() {
  digitalWrite(relayPin1, LOW);
  digitalWrite(relayPin2, LOW);
  val_1 = digitalRead(touchPin1);
  val_2 = digitalRead(touchPin2);
  if(val_1 ==1)
  {
  Serial.println("Pad 1 Touched");
  digitalWrite(relayPin1, HIGH);
  }
  if(val_2 ==1)
  {
  Serial.println("Pad 2 Touched");
  digitalWrite(relayPin2, HIGH);
  }
  delay(100);
  //Serial.println();
}

Basically I am asking if there is a more efficient way to code this.

Touch Sensors: Adafruit Standalone Momentary Capacitive Touch Sensor Breakout Adafruit Part Number: 1374

Relays: SunFounder Relay Module for Arduino and Raspberry Pi 5V DC Trigger by HIGHLO (HIGH Trigger)

What you are lacking is the else concept:

If a touch pad is pressed, then

Turn the relay on

else

Turn the relay off

Rather than turn the relay off every iteration, you only turn it off if the touch pad is not pressed.

That can be written as:

val_1 = digitalRead(touchPin1);

if(val_1 ==1)
{
  Serial.println("Pad 1 Touched");
  digitalWrite(relayPin1, HIGH);
} else {
  digitalWrite(relayPin1, LOW);
}

If you want your messages to be more meaningful and not spam, then you can remember the previous state and only do things if the state changes:

static uint8_t oldVal1 = LOW;

uint8_t val1 = digitaRead(touchPin1);

if (val1 != oldVal1) {
    oldVal1 = val1;
    if (val1 == HIGH) {
        Serial.println("Pad 1 Touched");
        digitalWrite(relayPin1, HIGH);
    } else {
        Serial.println("Pad 1 Released");
        digitalWrite(relayPin1, LOW);
    }
}


Linking the Arduino Bootloader In Atmel Studio I have been trying to get the Arduino bootloader to compile into my firmware binary in Atmel Studio. I got the bootloader project to link and compile. I use ArduinoCore and the bootloader as a dependencies to my main code. The dependency tree looks like:

ArduinoCore
bootloader
Main firmware

The Bootloader
It took me a bit to get the bootloader to accept the rest of ArduinoCore as a dependency but it compiles into a static library. I use the bootloader linker to specify the memory location of the bootloader binary. It should start at 0x0 and provide a jump to the main firmware, located at 0x2000.
Bootloader linker flags:
-Tbootloader_samd21x18.ld -Wl

And here are the contents of the linker script:
  FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x2000 /* First 8KB used by bootloader */
  RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000-0x0004 /* 4 bytes used by bootloader to keep data between resets */

This is based off of the .cProj file that comes with the linker. It is compiled as a static library so I can include it into my final binary.
Main Firmware
My code has both the ArduinoCore and the bootloader static libraries as dependencies:
libm
libArduinoCore
libbootloader

And I am using these linker flags:
-Tflash_with_bootloader.ld -Wl,--cref -Os -Wl,--check-sections -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align

The contents of this linker script are moved out by 8KB in order to accommodate the bootloader at the start of the binary:
    FLASH (rx) : ORIGIN = 0x00000000+0x2000, LENGTH = 0x00040000-0x2000  /* First 8KB used by bootloader */
    RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000

And yet, my entry point does not appear to ever hit the bootloader. It jumps straight to "main.cpp" from ArduinoCore. The firmware runs as expected, but the bootloader does not appear to have been included.
Is this some kind of dependency issue? Am I misusing the linkers?
Any help with getting this to compile under a single binary would be very much appreciated. Thank you very much!

This isn't exactly 100% the answer I was looking for, because I still want to know how I can use a static library build, as I mention in my post, and compile everything as a single binary. This method is essentially gluing two binaries together.
I found this great and informative post over here:
https://www.avrfreaks.net/forum/can-you-combine-appbootloader-using-as7
It uses srec_cat to concatenate two binaries after building them:
https://www.keil.com/support/docs/2666.htm
I use the offset specified from the '.ld' file using
srec_cat <firmware1.bin> -Binary <firmware2.bin> -Binary -offset 0x2000 -o <firmwareOut.bin>
As the post suggests, I set this up as a post-build event and set my build dependencies accordingly so that a full clean and make will produce a consolidated binary including the bootloader.
If anyone tries this, make sure you only use the non-bootloader binary generated by your main project build. The bootloader places new firmware at location 0x2000 and your firmware will break if it finds a bootloader at the location where the firmware is supposed to be. When uploading firmware to the bootloader, it does not overwrite the bootloader.


How to randomize the delay in Arduino Stepper code? How does one add a random DELAY between 10 and 20 seconds?

For example in the following stepper logic I have a delay of 11 seconds - expressed in milliseconds as: delay(11000).

What would I need to add (or modify) so this is randomized between 10 and 20 seconds?

//#define IN1  8
//#define IN2  9
//#define IN3  10
//#define IN4  11

int Steps = 0;
boolean Direction = true;
unsigned long last_time;
unsigned long currentMillis ;
int steps_left=4095;
long time;

void setup()
{
Serial.begin(115200);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);

}
void loop()
{
  while(steps_left>0){
  currentMillis = micros();
  if(currentMillis-last_time>=1000){
  stepper(1);
  time=time+micros()-last_time;
  last_time=micros();
  steps_left--;
  }
  }
   Serial.println(time);
  Serial.println("Wait...!");
  delay(11000);                     // delay timing
  Direction=!Direction;
  steps_left=4095;
}

Forgive the appearance of the code.  Everytime I post it gets butchered.  Hopefully it's understandable.

In setup(), add

randomSeed(analogRead(0));

This reads the value of an analog input pin, which if not connected, will float to relatively random values between 0 and 1023. This "seeds" the random number generator so the pattern of random numbers you will get later doesn't always give the same results each time you start the sketch.

In your delay() call, just replace the fixed value with a call to the random(min, max) function, as:

delay(random(10000, 20000));


Arduino PWM 1kHz and 10-bit resolution As the title says, I need 1khz frequency signal with 10-bit resolution. But I am not good with uControllers and complicated programming.

I need a simple code for this task.

I tried using this Interactive PWM from arduinoslovakia.eu but I dont know what the frequency is at 10-bit resolution and how to set frequency in this code.

I see you are talking about using the 16-bit timer, which is Timer 1 on the Uno.

Assuming you are using a Uno this code will do it:

// Clock frequency divided by 1 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 1000;

const byte outputPin = 10;  // Timer 1 "B" output: OC1B

void setup()
 {
  pinMode (outputPin, OUTPUT);

  // set up Timer 1
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1); // fast PWM, clear OC1B on compare
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  OCR1B =  (timer1_OCR1A_Setting / 2) - 1;           // 50 % duty cycle
  }  // end of setup

void loop()
  {
  }

You can change the 1000 in the calculation for timer1_OCR1A_Setting, within reason, to get other frequencies.

See my page about timers for more background information.


SIM900 and Mega 2560 not sending SMS I just bought a SIM900 Arduino shield from AZDelivery. I only have a Mega 2560 board, thus I am trying to use this although most examples (like the tutorial from AZDelivery) are with the Uno board. I am using the SIM card from my mobile phone, not having any PIN. This is the Arduino library I am using.

I didn't flash anything on the SIM900 board prior to testing, because in the instructions from AZDelivery Ebook this was not mentioned.
My NetLight LED is blinking constantly (1 blink per second) I guess it is not finding the mobile network.
At the momemt, I only have a 1A supply, though I've already ordered a new one with 2A. Could this be the reason for point 2? Does the board need 2A to log into the network?
Asuming it would log into the network, the AZDelivery Instruction Sketch/Example is using "SoftwareSerial.h" due to its compatibility to the Uno board. Since I am using a Mega board, can I just use D30 and D31 and set them as Rx and Tx using the SoftwareSerial library?
Can you give me a link to an up-to-date library and/or example for SIM900 working with the Mega 2560 Rev3 and Arduino 1.8.4?

I hope you can help me getting started with the SIM900 module.

I was just able to send an SMS (even with the 1A supply). Here the answers to my questions.

No, it is not necessary to flash the SIM900 board
I was not connected, because I didn't insert the SIM card properly on the shield.
No it does not necessarily need 2A for logging into network and obviously not for sending SMS though there might be reasons for the board consuming 2A during SMS sending, e.g. bad network connection.
If you want to use Sotware Serial, you need certain digital lines allowing software interrupts. In the case of the MEGA board, e.g. D10, D11 or for the UNO D7,D8.
I was using this tutorial to get communication via SoftwareSerial working. Afterwards I added the code for sending SMS.

I hope I can help some others who are looking for a low level description of how to get started with MEGA and SIM900.


Can't upload to Arduino UNO (kuman UNO) I am trying to upload my code to my new Arduino (Just got one today, so im very new).

I can compile my code with no problems, but uploading it gives me:

[Arduino: 1.6.11 (Mac OS X), Board: "Arduino/Genuino Uno"

Sketch uses 1,186 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
chmod: Unable to change file mode on /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: Read-only file system
/private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: Permission denied
/private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: exec: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: cannot execute: Undefined error: 0
/private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: exec: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: cannot execute: Undefined error: 0

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

It doesn't matter what i upload (tried to upload some of the examples).

As said i am very new, so if you need any more information to help me just ask.

Thanks in advance!

Check your port to which your arduino is connected. The port name can be checked from Arduino IDE. Click Tools -> Port -> There you can find the port name.
Open Terminal and type the following command.

sudo chmod 777 /dev/port_name

After this try to Recompile/Upload the code again.


What are the basic steps to make a printed circuit board? I created a shield for Arduino on a soldering board. The next step shall be to implement the circuit on a PCB. I'm new to this, so I'd like to know what the basic steps in designing a PCB are.

More specifically,

What software do I use for this? Is free software sufficient, or do I get substantially more value from a commercial package?
Can I have a single PCB printed by a commercial provider, or are there minimum quantities? What is the approximate cost for a shield-sized PCB in a small quantity - is it in the tens, or rather in the hundreds of bucks?

Of course, any pointers to good tutorials on the Web will be appreciated,  too!

Software packages are, amongst others

Fritzing (more target at beginners)
Eagle (free for board of size 100 x 80 mm (4 x 3.2 inches)).
KiCad (open source)

Companies that make you pcb in small quantities are e.g.

OSHPark
seeedstudio
Dirt Cheap Dirty Boards

I personally create my own double layer PCBs at home. I first started with the toner-transfer method, but now use photo lithography. I etch in Hydrochloric acid and hydrogen-peroxide. I can have a finished board in 1-2 hours, instead of having to wait a week or so. Great learning experience.


Lowest power possible in Arduino I have googled all around and I know about some tricks to make ATmega328 not being a power hog. I am using Arduino Nano V3.0.

However, I didn't find out what is the minimal consumption possible with it?

My project consists of an Arduino that will wake up each 10 seconds and, by bluetooth (BT) will scan for existing devices, and if one specific device is not listed, it will lit a LED for 5 seconds and then go to sleep again.

In sum:

Sleep for 10 secs
Wake up
Scan for BT devices
If device ABC is in the list go to 1.
Lit LED
Delay 5 secs
Go to 1.

For bluetooth I will use NRF8001, because it is the most efficient BT module I know so far.

Can you give me some ideas of what tricks should I use to make this ATmega328 and BT module last like one year with a 500mAh battery? Has anyone tried this that can share his experience? Is ATmega328 the right uC for this? I am using it just because I already have code/libraries for it.

  Creating the new tag 'nrf8001' requires at least 150 reputation. Try something from the existing tags list instead.

The issues regarding efficiency of power are:

The CPU speed
The Voltage
The Power Regulator (not supply)
The Peripherals

Address each one of these and don't over look any of them. Or any sub component. But note that some are more impacting than others.

while it is possible to lower the speed, It is more practical to just sleep. As you have indicated you are going to do.
Running at 3V instead of 5V is a big savings. Note that the 328 can run as low as 1.8V
DON'T use Linear Regulators. Most all Arduino's have a 7-12V to 5V(or 3.3V) Linear Regulator. This just burns the difference between the supply (aka battery) and the VCC, used.
pay attention to the peripherals. Likely this means getting rid of not needed devices. Example the USB to Serial chip that exists on the Nano. What is the lowest voltage can the radio run at? Must it run at a regulated voltage. Use the largest possible resistor values. Such as on pull ups. A 500K pull up will draw less current than a 10K. Where if too big any capacitance may slow it down. Which is likely acceptable.

One of the biggest savings is running directly off of the Battery without a Linear Regulator. Where the ATmega328P can run from 3V down to 1.6V. It would be recommend to use the Brown Out detector.

Also note that ALL batteries have a self discharge rate.  This will determine the maximum possible life of the battery, then minus your devices consumption.


not getting proper bitstream output in serial monitor using digitalRead I am producing a  data stream and feeding to a gpio pin. THe data is sampled at 2kbps. i want to dump this data into a file after a certain length of reading . how should i proceed with this ?

Without seeing your code it's impossible to tell just what is happening, but I would guess you are reading and printing the level of the wave, not the transitions from one level to another.

For instance:

As you can see, just reading regularly and printing it (which itself is quite slow) results in 11001101 rather than the 10101 that you want. That's because the speed of your reading/printing and the frequency of your wave are completely separate things and out of step with each other. There's nothing to tie one to the other.

Instead you need to look for the transitions from LOW to HIGH and from HIGH to LOW. Only when the input changes should you look to see what the new level is and print that.

As you can see the 1 and 0 are just after the change in level, since it's impossible to do anything during a change, only once the change has happened.

You might code that as something like:

void setup() {
    Serial.begin(115200);
    pinMode(3, INPUT);
}

void loop() {
    static byte oldValue = LOW;     // Place to store the previous level
    byte newValue = digitalRead(3); // Read the current level
    if (newValue != oldValue) {     // The input has changed
        oldValue = newValue;        // Save the current level
        Serial.print(newValue);     // Print it.
    }
}


PYM-1 PIR sensor current concerns I am busy toying with some PIR sensors to detect movement etc for a nightlight for my kids. One of the sensors I ordered is the PYM-1 PIR sensor.

The data sheet states the following:

Operating Voltage: 4,5~5V.
Standby current: 65 micro-amps (65uA)
Operating Current: 40mA (40 milli-amps)

The limit for current on the arduino pins is 40mA. According to documentation at the arduino site 40mA is the upper limit per pin and the site clearly states: Absolute Maximum Ratings - the point where damage will start to happen I would rather avoid sinking the current directly on the Arduino.

So my question is will sinking 40mA on a pin cause damage? I have not been visited by the blue smoke genie yet and would rather avoid it at this point.

I suspect it might be safer to run this via a transistor and external power than directly on the arduino?

This is completely acceptable for your intended purpose.

By itself it will act as a light on/off trigger as others have noted.
An Arduino could be added if you wish to add extra features when the PIR is triggered. In it's most basic light-switching form using an Arduino is overkill.

By itself it will act as a light on/off trigger as others have noted.
An Arduino could be added if you wish to add extra features when the PIR is triggered. In it's most basic light-switching form adding an Arduino is overkill.

When it comes to playing overkill can be good :-)

To use it to provide input to an Arduino and NOT to a mains level light:

NB relay contacts may only be connected to mains for light switching OR to the Arduino. NEVER to both at the same time.

Connect it's DC supply input to your Arduino (or other) power supply.
As long as the supply can provide 40 mA when needed it will work OK.
40 mA is a power supply rating This is unrelated to the Arduino pin loading.

Connect the output to an Arduino digital pin configured as an input.

The output is a relay, activated when an object is sensed.
When inactive the centre pin is probably connected to the right pin - Check with Ohm meter.

When activated the left pin in connected to the centre pin (see their diagram)

Connect ground to right pin.
Connect Arduino digital input to centre pin.
Connect a "high" level to left hand pin.
OR as Majenko suggests, just set the pin to have pullups enabled.

If connecting to V+ as shown then V+ can be Vcc  (=5V for a 5V Arduino, 3v3 for a 3V3 Arduino)
DO NOT set V+ to higher than Arduino's Vcc.
You can connect a say 1k to 10k resistor from V+ to the voltage source bur still do not set V+ above Vcc.
OK - just have pullups enabled:-)

eg (untested)

  int ADCMode = 0;
   int PIRPin = 6;                 // PIR connected to digital pin 6
   void setup()
   {
     pinMode(PIRPin, INPUT_PULLUP); // set PIRpin as input with pullup
   }
   void loop()
   {
    ...
     ADCMode  = digitalRead(PIRpin);   // $Read PIR status
   ...
   }

When the circuit activates digitalRead() will return a high.
When the circuit is not activated digitalRead() will return a low.

See here re Arduino pin modes


Control RGB led using microphones, getting the right components Sorry if this is too basic, but I am very new to arduino and electronics. I come from programming, I am trying to start a project where I can control an RGB led strip, I want to be able to control the light intensity and color of the light strip (something like this), using a microphone.

My goal is for frequency to control de color of the rgb light and the dB (Volume) to control the light intensity. I have found several microphones such as this ones. Can I get both frequency and dB input from this microphones?

Would I need some extra controllers for this project? Again I am very new with this, sorry by the basic questions.

It would be worth checking out the ColorChord project.  It runs on an ESP8266, not an Arduino, but it ought to get you going.


Arduino to DAC to ADC back to Arduino? My question is simple. Is the following possible?

I am using one Arduino Mega 2560 board and its SPI functionality to adjust voltages (0-4.096V) through a 12-bit DAC (MCP4822).

I would like to measure the output voltages from the DAC by feeding them through a 12-bit ADC and back to the Arduino. The DAC's output voltages that will be directly measured by the ADC will be displayed on an LCD and on LabVIEW.

Is this possible, given that both the DAC and the ADC have to be connected to the same SDI and SCK pins on the Arduino for SPI to work?

Yes, perfectly possible. Just provide two separate CS pins to select between the two devices.


Select from Custom Array without Repeat I found this great code to pick a random number from a "hat" without repeat:

/* RandomHat
  Paul Badger 2007 - updated for Teensy compile 2017
  choose one from a hat of n consecutive choices each time through loop
  Choose each number exactly once before reseting and choosing again
*/

#define randomHatStartNum 0  // starting number in hat
#define randomHatEndNum 25    // ending number in hat - end has to be larger than start
#define numberInHat (randomHatEndNum - randomHatStartNum) + 1

void setup()
{
  Serial.begin(9600);
  Serial.println("start ");
}

void loop()
{ // randomHat test
  for (int i = 1; i <= numberInHat; i++) {
    int x = randomHat();
    Serial.print(x);
    Serial.print(", ");
    delay(50);
  }
  Serial.println(" ");
}

int randomHat() {
  int thePick;    //this is the return variable with the random number from the pool
  int theIndex;
  static int currentNumInHat = 0;
  static int randArray[numberInHat];

  if  (currentNumInHat == 0) {                  // hat is emply - all have been choosen - fill up array again
    for (int i = 0 ; i < numberInHat; i++) {    // Put 1 TO numberInHat in array - starting at address 0.
      if (randomHatStartNum < randomHatEndNum) {
        randArray[i] = randomHatStartNum + i;
      }
    }
    currentNumInHat = abs(randomHatEndNum - randomHatStartNum) + 1;   // reset current Number in Hat
    Serial.print(" hat is empty ");
    // if something should happen when the hat is empty do it here
  }

  theIndex = random(currentNumInHat);                  //choose a random index from number in hat
  thePick = randArray[theIndex];
  randArray[theIndex] =  randArray[currentNumInHat - 1]; // copy the last element in the array into the the empty slot
  //                                                     // as the the draw is random this works fine, and is faster
  //                                                     // the previous version. - from a reader suggestion on this page
  currentNumInHat--;    // decrement number in hat
  return thePick;
}

I would like to use a custom array to choose from like so:

char *things[]={
"Thing 1",
"Thing 2",
"Thing 3",
"Thing 4",
"Thing 5",
"Thing 6",
};

Which is quite possible as I use the numbers from to first piece of code to select items from my custom array.

So I have two questions about this:

The first being the code first returns "hat is empty" before the numbers.

start
  hat is empty 11, 24, 17, .......
  hat is empty 4, 19, 23, .......

Is there a way to reverse this?

And secondly, I would like define the randomHatEndNum automatic by the lenght of my custom array, but I have trouble implementing that code. What is the right way to approach this?

The first being the code first returns "hat is empty" before the
  numbers.

Well, you have to comment out the line

Serial.print(" hat is empty ");

  I would like define the randomHatEndNum automatic by the lenght of my
  custom array,

To get the size of an array, the standard idiom is

const int numberInHat = sizeof(things) / sizeof(things[0]);

I rewrote your sketch.

The idea is use randArray to store all the remaining values to return. Then, randomly pick one value (to return) and replace randArray with -1, which signal that the value has been returned, so don't return it again.

The best for functions returning random values is always work in the range 0..n, and adjust that value in the calling code if you need some other range (like 1..n+1). It's simplier and simplify debugging.

/* RandomHat
  Paul Badger 2007 - updated for Teensy compile 2017
  choose one from a hat of n consecutive choices each time through loop
  Choose each number exactly once before reseting and choosing again
*/

char *things[]={
"Thing 0",
"Thing 1",
"Thing 2",
"Thing 3",
"Thing 4",
"Thing 5",
"Thing 6",
};

const int numberInHat = sizeof(things) / sizeof(things[0]);

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

void loop()
{ // randomHat test
  for (int i = 0; i < numberInHat; i++) {
    int x = randomHat();
    Serial.print(x); Serial.print(" ");
    Serial.println(things[x]);
    delay(50);
  }
  Serial.println("----");
}

int randomHat() {
  int thePick = -1;    //this is the return variable with the random number from the pool
  int theIndex;
  static int left = 0;
  static int randArray[numberInHat];

  if  (left == 0) {                                // hat is emply - all have been choosen - fill up array again
    for (int i = 0 ; i < numberInHat; i++) {    // Put {0, ..., n} into randArray.
        randArray[i] = i;
      }
    left = numberInHat;
  }

  // bEmpty always false at this point.
  while (thePick == -1) {
    theIndex = random(numberInHat);                  //choose a random index from number in hat
    thePick = randArray[theIndex];
   }

  left--;
  randArray[theIndex] =  -1;        // value theIndex is not longer available.
  return thePick;
}


How to get body temperature using MLX90614 DCI on Arduino The MLX90614 provides 2 temperature outputs, namely surface temperature and ambient temperature. But how do you calculate the right body temperature from these two outputs?
Here are the results of my experiment at a distance of 1 inch:
(Temperature centigrade)

If you see table above, in the range with an ambient temperature of 27°C the surface temperature shows, on average, 33°C, but it will go up when the ambient temperature is 29°C; then the surface temperature shows an average of 35°C.
If I test with a temperature device, then my body temperature at the same distance and target is in the range of 36.3°C to 36.7°C.
Please help me how to calculate / get body temperature from MLX90614 DCI.

Skin temp tends to be lower (and less stable) than sublingual (under-the-tongue) temp, which tends to be lower than core temp.
I don't think there's going to be any meaningful way to use ambient temperature to adjust skin surface temperature.
You'd be better off putting the surface temperature probe under your armpit for a few minutes. That should be more stable than other parts of your skin.
If the probe is small enough you might also put it in the finger of a sterile glove and hold it under your tongue.


How to choose SPI type used by RF24 library from application? I am developing a device with Ethernet shield (with Wiznet W5100) and NRF24L01+. I need to use Soft SPI due to a bug in the Wiznet chip. Next I am developing a different device with NRF24L01+ only. I want to use hardware SPI (besides other things it already contains a socket for NRF24L01+ connected to the default Arduino SPI pins).

It is very inconvenient to enable/disable #define SOFTSPI in RF24_config.h every time I want to work on the other device.

Is there a way how to choose the SPI type used by RF24 library in the application?

My current solution is to make a copy of RF24 to RF24_SoftSpi and RF24Network to RF24Network_SoftSpi. I enabled SOFTSPI in “_SoftSpi” versions (+ renamed all files, fixed includes and #ifndef statements in headers to avoid ambiguous errors).

Then in an application I just include RF24_SoftSpi instead of RF24 and RF24Network_SoftSpi instead of RF24Network to use software SPI.

With this workaround it is difficult to make updates to “_SoftSpi” libraries when a new feature is released.

Do you know of any better solution?

Using this RF24 library set, I am able to use or not softspi by doing #define SOFTSPI on my sketch, there's no need to define it on the RF24_config.h, you should be able to define it on your own sketch.

EDIT:

Arduino 1.6.5

#include <SPI.h>
#include "RF24.h"
#include "printf.h"
#define SOFTSPI //Define pins RF24_config.h

/****************** User Config ***************************/
/***      Set this radio as radio number 0 or 1         ***/
bool radioNumber = 0;

/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8     */
RF24 radio(8,9);

....
....
void setup() { ... }
void loop() { ... }


I bought an Arduino WDLduino uno board I thought I was buying an Arduino Uno board and received a "WDLEle WDLduino uno" board.  I think I got ripped by China, but can anybody tell me what driver to use, where to get it, or what the heck this board is?

HELP

I got the same problem here. But I found the solution. You must install a driver for chip CH340G. Here is all the steps http://www.instructables.com/id/Instalar-driver-para-CH340G/


Generating PWM signal 1-2 ms @ 333 Hz I'm currently working with the Talon SR Speed Controller and it requires a specific Input PWM Signal of 1-2 ms @ 333 Hz and an input resolution of 10-bit (1024 steps). Currently I use the Servo library to handle these requirements, but was having some issues of the motors jumping their dead-band from forwards to backwards really fast causing the motors to rock back and forwards a few millimeters. If the servo1.write(pwmValue); isn't my issues please let me know?

If there is a way to specifically achieve the 333Hz PWM signal for 4 motors of the same Uno or Due (most likely will transfer to a Due in a few days) I would like to implement that.

From my understand I can modify the timers registers for the arduino specifically, but don't know exactly how to do that or to achieve 333Hz. If someone could please help me understand this I would greatly appreciate it.

Speed SR  Speed Controller Information:

Input voltage 6-28 VDC
Continuous current 60 A
Peak current 100 A
Input PWM signal 1-2 ms @ 333 Hz
Input resolution 10-bit (1024 steps)
Output resolution 10-bit (1024 steps)
Output switching frequency 15 kHz
4% neutral dead band

I am playing on a Arduino UNO, you would have to compare the datasheets to determine differences.
For my research on this answer I am looking at:

Code/PwmFrequency (for a quick rundown)
Tutorial/PWM
TimerPWMCheatsheet (explains the prescaller and resulting frequencies)
varying the pwm frequency of timer0 and timer2
feature request: adjustable pwm frequencies
pwm frequency library (this is the one you REALLY want)
and the datasheet for the ATMega328

Also:

we know PWM pins are D3, D5, D6, D9, D10, D11
I am using D11 for this since I can attach my oscilloscope to the MOSI pin of the ISCP
D11 maps to PB3 (MOSI/OC2A/PCINT3) (see datasheet or this cool gfx)

Normal usage
First, let's see what happens when we set an arbitrary PWM on pin 11
int DUTY = 25;
analogWrite(11, DUTY * 256 / 100);

results in:

Freq: ~487Hz
Duty: ~25%
Time: ~2.05ms

This first point I will make is that with the given 490Hz the PWM duration is actually 2ms which seems to be close to what you want (you said between 1-2ms), maybe my misunderstanding there.

Playing with pre-scalers
From several of the links posted above, you will see that you have different pre-scalers available depending on which timer you are using: eg.
Pins 5 and 6: controlled by Timer 0 in fast PWM mode (cycle length = 256)
Setting     Divisor     Frequency
0x01        1           62500
0x02        8           7812.5
0x03        64          976.5625
0x04        256         244.140625
0x05        1024        61.03515625

TCCR0B = TCCR0B & 0b11111000 | <setting>;

Pins 9 and 10: controlled by timer 1 in phase-correct PWM mode (cycle length = 510)
Setting     Divisor     Frequency
0x01        1           31372.55
0x02        8           3921.16
0x03        64          490.20
0x04        256         122.55
0x05        1024        30.64

TCCR1B = TCCR1B & 0b11111000 | <setting>;

Pins 11 and 3: controlled by timer 2 in phase-correct PWM mode (cycle length = 510)
Setting     Divisor     Frequency
0x01        1           31372.55
0x02        8           3921.16
0x03        32          980.39
0x04        64          490.20
0x05        128         245.10
0x06        256         122.55
0x07        1024        30.64

TCCR2B = TCCR2B & 0b11111000 | <setting>;

(All frequencies are in Hz and assume a 16000000 Hz system clock.)

These are relatively simple to setup and use (the setting is at the bottom of each of the above code blocks), but you have to be mindful of playing with the pre-scaler of timer0 (which controls millis() and delay()). So if you have a choice, steer clear of timer0, or pwm pins 5 and 6.
Example of using just the inbuilt pre-scalers without any additional libraries:
#define PIN 11
void setup(){
    pinMode(PIN,OUTPUT);  // not absolutely required
    int DUTY = 20;
    TCCR2B = TCCR2B & 0b11111000 | 6;
}

void loop() {
  static long counter = 0;
  if(millis()%10==0){
      counter++;
      analogWrite(PIN, counter%255);
  }
}

I know you can manipulate the frequency better than that, and I have been playing with this for hours and then I finally stumbled upon the final link (which believe it or not, I found via YouTube!).

Using an External Library
To use the PWM library you will need to download it from Google Code, save/import/get it into your library folder, and restart the IDE. Once you do that, you can explicitly set the frequency (within limits, 333Hz is within those limits), and you should be set.
Code example:
#include <PWM.h>
int32_t frequency = 333;

#define PIN 10

void setup(){
    pinMode(PIN,OUTPUT);
    int DUTY = 20;
    InitTimersSafe();                    // won't touch timer0
    SetPinFrequencySafe(PIN,frequency);  // again, not timer0
    pwmWrite(PIN, DUTY * 256 / 100);
}

There is even a pwmWriteHR which allows for higher resolution, but that does not work with timer2 (which is only an 8-bit timer).
The matching, non-safe (ie initialises and uses timer0 as well) functions are:
InitTimer();  // and
SetPinFrequency(PIN,frequency);

The only limitation I have found so far is that it doesn't work with PWM pin D11. I have tested D3, D9 and D10 (they all worked fine), but I did not get around to testing D5 or D6.
Good luck, I hope this helps.


sending multiple signals at the same time, with short delay Is it possible to do something like this: send a HIGH signal to an output pin, after a 0.33s delay arduino sends HIGH signal to another pin, and after another 0.33s delay, arduino sends signal to third pin. There has to be 90 seconds long high signal for each pin, but with 0.33s delay between each other.

Sooo something like this; start of the high signal on left, stop on right side:

pin1: 0 ...... 90.00
pin2: 0.33 ... 90.33
pin3: 0.66 ... 90.66

Is there a way to solve this?

Yes. Read the BlinkWithoutDelay example and triplicate it.


How to start particular event for particular time using millis()? In my recent project, I want to run particular event for the particular time. For example, If I want to Turn ON my LED for 20 Second. And rest time LED must be off. I know using delay() it is possible but If we used delay() function then that time we can't do anything. So, I tried out millis() for that. I tried the basic code for this.

The code is below:

const int ledPin =  LED_BUILTIN;

int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 5000;

void setup()
{
  pinMode(ledPin, OUTPUT);
}

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

  if (currentMillis - previousMillis >= interval)
  {
    previousMillis = currentMillis;

    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    digitalWrite(ledPin, ledState);
  }
}

But the output of this is like LED ON for 5 Second and then LED OFF for 5 Second. And this thing happens continuously.But I don't want this. I just want to turn ON LED for 5 Second when I want and then LED off forever. And I tried out many logics for that somehow can't able to get this thing. Someone suggest me some idea about this.

Use an extra boolean variable. Some use the previousMillis and make it zero to tell that the delay is not active, but please don't do that. Let previousMillis be the value of millis and use an extra boolean variable.

To start the millis delay, three things are needed: enable the delay, set previousMillis, and turn the led on.

To stop the millis delay, two things are needed: disable the delay, turn the led off. There is no need to do something with the previousMillis since the millis delay will be disabled.

const int ledPin =  LED_BUILTIN;

unsigned long previousMillis;
const unsigned long interval = 5000UL;
boolean enableDelay = false;

void setup()
{
  pinMode(ledPin, OUTPUT);
}

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

  // Trigger the delay, I use analogRead.
  if (analogRead(A0) > 500)
  {
    enableDelay = true;
    previousMillis = currentMillis;
    digitalWrite(ledpin, HIGH);
  }

  // Checking the millis delay should be done in the loop.
  // This code is not inside the code to start the delay, but
  // at the same level as other code in the loop.
  if (enableDelay)
  {
    if (currentMillis - previousMillis >= interval)
    {
      enableDelay = false;
      digitalWrite(ledPin, LOW);
    }
  }
}

There are libraries that can do this. The above code is the basic way to make a millis delay. I have changed the variable "interval" to a unsigned long, because the other two (currentMillis and previousMillis) are also unsigned long. That makes it more straightforward. The currentMillis and previousMillis must be unsigned long, but it is okay if "interval" is a long.

This way of a millis delay can be used with a finite state machine. If your sketch has many states, and one of those states is to keep a fan or a motor on for some time, then you can use it. The variable "enableDelay" is probably not needed in a finite state machine, because the "state" variable tells if that specific state (with the millis delay) is active.


Sainsmart LCD 2004 - LiquidCrytal_I2C library issue unable to compile I bought a Sainsmart LCD2004 from Amazon to use with my Arduino Uno.
I understand that since this LCD uses I2C a new library needs to be downloaded.

From the sainsmart website I dowloaded the LCD 2004 rar
http://www.sainsmart.com/arduino/arduino-shields/sainsmart-iic-i2c-twi-serial-2004-20x4-lcd-module-shield-for-arduino-uno-mega-r3.html

When I try to compile the example titled helloworld I get the following error:

In file included from HelloWorld.pde:3:
C:\Users\r_yob_000\Documents\Arduino\libraries\LiquidCrystal_I2C/LiquidCrystal_I2C.h:81: error: conflicting return type specified for 'virtual void LiquidCrystal_I2C::write(uint8_t)'
C:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino/Print.h:48: error:   overriding 'virtual size_t Print::write(uint8_t)'

There seems to be a conflict between two functions returning different types.

I've tried searching the issue and found a lot of posts with similar errors.
The solution suggested is usually that a new version of the LiquidCrytal_I2C needs to downloaded. Or that one should use Arduino IDE version 1.0

I have downloaded tons of LiquidCrytal_I2C libraries and tried them all on IDE version 1.0 and 1.0.6 and I still get the same error message. I've even tried changing the LiquidCrytal_I2C.h file so that it returns the correct type and still have no luck.

Could I please get some help with this issue.

Thank you very much.

I just bought 3 of these that work well with this library
 LiquidCrystal_I2C2004V1.zip
(License: CC BY-NC 2012 http://www.wikispaces.com/user/view/TerryKing).

When installing this library in Arduino IDE (version 1.6 or later), use menu item Sketch | Include Library | Add .ZIP Library..., navigate to the folder where LiquidCrystal_I2C2004V1.zip was downloaded, and then open the zip file.

Use the I2C address in the example "HelloWorld" supplied with LiquidCrystal_I2C2004V1:

//YWROBOT
//Compatible with the Arduino IDE 1.0
//Library version:1.1
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup()
{
  lcd.init();                      // initialize the lcd
  lcd.init();
  // Print a message to the LCD.
  lcd.backlight();
  lcd.setCursor(3,0);
  lcd.print("Hello, world!");
  lcd.setCursor(2,1);
  lcd.print("Ywrobot Arduino!");
   lcd.setCursor(0,2);
  lcd.print("Arduino LCM IIC 2004");
   lcd.setCursor(2,3);
  lcd.print("Power By Ec-yuan!");
}

void loop()
{
}

Do not change the other library directory name; this one is compatible with the existing library. Just add it as a contributed library.


My ESP8266-01 doesn't want to respond to AT command after a successful flash! Well hello, experts,
I've been trying to fix my issue all time, but all in vain.
I have an Esp8266-01 with 1MB memory. I've flashed it with an official AT firmware V2.0.0 of espressif with the help of this tutorial-arduino as a usb/TTL-: "https://www.allaboutcircuits.com/projects/flashing-the-ESP-01-firmware-to-SDK-v2.0.0-is-easier-now/", and it was a successful flash.
However, when trying to send AT commands in the serial monitor at different baud rates nothing happens.
I'll provide you with all the information down here:

Schematic for both flash and normal mode:

I used the official flasher tool from espressif
I used both Arduino IDE and Termite with no results
I've uploaded the blink sketch successfully into my module, but it never runs and blinks.
After lots of tries and resets I started to receive some information:

But still no answers from this module!!!
Could you help me, please?

The tutorial is to flash SDK 2.0 AT firmware. The AT 2.0.0 firmware is build with RTOS SDK. The 2.0 AT firmware available on Espressif site was build with settings not compatible with esp-01. It is built for 2 MB flash and  communicates over pins 13 and 15.

The latest NonOS SDK AT firmware is 1.7.1 (SDK 3), but it requires 2 MB flash too. It is possible to flash it to 1 MB module with the 2MB-c1 parameter with esptool.py. (The OTA update command will not work.)

GitHub user loboris (Boris Lovosevic) builds customized versions of AT firmware with SDK 3 for all flash sizes. You can download the files from his ESP8266_AT_LoBo GitHub repository. If you can't run his flash.sh utility, then for 1 MB flash you can Flash Download Tool with bin/upgrade/esp8266_AT_1_2.bin file and the right addresses for 1 MB flash: boot_v1.7.bin on 0x0; esp8266_AT_1_2.bin on 0x01000; esp_init_data_default.bin on 0xfc000 and blank.bin on 0x7e000 and 0xfe000.


Nano can't get reply from ENC28J60 Ethernet Shield My Arduino Nano can't get a reply from my new ENC28J60 Ethernet Shield - I can't get any library examples to work. Using the UIPEthernet lib, and running the EchoServer example with logging turned up, I get:

ENC28J60::init DEBUG:csPin = 10
ENC28J60::init DEBUG:miso = 12
ENC28J60::init DEBUG:mosi = 11
ENC28J60::init DEBUG:sck = 13
ENC28J60::init DEBUG:Use Native hardware SPI
Enc28J60Network::writeOp(uint8_t op, uint8_t address, uint8_t data) DEBUG_V3:Function started
ENC28J60::init DEBUG_V3:Before readOp(ENC28J60_READ_CTRL_REG, ESTAT)
Enc28J60Network::readOp(uint8_t op, uint8_t address) DEBUG_V3:Function started
...

so it gets nicely into the Enc28J60Network::init function. But shortly after, it does a phyWrite, tries to read a response, and then times out.

ENC28J60::init DEBUG_V3:Before phyWrite(PHCON2, PHCON2_HDLDIS)
Enc28J60Network::phyWrite(uint8_t address, uint16_t data) DEBUG_V3:Function started
... lots of attempts to read
Enc28J60Network::phyWrite ERROR:TIMEOUT !!

And then it all starts to fail, and it never gets better. I tried the EtherCard lib, too, and it fails in a similar way.

I put the scope on the SPI pins, and I see reasonable stuff: activity on SCK and MOSI, nothing on MISO, and the SS (pin 10) switching ok - and the shield claims to use pin 10 (I briefly tried pin 8 as I flailed in confusion, but no luck there either).

So at this point, either I'm misunderstanding something, or the shield is DOA.

Update: Earlier, I strongly suspected the SCK line because it showed a very poor signal on my scope. But it turned out to be poor grounding on the scope probe, and the signal  was actually fine, a red herring. Thanks to @Majenko for drawing my attention to it.

Update 2: After getting no SPI response from the shield under any circumstances, my working hypothesis is that it was DOA. I've gone back to my UNO with W5100: all working fine. I have ordered more Nano ethernet shields, to arrive in a week or two, so I'll try with those, and provide updates/answers then.

The ENC28j60 shield for Nano has reset of the ENC28j60 chip on the pin 7 of the shield/Nano. Try to set the pin 7 HIGH.


3 AC current sensors using one Arduino Uno board measuring at 200Hz I'm new to electronics and need some help please.

I'm planning to measure current of a 3-phase output using one sensor for each phase (thus 3 sensors would be required). The frequency of data recording should be 200 Hz.

Performance/data transfer wise: Is one Arduino Uno board enough to plug in the three sensors and get the data transferred using the USB cable onto a PC? Or should I get one board for each sensor?

I appreciate your help.

Cheers.

lorena

Is the sampling speed enough?

It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate is about 10,000 times a second.

Ref.: https://www.arduino.cc/en/Reference/AnalogRead

Is the USB port fast enough?

The serial speed over USB is maximum 2Mbps and a fast calculation (200 samples/s x 3 sensors x 10 bit) 18kbps, so 2Mbps should be enough.


Powering the Arduino with a battery and reading the battery voltage I am trying to display the battery level as it is being used to power the arduino.

I have tried powering the arduino through the USB and the battery voltage is read accurately, when compared to the multimeter reading.
But when the battery is powering the arduino and being read, it keeps displaying 5.00V, when it should not be.

Just wondering what might be happening and how I can go about resolving this issue.

I have been trying to research some answers, and came across something about an 1.1V reference voltage, but not entirely sure what they mean.

Would appreciate any answers!
Thanks!

Here is my code for reference.

#include <SoftwareSerial.h>
SoftwareSerial BTserial(10,11);

int battPin = A1;

void setup() {
  pinMode(battPin, INPUT);
  BTserial.begin(9600);
  Serial.begin(9600);
}
void loop()
{
  int voltReading = analogRead(battPin);
  float volts = (voltReading/204.6);
  BTserial.print(volts);
  BTserial.print(";");
  Serial.println(volts);
}

I am using a 3.7V Lipo battery. It is connected to A1 and also Vin.

AFAIK, Arduinos are set up to use their operating voltage as the analogRead reference voltage by default.

So, what I think is happening is that you are trying to measure the battery voltage with the battery itself as a reference voltage.

This will, of course, always show "full scale".

You could use a voltage divider to bring the measured battery voltage down to about 1V (max) and use the internal reference of 1.1V for measuring.

Note that the 1.1V internal reference is stable, but not necessarily exactly 1.1V.


Native function name w/o parens -- expected behavior? I wrote a sketch that used the millis() function in several places. I got odd behavior because I inadvertently used the plain millis in one line, without the parens. It evaluated to zero when running.

Why didn't the compiler flag this as an undeclared variable? I suspect it's because the name was already in the symbol table, but I still would have thought it'd be caught. Is this a quirk, or expected? If expected, what is the benefit?

C/C++ is not my main language so be gentle. (-:

Edit as requested to show some code. This is an incomplete sample, but shows the usage:

const unsigned long GATE_OPEN_TIMER = 7000;
const unsigned long GATE_CLOSE_TIMER = 12000;
...
unsigned long gateStopTime = 0;
...

  if (isGateCycling) {                 // if open/close cycle is running
    if (isGatePassive) {               // if we're not applying power
      if (millis() >= gateStopTime) {  // if current delay expired
        digitalWrite(GateCloseRelay, ACTIVE);
        gateStopTime = millis() + GATE_CLOSE_TIMER;
        isGatePassive = false;

... followed by similar logic for the reverse direction. If any use of millis() is replaced by millis, the code falls over but the compiler sees nothing wrong.

I've made up a test case:

const unsigned long GATE_OPEN_TIMER = 7000;
const unsigned long GATE_CLOSE_TIMER = 12000;
unsigned long gateStopTime = 0;

void setup()
{
  if (millis >= gateStopTime) {  // if current delay expired
    gateStopTime = millis + GATE_CLOSE_TIMER;
  }
}
void loop()
{
}

Under IDE 1.6.9 I get these errors:

/tmp/arduino_modified_sketch_345879/sketch_oct27a.ino: In function 'void setup()':
sketch_oct27a:7: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
   if (millis >= gateStopTime) {  // if current delay expired
                 ^
/tmp/arduino_modified_sketch_345879/sketch_oct27a.ino:8:29: warning: pointer to a function used in arithmetic [-Wpointer-arith]
     gateStopTime = millis + GATE_CLOSE_TIMER;
                             ^
sketch_oct27a:8: error: invalid conversion from 'long unsigned int (*)()' to 'long unsigned int' [-fpermissive]
     gateStopTime = millis + GATE_CLOSE_TIMER;
                           ^
exit status 1
ISO C++ forbids comparison between pointer and integer [-fpermissive]

Under IDE 1.6.12 they are downgraded to warnings:

/tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino: In function 'void setup()':
/tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino:9:21: warning: ISO C++ forbids comparison between pointer and integer [-fpermissive]
       if (millis >= gateStopTime) {  // if current delay expired
                     ^
/tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino:10:33: warning: pointer to a function used in arithmetic [-Wpointer-arith]
         gateStopTime = millis + GATE_CLOSE_TIMER;
                                 ^
/tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino:10:31: warning: invalid conversion from 'long unsigned int (*)()' to 'long unsigned int' [-fpermissive]
         gateStopTime = millis + GATE_CLOSE_TIMER;
                                   ^

Sketch uses 512 bytes (1%) of program storage space. Maximum is 32,256 bytes.
Global variables use 13 bytes (0%) of dynamic memory, leaving 2,035 bytes for local variables. Maximum is 2,048 bytes.

So, the compiler isn't totally letting you get away with it. You should check the warnings. But why are the warnings only warnings?

Checking the generated compile command (using verbose compiling) I see that 1.6.12 has an extra option: -fpermissive.

From the documentation:

  Downgrade some diagnostics about nonconformant code from errors to warnings.  Thus, using -fpermissive allows some nonconforming code to compile.

So you have "nonconformant code" but you are getting away with it.

I don't know why the Arduino devs did that. The whole point of making things like that errors is so you fix them at compile time, rather than scratching your head about why things don't work at run time.

Clearly the symbol millis exists. But it is a function (or perhaps a pointer to a function) and thus shouldn't be just compared to a number or have a number added to it. That's what those errors were about in 1.6.9.

Just remember, in C, C++ and the ilk, to call a function you always use parentheses, even if you are passing no arguments.


Struggling with SD card read on Arduino I'm attempting to read data from my SD card, but I have strange behavior and can't figure out why this is happening.

I'm using CardInfo from the Arduino example and am trying to read the data from my SD card.

I'm faced with two different problems, but maybe they can be related:

1:  If I format my SD card from my Mac (FAT32), if my card is still empty, the program can read my card and output the right information. But if I add data from my Mac to the SD Card, card.init never initialise, and my data are never read (because of the hidden files). If I remove those hidden files, but let only the expected files be, the program never find them, like if my card was still empty. I don't know how to handle this.

2: From my Arduino, if I feed the card from the 3.3 V output, I get the

  Card type: SD2 Could not find FAT16/FAT32 partition. Make sure you've
  formatted the card

It only works on 5 V (but the card type becomes SDHC). So I've tried to feed my card with another 3.3 V/5 V supply (my Arduino is grounded to this supply as well), but this is only working on 5 V. On 3.3 V my card isn't detected. My wires to the SD card are about 15 inch. I don't know if it can affect it drastically, but this is the only 'weird' thing about this circuit. By the way I naively think my 3.3 V supply should handle that.

Here are my materials:
- Arduino Duemilanove

For the SPI wiring I'm using pin 10 for SS.
Using the Cardinfo from the Arduino library.

I recommend you get a MicroSD card breakout board from that link, or something similar. That's around $US 15.

That includes the logic level converters. That particular board is for the **micro* SD card, but similar converters could no doubt be found for an SD card. Or use that one with a micro-SD card and just get an SD converter for when you plug it into the Mac.

I personally have used the SDfat library without any problems. However since he started rewriting it, I did have some issues. I have a backup of an earlier version which might be useful if the live library doesn't work for you.

You might be best off not formatting the card, but leave it as factory formatted. That will probably be compatible with the Mac, and also the SDfat library.


EEPROM.get returns bad data I am using the attached code.
What I am trying to do is:

Test if there is a personalized "board serial number" written in the EEPROM (by previous code run)
If data found was not 7 characters (e.g SN-XXXX), then generate a serial number and save it to EEPROM

Problem is: it generates a serial correctly, it even stores and reads it a few times, but when I disconnect the USB cable and reconnect to test again, it returns some bad data from the EEPROM, like: ⸮^R⸮y⸮| which seems to pass my 7 characters test and it doesn't generate a new one.

What am I doing wrong ?

#include <EEPROM.h>

// board SERIAL number
char serial_characters[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"};
// will be filled as SN-A2KH
String serial_number;

void setup() {

  Serial.begin(9600);

  // Get the float data from the EEPROM at position 0
  EEPROM.get(0, serial_number);

  // serial from EEPROM valid
  if (serial_number.length() == 7) {
    Serial.println("Found valid serial in EEPROM");
    Serial.println(serial_number);
  }

  // serial from EEPROM not valid (e.g not: SN-XYZ5)
  if (serial_number.length() != 7) {

    Serial.println("Serial from eeprom is NOT 7 chars, generating a random serial");
    Serial.println(serial_number);

    // if analog input pin 0 is not connected, use noise from it in order to generate a random seed, otherwise random is not so random
    randomSeed(analogRead(0));

    // serial might be empty now, set a "SN-" prefix
    serial_number = "SN-";
    for (int i = 1; i <= 4 ; i++) {
      serial_number = serial_number + serial_characters[random(0, 35)];
    }
    Serial.println("Generated serial now: " + serial_number);

    // save to eeprom if format is valid
    if (serial_number.length() == 7) {
      EEPROM.put(0, serial_number);
      Serial.println("Written serial to EEPROM");
    }

  } // <<< serial from eeprom not correct, generated one

}

void loop() {}

You are saving a String object in EEPROM, which is useless. A string
object does not store the contents of your string. Instead, it just
stores:

the memory address where the actual contents (the characters) is
stored
the amount of memory allocated for this contents
the number of characters that actually make the string

This is what you are storing to, and retrieving from EEPROM. So you get
the correct number of characters (third item in the list above), but the
memory address now points to uninitialized RAM.

I suggest instead storing in the EEPROM a raw C string, i.e. an array of
8 chars (7 printable chars plus the terminating NUL). You could achieve
this by just changing the declaration of serial_number:

char serial_number[8];

For checking the validity, I would just check that it starts with "SN-"
and the last char is a NUL:

if (memcmp(serial_number, "SN-", 3) == 0 && serial_number[7] == '\0') {
    ...
}

You could do a more stringent validation though, and check that the
other 4 chars are within the valid set.

Edit: to build serial_number with random chars:

strcpy(serial_number, "SN-");
for (int i = 3; i < 7; i++)
  serial_number[i] = serial_characters[random(0, 36)];
serial_number[7] = '\0'; // terminating NUL


Can anyone help me figure out why this buffer is overflowing? (Updated) This should be fairly straightforward, but there must be something I'm not understanding about buffers.

I have serial data coming in to my Mega via Zigbee. I'm sending a string just like this: ~-0.6016800, where ~ is my unique starting delimiter and my end delimiter is a carriage return \n. I'm sure it's coming through the zigbee correctly, because I can see my string show up looking good in XCTU when I plug the zigbee into the PC. Here is my code:

const int numChars = 15;
char incoming[numChars];

static boolean Receiving = false;
static byte ndx = 0;
char startMarker = '~';
char endMarker = '\n';
byte K;
bool allreceived = false;

void Get() {
    memset(incoming, NULL, strlen(incoming));
    while (allreceived == false) {
        if (Serial.available() > 0) {
            K = Serial.read();
            if (Receiving == true) {
                if (K != endMarker) {
                    incoming[ndx] = K;
                    ndx++;
                    if (ndx >= numChars) {
                        ndx = numChars-1;
                    }
                }
                else {
                    incoming[ndx] = '\0'; // terminate the string
                    Receiving = false;
                    ndx = 0;
                    allreceived = true;
                }
            }
            else if (K == startMarker) {
                Receiving = true;
                ndx = 0;
            }
        }
    }
}

So somehow my buffer is overflowing or something, no matter how big I make it. I see the array start off as I expect it for the first few characters, then it turns into unintelligible characters. I think part of the problem might be that the serial data is coming through at a different rate or something, because I can see my starting delimiter ~ on my LCD screen in the middle of my array. The way it's set up, I should never be able to see my start delimiter unless I miss my end delimiter without ending the array. (Note- I've tried different unique end delimiters too, but this seems to work just the same)

Any ideas on what might be causing this??

EDIT: NOW TRYING THIS CODE- I'm still having the buffer overflow, and I'd be really grateful if someone could take a look.

Sending code:

void PayloadSendit(void) {

Payload[0] = '~';  //1 char unique start

if (outFormat == 0) {
    Payload[1] = '0';
    Payload[2] = '$';  //spacer
    strcat(Payload, stringval); //5 char for hashmarks
}
else {
    Payload[1] = '1';
    strcat(Payload, stringvalin);  //6 char for inch
}
if (dotpos <= 99) {
    Payload[8] = '@';  //spacer
    char dotpos2[2];
    sprintf(dotpos2, "%i", dotpos);
    strcat(Payload, dotpos2);    //2 char
}
else {
    char dotpos3[3];
    sprintf(dotpos3, "%i", dotpos);
    strcat(Payload, dotpos3);   //3 char ///////////////////////////
}

Payload[11] = '0';  //1 char for "no errors" code
Payload[12] = '*';  //1 char end delimiter
Serial.println(Payload);
Serial.flush();
memset(Payload, '\0', 13);

}

Receiving code:

  void Get2() {
    memset(Payload, '\0', bufsize);
    while (allreceived == false) {
        int K = Serial.read();
        switch (K) {
        case -1: // Nothing to read
            break;

        case '~': // Starting a new string
            Receiving = true;
            break;

        default: // Any other characters.
            break;

        }
        if (Receiving) {
            for (int i = 0; i <= 10; i++) {
                Payload[i] = Serial.read();
            }
            if (Serial.read() == '*') {
                Receiving = false;
                allreceived = true;
            }
            else { memset(Payload, '\0', bufsize); }  //destroy array if end delimiter not where it should be
        }

    }
}

My guess is this line:

memset(incoming, NULL, strlen(incoming));

When "incoming" hasn't yet been cleared, what is the length of it? It's whatever it counts up until the first '\0' character - and where is that character on the first run through? Who knows.

Instead you should memset the size of the buffer, not the number of non-NULL characters in the buffer:

memset(incoming, NULL, numChars);

However, that is a pointless operation, since you are storing a C string and (should be) properly terminating it, so it really doesn't matter what is in the array to begin with since you are just overwriting it anyway. So you can completely lose that whole function call.

You might like to re-write your receiving routine to use a switch/case construct instead of ifs and elses - it'll be much easier to follow:

#define EVER ;;

const int numChars = 15;
char buffer[numChars];

void Get() {
    int pos = 0;
    bool receiving = false;

    for (EVER) {
        int K = Serial.read();
        switch(K) {
            case -1: // Nothing to read
                break;

            case '\n': // Got the end of the string.
                if (receiving) return; // We have a valid string.
                pos = 0; // Reset pointer to start of buffer
                break;

            case '~': // Starting a new string
                pos = 0;
                receiving = true;
                break;

            default: // Any other characters.
                if (receiving) {
                    if (pos < numChars-2) {
                        buffer[pos++] = K;
                        buffer[pos] = 0;
                    }
                }
                break;
        }
    }
}


very lightweight low power microcontroller with memory? I have build a couple of projects using arduino.  For a new project I want to log skin surface temperature vs. time (just perhaps a few times per day) and possibly other easy to obtain info such as voltage.

I need to make everything as small and lightweight as possible (since it would be measuring skin temperature on a small mammal), i.e. below 5g, lighter if possible, ideally 3g, including the battery, so that it doesn't upset the 50-100g animal too much.

I read it might be possible to change the arduino pro mini to use less current by getting rid of the voltage regulator? but perhaps it is more sensible to change completely and learn to program another type of microcontroller which someone could recommend? It would need to be possible to operate it directly from a lightweight coin cell or similar lightweight battery. (I'm also not sure how to find a lightweight 3.3V battery for the arduino pro mini, I guess they exist but I can only find 3V batteries so far). If it has onboard memory to save temperature every few hours which could be downloaded later that would be ideal (I would also be interested if anyone has recommendations for memory). I know it's possible to buy an "Ibutton" but if I have time I would like to make my own so that I can add other sensors and obtain more information.

I made up a small torch locator which used an ATtiny85 powered from a button-cell (CR2032). It looks like this:

Other side:

That currently weighs 5.9g. The battery-holder weighs 1.6g so you could save that by making a more light-weight holder (perhaps a bit of plastic for insulation, and soldering directly to the battery). The chip socket weighs at least 0.5g, so you could save that as well by soldering to the processor pins. So we are down to 3.8g.

The ATtiny85 has 512 bytes of EEPROM which you could use to log readings to. I'm not sure about a clock if you are trying to save weight, but if you start it at a known time, you could have a reasonable estimate of the time by using the millis() function to find miliiseconds since startup.

I made another one a while ago which flashes an LED every couple of seconds:

That is similar. The processor is there (upside down under the chip socket) and the battery is underneath. That weighs 6g. The battery has lasted a couple of years, and that is flashing an LED every couple of seconds!

Instead of the LED you could have a thermistor to read the temperature.

You could program it to take a reading every few hours and save it to EEPROM. Then when instructed (eg. by joining a couple of pins) it could output the readings to another pin (via serial).

You could save more weight by using SMD (surface mounted) devices, and perhaps using a tiny circuit board you could get made up.

Code

The code for my torch locator is below. Of interest is the fact that it sleeps most of the time. Also it sleeps during the ADC sampling. Although in my case I am measuring a LDR (light dependent resistor) the code for measuring a thermistor would be similar. You just need to do some calculations at the end to turn the reading into a temperature.

// ATtiny85 torch detector
// Author: Nick Gammon
// Date: 25 February 2015

// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

/*

  Pin 2 (PB3) <-- LDR (GL5539) --> Pin 7 (PB2) <----> 56 k <----> Gnd

  Pin 5 (PB0) <---- LED ---> 100 R <-----> Gnd

*/

#include <avr/sleep.h>    // Sleep Modes
#include <avr/power.h>    // Power management
#include <avr/wdt.h>      // Watchdog timer

const byte LED = 0;          // pin 5
const byte LDR_ENABLE = 3;   // pin 2
const byte LDR_READ = 1;     // Ain1 (PB2) pin 7
const int LIGHT_THRESHOLD = 200;  // Flash LED when darker than this

 // when ADC completed, take an interrupt
EMPTY_INTERRUPT (ADC_vect);

// Take an ADC reading in sleep mode (ADC)
float getReading (byte port)
  {
  power_adc_enable() ;
  ADCSRA = bit (ADEN) | bit (ADIF);  // enable ADC, turn off any pending interrupt

  // set a2d prescale factor to 128
  // 8 MHz / 128 = 62.5 KHz, inside the desired 50-200 KHz range.

  ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);

  if (port >= A0)
    port -= A0;

#if defined(__AVR_ATtiny85__)
  ADMUX = (port & 0x07);  // AVcc
#else
  ADMUX = bit (REFS0) | (port & 0x07);  // AVcc
#endif

  noInterrupts ();
  set_sleep_mode (SLEEP_MODE_ADC);    // sleep during sample
  sleep_enable();

  // start the conversion
  ADCSRA |= bit (ADSC) | bit (ADIE);
  interrupts ();
  sleep_cpu ();
  sleep_disable ();

  // reading should be done, but better make sure
  // maybe the timer interrupt fired

  // ADSC is cleared when the conversion finishes
  while (bit_is_set (ADCSRA, ADSC))
    { }

  byte low  = ADCL;
  byte high = ADCH;

  ADCSRA = 0;  // disable ADC
  power_adc_disable();

  return (high << 8) | low;

  }  // end of getReading

// watchdog interrupt
ISR (WDT_vect)
{
   wdt_disable();  // disable watchdog
}  // end of WDT_vect

#if defined(__AVR_ATtiny85__)
  #define watchdogRegister WDTCR
#else
  #define watchdogRegister WDTCSR
#endif

void setup ()
  {
  wdt_reset();
  pinMode (LED, OUTPUT);
  pinMode (LDR_ENABLE, OUTPUT);
  ADCSRA = 0;            // turn off ADC
  power_all_disable ();  // power off ADC, Timer 0 and 1, serial interface
  }  // end of setup

void loop ()
  {
  // power up the LDR, take a reading
  digitalWrite (LDR_ENABLE, HIGH);
  int value = getReading (LDR_READ);
  // power off the LDR
  digitalWrite (LDR_ENABLE, LOW);

  // if it's dark, flash the LED for 2 mS
  if (value < LIGHT_THRESHOLD)
    {
    power_timer0_enable ();
    delay (1);  // let timer reach a known point
    digitalWrite (LED, HIGH);
    delay (2);
    digitalWrite (LED, LOW);
    power_timer0_disable ();
    }

  goToSleep ();
  }  // end of loop

void goToSleep ()
  {
  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  noInterrupts ();       // timed sequence coming up

  // pat the dog
  wdt_reset();

  // clear various "reset" flags
  MCUSR = 0;
  // allow changes, disable reset, clear existing interrupt
  watchdogRegister = bit (WDCE) | bit (WDE) | bit (WDIF);
  // set interrupt mode and an interval (WDE must be changed from 1 to 0 here)
  watchdogRegister = bit (WDIE) | bit (WDP2) | bit (WDP1) | bit (WDP0);    // set WDIE, and 2 seconds delay

  sleep_enable ();       // ready to sleep
  interrupts ();         // interrupts are required now
  sleep_cpu ();          // sleep
  sleep_disable ();      // precaution
  }  // end of goToSleep


How to stabilize magnetic levitation system? I followed everything from this project but still, the magnet is not levitating - https://www.hackster.io/jsirgado/magnet-levitation-with-arduino-eeeee4

The best I can do is to make the magnet jump up and down fast but it never levitates. Have tried changing PID setting from the project as aggressive and mild but still didn't achieve the final result.

I need advice from an expert to tell me what I am doing wrong here. All components are in good condition and 5v electromagnet is strong enough.

So what am I missing here? will implementing fast PWM mode be helpful?

The answer to the solution was quite simple. I just had to comment out all serial port reading and Arduino processing became 60 times faster which helped to levitate the magnet. Thanks to everyone who helped me here :)


Why wifiManager.setTimeout(60) is not working? in this code I am using wifiManager.setTimeout(60); so that when it fails to connect to the wifi it should restart. However, wifiManager.setTimeout(60) is not working at all. It get stuck and display these lines :

*WM: AutoConnect

*WM: Connecting as wifi client...

*WM: Using last saved values, should be faster

It never displays this :

"failed to connect and hit timeout"

which means wifiManager.setTimeout(60) is not working . Below is the code:

  #include <ESP8266WiFi.h>

 //needed for library
 #include <DNSServer.h>
 #include <ESP8266WebServer.h>
 #include <WiFiManager.h>

  void setup() {
       // put your setup code here, to run once:
       Serial.begin(115200);

      //WiFiManager
       //Local intialization. Once its business is done, there is no need to
       //keep it around
        WiFiManager wifiManager;
      //reset settings - for testing
      //wifiManager.resetSettings();

     //sets timeout until configuration portal gets turned off
     //useful to make it all retry or go to sleep
      //in seconds

      wifiManager.setTimeout(60);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
 //here  "AutoConnectAP"
 //and goes into a blocking loop awaiting configuration

  if(!wifiManager.autoConnect("AutoConnectAP")) {
     Serial.println("failed to connect and hit timeout");
     delay(3000);
     //reset and try again, or maybe put it to deep sleep
     //ESP.reset();
     ESP.restart();
     //ESP.deepSleep(20e6, WAKE_RFCAL);
    delay(5000);
   }

   //if you get here you have connected to the WiFi
   Serial.println("connected...yeey :)");

    ESP.deepSleep(20e6, WAKE_RFCAL);
    delay(3000);

 }

  void loop() {
  // put your main code here, to run repeatedly:

  }

I am using ESP8266 thing dev board. Can anyone please tell me what is wrong and how to resolve the issue ? Thank You!!

Try using setConfigPortalTimeout(60) instead of setTimeout(60)

Because it has been updated in version 0.10 of WiFiManager library.
see : https://github.com/tzapu/WiFiManager#010


It seems like the math of arduino is off [SOLVED] By changing the offset for the incoming data into int16_t type there won't be any rounding errors and the values I'm getting are all back to zero in the sensor its base position

This is my first project where I use Arduino.

Until today everything went good with the Arduino Pro Mini (3.3v).
But as of today I got a bit of a weird problem.
I am using a MPU gy-521 (doesn't really matter) and I'm working on calculating the actual movement.

The problem which occured is that I'm using a deadzone to negate the smallest numbers (I know, this isn't the right way to use data). The way I negate the numbers is with the following code

// Check deadzone values
  if (ax+axo < adz && ax+axo > -adz) ax = -axo;
  if (ay+ayo < adz && ay+ayo > -adz) ay = -ayo;
  if (az+azo < adz && az+azo > -adz) az = -azo;

  if (gx+gxo < gdz && gx+gxo > -gdz) gx = -gxo;
  if (gy+gyo < gdz && gy+gyo > -gdz) gy = -gyo;
  if (gz+gzo < gdz && gz+gzo > -gdz) gz = -gzo;

ax is accelerometer data over the x-axis, axo is the offset, adz is the accelerometer deadzone.

gx is gyroscope data over the x-axis, gxo is the offset, gdz is the gyroscope deadzone.

All of the other letters are the same, for different axis.
After getting the values within the offset basically set to 0 with the offset I'm doing the following.

// Calculate acceleration
  axa = (ax+axo) / aFactor * g;
  aya = (ay+ayo) / aFactor * g;
  aza = (az+azo) / aFactor * g;

  gxa = (gx+gxo) / gFactor;
  gya = (gy+gyo) / gFactor;
  gza = (gz+gzo) / gFactor;

The a- and gFactor are mentioned in the datasheet, but these values should all be 0 if the value of axis plus the offset is within the deadzone.
The problem is that I'm not just getting 0.00 values.
I'm also getting -0.00 and 0.01.

0.00    0.00    -0.00   0.00    0.01    0.01

Could someone enlighten me about what's wrong in my situation or if this is just a Arduino issue.

[EDIT]

The data originally from the sensor is from type int16_t (ax, ay, az, gx, gy, gz) and the other variables are doubles.

The values which are off are always the same ones: Accelerometer Z, Gyroscope Y and Z.

If your program is basically working but gives you rounding errors, it can be that you are facing some problems related to conversion from floating-point to binary or reverse. It is a very common problem in computer science. For example, the decimal number 0.1 has no exact binary  representation, it is infinite. For more information, you can read these pages:

http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/
https://www3.ntu.edu.sg/home/ehchua/programming/java/datarepresentation.html

In order to solve your problem, you can try to apply appropriate rounding to your results and if possible avoid mixing different data types and use double only if absolutely needed (which I guess is the case in your application).


Can't assign String to Array of String I have to input 5 words and organize.
In order to organize words, I have to get them into Array of String to compare.
I succeed to get char[buffer] into String in_str but somehow in_str doesn't
get into str[5].
is String str[i]=in_str;  Wrong?? How can I put in_str to Array of String str??

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

void loop() {
  int state = 1, len = 0 ,i=0, k=1;
  char buffer[128];
  String str[5];
  while (true) {
    if (state == 1) {
      Serial.print("Enter the ");
      Serial.print(k);
      Serial.print("th Word --> ");
      state = 2;
    }
    while (Serial.available()) {
      char data = Serial.read();
      if (data == '\n') {
        buffer[len] = '\0';
        String in_str = buffer;
        String str[i]=in_str;
        Serial.println(in_str);

        i=i+1;
        k=k+1;
        len = 0;
        if(i>4){state = 3; }
        else {state = 1;}
        break;
      }
      buffer[len++] = data;
    }
  if(state==3){
    Serial.println("After Sorting");
   for (int i = 0; i < 4; i++) {
    for (int j = i + 1; j < 5; j++) {
      int compare = str[i].compareTo(str[j]);
      if (compare > 0) {         String temp = str[i];
        str[i] = str[j];
        str[j] = temp;
      }
    }
  }

   for (int i = 0; i < 5; i++) {
    Serial.println(String(i) + " : " + str[i]);
  }

    break;
  }

  }
}

When you write String str[i]=in_str; that is wrong. You only write the type when you are declaring the variable, once.

When assigning, you need only write the variable name, not the type: str[i]=in_str;


Arduino can't find my custom library: fatal error, Motor.h not found etc I have been working on a project building a robot and using my own custom-built libraries to control it. However after converting all my old code into libraries Arduino can't find them.

Everything thing I have seen says to save them in the 'libraries' folder in with the sketches in MyDocuments and to reboot the Arduino Environment so it will recognize them.

Did that.

It even recognizes them in the sketch menu as libraries that can be imported. However, when I click on them to be included, a new blank line is entered into the sketch instead of an include statement. Perhaps this is some clue? I am really out of ideas at this point as to what I have done wrong.

I wanted to vote for the answer from trpropst, but I don't seem to be authorised to do so.

I had the same problem as Caleb. It turned out that the problem was that the user library directory /Arduino/libraries/ contained a library with a missing ".h" file. The Arduino IDE stopped loading the user libraries when it reached the library with the missing ".h" file.

i.e.

the folder "/Arduino/libraries/libraryA" existed

the file "/Arduino/libraries/libraryA/libraryA.h" existed

but the file "/Arduino/libraries/libraryA/libraryA.h" had an include

"#include <libraryB>" for which the folder "/Arduino/libraries/libraryB" existed but it did not contain a file "/Arduino/libraries/libraryB/libraryB.h"

I was trying to compile a program using libraryC, but not using libraryA or libraryB. I guess the lesson is do not develop libraries using the production tool chain.

edited to print < and > correctly


ESP8266 Stops Working After A While (Unknown Problem) have an esp8266.

i'm trying to create a DDNS updater.

it has to wait 5 min then do a GET request to a URL.

Here's my code:

/* Code For DNS Updater.*/

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#define LOOP_TIME 300000

const char* ssid = "SomeSSID";
const char* password = "SomePSWD";

const String address="http://dynamicdns.park-your-domain.com";
const String path="update";
const String pathHost="host";
const String pathPassword="password";
const String pathDomain="domain";

const String dnsName="my-example-host.com";
const String ddnsPassword="my-example-password";
const String updateHosts[]={
    "@",
    "subdomain1",
    "subdomain2",
  };

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

long nextUpdate=0;

void loop() {
  if(nextUpdate<millis()){
    if (WiFi.status() == WL_CONNECTED) {
    updateDNS();
    }else{
      connectWiFi();
    }
    nextUpdate=millis()+LOOP_TIME;
  }
}

void updateDNS(){
  Serial.println("Updating Hosts:");
  for(int host=0;host<(sizeof(updateHosts)/sizeof(String));host++){
    Serial.print(updateHosts[host]+": ");
    String assembledURL=address+"/"+path+"?"+pathHost+"="+updateHosts[host]+"&"+pathDomain+"="+dnsName+"&"+pathPassword+"="+ddnsPassword;
//    Serial.println("Host: "+updateHosts[host]+" URL: "+assembledURL);
    HTTPClient http;
    http.begin(assembledURL);
    http.GET();
    http.end();
    Serial.println("Done");
  }
}

void connectWiFi(){
  WiFi.begin(ssid, password);

  Serial.print("Connecting To ");
  Serial.println(ssid);
  Serial.print("Password: ");
  Serial.println(password);
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {

    delay(500);
    Serial.print(".");

  }
  Serial.println();
  Serial.print("Connected To ");
  Serial.println(ssid);
}

and it stops after a couple of hours - which isnt good for a DDNS updater.

EDIT: maybe it has something to do with my timer. will try an unsigned long instead.

I have had the "stops after a while" too and it turned out to be heap memory consumption and fragmentation that caused not having enough stack and heap space any more.

My solution: check the heap from time to time (in loop) and reboot the node when it comes down to a practical limit.

Alternate: avoid using the String type and other Heap usages.


Why do we declare constant lat and lon value static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;
What does this mean?
https://github.com/mikalhart/TinyGPSPlus/blob/master/examples/FullExample/FullExample.ino
The above link contains the full example program of that line.
This line is from tinygps++ library for extracting the coordinates and displaying in a table format. I'm using arduino uno, GSM module and GPS module to extract the coordinates and transmit it as message. Can anyone explain what dies this constant value mean and why do we use this?

Static variables are allocated storage only once in a program lifetime
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it and you can't change const variable's value
and i guess you know double is a data type that can save floating point numbers
that line declare two variables with names LONDON_LAT and LONDON_LON and both of them are in one line
and because london's latitiude and longtitude doesn't change the const keyword is used
also i guess because those variables are constants you can use #define visit https://www.arduino.cc/reference/en/language/structure/further-syntax/define/


Does sharing code on Arduino Create automatically grant any license rights? I have code I am happy to share under a GNU GPL License and which is marked accordingly. Before I upload it to Arduino Create Web Editor I want to check whether in doing so I inadvertently grant additional license rights. I have searched for any terms and conditions which may inform me but not found any as yet.

Arduino Create doesn't assume any licensing of any form. Sharing isn't a public thing. You have to specifically provide someone with a link to your sketch. If you choose to post that link publicly then that is your concern.

Any licensing should be included with your sketch.


Understanding Debounce code I don't understand the following Debounce code. (The complete code is at the bottom.) From what I understand, when the pin reads something, we wait at least 50 milliseconds before performing anything. But doesn't the reading variable get reset every loop iteration, so reading equals zero in the inner if-condition in every iteration.
What I think is the sequence of events: loop(), loop(), loop(), "loop(), button press, reading=1, set lastDebounceTime, first if condition fails because we have to wait, set lastButtonState=1", loop(), loop(),loop(),"loop() enough time has passed, but since no button press at in this iteration and the last few, reading and lastButtonState equal zero", loop(), ... .
However, this code works.
Why do we save reading in a local variable? Won't the code virtually always be this, then:
if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the debounce
    // delay, so take it as the actual current state:

    // if the button state has changed:
    if 0 != buttonState) {
      buttonState = 0;

...

Entire code:
/*
  Debounce

  Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
  press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's a
  minimum delay between toggles to debounce the circuit (i.e. to ignore noise).

  The circuit:
  - LED attached from pin 13 to ground
  - pushbutton attached from pin 2 to +5V
  - 10 kilohm resistor attached from pin 2 to ground

  - Note: On most Arduino boards, there is already an LED on the board connected
    to pin 13, so you don't need any extra components for this example.

  created 21 Nov 2006
  by David A. Mellis
  modified 30 Aug 2011
  by Limor Fried
  modified 28 Dec 2012
  by Mike Walters
  modified 30 Aug 2016
  by Arturo Guadalupi

  This example code is in the public domain.

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

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH), and you've waited long enough
  // since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the debounce
    // delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);

  // save the reading. Next time through the loop, it'll be the lastButtonState:
  lastButtonState = reading;
}

(Debounce code taken from: https://www.arduino.cc/en/tutorial/debounce.)

loop() does not need any time and repeats permanently.
lastButtonState is reading from previous loop run.
As long as the button bounces, lastDebounceTime is updated.
Only when the button has settled (either pressed or released), the condition
  ((millis() - lastDebounceTime) > debounceDelay)

becomes true and the code is executed -> if buttonState (the previous debounced state) and reading show a change to HIGH, the led state is toggled.
Not sure if this explanation makes anything clearer, as it is clear already as it stands, IMO.


Using NodeMCU D8 (GPIO15), D4 (GPIO2) and D3 (GPIO0) pins I am using a NodeMCU board and have already used 6 digital pins as output for interfacing with the LCD. I intend to use 2 more digital pins, one as input and other as output for interfacing an ultrasonic sensor.

D8, D4 and D3 are the only digital pins remaining. I understand that D8 (GPIO15), D4 (GPIO2) and D3 (GPIO0) pins of the NodeMCU  have special boot-controlling uses. So how can I use those pins as generic digital pins. Any help is appreciated.

The boot setup pins have pull-up on board (0, 2) and pull-down (15) to ensure the correct boot. io 0 (D3) is additionally wired to the reset circuit controlled over USB to put the esp8266 into bootloader a.k.a. flashing mode.

io 0 must be HIGH for normal boot, io 2 must not be LOW (can float according to spec).

If you attach a device to this pins, the device must respect the boot state. Some devices will pull-down or pull-up a wired pin. Usually it is not documented. You can't use such devices on boot config pin which requires the other state.

The pull-up and pull-down can influence the attached device or readings from the device. For some elements it can be advantageous.

Best is to use this pins for elements which would need pull-up or pull-down anyway. For example buttons/switches or sensors which behave like buttons or switches.

In my project with Wemos D1 R2 I had signal to relay module on io 0, speaker module (with amplifier) for tone() function on io 2. I could not use a relay or mosfet module on io 2. On io 15 I had a reed relay module control signal, which I didn't want to go HIGH at boot as most esp8266 io pins do.


Sharing a Digital Pin / What to do when two components need a specific Digital Pin? I am new to the world of Arduino and picked up an Uno R3. I have run into a situation where I have two components that specifically need digital pin 11, 12, 13 as specified by the libraries used to interact with them.

Each component also uses other pins that were able to be specified as different with the libraries but for those 3 the libraries say I cannot change them. What do you do in a situation like this? Is it somehow possible for two components to use the same pins? Any help is appreciated.

The two libraries I am trying to use are https://github.com/nRF24/RF24 (Wifi Receiver & Transmitter using component nrf24l01+) and https://github.com/steigeia/RFID_UNID_LOGGER/blob/master/libraries/AddicoreRFID/AddicoreRFID.h (RFID Reader/Writer using component RC522).

It seems probable that both libraries use SPI which connects to the SPI hardware on the chip via those pins. See How do you use SPI on an Arduino?

You haven't said what libraries, nor what hardware, but you possibly may be able to share those pins between the two devices. They would both need separate slave select pins. Often D10 (digital pin 10) is used as a default for slave select.

Another possible solution is to use "bit-banged" SPI for one device. I have a page on my forum about SPI which includes a bit-banged software implementation.

The library is at https://github.com/nickgammon/bitBangedSPI and is quite short.