Struggling to understand how Bluetooth serial is related to USB on Arduino I've recently acquired a Bluetooth module to attach to my Arduino Uno, but I'm trying to draw parallels to the standard method of communication that I'm familiar with, which seems to be just directly reading or writing to sensors through methods like digitalRead and digitalWrite, respectively. Additionally however, it seems like it's also possible to connect to a serial console, through the Serial class. These make sense, and I've used both individually (serial console viewed by the built-in Serial window in Arduino IDE, and serial write done through Serial.print/println()).
However, in the Bluetooth module I purchased (HW-10), there are pinouts that connect to the TX/RX ports, which I've currently left unconnected since I'm not using the Bluetooth module or any other serial module. My question is, once I connect these, does this completely replace the connection through USB that is currently used to interface with the Uno?
If so, I had a set of specific functionalities in mind for whether these would be "replaced" by connecting the module through the 4 pinouts (TX, RX, VCC, GND):
1. Serial: Can I write and access the serial monitor through the IDE by connecting to 9600 baud, both in code and in the Serial Monitor
2. Pins: Do these connections also allow me to write and read signals from all of the pins, including analog and digital
3. Sending code: Can I still send code through Bluetooth without needing a USB connection?
Apologies if this question seems really obvious or specific, I'm confused as I've read a bunch of wording saying that the Bluetooth module uses a "serial connection", when I only understood serial functionality as being a method of outputting text, not controlling the Arduino. Thanks in advance for help!

I don't actually know what a UART is

UART (Universal Asynchronous Receiver Transmitter) is the technical term for the communication interface, which is called Serial in Arduino speak. It's often called UART, because that is more precise, since there are many different communication protocols, which also work serially (meaning transferring data bits one after another in contrast to parallel, where multiple bits are transferred simultaneously), like I2C, SPI or USB. All serial protocols, but totally different from the Arduino Serial interface. Yes, this is a bit confusing. I guess the Arduino term Serial was coined to make the learning curve less steep for beginners (hiding complexity can also make things confusing unfortunately).
So UART is the same as the Arduino Serial interface.

once I connect these, does this completely replace the connection through USB that is currently used to interface with the Uno?

Here it is good to know, how the USB communication works on the Uno. The microcontroller on the Uno (Atmega328p) does not have a native USB interface. So it cannot speak to USB itself. For that there is an extra microcontroller on the board (I think an Atmega32u4). This controller has a native USB interface and it acts as a USB to Serial bridge (it creates a virtual serial interface on the PC and translate between that and its physical Serial/UART interface). The Atmega328p (which you program with your code) has it's RX and TX pins connected to the RX and TX pins on the Atmega32u4, which can then translate between the Serial/UART protocol and the USB protocol. Thus the Atmega328p doesn't know anything about USB. I just talks via Serial/UART to the Atmega32u4. In fact it also doesn't know anything about bluetooth. Most bluetooth modules for Arduino are also just bluetooth-Serial bridges
Now you need to know, that Serial/UART is made for one-to-one connections. With multiple devices you can get problems, when multiple devices try to send data at the same time. I this case (BT module RX to Arduino TX and vice versa) you would get garbled data, if you try to simultaneously send data from bluetooth and USB to the Arduino. The signals would overlap on the Arduinos RX pin, corrupting the data.
That means, that you don't want to send from both interfaces. In fact it is the easiest way to just use one Serial/UART  interface for only one device. If you leave the Serial Monitor (or any other Serial communication program) closed on the PC, the PC will not interfere with the communication. Though you need to disconnect the bluetooth module, when you write your program to the Arduino, since this is done via Serial and you don't want it to meddle with the data.
So in result the bluetooth module will not "replace" the connection through USB. It will be added and it is your duty to prevent data corruption.

Serial: Can I write and access the serial monitor through the IDE by connecting to 9600 baud, both in code and in the Serial Monitor

Yes. You don't need to use 9600 baud necessarily. The only requirement is, that you use the same baud number in both sketch and Serial Monitor. That number just represents the speed, that the data is send in. Both sender and receiver need to agree on the same communication speed, or the receiver will not be able to read the data. Imagine someone talking to you, but talking twice the speed with that you are able to understand the words. You will not be able to understand much, because the speaker is just too fast. Either you would need to change your hearing/understanding speed or the sender needs to change it's speaking speed, to make the two match.
9600 baud is just one of the standard baudrates, though one of the lower ones. If you need it to be faster (maybe because you are sending much data in fast succession), you might want to use a higher baudrate.

Pins: Do these connections also allow me to write and read signals from all of the pins, including analog and digital

That is up to you. Serial/UART is just a communication interface. How it is used is up to you. You already have seen, that it is often used to output text for a user to read over the Serial interface, often used as a way to debug the code by sending specific text at specific places in the code. Since that connection works in both ways, you can also program the Arduino to receive commands over Serial/UART and then act upon them.
Here the overlaying communication protocol comes in. Serial/UART just transmits a series of bytes over its two lines. It doesn't care, what these bytes mean. It can be text (for example encoded via the ASCII standard, as the Serial Monitor does), or it can be just some binary data. Also there is no concept of "messages". There are only individual bytes and you don't have control over when exactly they are sent. So to make meaningful use of Serial/UART you need to use an extra communication protocol on top of Serial/UART, that the receiver understands.
When you send text to the Serial Monitor you are the receiver. Thus you would send text (because you can understand text) and a natural way for humans to distinguish individual messages is to use a delimiter character. In normal text that can be a period, though in this field going to a new line has somewhat evolved to the standard (so the delimiter character is the newline character '\n'). If you read the delimiter character (either yourself on the Serial Monitor, or the Arduino in your program), that marks the end of the message. You can also use that text based approach in your Arduino program (and I would say that is the easiest way). Though you don't need to. You could also use any binary protocol on it (or even invent your own protocol).
I would suggest you look at the examples in the Arduino IDE, that involve Serial and maybe try some tutorials on the web. There are many of them available.

Sending code: Can I still send code through Bluetooth without needing a USB connection?

You don't need an USB connection for Serial/UART to work. In fact the Atmega328p, which you program on the Uno, doesn't care about the USB connection at all. It only knows Serial/UART.

I hope that gave you a good overview over that topic. When you understand these core concepts you will be able to understand the tutorials and examples on the internet.


ESP8266 print DNS address (obtained via DHCP) I've set up an ESP8266 (Wemos D1 Mini) to get IP-information via DHCP.
Everything works fine and I can print the information :

Serial.print(WiFi.macAddress());
Serial.print(WiFI.localIP());
Serial.print(WiFi.subnetMask());
Serial.print(WiFi.gateway.IP());

But how do I print the DNS-address ??

I cant find a function for this ???

/Kind regards : Gurra

Serial.println(WiFi.dnsIP());

If you have more than one DNS server you can specify the index:

Serial.println(WiFi.dnsIP(1));


LIght bulb to light up I'd like to write a JavaScript function that lights up an led light for X milliseconds depending on the response from the JavaScript function.

function HowManySeconds() {
   setTimeout(HowManySeconds,5000)
   return 1000
}

The JavaScript function will come from a website, so I suppose I would need an Internet enabled device that connects to my router and can 'browse' to my website.

Q: What do I need to buy? A tessel? An Espruino?

You could try the intel galileo or the intel edison with arduino shield. They can be programmed with a variant of the arduino ide, but it is possible to call also programs from the native linux os. Or you could have a look at the esp826.
At least on the edison it is possible to run node.js, while the esp supports lua.


How come people connect their arduinos to buzzers without any coil protection? If you connect your arduino to a motor you use this schematic:

However, when it comes to buzzers, which also have a coil, no one protects the circuit:

What the hell is going on? Are these just buzzers "coiless"? How can I find the type of buzzer I have?

That kind of "buzzer" doesn't have a coil.  It is a "Piezo Transducer" and uses a crystal to produce the sound.

When you're using a real speaker and producing sound you are doing it very differently to switching a motor or a relay on and off.  You're generating a much smoother waveform and you don't have the sharp "ON-OFF" that causes a collapse of the magnetic field.  You're actually gradually reducing the power and then reversing it to remove the magnetic field then apply a new one in the opposite direction (if you have wired it right of course).

Also the currents involved in driving a speaker like that are minuscule compared to switching a relay, especially when driven direct from the Arduino.  For louder volumes you will use an amplifier, and that deals with the whole protection within itself since it is designed to drive a speaker.


Error while sending message using gsm sim900a module interfaced with arduino uno The code used for interfacing the gsm module with arduino for sending a message is as follows :-

#include <GSM.h>

#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess; // include a 'true' parameter for debug enabled
GSM_SMS sms;

// char array of the telephone number to send SMS
// change the number 1-212-555-1212 to a number
// you have access to
char remoteNumber[20]= "12125551212";

// char array of the message
char txtMsg[200]="Test";

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

  Serial.println("SMS Messages Sender");

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while(notConnected)
  {
    if(gsmAccess.begin(PINNUMBER)==GSM_READY)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
  sendSMS();
}

void loop()
{
// nothing to see here
}

void sendSMS(){

  Serial.print("Message to mobile number: ");
  Serial.println(remoteNumber);

  // sms text
  Serial.println("SENDING");
  Serial.println();
  Serial.println("Message:");
  Serial.println(txtMsg);

  // send the message
  sms.beginSMS(remoteNumber);
  sms.print(txtMsg);
  sms.endSMS();
  Serial.println("\nCOMPLETE!\n");
}

the error is found on the 3rd line
    GSM_SMS sms;
as GSM_SMS is not a name type.
what point am i missing here...??

thank you in advance.

Update your IDE software. You need IDE 1.0.4 or later.
I copied your code into my 1.0.5 IDE and compiled it without any error. So it is most probably your version of the Arduino IDE.


What is the maximum number of sensors that can be operated on a single Aurdino unit I currently have an Aurdiuno uno and a motor driver shield: (http://www.hobbytronics.co.uk/arduino-motor-shield).

Now, I would like to run the following mechatronic devices:
3 bi-direction motors,
1 servo,
1 hall effect sensor (digital),
2 infra-red sensors,
1 magnetometer,
1 ultrasonic sensor,

Will the Aurdiuno uno paired with the motor sheild be able to run these components or will I need to buy an Aurdiuno mini? Could I please gain some insight into how you figure out what pins are required and how would i connect the sensor pins to the motor sheild since it does not have any direction slip on connections like the Aurdiuno Uno. Will I need to solder the sensor connections on?

Thankyou

Will the Aurdiuno uno ... buy an Aurdiuno mini?

The main differences between the uno and mini are:

footprint
6 (uno) vs 8 (mini) analog inputs

You will get two extra analog inputs and a much smaller size at the cost of the shield not fitting anymore.

  Now, I would like to run the following mechatronic devices: 3 bi-direction motors, 1 servo, 1 hall effect sensor (digital), 2 infra-red sensors, 1 magnetometer, 1 ultrasonic sensor, Will the Aurdiuno uno paired with the motor sheild be able to run these components?

According to the website the shield supports up to 4 motors or 5 servos, so i would guess that it would work.

if the shield can't do 3 motors and 1 servo at the same time, then you can just use the servo library and a pin for that.

The shield requires 3 pins to function; so you need 3 or 4 pins depending on configurations.

Inputs 1 digital, 4 analog; 1 Digital I\O, 1 Analog In

so it looks like you need 4-5 DIO pins and 4 analog pins, which the uno has so yes.

If you were using motor driver boards instead of a shield the cost would be

2x PWM per Motor/driver combo = 6 PWM
1 DIO for servo
1 DIO for digital input
4x Analog Inputs

Which also fits in the budget all 6 of the PWM DIO pins, + 2 more (leaving 6 of the 14) and 2/3rds of the analog pins (also good you can leave A3,4 alone since they share a timer and only use the other ones)


Default value of global variables is not set I am tracking a bug in the Marlin source code.

Background

Just for those who is not familiar with Reprap 3D printer and G-code: Marlin is firmware that controls a RepRap 3D printer. It receives G-code from a host computer (or read from SD card). Here the important thing is that if you send the "M114" command, it would report information about axis positions. Here, I extended this command to make it print some internal variable as well.

The Problem

In Marlin.ino file there is a line that says:

volatile int extrudemultiply=100; //100->1 200->2

However my RepRap keeps extruding (and worse, ejecting back) a huge amount of filament. So I added some debug output for M114 command to output this value. It turns out this value is not the default value, 100, but something like 12374.

I thought somewhere inside the setup() function this value might be changed. So I defined another variable,

volatile int orig_extrudemultiply = 100;

And then at the first line of setup() function, I added the following line.

orig_extrudemultiply = extrudemultiply;

Finally, I output this value for the M114 command. Still, it is not 100. So it looks like the default value is not effective.

The Question

Although I have experience in C programming, I am new to Arduino development. How is a global variable being initialized in Arduino? In my case, what is the proper way to initialize this value?

Versioning

I originally posted the official Marlin link for the reference. However,
the version I actually use is this fork from the RepRap Pro team. I was just following the Melzi entry of the RepRap wiki, because my board is Melzi. I am not sure whether the latest version of Marlin works for my board.

Further details

As the commenter said, the first thing I thought of was memory corruption. So I wanted to narrow the problem down. Since that value is configurable through M302 SXXX command, I tested this command, and it works without difficulty. This means there is nothing in the loop function or the ISRs can affect this value when it is running stably. So I consider the problem must be in the setup function or earlier.

Further tests shows that setting this value at the end of setup or even at the beginning of setup still works fine. This means the setup function may not be the problematic one. The test in "The Problem" session was the last step, which, in my opinion, means the course of the problem must being run before entering setup.

UPDATE

Further examination shows that although it looks like it works when I set the default value in the first line of setup(), but that it is just luckily being 100. So once I add more padding variables it stops working until I move the default setting after the following line in setup():

EEPROM_RetrieveSettings(); // Loads data from EEPROM if available

However, since I greped for extrudemultiply before any test, and I didn't figure out this function, this function should not change this value. I guess there is some data overflow inside this function, so the value was changed expectationally.

I got to figure out what is wrong in this function.

This variable is declared volatile which is generally meaning that it can be modified by an Interrupt Service Routine (ISR).

So it is perfectly possible that this ISR gets called before your setup() function gets called and then it may modify this variable.

In C and C++, variables defined as type variable = xxx; are guaranteed to be initialized before any of your code starts to run.

So this means you must look for the root of the problem somewhere else.

Don't forget that it is perfectly possible that some code gets run before setup() is called.

You may try to search for the code that runs before setup(); unfortunately it can be hard to find out this code:

Indeed, in C++, there are a lot of possibilities for code to execute even before the main() function gets called; for instance, declaring an instance of a class as a global variable, will call the class constructor before main().

So you would have to find out all class instances declared as global variables in all source files, and then check the class constructor that gets called for each instance.

Another way could be to check the assembly produced for your program and find all calls occurring be fore main(), but it can be harder if you can't read assembly.


Burning sketch with I2C Not a pure Arduino question really. I'm actually using a standalone ATmega168. So far I've been using AVR-ISP programmer (working from AVR Studio) to program the chip. After everything is done, the chip will be covered and I will only have access to the I2C pins. The MISO,MOSI, etc pins will be unreachable.

I was just wondering if there was a way to use the I2C pins to update the program that is burned on the chip. I won't need to burn the bootloader again, but just to update the program if it needs to be.

You need to write a I2C bootloader to the AVR. There seems to be a project that has already created such a bootloader.

Atmel has provided a TWI/I2C bootloader for their XMega processors (not the ATmega168).

Next problem is uploading the code via I2C. You'd need some hardware to convert USB  to I2C. And some software to talk to this hardware. The last part is probably supported by AVR studio, as Atmel has provided an I2C bootloader. Though I'm not sure both of the above bootloaders are using a compatible protocol over the I2C.


Burning a bootloader onto my Arduino MEGA 2560 without another arduino board, or isp board My youtube video explains it. It's starting to get on my nerves.

You need a programmer (isp or Arduino board as programmer). It is not possible to burn a bootloader without it. The USBasp version 2 plus a 10 to 6 pin adapter cost about 2 dollars.


Arduino IDE giving a blow to battery back-up of PC When I have serial plotter open in the Arduino IDE with serial communication going on, the fans of my PC go full speed. On checking I found that Java(TM) Platform SE binary(32 bit) is using about 29% of the CPU.

This gives a big blow to the PC's battery back-up. Is there some way to reduce the CPU usage ?

  The IDE version I use is Arduino 1.8.4

OS : Microsoft Windows 10 Home (64 bit)

PC : HP Au620 TX (laptop)

processor : Intel i5 7th gen (7200)

RAM : 8GB

Run Arduino IDE in a virtual machine which allows CPU allocation. Set a strict limit on CPU resources in that VM, like 200..500 MHz.


digitalRead() function of Arduino doesn't read Input value sent by sensor after detecting the object I'm trying to turn ON the LED(inbuilt/PIN13) when photoelectric proximity sensor(12v) senses any object. Sensor is connected on pin 2. Assigned pin 2 as INPUT, I've got a 12v spdt relay for switching. 12v output from sensor is fed to coil, on the other end 5v supplied to COM pin and "Normally Open"(NO) pin to Arduino (with pull-down resistor). When 'NO' connected to loose LED it works properly (shows 5V on voltmeter when object is detected). But when connected to Arduino digitalRead(), it always returns LOW/0.
//code
int a=0;
void setup() {
  pinMode(2,INPUT);
  pinMode(13,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  a ==  digitalRead(2);
  Serial.println(a);
  if(a==HIGH){
    Serial.println("Object Detected");
    digitalWrite(13,HIGH);
  }else{
    Serial.println("There's no object");
    digitalWrite(13,LOW);
  }
  delay(1000);
}

a == digitalRead(2) must be a = digitalRead(2). You also better change the if clause to if(a) to avoid true/HIGH/1 confusions.
If you had formatted the code properly, you'd have safed some time (you just need to select the code and press the {} button).
You also better replace the relay with a voltage divider (as I mentioned in my comment), because as long as you don't have a datasheet for the sensor you can't be sure that the sensor is designed to source that much current. If the sensor is supposed to drive a TTL logic, it will eventually fail, just like you don't drive relays with GPIOs directly. And beside that you need a freewheeling diode across the relay coil to deal with back EMF which will also harm the sensor.


Bluetooth not transmitting refreshed sensor values I have a 9 DOF sensor attached to a BLE chip and Arduino Uno. I want to send the position measurements (i.e. x, y and z coordinates) from the sensor to my iPhone app (Bluefruit LE). The code below starts off well and I am able to see the coordinates on the iPhone. But after showing 6 sets of x-y-z coordinates on the phone all it prints are the x-coordinates. The y and z coordinates do not get shown on the phone at all. I have put the code below (likely not the most efficient code). Any suggestions on how to fix it will be very helpful. thanks in advance.

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>
#include <SPI.h>
#include "Adafruit_BLE_UART.h"

/* Set the delay between fresh samples */
#define BNO055_SAMPLERATE_DELAY_MS (100)

#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 2
#define ADAFRUITBLE_RST 9

Adafruit_BNO055 bno = Adafruit_BNO055(55);
Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ,     ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

void displaySensorDetails(void)
{
sensor_t sensor;
bno.getSensor(&sensor);
Serial.println("------------------------------------");
Serial.print  ("Sensor:       "); Serial.println(sensor.name);
Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
Serial.print  ("Max Value:    "); Serial.print(sensor.max_value);
Serial.print  ("Min Value:    "); Serial.print(sensor.min_value);
Serial.print  ("Resolution:   "); Serial.print(sensor.resolution);
Serial.println("------------------------------------");
Serial.println("");
delay(500);
}

/*
Arduino setup function (automatically called at startup)
*/

int x = 0;
int row = 0;
void setup(void)
{
Serial.begin(9600);
Serial.println("Orientation Sensor Test"); Serial.println("");
Serial.println("CLEARDATA");
Serial.println("LABEL,x,y,z");

/* Initialise the sensor */
if(!bno.begin())
{
/* There was a problem detecting the BNO055 ... check your connections */
Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
while(1);
}

delay(1000);

/* Display some basic information on this sensor */
displaySensorDetails();
bno.setExtCrystalUse(true);

BTLEserial.begin();

}

aci_evt_opcode_t laststatus = ACI_EVT_DISCONNECTED;

void loop(void)
{

BTLEserial.pollACI();

/* Get a new sensor event */
sensors_event_t event;
bno.getEvent(&event);

/* Display the floating point data */

Serial.print("X: ");
Serial.print(event.orientation.x, 4);
Serial.print("\tY: ");
Serial.print(event.orientation.y, 4);
Serial.print("\tZ: ");
Serial.print(event.orientation.z, 4);
Serial.println("");

/* This is the code that sends x, y and z coordinates to BLE */
  uint8_t sendbuffernew_x[20];
  char buff_x[20] = "";
  String xorient = "";
  dtostrf(event.orientation.x, 4, 1, buff_x);  //4 is mininum width, 6 is precision
  xorient += buff_x;

  xorient.getBytes(sendbuffernew_x, 20);
  char sendbuffersizenew_x = min(20, xorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_x, sendbuffersizenew_x);
  memset(sendbuffernew_x, 0, sizeof(sendbuffernew_x));

  uint8_t sendbuffernew_y[20];
  char buff_y[20]= "";
  String yorient = "";
  dtostrf(event.orientation.y, 4, 1, buff_y);  //4 is mininum width, 6 is precision
  yorient += buff_y;

  yorient.getBytes(sendbuffernew_y, 20);
  char sendbuffersizenew_y = min(20, yorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_y, sendbuffersizenew_y);
  memset(sendbuffernew_y, 0, sizeof(sendbuffernew_y));

  uint8_t sendbuffernew_z[20];
  char buff_z[20]="";
  String zorient = "";
  dtostrf(event.orientation.z, 4, 1, buff_z);  //4 is mininum width, 6 is precision
  zorient += buff_z;

  zorient.getBytes(sendbuffernew_z, 20);
  char sendbuffersizenew_z = min(20, zorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_z, sendbuffersizenew_z);
  memset(sendbuffernew_z, 0, sizeof(sendbuffernew_z));

delay(1000);

delay(BNO055_SAMPLERATE_DELAY_MS);
}

That's an incredibly complex way of outputting a floating point number as a string. You may possibly be fragmenting RAM with your use of String, and those String additions. Try replacing:

  uint8_t sendbuffernew_x[20];
  char buff_x[20] = "";
  String xorient = "";
  dtostrf(event.orientation.x, 4, 1, buff_x);  //4 is mininum width, 6 is precision
  xorient += buff_x;

  xorient.getBytes(sendbuffernew_x, 20);
  char sendbuffersizenew_x = min(20, xorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_x, sendbuffersizenew_x);
  memset(sendbuffernew_x, 0, sizeof(sendbuffernew_x));

  uint8_t sendbuffernew_y[20];
  char buff_y[20]= "";
  String yorient = "";
  dtostrf(event.orientation.y, 4, 1, buff_y);  //4 is mininum width, 6 is precision
  yorient += buff_y;

  yorient.getBytes(sendbuffernew_y, 20);
  char sendbuffersizenew_y = min(20, yorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_y, sendbuffersizenew_y);
  memset(sendbuffernew_y, 0, sizeof(sendbuffernew_y));

  uint8_t sendbuffernew_z[20];
  char buff_z[20]="";
  String zorient = "";
  dtostrf(event.orientation.z, 4, 1, buff_z);  //4 is mininum width, 6 is precision
  zorient += buff_z;

  zorient.getBytes(sendbuffernew_z, 20);
  char sendbuffersizenew_z = min(20, zorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_z, sendbuffersizenew_z);
  memset(sendbuffernew_z, 0, sizeof(sendbuffernew_z));

by:

  char buff[10];

  dtostrf(event.orientation.x, 4, 1, buff);
  BTLEserial.write(buff, strlen (buff));
  dtostrf(event.orientation.y, 4, 1, buff);
  BTLEserial.write(buff, strlen (buff));
  dtostrf(event.orientation.z, 4, 1, buff);
  BTLEserial.write(buff, strlen (buff));


displaying a 3 digit clock time on a 4 digit 7 segment display I purchased one of these 4 digit 7 segment displays using a TM1637.

I installed the TM1637 display library from the libraries manager and included it:

(#include <TM1637Display.h>).

I am trying to display the time, and I would like, preferably, to display 3 digit times with a colon, but without the leading zero.

I found this great reference online for using the library., and saw the usage for numbers with colons:

showNumberDecEx(number, dots, leading_zeros, length, position)

according to the guide, to have the colon in the center, you would pass 0b01000000 as the dots parameter.

And I figured that if I then want to display, for example, the time 1:36, then my number parameter would be 136, my leading_zeros parameter would be 0 (false), my length would be 3 for a 3 digit number, and my position would by 1 to start the number in the zero-indexed second position:

display.showNumberDecEx(136, 0b01000000, false, 3, 1); //displays 5136

But this displayed 5136 with no colon.

I tried a number of other things, including:

display.showNumberDecEx(136, 0b01000000, true, 3, 0); //displays 13:66
display.showNumberDecEx(136, 0b01000000, false, 3, 0); //displays 13:6A

I finally found code from this site, which works to display the time (albeit with a leading zero), but I don't fully understand it:

display.showNumberDecEx(1*100+36, 0x80 >> 1, 1, 4, 0);

I get that 1*100+36 represents number of hours plus minutes, but I don't get the 0x80 >> 1 bit. I'm assuming the rest of it is just saying make it a 4 digit number and add a leading zero.

Can anyone possibly:
* help me understand the above working code
* tell me an easier way to construct a time so that I can ideally just pass a 3 or 4 digit number and have it automatically render out a clock time with separating colon
* tell me why my previous attempts were incorrect

I tested your first code line and it outputs a right aligned 136 without colon at my display. (Said I have only a colon at the middle and no decimal points)

The 5 at the fist digit (and also the A at your third code line) must have been set somewhere beforehand. The function does not change the unused digit, so it will stay whatever you set it to beforehand (Even from before the last reset of the Arduino. The display doesn't reset with the Arduino). You can set the segments for that digit to zero (or set all segments to zero, to clear the complete display) before you show the decimal number.

About the colon: Here it is important on which position you start the printing of the number. The colon/decimal point bitmask, that you provide the function with, is seen from the starting position, that you provide. The middle colon of a 4 digit display is wired to the second digit. When providing 1 as the starting position, you start with the second digit. Thus the colon bitmask must set the most significant ("first") bit, to enable the middle colon, since it belongs to the first digit, that is processed by the function. Meaning:

position = 0 and bitmask = 0b10000000 --> colon/decimal point at first digit on
position = 0 and bitmask = 0b01000000 --> colon/decimal point at second digit on
position = 0 and bitmask = 0b00100000 --> colon/decimal point at third digit on
position = 1 and bitmask = 0b10000000 --> colon/decimal point at second digit on
position = 1 and bitmask = 0b01000000 --> colon/decimal point at third digit on
position = 2 and bitmask = 0b10000000 --> colon/decimal point at third digit on
position = 2 and bitmask = 0b01000000 --> colon/decimal point at fourth digit on

The 0x80 >> 1 is just a different representation of your binary number. 0x80 is the hexadecimal form of the binary 0b10000000. The >> operator shifts the byte to the right, here by one digit. Thus:

0x80 >> 1 = 0b10000000 >> 1 = 0x40 = 0b01000000

So the code, that you found, enables the colon/decimal point at the second digit.

  tell me an easier way to construct a time

Easier it relative. I used such a display in a project to display a time and used two showNumberDecEx() calls; one for the minutes and one for the seconds:

display.showNumberDecEx(seconds, 0x00, true, 2, 2);
display.showNumberDecEx(minutes, 0x40, true, 2, 0);

Having directly minutes and seconds may make it easier for you. About the no-leading-zeros: Since the library always prints left to right, you need to handle that by yourself. But that is rather easy. One if statement to check, if the minutes are greater than 9 or not. Depending on that you set the position to 0 or 1.

display.showNumberDecEx(seconds, 0x00, true, 2, 2);
if(minutes > 9){
    display.showNumberDecEx(minutes, 0x40, false, 2, 0);
} else {
    display.showNumberDecEx(minutes, 0x80, false, 1, 1);
}

You could put that into a function, so that you don't have to write this code multiple times.

Note: For my last code snippet to work, you should first clear the display (or optionally only the first digit), so that no number from before will be displayed there.


How do i properly read an analog pin on attiny85? Anyone ever run into a problem with your attiny not reading  your analog pins correctly? (-1023 or 1023 or 0 value) How did you resolve the issue?

Here's what my code looks like now :

4th revision of code as of 5/6/2015 8pm:

int NTC = A1; // thermistor
int switchPin = PB1; // push button
int LED = PB0;  // led

// button latch
byte ButtonState;
byte lastState = LOW;
byte count = 0;

 //brightness level of each different mode
int low = 50;
int med = 140;
int high = 255;
int dim = 0;

int ADCcount = 0;

void setup()
{

 pinMode(switchPin, OUTPUT);
 pinMode(LED, OUTPUT);

  }

 void loop()
 {

  ADCcount = analogRead(NTC);

delay(100);

  ButtonState = digitalRead(switchPin);

  if(ButtonState && ButtonState != lastState)  // button latch, no debounce      needed.
   {
      if(count < 4) // This will check to see if the count is within a range of  0 - 255
                 // anything over that, it will reset count back to 0. Of course
      count += 1;  // same as count = count + 5;
      else
      count == 0;
        }

    lastState = ButtonState;

   if (count == 0)
  {analogWrite(LED,0);}
    else if (count == 1) { if(ADCcount < 500) {analogWrite(LED,high);}
      else{ if(ADCcount > 525){analogWrite(LED,low);}
       }
          }
      else if (count == 2 ){analogWrite(LED,med);}
      else if (count == 3) {analogWrite(LED,low);}
      if(count >=4) {count = 0;}
      delay(50);
 }

simulate this circuit – Schematic created using CircuitLab

The improper bush-button event handling is likely to cause the problem. One way to properly react to the external environment signals could be constant polling or using interrupts. With constant polling, all the time is spent on the checking the status of the button. With interrupts, the program is executed as it should, and only if interrupt happens - the execution jumps to the interrupt subroutine, executes it, and goes back to the main code where it left off.

In your case, you can use pin 7, for example, for push button signal. It can have a function of INT0. Read Section 9. Interrupts of the datasheet - it is straight forward.

I do not completely understand what your program should do, but I will try to convey the general approach of using subroutines:

volatile bool pressed = false;
int main(void)
   {
   MCUCR |= (1<<ISC01 |1<<ISC00);       // set INT0 to interrupt on rising edge of pin7
   sei();                               // enable global interrupts

   while(1){
      if (pressed) then do something; //You can disable interrupts here so your code is not interrupted by cli();
      pressed = false; // reset the state
      else do something else;
   // you can re-enable your interrupts here by sei();
   }
}

// only happens when the change on pin 7 is from LOW to HI
ISR(INT0_vect){
pressed = true; // update the pressed status
}

If you want to use pin6 for push button, you should enable the PCINT1 instead of INT0 and change the ISR to handle the PCINT1 interrupt. In this case, pin 6 will react on voltage toggle (from HI to LOW, or the other way) and you can not discriminate rizing/falling edges. In that way, you must read pin6 within the instruction subroutine to know if it is hi or low.

EDIT:

I would suggest to stop the calculations in the Temp() function after the

  average = SERIESRESISTOR / average;

line due to the fact that you have only three operating modes for the LED. Thus you can, back calculate the average value that makes your steinhart value to be, for example >30. This way, all other values greather/smaller than that value will also fall under the same condition depending on whether average/steinhart are directly/inversely proportional.

When you determine the three ranges of raw average values you can use them directly in the Mode() function. Eventually, you can optimize you code even further, by performing monotonic read instead of burst reads. If you keep a buffer, you do only one addition of the most recent sample and subtracting the oldest sample. For this you will need two pointers and one memory for to store sum, but you will not need to do nSamples additions:

read (newSample);
sum += newSample;
sum -= oldestSample;
average = sum/numSamples;
update pointers to the memory for oldest sample and for the feature sample;


WiFi module ESP8266-01 for Arduino not working I am new to using Arduino just bought my first one yesterday, and I also got an WiFi module. The Arduino I got is another brand but should be the same as the Arduino Uno rev 3 and I got the ESP8266-01 wifi module.

I've tried doing some simple examples projects following some YouYube videos, and all those have worked without problem.

What I am trying to create is a simple magnetic door switch. When it's opened I get a signal to my computer. Getting the magnetic door switch wired with the Arduino and getting an LED to light up when the magnetic switch opened worked without problem.

But to set up the wifi module, I can't get it to work.

I have spent hours and hours watching tutorials reading all I can find to trying everything to get this to work, but no luck.

I don't know If I am doing something wrong (probably) or if something is broken.

These are the instructions I am trying currently.

Video of my Arduino setup

For the Arduino board I use 12v DC in and USB from my PC.

Code:

#include "Arduino.h"
#include "ESP8266.h"

#include "SoftwareSerial.h"
SoftwareSerial  ConsoleOut(8, 9);

#define SSID  "ASUS"
#define PWD   "tmpPassword"

void setup() {
  char  *ipAddress, ap[31];

  WiFi.reset(WIFI_RESET_HARD);
  WiFi.begin(9600);
  ConsoleOut.print("flag2");
  if (WiFi.join(SSID, PWD) == WIFI_ERR_OK) {
    ipAddress = WiFi.ip(WIFI_MODE_STA);
    ConsoleOut.print(F("\n\rIP address:"));
    ConsoleOut.print(ipAddress);
    ConsoleOut.print(':');
    ConsoleOut.print("flag1");
    if (WiFi.isConnect(ap))
      ConsoleOut.println(ap);
    else
      ConsoleOut.println(F("not found"));
  } else
    while (1);
}

void loop() {
  if (WiFi.connect((char *)"www.google.co.jp", 80) == WIFI_ERR_CONNECT) {
    if (WiFi.send((const uint8_t *)"GET / HTTP/1.1\r\n\r\n") == WIFI_ERR_OK) {
      int16_t c;
      uint16_t len = WiFi.listen(10000UL);
      while (len)
        if ((c = WiFi.read()) > 0) {
          ConsoleOut.write((char)c);
          len--;
        }
    } else
      ConsoleOut.println(F("Send fail"));
    WiFi.close();
  } else
    ConsoleOut.println(F("TCP connect fail"));
  WiFi.disconnect();
  while (1);
}

Code:

Different from the example sketch is that I use 2K instead of 3K resistors for R2, R4 and 1K for R1, R3. (2K on left side in the video 1K on the right side)

The LED of the WiFi lights red constantly. I don't know what that means,  and the blue LED on the wiFi module lights up whenever I upload a sketch to the Arduino.

Thanks in advance. Any help is really, really appreciated.

Use this code to send commands to the ESP:

#include <SoftwareSerial.h>

    SoftwareSerial esp8266(2, 3);

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

      esp8266.begin(9600);
    }

    void loop() {
      while(esp8266.available()) {
         Serial.write(esp8266.read());
      }

      while(Serial.available()) {
        esp8266.write(Serial.read());
      }
    }

This simply reads everything from the ESP chip and sends it to the console and vica versa.

To modify the baud rate on the chip, send the following command in the serial monitor:

AT+UART_DEF=9600,8,1,0,0

This sets the baud rate to 9600 and remembers it for further use.


Need some help in coding a "timer" in an if else statement I want to code something like a "timer" (don't know what to call it) in an if else statement in my arduino uno.

Basically I have 2 buttons. If the button1 is pressed and button2 is also pressed in a certain amount of time (let's say 3 seconds), the code will execute. If button1 is pressed but button2 is not pressed within 3 seconds then it will loop back up. How do I go about writing this code?

I've included a flowchart to make my question clearer.

Thanks all :)

if(digitalRead(button1) == LOW)       // this is where I need help
{
  if(digitalRead(selectbutton) == LOW)
  {
    for(x=1; x<=30; x++)
    {
      digitalWrite(dir, HIGH);
      delayMicroseconds(10);
      time_now = millis();
      digitalWrite(led, HIGH);
      while(millis() < time_now + 50)
      {
      }

      time_now = millis();
      digitalWrite(led, LOW);
      while(millis() < time_now + 50)
      {
      }
    }
    x=0;
  }
}

else if(digitalRead(button2) == LOW)    //same here >_<
{
  if(digitalRead(selectbutton) == LOW)
  {
    for(x=1; x<=10; x++)
    {
      digitalWrite(dir, LOW);
      delayMicroseconds(10);
      time_now = millis();
      digitalWrite(led, HIGH);
      while(millis() < time_now + 150)
      {
      }

      time_now = millis();
      digitalWrite(led, LOW);
      while(millis() < time_now + 150)
      {
      }
    }
    x=0;
  }
}

}

A flowchart is not bad, but it's not really the most appropriate kind of
diagram for this sort of problems. You should try to think in terms of
finite state machines instead, which is a very useful concept
whenever you try to implement “reactive” systems, i.e. systems that have
to react to some kind of input.

Here is your problem, as I understand it, translated into a state
diagram:

This system has two states:

“waiting”, when it waits for the first button to be pressed
“stand by” when the first button has been pressed and it waits for the
second.

Pressing button 1 makes a transition from “waiting” to “stand by”. The
transition back to the initial “waiting” state can be triggered by two
distinct events:

3 seconds spent in the “stand by” state
the user pressing button 2.

Note that in the second case, the system runs your code while making the
transition.

Once you have the state diagram, and assuming you have read (and
understood) the finite state machine tutorial I linked to, translating
the diagram into code is almost trivial.


NRF24L01+ Issues antenna I have 2x NRF24L01+ communicating but they are unreliable. It doesn't matter if they are right night to each other or 100ft away. For some odd reason when I place my hand on the antenna it work perfectly. Why would this be?
I have one set up to send and one to receive. All I am sending from one to the other is a 3 digit number to turn on a relay.

I found a solution. As the signals where too close I found where I could tone down the signal strength using:

   radio.setPALevel(RF24_PA_MIN);

Because I didn't want to loose long range capabilities too I send my packet out 4 times at this lower signal and then increase the strength back to max to send out another 4 packets. This way my close range and far range relay will receive the signal.


Is an Arduino Uno made in the USA compatible with SunFounder shields? I bought an Arduino Uno from Radio Shack. I was under the impression it was the authentic model made in Italy. I read on Arduino.cc that the USA version is licensed and essentially the same. I then went to Amazon and ordered an RBG shield, and what I thought was the starter kit that is used with the examples on the IDE. I received the package and it is from SunFounder. Will this work with the IDE on the website and the Arduino I have from Radio Shack?

Use the latest official Arduino IDE : Arduino IDE

Every Arduino Uno and all the clones are compatible. Some clones have the CH340G usb-serial chip and require an extra driver. If you look very hard, you might find an Arduino Uno board that is not version 'R3' and does not have SDA and SCL near the USB connector, or does not have the polyfuse for USB 5V, or uses an ATmega328 instead of a ATmega328P. There is a chance of maybe 1 in 10,000 that you find a wrong Uno board, and in most cases those are still compatible.

Do you mean the SunFounder RGB Matrix Driver Shield? That should be no problem.


How to add colour change to the strobe coding? I have this strobe effect working. However, I would like to change the colour of the LEDs after each 'strobe sequence'. How can it be achieved?
The code I am using is this one:
    // Basic code NeoPixel
    // wwww.arduinoplatform.com

    #include <Adafruit_NeoPixel.h>
    #ifdef __AVR__
     #include <avr/power.h> // Required for 16 MHz Adafruit Trinket
    #endif

    // Which pin on the Arduino is connected to the NeoPixels?
    // On a Trinket or Gemma we suggest changing this to 1:
    #define LED_PIN    6

    // How many NeoPixels ar
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, 6, NEO_GRB + NEO_KHZ800);

    void setup() {
      strip.begin();
      strip.show(); // Initialize all pixels to 'off'
    }

    // *** REPLACE FROM HERE ***

    void loop() {
      // Slower:
      // Strobe(0xff, 0x77, 0x00, 10, 100, 1000);
      // Fast:
      Strobe(0xFF, 0x00, 0xF8, 10, 50, 1000);
    }

    void Strobe(byte red, byte green, byte blue, int StrobeCount, int FlashDelay, int EndPause){
      for(int j = 0; j < StrobeCount; j++) {
        setAll(red,green,blue);
        showStrip();
        delay(FlashDelay);
        setAll(0,0,0);
        showStrip();
        delay(FlashDelay);
      }

     delay(EndPause);
    }

    // *** REPLACE TO HERE ***

    void showStrip() {
     #ifdef ADAFRUIT_NEOPIXEL_H
       // NeoPixel
       strip.show();
     #endif

    }

    void setPixel(int Pixel, byte red, byte green, byte blue) {
     #ifdef ADAFRUIT_NEOPIXEL_H
       // NeoPixel
       strip.setPixelColor(Pixel, strip.Color(red, green, blue));
     #endif
    }

    void setAll(byte red, byte green, byte blue) {
      for(int i = 0; i < 64; i++ ) {
        setPixel(i, red, green, blue);
      }
      showStrip();
    }

I guess you want to cycle through a list of defined colors with your strobe effect. For that you can save the colors in a 2-dimensional array and then cycle through the array with a for loop. The 2-dimensional array is then a group of colors, each defined by the 3 numbers for a RGB value. Somewhat like this:
#define NUM_COLORS   5
byte colors[NUM_COLORS][3] = {
    {0xFF, 0, 0},
    {0, 0xFF, 0},
    {0, 0, 0xFF},
    {0xFF, 0xFF, 0},
    {0, 0xFF, 0xFF}
};

void loop(){
    for(int i=0;i<NUM_COLORS;i++){
        Strobe(colors[i][0], colors[i][1], colors[i][2], 10, 50, 1000);
    }
}

Note, that this is not a complete code, but only the interesting parts. You can incorporate this into your code. You can change the number of colors and the colors itself to your liking (I only took some example values, that are easy to recognize).


How get assembler/preprocessed code for library I am using https://github.com/sudar/Arduino-Makefile project with https://github.com/ladislas/Bare-Arduino-Project to compile my Arduino projects from Linux command line. I put as much as possible functionality to libraries for reuse (and use the same libraries from many projects too).

Now I had run to some problems and I am not sure, if I am using the language (C/wiring/...) properly, as a lot of #define macros are used. I think, that seeing the resulting code would help me greeatly in finding, wheather some specific lines are compiled into what I want them to be compiled. I am interested mainly in the library code, even if it would mean to dump full program together with all used standard libraries. (I can find my way in large files.)

I would prefere intermediate files, as I suppose they could contain more info than just dissassembled .HEX file, but if this assumption is not correct, and I can get the same from .HEX, than I can use that way as well.

Question: How to get intermediate files (Ideally both "plain C" after preprocessing all macros AND "plain ASM" after compiling the code) ideally with corresponding lines of original code as comments inside.

Subquestion: In the above, how to disable optimalisation as much as possible, to get the code more verbatim similar to original C (I know, that it would hurt both speed and size and I do not care - I just want to be sure compiler does undertand my code the same way as I myself and if not, then see, where I made mistakes)

Thanks for all suggestions :)

You can get the generated assembly by passing the -S option to
avr-g++. The makefile you are using has a rule for that, so you would
just type

make build-*/my_file.s

to get the assembly for my_file.cpp.

For the pre-processed C++, you use the -E option. There is no rule for
that in the makefile, so you will have to write yo own, or manually
invoke the compiler. At a minimum:

avr-g++ -mmcu=my_mcu -E my_file.cpp > my_file.i

You may want to add -DF_CPU=... -DARDUINO=... just like the makefile
does when compiling the same file.


using a switch case with a 5-position switch and serial output I'm trying to get started on developing a menu system for my LCD1602. I have a Parallax 5-position switch (up,down,left,right,center) and I would like to interface the two.
I've been trying to get some code working but I'm kind of lost. I don't have a lot of recent experience with Arduino and could use some advice. I realize that there is a version of the 1602 that comes with a keypad integrated into the circuit but I don't have that model. I have a plain-jane screen and a separate 5-position switch.
I'm also aware that the easiest way to accomplish what I desire is with a resistor network and mapping the ADC values. However, I don't want to make an analog switch, I want to make a digital switch.
Is there any way I can take the pins and put them into an array and then translate that into a switch case statement?
I've tried several different ideas and nothing seems to be working. Forgive the example code, it's hacked together.
below is my code
*/

// constants won't change. They're used here to set pin numbers:
char buttonChar1 = 'a';     // the number of the pushbutton pin
const int buttonPin1 = 2;
const int buttonPin2 = 3;
const int buttonPin3 = 4;
const int buttonPin4 = 5;
const int buttonPin5 = 6;
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState1 = 0; // variable for reading the pushbutton status
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;
int buttonState5 = 0;
int pinsArray[5] = {2, 3, 4, 5, 6};
void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);
  pinMode(buttonPin4, INPUT);
  pinMode(buttonPin5, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState1 = digitalRead(buttonPin1) == 2;
  buttonState2 = digitalRead(buttonPin2) == 3;
  buttonState3 = digitalRead(buttonPin3) == 4;
  buttonState4 = digitalRead(buttonPin4) == 5;
  buttonState5 = digitalRead(buttonPin5) == 6;
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:

  switch (pinsArray[5]) {
    case 2:    //
      digitalWrite(ledPin, HIGH);
      Serial.println("button1");
      break;
    case 3:     //
      digitalWrite(ledPin, HIGH);
      Serial.println("dim");
      break;
    case 4:    //
      Serial.println("medium");
      break;
    case 5:    //
      Serial.println("bright");
      break;
  }
  }

When you want to perform actions in response to button presses, you
should take care of reacting to the signal edges rather than levels.
In other words, you perform the action only when the signal changes from
LOW to HIGH, not every time you see it HIGH.
You should also read about button bounce, and either implement your own
debouncing or use an existing library. Below is an example using
Bounce2, but there are other options:
#include <Bounce2.h>

const uint8_t pinDim    = 3;
const uint8_t pinMedium = 4;
const uint8_t pinBright = 5;

Bounce buttonDim, buttonMedium, buttonBright;

void setup() {
    buttonDim.attach(pinDim, INPUT);
    buttonMedium.attach(pinMedium, INPUT);
    buttonBright.attach(pinBright, INPUT);
}

void loop() {
    buttonDim.update();
    buttonMedium.update();
    buttonBright.update();

    if (buttonDim.rose()) {
        Serial.println("dim");
    }
    if (buttonMedium.rose()) {
        Serial.println("Medium");
    }
    if (buttonBright.rose()) {
        Serial.println("bright");
    }
}

You could also, as suggested in Michel Keijzers' answer, use arrays for
the pins and Bounce objects. While these would help streamline the
calls to attach() and update(), they will not help with the meaty
part of the code, i.e. reacting to the presses. There, I would prefer
the button to have descriptive names.


How could i synchronize 2 signals unsigned long Htime;
unsigned long Ltime;
unsigned long Ttime;
unsigned long f;
int N;

void setup() {
  // put your setup code here, to run once:
cli();
  TCNT2 = 0;
  TCCR2A = 0;
  TCCR2B = 0;
  Serial.begin(9600);
  pinMode(5,INPUT);
  pinMode(3,OUTPUT);
  pinMode(11,OUTPUT);
  TCCR2A = (1 << COM0A1) | (1 << COM0B1) | (1 << WGM21) | (1 << WGM20);
  TCCR2B = (1 << WGM22) | (1 << CS22) | (1 << CS21) | (1 << CS20);
  TIMSK2 = (1 << OCIE2A);
}

void loop() {
  // put your main code here, to run repeatedly:
  Htime = pulseIn(5, HIGH);
  Ltime = pulseIn(5, LOW);
  Ttime = Htime + Ltime;
  f = 1000000 / Ttime;
  Serial.println(f);
  N = (16000000 / 1024 / f ) - 1;
  OCR2A = N;
  OCR2B = N/2;

}

Hi this is what i have written. and i need output a square wave with timer, its frequency is measured from input signal in pin 5. After connecting the oscilloscope, i see the problem, there is phase shift between 2 signals. How could i synchronize this 2 signals?(rising edge to rising edge, falling edge to falling edge) Thank u so much for your help!

Given that only the falling edge of your input is sharp and well
defined, I suggest the following approach:

Use the input-capture feature of Timer 1 to get a timestamp on the
falling edge and trigger an interrupt.
In the ISR, start by toggling the output in order to set it low. Then
compute the period of the signal (timestamp of this falling edge minus
timestamp of the previous one) and program a compare register to
trigger a compare match event after half a period.
The compare match would automatically toggle the output pin again, by
using the “toggle on compare match” timer output mode.

The following program attempts to implement this approach. Note that it
is completely untested. Input is on pin 8 (i.e. PB0 and ICP1). Output is
on pin 9 (i.e. PB1 and OC1A). The timer is set to run at F_CPU/8 in
order to accommodate frequencies as low as about 30.1 Hz. A
different prescaler should be used if lower frequencies are needed. The
program does not rely on the Arduino core, and thus defines its own
main() instead of setup() and loop().

ISR(TIMER1_CAPT_vect)
{
    TCCR1C = _BV(FOC1A);  // force output compare -> toggle output
    static uint16_t last_capture;
    uint16_t capture = ICR1;
    uint16_t period = capture - last_capture;
    last_capture = capture;
    OCR1A = capture + period/2;  // compare match after 1/2 period

    // If output is high, toggle again.
    if (bit_is_set(PINB, PB0))
        TCCR1C = _BV(FOC1A);
}

int main()
{
    // Set OC1A = PB1 = digital 9 as output.
    DDRB = _BV(PB1);

    // Configure Timer 1.
    TCCR1A = _BV(COM1A0);  // toggle OC1A on compare match
    TCCR1B = _BV(CS11);    // clock at F_CPU/8
    TCCR1C = _BV(FOC1A);   // force output compare -> toggle output
    TIFR1  = _BV(ICF1);    // clear capture flag
    TIMSK1 = _BV(ICIE1);   // enable capture interrupt
    sei();

    for (;;) {}
}


Powering Arduino AND Relays I have a 5V (5.3V) switching transformer that goes to a 7805 voltage regulator and powers Arduino, Arduino controls 4 relays using BJTs. those relays getting power directly from the same power source.

Arduino and it's modules + LCD uses ~40ma, each relay consumes 70ma. total current is around 350ma lets say 400ma.

The problem is 5V isn't enough to power Arduino, modules, sensors and relays. LCD gets very dim etc...

it works with 9V but 7805 gets really hot ~70 centigrade while having a heat sink on!

If i remove the 7805 and switching power burns or something bad happens then there's nothing in between to protect the Arduino!

What's the solution for this situation?

EDIT: for anyone who may have the same problem; I solved the problem with using a proper switching power salvaged from an old USB type-C charger and removed the 7805 voltage regulator, there's no heat anymore and it's working perfectly.

Linear regulators such as the 7805 operate by dissipating the additional voltage until their rated voltage remains.
This - as you noticed - requires a higher voltage  than the rated voltage.
Some variants, labeled as LDO for low drop-out, have reduced requirements for this, but normal 7805 usually require around 7 V to operate correctly.

The difference to the rated voltage is dissipated as heat as per P = U * I, with U being the voltage difference, and I the current pulled by your circuit.

You can use the switching power supply directly, or use a more advanced voltage regulator like the R-78E5.0 directly from 9 V, which has far lower losses.

Another option would be using the 5V from the switching transformer to drive the (less delicate) relays, and use the 7805 only for the MCU and display, but you would still want to use a heat sink in that case.


My DS18B20 is reading high. How can I get it to return the correct temperature? I am working on a heating control system for my home, but having problems with the temperature sensor reading higher than I expect.

I have a 5V Arduino Mini Pro clone hooked up to a relay module, an HD47780 display and a Tiny RTC module, with a DS18B20 attached to it.

The DS18B20 is powered from the 5v Vcc applied to the Tiny RTC module rather than using parasitic power on the DQ line (as I wasn't sure if the Onewire libraries supported this mode of operation) and the DS18B20 datasheet says that Vcc may be between 3.0v and 5.5v. I measured the regulated power from the Mini Pro's  being at 5.2v.

I am comparing the temperature from the DS with the existing room thermostat (bi-metallic), an RS desktop temperature monitor with two sensors, a small 'thermo-hygrometer' and a bi-metallic fridge thermometer (in the upper quarter of its temperature range)†. The readout from the DS is always around 1-2 degrees higher than the readout from the other sensors, which are within a degree of each other.

† Not the actual one, but something similar.

Reading various forums I have heard that these sensors are quite accurate but can suffer from localised heating from components near them, so I moved the sensor onto a 20cm cable and positioned it well away from the rest of the electronics. This made no difference.

I then read that the DS can become self heating if it is supplied with too high a Vcc voltage, so I added a Red LED with 1.7v drop and measured the new voltage over the DS as 3.5v, but again, after waiting for the temperatures to stabilise once more, this made no difference.

Can anyone suggest why the DS may be reading high and what I can can do to prevent this?

I've put a lot of DS18B20 sensors in place now on various sensor nodes - maybe 50 or so. I've learnt a bit about the readings returned from them. I know you have isolated some of these as not being the cause, but it is good to confirm that they are issues.

I don't know if you are using Celsius or Fahrenheit, so the degree of the problem isn't clear.

Localised heating

I don't think of Arduino as a "hot" chip, but putting a DS18B20 in an enclosure with an Arduino and LCD caused me to see readings 2-3°C higher than expected.

Moving it outside the enclosure fixed this.

Heating from high Vcc/frequent conversions

If you supply the chip with a high Vcc and perform frequent conversions (i.e. as frequently as you can), the chip does warm up. I have seen this increase readings by 1-2°C.

I haven't seen the problem with high Vcc alone, but I operate most DS18B20 in parasitic mode and convert at most once every 10s. The ones operated in active mode generally have the powered turned off when not being used.

OneWire and DallasTemperature do support parasitic mode.

Not all temperature sensors are created equal

I had a number of temperature sensors before I started playing around with DS18B20. Almost without exception, these under-read. Most of them are based on thermistors and calibration is poor. I thought the DS18B20 were over reading, but when I used a good thermocouple and meter, I could validate that they were correct.

This was about learning to trust the DS18B20.

Heat conducted along wire

If you have the sensors on a wire, the wire conducts a surprising amount of heat. This can be an issue when running wiring along pipes.

Fake DS18B20

These sensors are very popular, and this seems to have caused fakes to appear. I have a batch of stainless steel waterproof sensors that over-read and the timings were out. They worked with the OneWire library, but not a DS2482 OneWire master. I have heard of the normal TO-92 cased ones being fake as well.


Pressure transducer / sensor (0.5 - 4.5V) innacurate analog pin readings I have a relatively cheap 0-15psi pressure transducer. It has 3 pins - ground 5V and signal. The signal outputs a voltage of 0.5V to 4.5V based on pressure from 0psi to 15psi. I can verify it does respond to significant pressure increases so it works at least to a point.

The issue is that the reading from arduino can differ by over 50% when at ambient atmospheric pressure (resting on a table). It should be significantly more accurate if the sensor data are to be trusted. The code is basic:

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

void measurePressure(){
  int rawReading = analogRead(A0);   // Range : 0..1024
  //float rawVoltage = (rawReading * (4.5 / 1023.0)) + 0.5;

  Serial.print("Raw reading: ");
  Serial.println(rawReading);

}

void loop() {
  measurePressure();
  delay(1000);
}

The output variations are not entirely random, it seems that the reading goes down and up in intervals of roughly 5-15 seconds. Below is a sample output:

Raw reading: 61
Raw reading: 67
Raw reading: 70
Raw reading: 73
Raw reading: 74
Raw reading: 78
Raw reading: 75
Raw reading: 82
Raw reading: 85
Raw reading: 90
Raw reading: 89
Raw reading: 97
Raw reading: 103
Raw reading: 119
Raw reading: 146
Raw reading: 165
Raw reading: 171
Raw reading: 168
Raw reading: 163
Raw reading: 150
Raw reading: 143
Raw reading: 118
Raw reading: 88
Raw reading: 70
Raw reading: 62
Raw reading: 64
Raw reading: 72
Raw reading: 78
Raw reading: 80
Raw reading: 82
Raw reading: 88
Raw reading: 92
Raw reading: 102
Raw reading: 134
Raw reading: 160
Raw reading: 170
Raw reading: 172
Raw reading: 166
Raw reading: 158
Raw reading: 149
Raw reading: 132
Raw reading: 100
Raw reading: 73
Raw reading: 63
Raw reading: 61
Raw reading: 71
Raw reading: 77
Raw reading: 79
Raw reading: 84
Raw reading: 90
Raw reading: 90
Raw reading: 99
Raw reading: 134
Raw reading: 161
Raw reading: 170
Raw reading: 166
Raw reading: 161
Raw reading: 151
Raw reading: 133
Raw reading: 103
Raw reading: 81
Raw reading: 68
Raw reading: 63
Raw reading: 63
Raw reading: 71
Raw reading: 73
Raw reading: 81
Raw reading: 83
Raw reading: 85
Raw reading: 89
Raw reading: 98
Raw reading: 128
Raw reading: 161
Raw reading: 171
Raw reading: 166
Raw reading: 159
Raw reading: 145
Raw reading: 120
Raw reading: 85
Raw reading: 67
Raw reading: 57
Raw reading: 63
Raw reading: 72
Raw reading: 75
Raw reading: 83
Raw reading: 85
Raw reading: 89
Raw reading: 97
Raw reading: 130
Raw reading: 164
Raw reading: 172
Raw reading: 163
Raw reading: 155
Raw reading: 135
Raw reading: 101
Raw reading: 69
Raw reading: 60
Raw reading: 62
Raw reading: 72
Raw reading: 78

I tried adding 4.7k pull down resistor with no change but that was just a blind try. I have a multimeter connected as well and the reading seems to be more stable ranging from about 0.495V to 0.535V (variations do not seem to match arduino output).

What could be causing the issue?

I tried same setup with arduino uno and the problem is gone. It also works on micro as long as gnd and 5v pin is connected to uno. Uno measured voltage is 4.88V and micro 4.60V could a voltage difference this small cause this? What else could this be?

Reinstatement of incorrect edits by Annonomus Person
(AP: Please do not edit answers in such a way that you entirely change their meaning. In the current discussion "the board" is meaningless. We are trying to distinguish between symptoms seen in two different 'boards', an Arduino Uno, and an Arduino Micro.)

Looks to me like the problem is with the Arduino Micro's 5V supply then.

If you are powering the Micro from an external supply (not USB), then 4.6V on the Micro's "5V" output would indicate that the 5V regulator is not operating within its expected range.

If you are powering from USB, then the regulator is not in play. The 4.6V would indicate a problem with the USB's 5V supply.

Likely possibilities:, either the upstream supply is inadequate, or the micros and whatever is attached to it is drawing too much current.

I suspect that the transducer output is fluctuating in a way that's too rapid to be seen by your meter, but which is sampled by the Arduino Micro, giving your varying result numbers.

Either the "4.6V" is inadequate to run the transducer, causing erratic transducer output, or the 4.6V itself is fluctuating, with similar results at the trans output.

And you might also check the ground between micro and transducer -- are you sure that's wired correctly?


HID with bidirectional communication I want to build a gamepad HID using the Arduino Micro, and intend to use Nico’s HID library for that.

But I would like to send some config info from the PC to the Arduino HID as well.

Can you have a gamepad that not only sends state to the PC, but also receives a configuration from the PC?

I intend to use this with a Linux PC as host.

Yes, but the configuration side of things will not be part of the gamepad HID.  You will need to set up a second communication channel - be that serial or raw HID - to do the configuration.


Arduino with HC 08 bluetooth module I am connecting Arduino Uno R3 with HC 08 module lie following

Arduino 5v -> HC 08 Vcc
Arduino gnd -> HC 08 gnd
Arduino Pin 5 -> HC 08 RXD
Arduino Pin 6 -> HC 08 TXD

Then I connected two LEDs to 9 and 10 pins

Then loading following sketch.

#include <SoftwareSerial.h>

int availableLEDpin = 9;
int notAvailableLEDpin = 10;
SoftwareSerial hc_08(5, 6); // RX-5, TX-6
void setup() {
  pinMode(availableLEDpin, OUTPUT);
  pinMode(notAvailableLEDpin, OUTPUT);
  Serial.begin(9600);
  hc_08.begin(9600);

}

void loop() {
  hc_08.listen();
  if (hc_08.available()) {
    Serial.println(hc_08.read());
    digitalWrite(availableLEDpin, HIGH);
    digitalWrite(notAvailableLEDpin, LOW);

  }
  else {
    digitalWrite(availableLEDpin, LOW);
    digitalWrite(notAvailableLEDpin, HIGH);
  }
  delay(100);
}

I am trying to connect to bluetooth from y iOS application. The application is searching and connecting to the HC 08 correctly. And sending data successfully - Swift code log showing sent successfully.

But back in Arduino, always led connected to pin notAvailableLEDpin is glowing and nothing is printing in serial monitor. What is wrong with my implementation?

You have the receive port on your arduino connected to the receive port on your bluetooth module. Connect pin 5 to the Tx on your module and connect pin 6 to the Rx on your module.


Can i use Arduino IDE with the Wemos D1 R2 AND also use its ESP8266 module to send AT commands? I have recently started digging into ESP8266 and learned a little about AT commands and i would really like to add the Wi-Fi functionality in my electronics project, which already uses an Arduino UNO R3. I think it would be much easier to use the Wemos D1 R2 since it is basically an UNO + ESP8266. Here is a link to the official product information page: https://wiki.wemos.cc/products:d1:d1 and its schematic: https://wiki.wemos.cc/_media/products:d1:d1_v2.0.0.pdf

I would like to know if it's possible to use the Arduino IDE to program on the Wemos D1 as i do with the normal UNO but also at the same time, be able to send AT commands using its on-board ESP8266?

A year ago I ported my project from Uno with esp8266 (Uno WiFi Dev Ed) to Wemos D1 R2.

Wemos D1 R2 board has esp8266 as the only MCU. The AT firmware is an application running in the esp8266. An Arduino sketch with esp8266 boards package is an application too, so it replaces the AT firmware.

Instead of AT commands you will use for networking the WiFi library of the esp8266 arduino package. It is much simpler and there are many examples.

The esp8266 and the D1 R2 board have 3.3 V logic level on pins. So be careful with inputs and check if your devices will read the 3.3 V as HIGH.

In code use Dx constants matching the labels on the board. D1 R2 has less pins then Uno. I recommend to use I2C devices if possible. I had a Grove Base shield on D1 R2, so I have a mapping of D1 R2 pins to 'Uno' pins.

Some of the esp8266 pins are read at boot as boot configuration. Pins D3 (io 0)
and D4 (io 2) have pull-up on board and pin D8 (io 15) has pull-down on board. Not all devices will work on this pins. Here is a pin overview of the NodeMcu and Wemos boards.

The esp8266 has only one ADC pin. The A0 of the esp8266 can read 0 to 1 V. Wemos boards have a voltage divider on A0 so the board's pin can read 0 to 3.3 V. Don't read A0 in every loop. WiFi part of the esp8266 uses the ADC hardware too and continuous reading of A0 interferes with WiFi operations.

The Wemos D1 R2 has a strong power regulator 7 to 20 V for Vin and power jack. You can power devices from 5V and 3.3V pin. I use Grove relay modules powered from 5V pin and controlled by logic signal at 3.3 V.


How to convert String to byte array I have the code, it's purpose is to receive the string from a comport like:
Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
and translate it into four byte arrays byte user1[16], user2[16], pass1[16], pass2[16]. Here's the code:

String inString = ""; // COM port incoming data buffer

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Start");
}

void loop() {
  // put your main code here, to run repeatedly:
  // Receive data from com port
  while (Serial.available() > 0) {
    int inChar = Serial.read();

    if (inChar != '\n') {
      inString += (char)inChar;
    } else {
      // New line
      String Action = inString.substring(0, 3);
      if (Action == "Set") {
        SetCard(inString);
      } else if (Action == "Get") {
        Serial.println("1");
      } else {
        Serial.println(Action);
      }
      inString = "";
    }
  }
}

void SetCard(String Data) {
  Serial.println(Data);
  // Data Set@user1@user2@pass1@pass2
  // Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
  byte user1[16], user2[16], pass1[16], pass2[16];

  String user1str = inString.substring(4, 20);
  String user2str = inString.substring(21, 37);
  String pass1str = inString.substring(38, 54);
  String pass2str = inString.substring(55, 71);

  Serial.println("Strings");
  Serial.println(user1str);
  Serial.println(user2str);
  Serial.println(pass1str);
  Serial.println(pass2str);

  Serial.println("Arrays");
  user1str.getBytes(user1, 16);
  user2str.getBytes(user2, 16);
  pass1str.getBytes(pass1, 16);
  pass2str.getBytes(pass2, 16);

  writeByteArray(user1, 16);
  writeByteArray(user2, 16);
  writeByteArray(pass1, 16);
  writeByteArray(pass2, 16);
}

void writeByteArray(byte array[], int arrlength)
{
  for (int j = 0 ; j < arrlength ; j++) //print the block contents
  {
    Serial.write (array[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
  }
  Serial.println("");
}

When I run this code and send my string through a com port I expect the output:

Start
Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
Strings
1234567890123456
1234567890123456
1234567890123456
1234567890123456
Arrays
1234567890123456
1234567890123456
1234567890123456
1234567890123456

And yet, I receive

Start
Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
Strings
1234567890123456
1234567890123456
1234567890123456
1234567890123456
Arrays
123456789012345
123456789012345
123456789012345
123456789012345

Why? And how do I receive desired output?
getBytes docs

Why? And how do I receive desired output? getBytes docs

The String member function getBytes() will null-terminate the string. You must add space for that.

  byte user1[17], user2[17], pass1[17], pass2[17];
  ...
  user1str.getBytes(user1, sizeof(user1));
  ...
  Serial.print((char*) user1);

That should do the trick.


Arduino Uno board with male header pins I am currently working on a project that would greatly benefit from an arduino uno board with male headers soldered on instead of the female connectors. My question is hence extremely simple, yet I was not able to find an answer myself. Are there uno formfactor boards out there, with male header pins. I have found versions without headers for other boards, but not for the uno. Since I have already designed and 3d printed an enclosure that fits the uno and want to lower the overall height this seems like the easiest way to achieve this.

I often unsolder the female connectors to solder wires directly. I would simply unsolder then and solder male headers in their place.


Ideal power supply for ESP8266 What is the ideal power supply for this module? What do you use that works ok?

Will the AMS1117 work?

Yes, that will work. However, ignore the entire description.

That is NOT a buck regulator - it is a low-dropout linear regulator.  Thus it will waste power as heat - the more current you draw the hotter it will get.

The '1117' range of regulators are pretty much ubiquitous. I use them in a wide range of products and situations where power consumption isn't critical (i.e., not battery based products).

For lower power requirements you want to get a real buck regulator. Something more like this: http://www.ebay.co.uk/itm/301842020065

Note that it's an adjustable module, and you will need to first use a multimeter to adjust the output to 3.3V before you connect it up.

Because they are adjustable they are a great thing to keep around since you can use them for all sorts of different situations.


Distance from Arduino UNO to LCD: How far? How far from the UNO can I place an LCD (the typical 16x2)? Assuming that everything that is plugged into the LCD comes directly from the Arduino (power and data).

I'd like to mount the LCD on the wall at eye level, my "box" will be on the floor, close to a power source.

The actual distance depends highly on several other factors:

Wire thickness / current carrying capacity / resistance
RFI (Radio Frequency Interference) environment
Data rate that you write to the LCD (Maybe you are using an I2C or SPI backpack)

In general, even 5 meters is probably going to work if you use sufficient wiring, but try it and see.

You may also need to add shielding to mitigate RFI.


Does RFID-RC522 supoort tk4100 chip protocol ISO18000-2C 10 digital ID card? I have ordered a starter kit and received RFID reader is

  RFID-RC522

module with one card and tag now I need more RFID card for my project and I can't find the supported card type for my project please can any one tell me supported card types and if this card supports my device this is the card type

  tk4100 chip protocol ISO18000-2C 10 digital ID number

The MFRC522 on your kit is designed to communicate with ISO/IEC 14443 A/MIFARE and NTAG cards.

Search for Mifare Classic or Mifare Ultralight or NTAG213, NTAG216 ... cards.


How can I connect multiple MCP23017's to an arduino? I am working on a project and I am trying to figure out how to connect multiple MCP23017 IO Expanders to one arduino. All of the guides that I have found in my quest for information only explain how to connect one MCP chip or how to address multiple MCP chips. None seem to explain how to connect them physically. BTW, I am talking about the I2C version of the chip.

If you know how to connect one chip you know how to connect many chips.  One or eight it's the same.

All the SCL pins connect to the SCL pin of the Arduino. All the SDA pins connect to SDA on the Arduino.

Just make sure that each chip is given a unique address using the A0-A2 pins as detailed in the datasheet.


ld.exe:linker_script.ld:138 cannot move location counter backwards | ArduinoFFT Error Board: Arduino Nano 33 BLE Sense
I'm pulling PCM data from an onboard microphone and running it through the arduinoFFT library (version 1.5.6) to obtain a spectrogram. Since the arduinoFFT library requires the data be an array of doubles, I've converted the data from short to double, and started the FFT process. The FFT.Windowing() function worked fine, but I get the error at the FFT.Compute() function call (line 77). The error goes away when I remove the function call. The error:
Found 25 compatible libraries
Scanning dependencies...
Dependency Graph
|-- <arduinoFFT> 1.5.6
|-- <PDM> 1.0
Building in release mode
Linking .pio\build\nano33ble\firmware.elf
c:/users/benlu/.platformio/packages/toolchain-gccarmnoneeabi/bin/../lib/gcc/arm-none-
eabi/8.2.1/../../../../arm-none-eabi/bin/ld.exe:linker_script.ld:138 cannot move location counter
backwards (from 000000002004a470 t
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\nano33ble\firmware.elf] Error 1

And the code:
#include "Mic.h"
#include <arduinoFFT.h>

// FFT

arduinoFFT FFT = arduinoFFT(); /* Create FFT object */
/*
These values can be changed in order to evaluate the functions
*/
const uint16_t samples = 16128; //This value MUST ALWAYS be a power of 2
const double signalFrequency = 16000;
const double samplingFrequency = 16000;
const uint8_t amplitude = 100;
/*
These are the input and output vectors
Input vectors receive computed results from FFT
*/
double vImag[samples] = {0};

// buffer to read samples into, each sample is 16-bits
short* sample_buffer;

// number of samples read, read from Mic class on loop
volatile int samples_read;

// The length of the buffer to use. Currently set to 4 seconds.
int buffer_size = 16000;
double double_buffer[16384] = {};

// Instantiate
Mic mic;

// DO NOT PRINT INSIDE THIS FUNCTION - Causes it to hang.
void onPDMdata() {
  mic.sample();
}

void setup() {
  Serial.begin(115200);
  while (!Serial);
  PDM.onReceive(onPDMdata);
  PDM.setBufferSize(16128);

  Serial.println("3...");
  delay(1000);
  Serial.println("2...");
  delay(1000);
  Serial.println("1...");
  delay(1000);
  Serial.println("Listening!");

  mic.begin();
}

void loop() {

  // wait for samples to be read
  samples_read = mic.samples_read();

  // If desired buffer size is reached.
  if (samples_read >= buffer_size) {
    // Retrieves audio buffer
    sample_buffer = mic.sample_buffer();

      // print samples to the serial monitor or plotter
      for (int i = 0; i < samples_read; i++) {
        double_buffer[i] = (double)(sample_buffer[i]);
        Serial.println(double_buffer[i]);
      }

    Serial.println("---------- SAMPLE BREAK ----------");

    FFT.Windowing(double_buffer, samples, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
    FFT.Compute(double_buffer, vImag, samples, FFT_FORWARD); /* Compute FFT <--------------------- THIS LINE */
    // FFT.ComplexToMagnitude(double_buffer, vImag, samples); /* Compute magnitudes */

    // delay for data collection only, comment when not collecting
    delay(1000);
    Serial.println("Listening!");

    // clear the read count and resume recording
    mic.clear_buffer();
  }
}

Where can I start to troubleshoot this issue? I've not had to deal with linker errors before, so any pointers would be greatly appreciated. Thanks in advanced!

Short Version
The short answer is that you've exhausted RAM.
These two arrays alone:
const uint16_t samples = 16128;
double vImag[samples] = {0};
double double_buffer[16384] = {};

...are occupying (16128 + 16384) * 8 == 260096 bytes of memory.  There's only 262144 bytes of RAM in entirety.
The way the linker script is set up at least 1024 bytes are reserved for the stack, and there is no doubt at least another kByte in use somewhere.  In the Mbed OS and Arduino core files if nothing else.
As for why it fails only when you call Compute, that comes down to the compiler optimizer discovering that one (perhaps both) of your arrays are not actually used and so not entering into the mix when the linker is run.
Details
In theory, you should have gotten a somewhat nicer and easier to understand message from an ASSERT in the linker script:
ASSERT(. <= (ORIGIN(RAM) + LENGTH(RAM) - 1024), "heap region overflowed into stack");

So, you should have seen an error "heap region overflowed into stack" on your screen instead, which is maybe not the easiest thing for an Arduino user to decipher, but heap and stack are terms likely to be recognizable as memory-related sooner or later.
However, the linker executable shipped with the current version 1.3.2 of the Arduino core for Mbed ignores ASSERT statements completely; I have tested this (and tested my understanding of my test using an amd64 linker).  Presumably, there's a build option for the linker or a command-line or configuration file option that controls that, but I haven't found it yet.  In any case, it ignores a helpful ASSERT and instead proceeds to fail on line 138 mentioned in the error message:
 . = ORIGIN(RAM) + LENGTH(RAM) - 1024;

You can see it involves the same expression, just without a useful message if something goes wrong.  The "location counter" in the message is a linker related term that roughly means "where the next thing will be placed in memory" as it cobbles together your final executable from separately compiled chunks.  You've used so much RAM in your program that the location counter has been pushed past where the linker script wants to place the __HeapLimit symbol, 1K from the end of the MCU's RAM.  The location counter is supposed to increase monotonically.  So, evaluating this expression results in an erroneous attempt to "move location counter backwards".


to increase the reading and writing/printing speed of data from Arduino Nano to Raspberry Pi 3B+ In my project, I have to read the input pin number(send by RPi), where 8 sensors are attached to Arduino Nano, after reading Arduino Nano send the real-time values of all sensors through serial USB communication. All is fine, but my problem is that I need to speed up the sending of data since it takes to long to read from Rasberry pi.
I put the delay of 70 milliseconds but if I try to reduce more than that, I encounter a problem i.e data overwrites. My baud rate is 115200.
Kindly help me with the code to make it fast.

int analogInputPin;
float voltage;

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

void loop() {
  // if any data on the serial port are available
  // read it and try to update the analogInputPin
  // based on the number that was read on the serial
  if (Serial.available() > 0) {
    analogInputPin = Serial.parseInt();
  }

  // read the analog value:
  int analogInputPinValue = analogRead(analogInputPin);
  voltage=(5./1023.)*analogInputPinValue;

  // print the results to the serial port:
  // the output should have the following form: INPUTPIN:VALUE
  // followed by a newline character
  Serial.print(analogInputPin);
  Serial.print(":");
  Serial.print(voltage);
  Serial.println("");

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

parseInt reads digits and stops after a non-digit characters occurs or the function times out because no next characters arrives. The timeout is at default 1 second. So this is where you loose time.

Simplest solution for your code is to send some non-digit character after the number sent from Raspberry. This will terminate parseInt immediately. Usual is to send a new line character. It will separate the numbers nice if you debug the communication with prints to serial terminal.

Not a very good option, but I mention it, is to set the timeout of blocking read functions like the parseInt to a smaller time with Serial.setTimeout(ms).

To really speed up the communication you would send the numbers in binary form and not as text like you do now.


Watchdog timer stuck in restart loop? (green led flashing) I am trying to set up a way to reboot arduino on command. The code below should do that but it seems like my arduino just get's stuck in some sort of a loop where I cant upload or get any serial output. The green led (pin 13) flashes very fast. The only way to stop this is to cut power to the device, even reset button does not work. This happens only when "R" is received via serial or if wdt_reset() function is commented out.

#include <avr/io.h>
#include <avr/wdt.h>

int ledPin = 3;

void setup()
{
  MCUSR=0;
  wdt_disable();
  Serial.begin(57600);
  Serial.println("BOOT!");
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  delay(500);
}

void loop(){
  if (Serial.available() > 0){
    char cmd = Serial.read();
    if (cmd == 'R'){
      Serial.println("R received!");
      wdt_enable(WDTO_1S);
      delay(2000);
      Serial.println("1 SEC.");
    }
  }
  wdt_reset();
  digitalWrite(ledPin, HIGH);
}

What am I doing wrong?

One of the most obvious issues here is that you are enabling the watchdog timer with a delay of 1S and then you are asking the micro controller to sleep for 2S, printing something and then going back into the loop. This, in theory, should be fine(your wdt should trigger a reboot during the 2 second wait) but I've seen it cause issues.

Additionally some bootloaders(notably the Optiboot bootloader on Uno and newer boards) can have issues with watchdog timers causing the wdt to remain enabled after reset even though the setup loop disables it. To start with - try increasing the wdt time to something greater than 2S(you should be able to do WDTO_8S) and see if the issue persists.

EDIT - The OP is using an Arduino Pro Mini clone. The included bootloader on the Arduino Pro Mini does not support system restarts by the WDT. Essentially, on a device with a bootloader that does not support WDT restarts, the board will restart but the timer / reset will not causing the board to continuously reset on reboot. There are alternative bootloaders for Arduino boards that may resolve this issue. Another solution is to use a different method to reboot the board.


What does it mean in I2C, "NACK received"? I am reading about I2C. On this site:

http://playground.arduino.cc/Main/WireLibraryDetailedReference#endTransmission

It says that endTransmission() can return one of the following status codes:

0: Successful send.
1: Send buffer too large for the twi buffer. This should not happen, as the TWI buffer length set in twi.h is equivalent to the send buffer length set in Wire.h.
2: Address was sent and a NACK received. This is an issue, and the master should send a STOP condition.
3: Data was sent and a NACK received. This means the slave has no more to send. The master can send a STOP condition, or a repeated START.
4: Another twi error took place (eg, the master lost bus arbitration).

If I attach nothing to my Arduino (or with pull-up resistors to both SDA/SCL), I always get status 2. But how can a NACK (or anything) be received when there is nothing to communicate with? Does it mean something else?

Here is my example code

#include "Wire.h"
void setup() {
  Serial.begin(9600);
  Wire.begin();
}
void loop()  {
  Wire.beginTransmission(42);
  Wire.write(0);
  byte status = Wire.endTransmission();
  Serial.println(status); // always prints 2
}

A NACK is signaled by an acknowledgement slot in which SDA remains high while SCL cycles under control of the master.

Since high is the un-driven state of the pulled-up bus, in the absence of a peripheral at the selected address to positively acknowledge by pulling it down, a NACK condition will passively result.


Pinout of Arduino 9 Axes Motion Shield I bought an Arduino 9 Axes Motion Shield without looking at the pinout. I'm worried it won't work with my Adafruit Motor Shield v1.

It seems the 9 axes shield uses I2C, a reset pin and several other pins for the TinkerKit Input, Output and TWI connectors. Does anyone have a list of specific ports used by the shield on the Arduino UNO?

It also seems that my Arduino UNO r1 only has the original analog pins for I2C, while the 9 axes shield uses the new pins next to the digital pins.

update: I asked support from arduino.org on twitter and on their forums, no reply yet and it seems their twitter account has been suspended. Should have bought a Genuino I guess.

The I2C pins on the V3 shield are just copies of A4 & A5 - so just run a jumper wire some way.

BTW that Motion shield looks like it only uses 1 interrupt pin in addition to I2C, so you may be ok.

The motor board does have a library at https://learn.adafruit.com/adafruit-motor-shield/downloads and you can look at the code to see what it uses.

I personally use the mpu6050 - same kind of thing, I2C one interrupt but only 6DoF (which is plenty).  The 6050 has been superseded with the 9150, 9DoF.  6050 break out boards sell for $6 (or less).  Actually I put all this together on one piece (http://www.spiked3.com/new-products/)


How do I make two (or more) pins available on my server url? I have a webserver configured on my esp8266 with is set to fire off electrical relay0 on my 8 port relay board.
The device initializes relay0 perfectly and without errors.
But when I configure the second relay1, i get no response from my second url.
//note, when you write to low, you turn the switchport on. It's backwards for some reason
#include <ESP8266WiFi.h>
#define statusLed 2   // built-in led for the ESP8266-12

const char* ssid = "myssid";
const char* password = "mypass";

int switchPin0 = 16;
int switchPin1 = 5;
int switch0;
int switch1;

WiFiServer server(80);

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

  pinMode(statusLed, OUTPUT);
  pinMode(switchPin0, OUTPUT);
  digitalWrite(switchPin0, HIGH);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  digitalWrite(statusLed, HIGH);
  Serial.println("");
  Serial.println("WiFi connected");

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

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

}

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

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

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

  client.flush();

  // Match the request

  int value = HIGH;
  if (request.indexOf("/SWITCH=0") != -1){
    digitalWrite(switchPin0, LOW);
    digitalWrite(statusLed, LOW);   // blink led
    delay(1);
    digitalWrite(statusLed, HIGH);
    //set water pump time here
    delay(8000);
    digitalWrite(switchPin0, HIGH);
    value = HIGH;
    ++switch0;
  } else if (request.indexOf("/SWITCH=1") != -1){
    digitalWrite(switchPin1, LOW);
    digitalWrite(statusLed, LOW);   // blink led
    delay(1);
    digitalWrite(statusLed, HIGH);
    //set water pump time here
    delay(8000);
    digitalWrite(switchPin1, HIGH);
    value = HIGH;
    ++switch1;
  } else {

    }

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("");

  client.print("Switch pin is now: ");

  if(value == HIGH) {
    client.print("Off");
  } else {
    client.print("On");
  }
  client.println("

");
  client.println("Switch 0");
  client.println("Click here  to send a measured amount
");
  client.println("Number of times plant 0 has been fed is ");
  client.println(switch0);
  client.println("

");
  client.println("Switch 1");
  client.println("Click here  to send a measured amount
");
  client.println("Number of times plant 1 has been fed is ");
  client.println(switch1);
  client.println("");

  delay(1);
  Serial.println("Client disconnected");
  Serial.println("");
  digitalWrite(statusLed, LOW);   // blink led
  delay(1);
  digitalWrite(statusLed, HIGH);

}

my counter will update, but the relay pin never fires for relay1. relay0 works fine. I can swap the ports and then the second relay will work and not the first. I just can't manage both.
How do I get a second (or more) relay ports to initialize via webpage?

It looks like you forgot to initialize switchPin1 to be an output.
Add the following to your setup() (for example, right after the corresponding initialization commands for switchPin0):
void setup() {
    ....
    pinMode(switchPin1, OUTPUT);
    digitalWrite(switchPin1, HIGH);
    ....
}


Perform function after a period of time I am working on a project that I am supplying with voltage an LED through a digital pin (26) and I want the LED to be switched off after 4 seconds.

I am using Arduino Mega2560 and I am programming it using Arduino's IDE version 1.6.10. I have installed the SimpleTimer library .zip method but it does not seem to function.

Code

#include <SimpleTimer.h>

SimpleTimer timer;

void setup() {
pinMode(26, OUTPUT);
digitalWrite(26, HIGH);

timerId = timer.setTimeout(4000, switchOff);
}

void switchOff() {
  digitalWrite(26, LOW);
}

void loop() {
}

The problem is that the LED stays just on (digitalWrite(26, HIGH);) instead of going to the switchOff function and turning off (digitalWrite(26, LOW);). I have also tried using Timer1 and Timer libraries but they also do not work. Can someone who has made any of the libraries work, provide me with some guidance?

You have to call timer.run() inside loop function.

The SimpleTimer library is more like a scheduler. You call at every so often, and it checks if there is any event that has expired.


Conditional compilation, how to determine whether a variable has been declared? Whilst using #if/#end constructs, how can I determine whether a specific variable has already been declared?,
e.g.,

#if [the variable "pinname" has been declared]
Serial.print(F("Pin name: "));
Serial.println(pinname);
#end

If this question has been addressed, I cannot find a reference for it.

Normally you use the "#ifdef" directive.

The opposite is "#ifndef".

For example, if you only wanted to include variable definitions once many use this pattern for a header file named, say, "my_variables.h":

#ifndef MY_VARIABLES_H
#def MY_VARIABLES_H

int counter;
bool flag;

#endif

In this way, no matter how many times you include this file, you only define the variables once.  Because after the 1st time the compiler sees this file, the variable MY_VARIABLES_H is defined and the subsequent time the compiler sees this file, the compiler will skip over the variable defines.


When are global constuctors executed? Apologies if this has been discussed before but I couldn't find anything.
I have written a simple LED class. For illustration (it is actually a bit more complex) but it goes something like;
class LED {
    LED(byte pin);
  private:
    int _pin;
};

And the constructor is simply;
LED::LED(byte pin) {
    _pin = pin;
};

and I create a global instance of this class at the top of my code thus;
LED redLED(5);

It is necessary to create this as a global object because (a) I can't create the object in the setup() function because it would go out of scope and (b) I can't create in the loop() function because I don't want to create an infinite number of these objects.
This all seems to work OK but it just leaves me wondering exactly when this constructor gets executed? I suppose that it must be before setup()?
Answered!
Many thanks to all the respondents. So when using the Arduino IDE the build process must silently insert the main() procedure. I was not aware that it did this. I guess that most of the time you can get away with not knowing when the global constructors are called.
It is good practice (I think) to create a "wrapper" class for all/any external (or perhaps internal) hardware devices that are connected to your arduino. And it is thus perhaps tempting (but risky) to do initialisation work in the constructor.
So given what I now know, it is better to create an "init()" method for such classes that can be called from setup(). Even if just to do the the pinmode() call.
Thanks again.

The global constructors run right after the initializations performed by
the C runtime startup code, and right before main() gets called.
In a nutshell, the C runtime initialization code:

does some low-level initializations (e.g., setup the memory)
calls the global constructors
calls main(), which in turn

calls init() to do the Arduino-specific initializations
calls setup()
repeatedly calls loop()

The fine details are probably platform-specific. For AVR-based boards,
they are documented in the avr-libc manual.