Arduino code not working Basically its an arduino project in which i am using an analog temperature sensor ky 013. The sensor is reading the temperatures correctly but what i want is to print the temperatures showed on the serial monitor to a lcd screen. I did the wiring and everything correctly  but there is something wrong with the code which i couldnt figure out.
Here is the code.

#include <math.h>

#include <LiquidCrystal.h>
LiquidCrystal lcd = LiquidCrystal(12, 11, 5, 4, 3, 2);

const int sensorPin = A0;
int switchState=0;

double Thermistor(int RawADC)
{
    double Temp;
    Temp = log(((10240000/RawADC) - 10000));
    Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
    Temp = Temp - 273.15;
    return Temp;
}

void setup()
{
    Serial.begin(9600);
    lcd.begin(16, 2);
    pinMode(sensorPin,INPUT);
}

void loop()
{

 switchState=digitalRead(sensorPin);
 int readVal=analogRead(sensorPin);
 double temp =  Thermistor(readVal);
 Serial.print("Temp. : ");
 Serial.print(temp);
 Serial.println(" Celsius");
 lcd.clear();
 lcd.setCursor(0,0);
 lcd.print("Temp: ");
 lcd.print(temp);
 lcd.print(" C");
 delay(500);
}

Please format your code.  I know it takes longer, but the payoff is in readability and maintainability.  It's well worth the extra effort.

LiquidCrystal lcd = LiquidCrystal(12, 11, 5, 4, 3, 2);

const int sensorPin = A0;
int switchState = 0;

double Thermistor(int RawADC)
{
    double Temp;
    Temp = log(((10240000 / RawADC) - 10000));
    Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp)) * Temp);
    Temp = Temp - 273.15;
    return Temp;
}

void setup()
{
    Serial.begin(9600);
    lcd.begin(16, 2);
    pinMode(sensorPin, INPUT);
}

void loop()
{
    switchState = digitalRead(sensorPin);
    int readVal = analogRead(sensorPin);
    double temp = Thermistor(readVal);
    Serial.print("Temp. : ");
    Serial.print(temp);
    Serial.println(" Celsius");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Temp: ");
    lcd.print(temp);
    lcd.print(" C");
    delay(500);
}

I think the problem is the

lcd.print(temp);

Try casting it to a float from a double (and two decimal places).  Maybe you just need the decimal places.

lcd.print((float)temp, 2);


Arduino MKR Zero problem with new UART comunication I'm currently using an Arduino MKR Zero board and I need to add a new communication because the Serial1 on pins 13 and 14 is already used by another device.

I've followed this tutorial from Arduino official website to create a new serial communication, but using the given code I have no communication on pins 0 and 1.

The code compiles, but it doesn't work when uploaded to the MKR Zero board.
I've noted that IrqHandler() is not highlighted in my Arduino IDE (it remains black).

So, should I install some library?

Thank you.

When a library does not highlight, it might be that the library is not coded to be highlighted (see here).

If you installed the library yourself, you may have put it in the wrong path.


Fastest communication between Arduino and PC I am using an Arduino 2 which collects data from a set of microphones and stores it in an array of unsigned short of 40000 elements and sends them to the PC via Serial USB.

It is working but I'd like to obtain more speed without any errors.

Can you suggest me the best way to do it? Even changing communication.

Thank you

Switch to using SerialUSB instead and use the other USB port. The baud rate is meaningless then - it runs at the speed of the USB port, which is a lot faster than serial (Linux reports it as 480Mbps, though I can't see an 84MHz chip doing that...).

void setup() {
    SerialUSB.begin(115200); // The number is irrelevant but it needs something in there
}

void loop() {
    SerialUSB.println(millis());
    delay(100);
}

For greater throughput you could devise some packet-based binary protocol to optimize your data flow to use less bytes.


TFT and SD don't work together I use a 2.8" TFT Touch Shield v1 and I want to read some data that were stred in sd and plot them with the tft.

When the following code is ordered, to access the data. TFT freezes.... but the code's execution is continued...

    pinMode(SS, OUTPUT);
    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
       Serial.println("Card failed, or not present");
    // don't do anything more:
       while (1) ;
    }

    Tempfile = SD.open("DATALOG.TXT",FILE_READ);
    if (! Tempfile) {
       Serial.println("error opening datalog.txt");
    // Wait forever since we cant write data
       while (1) ;}

I tested the code on the example of the tft graphics test... and the result was a freezed tft...

I tried also to run the example: tftbmp but the tft remains black. Once again the code is executed in the loop as i receive results from the Serial monitor but tft is black...

I use an Arduino Uno R3.

Any tip is welcomed

old topic, but since I'm having the same issues I'll share what I found.

chipSelect is usually 10 for arduino uno, some exemples have other pin setted.

also I found a guy claiming he fixed his issues setting after

pinMode(SS, OUTPUT);
digitalWrite(SS, HIGH);


Wemos D1 doesnt drive Relay I recently bought a Wemos D1 board and tried to connect a relay and test its connection.

I got an example server from here and executed. I connected D5 to a Relay's data and 5v and GND from Wemos board.

But this does not change the state of relay, it always remains high. I connected a LED for D5, it works perfectly with client's response.

Then I powered relay using an external 5v and ground connection, but the same result.

I have checked for possible solution, but coulnt find an answer.

The relay I am using is this one

The board which you are using is operating on 3v3. Even if you try to run the relay using the D5 or any other pin on the board, you may not be able to run it successfully at all times. In this case, you can go for either MOSFETs or Pull-up resistors so that you can hold the voltage to 5V for triggering the relay. I would personally suggest to go for a PNP type.

As requested by Sachith, here is the circuit suggested for the problem stated. Just note that the voltage source should be +5 V (which is +1 V in the schematic). Also, the MOSFET is not the specific one, it is just for the schematic purpose.

simulate this circuit – Schematic created using CircuitLab


How to load page from SD card and still show live data from sensors? I am just wondering, how can we display page from SD card and still show live data from sensors?

I have web server running on Arduino mega using ethernet shield, in my sketch I am doing client.print to build content of a page being displayed, and refreshing it display live data.

But I can't think of a way how can I load page from SD card and display data from sensors.

Based upon this W3C example you can have w3-include-HTML.js file with the following contents:

function w3IncludeHTML() {
  var z, i, a, file, xhttp;
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    if (z[i].getAttribute("w3-include-html")) {
      a = z[i].cloneNode(false);
      file = z[i].getAttribute("w3-include-html");
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          a.removeAttribute("w3-include-html");
          a.innerHTML = this.responseText;
          z[i].parentNode.replaceChild(a, z[i]);
          w3IncludeHTML();
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      return;
    }
  }

Now you can put this in your .html file:

and then you can use something as:

server.on("/generated_data.html", live_data);

If you want to be able to use server.on() you must include <ESP8266WebServer.h> but you can serve the content the way you like. You can examine the ESP8266WebServer::on() method source code and adapt it according to your needs or you can just use that method as is.

Everything until now will result with calling the live_data() function and inserting it's response into the div which has the attribute w3-include-html="generated_data.html".

Now you only need to generate the live data inside the live_data() and to send the response:

void live_data() {
  String data_from_sensor;

  // read here the data from some sensor and store it in data_from_sensor
  String response = "
Live data

The data is: " + data_from_sensor + "some unit
";
  server.send(200, "text/html", response);
}

And that's it. The live data generated inside live_data() will show where was the empty div with w3-include-html attribute.

Of course, you can have more divs with different w3-include-html attributes and belonging server.on() statements.

There are many ways, this is just an example so you can get an idea from where to start. This code will not update the live data on and on but now that you know the mechanism, you can modify the code to do whatever you like.


How can I detect a disconnected pin? I'm trying to build a system where if a cable gets disconnected from a pin (any pin), an action is executed.

I am wondering how to set this up. Can I simply wire the 5V to a pin and read its status or will this mess up the Arduino? Should I use any resistors? How should I connect this to the GND?

Please bear in mind that I'm pretty new to all of this.

The way to do this, since there is no digital value in between HIGH and LOW, is to actively create a signal on the pin you can recognise.  Note that if the signal coming in to the pin is a datastream (a sequence of HIGH and LOW) that runs all the time this may not work reliably, but it's good for things like buttons and other simple sensors.

Any signal on a wire has a drive strength.  This is basically how powerful the signal is and how good it is at overriding other things happening on the same wire.  It is closely related to the output impedance of the source (what is sending the signal).  For things like buttons and switches that is basically the value of the pullup resistor used.

To actively sense if a pin is disconnected or not you need to temporarily connect it to a known signal level at the same time as it's connected to the wire (or not connected if it happens to be not connected).  This known signal level has to be of a weaker drive than the source signal by several orders of magnitude.  This ensures that if you try superimposing your test signal over the incoming signal the incoming signal swamps out the test signal and you don't see it at all.  For instance, if your source has 10KΩ impedance (say a button with 10KΩ pullup resistor) then a test signal with source impedance of 1MΩ would be suitable.

Each pin to be tested can be connected to its own 1MΩ (in this example) resistor, and those resistors are all connected to the same extra IO pin:

In this example pin D2 is the test pin, and pins D4-D7 are your inputs.

So under normal circumstances pin D2 is set as an input and completely ignored.  When you come to test the pins, though, you set it as an output.

You then set D2 to be HIGH and read each of D4 through D7.  Any that read as HIGH are candidates for being not connected.

You then set D2 to be LOW and read the pins that read HIGH before.  Any that now read as LOW are disconnected.

You then set D2 back to being an input again so it doesn't interfere with normal operations.

If you just want to know if current is flowing in a wire you can use what is called a shunt resistor.  This is a small resistor (maybe 1Ω) that is placed in-line with the wire and you measure the voltage (using Arduino analog inputs) at both sides of the resistor.  The voltage dropped across the resistor is directly proportional to the current flowing through it thanks to Ohm's Law:

  I=V/R

For instance:

If the voltage read by A1 should be 5V (the voltage the wire is connected to) and the voltage read by A0 should be 4.93V, the voltage dropped by the resistor would be 5-4.93 = 0.07v.  With the 1Ω resistor the current would be 0.07/1 = 0.07A, or 70mA.

With the wire at OUT disconnected there will be zero current flowing since there is no circuit.  So re-arranging the formula above we can prove that we can tell it's disconnected.

If I=V/R then V = RI.  Therefore V = 1Ω × 0A = 0V.  So the voltage dropped across the resistor would be 0V, so A0 and A1 would be equal (discounting any noise). A0 and A1 would both read 5V.  Similarly, if the wire IN was disconnected instead then A0 and A1 would both read 0V.

For sensing higher currents you use a smaller resistance, and for sensing smaller currents you use a larger resistance - this allows for a voltage drop to be generated that is within a suitable range for the sensitivity of the ADC doing the reading.  For the Arduino that's a 10-bit ADC, so it can sense (with a 5V VREF) 5/1024=4.882813mV per LSB.

Note that if you are working with voltages above that at which the Arduino operates you will need to separate or otherwise scale those voltages.  There are special devices designed especially for this task called high side current shunt amplifiers.  They also allow you to use a smaller resistance than you would otherwise need which is less intrusive to your circuit (less voltage drop).


Uploading to atmega328 over serial with arduino bootloader running at 2MHz I want to run an atmega328 on a breadboard at 2MHz and upload to it via the serial pins (pins 2 and 3). So I am setting the clock divide by 8 fuse bit to enable this, meaning the atmega runs at 2MHz eith the 16MHz crystal. But I can't upload, probably because the bootloader is not expecting the clock to be running at 2MHz. The baud rates are probably mismatched by 8 times, the IDE is trying to upload at 57600 but since the bootloader code is not aware its being clocked at 2MHz, its probably running 8 times too slow. I've messed around a bit with the arduino conf files changing baud rates but had no joy. I was wondering if anyone knows how to do this off the top of their head.

Thanks, Pete

Unprogram the CKDIV8 fuse and add the following to the sketch instead, near the beginning:

#include <avr/power.h>

void setprescaler(void) __attribute__ ((naked)) \
  __attribute__ ((section(".init1")));

void setprescaler(void)
{
  clock_prescale_set(clock_div_8);
}

This will do essentially the same thing as the fuse, but won't interfere with the bootloader.


Print the response from GSM shield I have a GSM shield connected with my Intel Galileo board.

I intend to connect the board with serial communication at a baud rate of 115200 instead of the GSM library. I want to print the results of "at" commands in my serial window, how should I do it?

I have only worked with the SIMCOM series of GSM modules like the SIM900 and the SIM808. Here is a sample of the kind of code you should be looking at using.
It will send one "AT" to the GSM module and then it will spit out the result in the serial monitor.

void setup()
{
  Serial.begin(115200);
  int bytesSent = Serial.write(“AT\r\n”); //send "AT" and send the end of line characters to signify end of the command
 }

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


How to get the firmware (hex) file from a .ino file containing the code I currently have a .ino firmware file that I use in the Arduino IDE to program an ATmega328 micro-controller. I would like to get the file that the Arduino IDE uses to program the micro-controller.

Probably the IDE uses a hexadecimal (hex) file or something and sends it to the micro-controller through the serial.

How can I get this file being the only file that the IDE generates is the .ino?

You are asking how to locate the compiled hex file. It's easy! Follow these steps:

In the Arduino IDE select Sketch > Export Compiled Binary. This performs a compile. Once complete, this command places a copy of the compiled .hex file into the directory of your sketch.

Then either browse to the sketch folder or in the IDE select Sketch > Show Sketch Folder.

This generates two hex files for the target micro-controller; one with the bootloader and one without the bootloader. These hex files can be uploaded to the micro-controller using a programmer such as the Atmel Ice or AVRISPmkII.


Student Project Inquiry(Building a Self Balancing robot) I am currently building a self balancing robot using an L298N motors driver,and MPU6050 using an arduino microcontroller.

I managed to control my motors movements with no issues. After I extracted the data from my MPU6050 which was easy by using MPU6050 library I faced a problem: When linking the motors movement according to MPU6050 readings, the sensor freezes and stops showing its data on the serial monitor after giving couple of readings, the motors keep moving. I even have capacitors soldered into my motors to filter the noise. I am definitely sure my sensor works perfectly because it was tested before implemented into the motors drivers circuit and code.

If anyone can give me any hints why does the MPU sensor stop giving readings please.

Thanks.

The MPU6050 is an I2C device.  By default the Arduino uses the internal pullup resistors in the IO pins for the pullups on the I2C bus.

This is bad - it makes the I2C bus very susceptible to noise, and motors are very noisy devices.

You need to make sure you have appropriate pullup resistors on the I2C bus (3.3KΩ is good) and keep the I2C wires as short as you reasonably can.

Also keeping power sources as separate as possible is essential.  Don't be tempted to use the 5V power from the Arduino to power your motors - you must use an external power source, or the motors will cause havoc with the microcontroller circuitry and communications.


How do I calibrate an ESC after connecting it to an Arduino? I'm trying to connect an Arduino to an Electronic Speed Control and failing horribly. I'll explain what I've done so far, and then I'll explain the problem.

Before we get there, here's the list of parts I'm using:

Arduino Uno (genuine)
6V to 8.4V rated 18300 RPM 350 g-cm brushed motor.
Traxxas XL-5 brushed motor ESC. 1600 Hz is the highest PWM signal it accepts, if I'm not wrong.
Venom 4200mAh NiMH 8.4V battery pack (will replace soon with a 7.2V).

So I first connected the ESC to the motor. The connection is this bullet lead connection (the connection seems intact), and then the ESC to the Arduino. I connected the white wire to pin 9 and the black wire to ground. If I'm not wrong, this is the standard servo motor setup. I then plugged the Arduino into my computer, which has an intact USB port. Lastly, I connected the battery pack to the ESC.

Now I've tried to upload some basic code to try and calibrate my ESC, but it just plain our refuses to work. Under no circumstances will the motor run.
The code I'm using just sends the signal sent by the signal monitor.

I'm a complete noob to Arduino, so I don't know what could be wrong. The program I have in mind needs to be able to run while not connected to the computer, activate when a push-button switch is activated, run the motor for a certain distance (which involves an encoder, right?), and then stop.

Any pointers or things I could be doing wrong?

int value = 0;
Servo myservo;
void setup() {
    firstESC.attach(9);    // attached to pin 9
    Serial.begin(9600);
}
void loop() {
    myservo.writeMicroseconds(value);
    if(Serial.available())
        value = Serial.parseInt();    // Parse an Integer from Serial
}

and the one here:

#include <Servo.h>
#define MAX_SIGNAL 2000
#define MIN_SIGNAL 700
#define MOTOR_PIN 9
Servo motor;
void setup() {
    Serial.begin(9600);
    Serial.println("Program begin...");
    Serial.println("This program will calibrate the ESC.");

    motor.attach(MOTOR_PIN);

    Serial.println("Now writing maximum output.");
    Serial.println("Turn on power source, then wait 2 seconds and press any key.");

    motor.writeMicroseconds(MAX_SIGNAL);

    // Wait for input
    while (!Serial.available());
    Serial.read();

    // Send min output
    Serial.println("Sending minimum output");
    motor.writeMicroseconds(MIN_SIGNAL);
}
void loop() {
}

^shamelessly copied from the internet

The is a standard with RC connectors, that is Black always goes to ground white/orange goes to the signal and red/brown goes to 5V.

I don't know if you have made a typo, but you need to connect the white to D9 and the black to GND. Here is a instructables post, it describes using a brushed ESC step two reiterates the colour code standard.

You would also need a rotary encoder or shaft encoder to tell the distance moved, there are lots of ways to achieve this from simple(coded disk and IR arrangement) to custom made PCB add-ons.


Car dome light fading with arduino nano So I'm working on my car and now I've got my sights on the electrical system. I've installed a keyless entry system and a pulse timer for the dome light. Now, I'd like to give the dome light the fade effect all the modern cars have. After looking around, it seems an Arduino would be the most reliable.

I currently own an board similar to the Arduino Nano, specifically the SainSmart Nano. So I've determined that I'd power the board with a constant 12V, use pin 7 as input, and use pin 9 as output.

My code:

int domeLightIn = 7;
int domeLightOut = 9;
int brightness = 0;
int fadeAmount = 5;

void setup() {
  pinMode(domeLightOut, OUTPUT);
  pinMode(domeLightIn, INPUT);
  digitalRead(domeLightIn);

}

void loop() {
  // Case 1: State of Door: Open/Closed
  // Case 2: State of Switch: On/Off
  // Case 3: State of KES: Active/Inactive

  //Case 1: If door is closed and led is off, brightness remains 0;
  //Case 2: If switch is off and led is off, brightness remains 0;
  //Case 3: If KES is inactive and led is off, brightness remains 0;
  if (digitalRead(domeLightIn) == LOW && brightness != 255){
    brightness = 0;
  }

  //Case 1: If door is open and led is off, brightness will fade in;
  //Case 2: If switch is on and led is off, brightness will fade in;
  //Case 3: If KES is active and led is off, brightness will fade in;
  if (digitalRead(domeLightIn) == HIGH && brightness != 255) {
    for (brightness = 0; brightness < 255; brightness = brightness + fadeAmount) {
      analogWrite(domeLightOut, brightness);
      delay(35);
    }
  }

  //Case 1: If door is closed and led is on, brightness will fade out;
  //Case 2: If switch is off and led is on, brightness will fade out;
  //Case 3: If KES is inactive and led is on, brightness will fade out;
  if (digitalRead(domeLightIn) == LOW && brightness == 255) {
    for (brightness = 255; brightness > 0; brightness = brightness - fadeAmount) {
      analogWrite(domeLightOut, brightness);
      delay (35);
    }
  }
}

I am unsure whether I am using digitalRead() correctly along with wiring the input. So, am I doing this right? or perhaps there is a better way?

You're not using digitalWrite properly. You should do:

if (digitalRead(domeLightIn) == LOW && brightness != 255){

Just a sidequestion. What is pin7 connected to? If it's a 12v signal, you'd have to convert it down to 5v somehow.

Also, the 12v in the car can be up-to 14v, and can have some huge spikes. Not sure if the sainsmart's regulator can handle those spikes. It might die prematurely. It's also just wasting 60% (generating heat!), turning 12v to 5v. I would suggest adding one of those cheap car-phone-chargers.


Can a Ethernet USB Dongle be instead of ethernet shield for arduino? Can a Ethernet USB Dongle be instead of Ethernet shield for arduino in order to cut costs?


Arduino car on bluetooth remote appears to crash when motors started I built a Arduino robot car which accepts instructions via bluetooth. The instructions are pretty simple, they tell the car to stop, go forward, reverse, turn left or turn right.

When I have the car powered through the computer USB (ie when I have just uploaded the sketch), all works fine. However, when I run off independent battery power, the arduino seems to restart whenever I give the car an instruction which means the motors have to operate.

I know the sketch is restarting inside the Arduino because the blue tooth terminal displays the startup text which is inside the 'setup' function.

What is going wrong here? What issue am I encountering?

The board is an Arduino UNO with an Arduino Motor Shield attached. The blue tooth and two sonic sensors are attached to the motor shield pins.

Also, I have a 9V battery attached to the motor shield. Plus 4 times 1.5V batteries powering the UNO. Am I screwing up the power at all? Getting too much? Or too little?

it sounds like the motors are pulling down the battery voltage enough to reboot the Arduino; and the USB-port is able to supply enough current without as much voltage drop.

We'd need to see a schematic, but check that the power supplied to your Arduino and power supplied to the motors are completely independent; that the Arduino only supplies current to a switch or a relay in the motors' power circuit but not to the motors themselves.


DAC using Arduino Leonardo I am as new to Arduino as it can get. To start off, I am trying to build a DAC using an Arduino Leonardo. I have a digital signal coming from my dual differential comparator. I want to convert this to an analog signal.

First, I will read the digital signal in a digital pin (can someone point me which is good? There are so many of them. I was overwhelmed). Then I send out a PWM signal (confused with the pin again). Then I use a simple RC circuit to filter out the PWM signal to produce a simple sine wave.

Am I going towards the correct direction? If not, please any suggestion would be helpful.

Yes you are going in the right direction.

Comparators
You haven't as yet detailed how you plan to connect the 2 comparators to the Arduino, but I imagine it would be something similar to this:

simulate this circuit – Schematic created using CircuitLab

In the circuit above, X and Y are either high or low based on the analog voltages of A, B, C & D. I have created a truth table below with some arbitrary voltages to output. The value column corresponds to the value needed for the analogWrite() function.

Note: If you need your analog output to be able to source some current you can add an Op-Amp in a unity gain configuration at the output of the RC filter.

Examples To Read
To output the analog value, the 4 best suited inbuilt examples/tutorials to look at are:

Dimmer: Send serial values to change the brightness of an LED.
Fading: Use an analog output (PWM pin) to fade an LED.
Analog In Out Serial: Read an analog input pin, map the result, and then use that data to dim or brighten an LED.
Read ASCII String: Parse a comma-separated string of integers to fade an LED.

What all of these examples have in common is the analogWrite() function:

// writes the analog value (range from 0 to 255):
analogWrite(pin, value);

Dimmer is a simple example where a serial value is read and then output on one of the PWM pins.
Fading is probably the most basic example of using the analogWrite() function (PWM output).
I included Analog In Out Serial as it uses the map() command.
I included Read ASCII String as it shows how to parse multiple values on the serial string.

PWM Pins
You can use pins 3, 5, 6, 9, 10, 11, and 13 on the Arduino Leonardo to output the PWM using the analogWrite() function.

Control
I recommend the following tutorials for your control. You could either use the if-else command or the switch-case command.


Cheap LCD with Few Pins I am working on a project with an Arduino Nano that includes a keypad, screen, and the NRF4001 transceiver. The keypad requires 7 digital pins to operate, the wireless transceiver uses pins D9 - D13 with the RF24 library I am using. Now, that leaves me with 1 Digital Pin left for a screen unless there is an I2C screen I could use.

That would be easy enough to find except that I have some limitations. If at all possible I would like the screen to be under 5 dollars and about the size of a Nokia 5110. The Nokia uses to many pins and does not tolerate 5v logic levels I've heard. An OLED 0.96 inch is only a 4 bucks and is I2C, but it is too small. I could make a board for the keypad that used different values of resistors and one analog pin to detect different buttons but would rather not go that route if there is any easier way to get around this.

Are there any options out there that would suffice my pin, cost and size conditions or am I being too picky?

You can use a single analog pin to read an entire keypad.

First, read up on voltage dividers - they let you convert a resistance into a voltage. You will need to know this later on.

A keypad typically has 4 inputs, and 3 outputs (or vice-versa). Label the 4 pins A,B,C,D and the 3 pins E, F, G. You will be wiring A up to a voltage supply, and G up to an analog pin, and via a suitable resistor to ground. This becomes your voltage divider.

Then, put a resistor between A+B, B+C, C+D, and between E+F, F+G. So, if you press the button that connects A to G, there will be no resistance (=+5V). If you press the button that connects A to F, then the resistance will be that of the resistance F->G. If you press the button that connect D and E, the circuit goes: VCC-A-resistor-B-resistor-C-resistor-D-pushbutton-E-resistor-F-resistor-G - Arduino analog pin. With no button pressed, the voltage will be 0.

You will need to work out different resistors in advance, to give you as even a range as possible between 0 and 5 volts (the critical thing being the smallest difference). You can calculate the resistance of any combination here: http://www.calculator.net/resistor-calculator.html and you can use Ohm's law to calculate the final voltage. This depends on what you have in your kit. I ended up making a spreadsheet, and then trying random resistor values until I got a good spread.

DO NOT use any resistors under 1kOhm.

Once you have the right spread, make it up on a solderless breadboard. Measure the voltage with your arduino (use the "readanalogvoltage" sketch, take out * (5.0 / 1023.0) , and make up a table - press button 1, you get a reading if A, press button 2, get a reading of B. Include the reading when no button is pressed, which should be 0.

Then find the numbers exactly in between.

For example, if the lowest three readings are 0,20,37 for no button, A, and B pressed, respectively, then in your code, you will say: if the pin measures less than (half way between 0 and 20=) 10, then no button is pressed; else if the pin measures less than (half way between 20 and 37=) 29, then button A is pressed... and so forth.


Which sensor i can use to transmit some values from Arduino Uno to phone using bluetooth? I want to transmit some values from arduino uno to my phone using bluetooth.
Which sensor i can use?I want to see some options because i'm a little bit uncertain.Thanks to all which can give me an advice !  :)

It's not a sensor, its a module. A quite popular module is the HC-05. It's a very simple to use module with a lot of support by the community. Cheap and great for projects.


How is it possible that my skin temperature is so constant? Here's the code

#include <OneWire.h>

int DS18S20_Pin = 3; //DS18S20 Signal pin on digital 3
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
//Temperature chip i/o
OneWire ds(DS18S20_Pin);  // on digital pin 3

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

void loop() {
  if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        float temperature = getTemp();
        Serial.println(temperature);
    } //just here to slow down the output so it is easier to read

}

float getTemp(){
  //returns the temperature from one DS18S20 in DEG Celsius

  byte data[12];
  byte addr[8];

  if ( !ds.search(addr)) {
      //no more sensors on chain, reset search
      ds.reset_search();
      return -1000;
  }

  if ( OneWire::crc8( addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return -1000;
  }

  if ( addr[0] != 0x10 && addr[0] != 0x28) {
      Serial.print("Device is not recognized");
      return -1000;
  }

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

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

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

  ds.reset_search();

  //byte MSB = data[1];
 // byte LSB = data[0];

  float tempRead = ((((int)data[1]) << 8) | data[0]); //using two's compliment
  float TemperatureSum = tempRead / 16;

  return TemperatureSum;

}

Examine your code closely.  It appears that you are partially implementing extended resolution calculations in this line of code:

  float TemperatureSum = tempRead / 16;

In the DS18S20 specifications the extended resolution equation used is:

 TEMPERATURE = TEMP_READ * 0.25 - ((COUNT_PER_C - COUNT_REMAIN) / (COUNT_PER_C))

Where COUNT_PER_C is a DS18S20 register containing a value of up to 16.  Maybe that is where 16 originated?

I believe what you want to do is divide the recovered value by 2.0 base on table 1 from the DS18S20 specifications:

  float TemperatureSum = tempRead / 2.0;

Don't forget the "." in case the compiler you are using decides to do integer math dripping the "float" part before assigning it to TemperatureSum.


Arduino(s) not resetting on Serial connection lost / re-established - why? it seems that I accidentally found a way to make my two Arduino nano clones run without resetting on serial connection close/reconnect. On one hand, this behavior is much closer to the desired behavior and on the other hand it feels hackish, because I don't know the cause yet.

The devices are still able to be flashed with new firmware

I assume that it has to do with the usage of socat as proxy for the devices in question. The described behavior was first observed after playing with socat. The command that finally worked for me:

/usr/bin/socat -s -d /dev/ttyACM3,b115200,cs8,parenb=0,cstopb=0,clocal=0,raw,echo=0,setlk,flock-ex-nb,nonblock=1 PTY,link=~/.pyduin/ttyACM3.tty,b115200,cs8,parenb=0,cstopb=0,clocal=0,raw,echo=0,setlk,flock-ex-nb,nonblock=1

An Arduino Uno with the exact same firmware/treatment does not show the same bahavior.

Any ideas what had gone wrong? And how to restore the default FTDI behavior?

What you have done is to disable the "HUPCL" signal that is sent when the port is opened/closed.

You can turn the signal back on with:

$ stty -F /dev/ttyACM3 hupcl

And you can turn it off again with:

$ stty -F /dev/ttyACM3 -hupcl

HUPCL means "HangUP on CLose".


RS-485 Serial communication problem with arduino I use 485 modules to transmit data serially from one arduino uno to another uno.
If I connect the 2 arduino boards directly without using the rs485 module, the data is sent and received without a problem. But when using the rs485 module, the transmission stops.
Tx code:
void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.write(200);
    Serial.flush();
    delay(50);
}

Rx code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

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

void loop() {
    if (Serial.available()) {        // If data has come in from Master
        int reply= Serial.read();    // Read the byte
        delay(10);

        lcd.print(reply);
    }
}

I can't see what is the problem. I checked every thing wiring and the code is so simple. I'm just sending one number 200 and want to display it on the rx.
Please help. If anyone has an idea about this problem thanks any way.

In modbus there are two pins which are as DE and RE which you need to set and reset while transmitting the data. Also you can check Modbus this library it has some examples which could be useful to you also in arduino Uno don't use software serial for transmitting the data use the hardware serial only I will suggest implement your code on arduino Mega if you have any and then port the code for Uno. Just go through the library you will find some helpful examples and it will solve your issue


Low-Power library question i'm study the Low-Power library to better undertand how it works.
In this part of code i have some question.

Sometime he uses commands like:

power_timer1_disable();
power_timer0_disable();

but in other part of code, example "TIMER2_OFF":

if (TCCR2B & CS22) clockSource |= (1 << CS22);
if (TCCR2B & CS21) clockSource |= (1 << CS21);
if (TCCR2B & CS20) clockSource |= (1 << CS20);

// Remove the clock source to shutdown Timer2
TCCR2B &= ~(1 << CS22);
TCCR2B &= ~(1 << CS21);
TCCR2B &= ~(1 << CS20);

power_timer2_disable();

he uses the register code and, in the end, the function.

Someone can explain to me why?

It's doing basically this:
clockSource = TCCR2B & (_BV(CS22) | _BV(CS21) | _BV(CS20)); // store prescaler
TCCR2B &= ~(_BV(CS22) | _BV(CS21) | _BV(CS20));             // select "no source" - disable clock source
power_timer2_disable(); // disable whole timer2 in Power Reduction Register

Definition of power_timer2_disable macro is:
#define power_timer2_disable()  (PRR |= (uint8_t)(1 << PRTIM2))

In short, you have to turn off the clock source before the power gets cut off by PRR register (to avoid unexpected behaviour).

Power Reduction Register
The Power Reduction Register (PRR), provides a method to stop the
clock to individual peripherals to reduce power consumption. The
current state of the peripheral is frozen and the I/O registers can
not be read or written. Resources used by the peripheral when stopping
the clock will remain occupied, hence the peripheral should in most
cases be disabled before stopping the clock. Waking up a module, which
is done by clearing the bit in PRR, puts the module in the same state
as before shutdown. Module shutdown can be used in Idle mode and
Active mode to significantly reduce the overall power consumption. In
all other sleep modes, the clock is already stopped.


Cannot successfully implement singleton I have spent the better part of today trying to figure out why I can't get this to work...
I have this project where, because of previous design considerations, have implemented a singleton class that initializes a bunch of separate sensors in this system that I am running.
The system was originally built for the Particle Boron, but now I am trying to make it work with the Adafruit Feather M0, so I have had to refactor several things and omit lots of lines of Particle RTOS specific things.
However, in doing this, I find that my singleton class no longer works.
Sensors.h:
.
.
.

class Sensors{

    static Sensors *instance;

public:
    static Sensors *getInstance() {
        if (!instance) {
            instance = new Sensors;
        }
        return instance;
    }

}

private:
    Sensors();

.
.
.

Sensors.cpp:
.
.
.

Sensors::Sensors() : dht22(DHTPIN, DHTTYPE) {
#ifdef PLATFORM_ID
    sensorLog("app.Sensors");
#endif
}

.
.
.

main.ino:
.
.
.

// Sensors
Sensors *Sensors::instance = nullptr;
Sensors *allSensors = allSensors->getInstance();

void setup(){

.
.
.

As I try to compile this with ArduinoISP, no matter what I try, I get the following error:
sketch/main.ino.cpp.o: in function `Sensors::getInstance()':
sketch/lib/Sensors/src/Sensors.h:23: undefined reference to `Sensors::Sensors()'
collect2: error: ld returned 1 exit status
exit status 1
[Error] Exit with code=1

I have tried things like changing the line
instance = new Sensor;

to
instance = new Sensor();

making the instance public, changing the Sensor constructor, but all of this to no avail. Could this be a compiler issue? Why would this work on a Particle board, but not an Adafruit Feather M0?

Singletons aren't a thing in Arduino. Sure, you could do it, but in general you'd make a class then instantiate a global object for that class. Most often that global object is instantiated in the library itself, not the sketch.
Unless you're using an advanced chip with an RTOS (such as ESP32) and making use of the threads of that RTOS heavily there is no benefit to having a singleton.
But to answer your actual question: it's probably because you are trying to use the Sensors() constructor at a time before the compiler knows what the Sensors() constructor is. You would have to add some form of forward declaration so that the compiler knows what you mean when you talk about the Sensors() constructor.  In general a simple:
class Sensors;

at near the top of your header before the class is actually defined can help in these situations;


Using Rx and Tx pins(0 and 1) on Arduino Uno for GSM I am using a GSM module sim800. My module responds to the output given by my PIR sensor and sends sms according to it. My module has got +5V, GND, Rx and Tx pins. What are the pin connections that I have to make?

You have a choice.

Always:

GND => GND
+5V => +5V

Then, either:

TX => RX (0)
RX => TX (1)

and use the hardware UART "Serial", but that then means that uploading new code to your Arduino becomes an arduous task since the usage pins 0 and 1 will interfere with that.  So the other option:

TX => Any pin
RX => Any pin

And then use SoftwareSerial to set up a secondary "bit banged" serial port on the two pins you choose.


Can anyone tell me about the onboard accelerometer of LightBlue Bean? I would like to know the specs of the accelerometer used on a LightBlue Bean before buying one, but I couldn't find any info online. Anybody has an idea?

There is a reference to the accelerometer datasheet from the Arduino Reference page


Leading Zeroes on Arduino Ethernet MAC Address How can I pass the MAC address to Ethernet shield with leading zeroes?
I change the default MAC address from DEADBEEFFEED to something like DEADBEEFFE01. So I only change the last number from 0xED to 0x01. My board is communicating to a separate server and when I look at the MAC in that server, my board is listed as DEADBEEFFE1.
It's not as simple as printing the MAC address with padded zeroes as the board is actually removing it.
I've looked at the Ethernet library and I saw that the mac is passed as an array of uint8_t. I think that's why, the last number is read as 1 (which is correct) but passed as just that.
Is there a way for the MAC to pass leading zeroes?

Writing this in case someone in the future might be interested.
The values passed in the Ethernet library is correct. The last value, 0x01 must be 1 and is written correctly, 0x01 in the registers of the W5500 inside the Ethernet shield.
Where I've got it wrong is how I pass the MAC address to the server. I'm basically creating a string for a json message. In there, I've put %02x to make sure that zeroes are padded.


Is RX1 and TX0 the same thing as TX and RX? Will there be a difference in the way I program it? I have an Arduino.

I'm not sure if RX1 and TX0 the same thing as TX and RX? Will there be a difference in the way I program it?

For example, do I treat RX1 and TX0 as RX and TX in the Arduino IDE when coding?

This is the chip I have. On the chip it says "ProMini R160JAC6v" and when I program it, it programs under 5V 16MHz with ATmega 328. Notice RST RX1 and TX0 are on the top left corner.

It's not RX1 and TX0 but RXI and TXO

That is receive input and transmit output,

Exactly the same as RX and TX just with the data direction explicitly shown in the lettering.


USB Serial port not recognized Have both an Arduino Uno R3 and a Blend Micro that I have used to prototype a number of projects. Just got a new MacBook Pro and cannot get it to recognize the boards through the USB serial port.

I am using the same USB cable as before so I know it is not power only.

Have tried both USB ports. Have also tried them with other devices, so I know they work.

I have tried installing both the FTDI and CH34x drivers (both the older and the new signed one).

Don't know what to try next... any help?

I have an Arduino Uno which works on my Mac running 10.11.3 this uses the Serial Port /dev/cu.usbmodemFA131.

It is 18 months since I installed this (on a previous OS) and I can't recall whether I had to install a driver

ioreg -p IOUSB shows this as

  | | +-o IOUSBHostDevice@fa130000  <class AppleUSBDevice, id 0x100000955, registered, matched, active, busy 0 (40 ms), retain 13>

system_profiler SPUSBDataType shows this as:-
            Communication Device:

          Product ID: 0x0043
          Vendor ID: 0x2341
          Version: 0.01
          Serial Number: 5543434373335120A2B0
          Speed: Up to 12 Mb/sec
          Manufacturer: Arduino (www.arduino.cc)
          Location ID: 0xfa130000 / 3
          Current Available (mA): 1000
          Current Required (mA): 100
          Extra Operating Current (mA): 0


Passing user defined callback functions to a library method I developed an Arduino library that have a method called "process". This method is a Void function and must be called inside the loop and most of the time the library handles everything by it self:

#include <HookNinja.h>

HookNinja hookninja;

void setup()
{}

void loop()
{
  hookninja.process();
}

The idea is to keep the user program a simple as possible. Sometimes "process" have some data to give back to the user so he can use it as he likes. A simple approach is not to make process void and make the user check for the return value of process:

void loop()
{
  someVariableType foo;
  foo = hookninja.process();
  if(foo) {
    //user defined things
  }
}

But the data returned by process could be anything, from an int to an array of Strings, only the user knows the return type, also this method seems not very elegant. Im not an expert of C++, for me the ideal solution will be an object oriented approach were the user pass a function to process that can be called from the library, but I have no idea how to do this in C++, something like:

void userFunction(type param) {
  //do something with param
}

void loop() {
  hookNinja.process(some how pass userFunction here)
}

A common solution would be to have the user provide a callback which
takes no arguments and returns nothing. This is how attachInterrupt()
works, so it may be the least surprising approach for your users. The
user function can then get data from the rest of the program using
globals.

If you really prefer passing an argument to the user function, the
problem is you do not know the data type. The usual approach in plain C
is to give it a “generic” pointer, and let the user cast it into a
pointer specific for his data type. This is how functions like qsort()
work:

HookNinja hookninja;

void userFunction(void *param) {
    someVariableType foo = * (someVariableType *) param;
    //do something with foo
}

void setup()
{
    hookninja.attachCallback(userFunction);
}

void loop() {
    someVariableType foo = something;
    hookNinja.process((void *) &foo);
}

A cleaner C++ approach could be to make you class a template that is
specialized for the type of the user data:

HookNinja<someVariableType> hookninja;

void userFunction(someVariableType param) {
    //do something with param
}

void setup()
{
    hookninja.attachCallback(userFunction);
}

void loop() {
    someVariableType foo = something;
    hookNinja.process(foo);
}

But keep in mind that many Arduino users may not be familiar with
templates.


Converting ASCII value to String I have this code.

String incoming;   // for incoming serial data

void setup() {
    Serial.begin(9600);  // opens serial port, sets data rate to 9600 bps
}

void loop() {

    // send data only when you receive data:
    if (Serial.available() > 0) {
            // read the incoming byte:
            incoming = Serial.read();
            String mysrr = String(incoming);
            // say what you got:
            Serial.print("I received: ");
            Serial.println(mysrr);
    }
}

A few of you will recognise this as an Arduino example.

However, when I run it ( I sent it the message "hi"), I get this in the serial:

I received: 104
I received: 105

Why is this happening?

Serial.read() returns an int not a String. https://www.arduino.cc/en/Serial/Read

Use an int for incoming (as the example). Or even better use a char and skip all the strings.

Cheers!


Possible to determine at runtime whether a pointer is declared PROGMEM? Is it possible to determine at runtime whether a pointer points to PROGMEM'ed values or regular values? This would give some flexibility when writing code that handles both.

Not really, if you are asking whether you can determine (simply from its value) whether 0x100 is in RAM or PROGMEM. Both are possible candidates for a memory location.

The F() macro works around this by changing the type of a variable at compile-time, so that the compiler can select a suitable method of printing. For example:

Serial.println ("Hello, world");
Serial.println (F("Hello, world"));

In this case the appropriate println function is chosen at compile-time by the compiler, based on the type (one would be a const char *, the other a __FlashStringHelper type).

You are best off designing a way (similar to the F() macro) where you can make the decision at compile time.


Running stepper motor for specified no. of turns with Arduino? I hope you are doing well.
I want to run a pretty big stepper motor for a specified number of turns, take, for instance, 25. Easy! But not for a beginner with Arduino and I'm not an electrician!
Here is my purpose once again: Rotate my stepper motor for 25 rounds at the maximum speed possible.
Here is a similar circuit that I found on the internet. If you ignore the potentiometer, that would be my circuit!

I think my purpose in kind of simple. But I don't know anything about the code. I would appreciate any advice or helpful complementary code! :)

Here's a post that will get you started.  It uses a Teensy 3.5, but the motor driver code will be the same. You will also need to modify the low-level driver functions to match with the actual motor driver module being used.  However, if you use a Teensy 3.5 and the L298N motor driver, you should be able to use the program with little or no modifications.


Makeblock Arduino keeps stopping from motor overpower protection I got a makeblock Arduino. Sometimes when I make it go forward at full speed, all motors stop for 3 seconds and it beeps shortly. I think it is that the motors are a little hard to turn for a moment and it stops to prevent damage to the motors. It is getting very annoying. Is there any way to disable it or make it less sensitive?

It is unlikely the pause in operation is because of the motors.  It is more likely the Makeblock is stopping because the  motor controllers are too hot.  Next time try to identify which chips on the board are controlling the motors and test if they are getting hot to the touch.  If so, consider adding heat sinks to these chips to mitigate any heat dissipation problems.

An alternative explanation involves a limited power supply.  It could be that when the motors are demanding high current, the voltage drops and the processor resets.  Consider a power supply that can offer more amperage.  Or larger capacity batteries.


Optical Incremental Encoder Reading using Arduino UNO I have a HP Optical Incremental Encoder (256 CPR) in which

Pin 1 = A,
Pin 2 = VCC,
Pin 3 = GND,
Pin 8 = B.

I already read and see tutorials for rotary encoder such this one:
https://playground.arduino.cc/Main/RotaryEncoders

I have written a program that is supposed to print out the position of my encoder, however I am only getting zeros in my serial monitor. I want to be able to use interrupts. I would like to actually return the position in degrees of my encoder as we rotate it.

I was able to get it to work. I wasn't connecting my pin properly to my Arduino.

    #include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

#define encoderPinA 2
#define encoderPinB 3
#define CPR 256
volatile int counter =0;
volatile boolean flag;

volatile int var_degrees =0;

void setup() {

  pinMode(encoderPinA, INPUT);
  pinMode(encoderPinB, INPUT);
  Serial.begin (9600);
  attachInterrupt(digitalPinToInterrupt(encoderPinA), isr, RISING);
  lcd.clear();

}

void loop() {

   if(flag == true){
        var_degrees = ((360/256.0)*counter);
        Serial.println(var_degrees);
        lcd.setCursor(0, 1);
        lcd.print("Degrees: ");
        lcd.setCursor(9, 1);
        lcd.print(var_degrees);
        flag = false;
  }

}
//Interrupts

void isr_2(){
flag = true;
  if(digitalRead(encoderPinA) == HIGH){
    if(digitalRead(encoderPinB) == LOW){
      counter = counter -1; //COUNTER CLOCK WISE
    }
    else{
      counter = counter +1; //CW
    }
  }
  else{
    if(digitalRead(encoderPinB) == LOW){
      counter = counter + 1; //CW
    }
    else{
      counter = counter - 1 ; //CCW
    }
  }
}

You are attaching your interrupt incorrectly. You should not pass in the pin number, but the interrupt number. There is also a handy function that converts a pin to the right interrupt number:

attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);

So, your code should be:

attachInterrupt(digitalPinToInterrupt(encoderPinA), isr,CHANGE);

Also, you should declare your counter variable to be volatile, since it is modified within an ISR, and thus the compiler should not assume that it doesn't change even though the loop() never changes it:

volatile int counter = 0;


fatal error: avr\wdt.h: No such file or directory in arduino due I am using Arduino DUE for vehicle tracking gps/gprs device. Before using Arduino DUE I used Arduino UNO. When I am trying to load my code in Arduino DUE It shows me "fatal error: avr\wdt.h: No such file or directory". I can't delete watchdog from my code as it is so important for my device.
Now how can I solve this problem ?

The Due is a very different board than the Uno. It uses a completely different architecture (ARM vs AVR). You can't use AVR-specific  code on an ARM chip, and the Watchdog code is AVR-specific.

You will have to find (or write) the equivalent ARM code using the Due's register set instead.


How to count number of bytes appearing in the Arduino serial? I need to count the number of bytes appearing in the serial (UART bus) bus, how to count bytes in Arduino with Arduino Serial functions? is this possible?
Application -
RS485 communication with multiple boards without slave ID
slave boards will send data to the master board when,
1st 10 bytes = masters send a 10byte message to all slaves
slaves listening to the bus always until it is the turn to send the data
when byte count is 10, slave 1 sends data 5 bytes to master
when byte count is 15 (10+5), slave 2 sends data 5 bytes to master
when byte count is 20 (15+5), slave 3 sends data 5 bytes to master
max count is 25 known value

Serial.available() returns the number of bytes available for reading in the buffer.
int nBytes=Serial.available();
if (nBytes > x) {
............
............
............
}


Why the need to use the volatile keyword on global variables when handling interrupts in Arduino? I am familiar with the keyword Volatile being used to declare variables that are shared among multiple threads on a software application (basically on a multithreaded application).

But why do I need to declare a variable as Volatile when running the code on an an Arduino interrupt? Is the code running in the interrupt executing on different thread? Is there something else going on?

First, it's volatile not Volatile. I cover these concepts in my page about Interrupts however to avoid giving a link-only answer I'll repeat the relevant bits.

What are "volatile" variables?

Variables shared between ISR functions and normal functions should be declared volatile. This tells the compiler that such variables might change at any time, and thus the compiler must reload the variable whenever you reference it, rather than relying upon a copy it might have in a processor register.

For example:

volatile boolean flag;

// Interrupt Service Routine (ISR)
void isr ()
{
 flag = true;
}  // end of isr

void setup ()
{
  attachInterrupt (0, isr, CHANGE);  // attach interrupt handler
}  // end of setup

void loop ()
{
  if (flag)
    {
    // interrupt has occurred
    }
}  // end of loop

Critical sections ... accessing volatile variables

There are some subtle issues regarding variables which are shared between interrupt service routines (ISRs) and the main code (that is, the code not in an ISR).

Since an ISR can fire at any time when interrupts are enabled, you need to be cautious about accessing such shared variables, as they may be being updated at the very moment you access them.

First ... when do you use "volatile" variables?

A variable should only be marked volatile if it is used both inside an ISR, and outside one.

Variables only used outside an ISR should not be volatile.
Variables only used inside an ISR should not be volatile.
Variables used both inside and outside an ISR should be volatile.

eg.

volatile int counter;

Marking a variable as volatile tells the compiler to not "cache" the variable's contents into a processor register, but always read it from memory, when needed. This may slow down processing, which is why you don't just make every variable volatile, when not needed.

Atomic access

Consider this code:

volatile byte count;

ISR (TIMER1_OVF_vect)
  {
  count = 10;
  }

void setup ()
  {
  }

void loop ()
  {
  count++;
  }

The code generated for count++ (add 1 to count) is this:

 14c:   80 91 00 02     lds r24, 0x0200
 150:   8f 5f           subi    r24, 0xFF     <<---- problem if interrupt occurs before this is executed
 152:   80 93 00 02     sts 0x0200, r24   <<---- problem if interrupt occurs before this is executed

(Note that it adds 1 by subtracting -1)

There are two danger points here, as marked. If the interrupt fires after the lds (load register 24 with the variable count), but before the sts (store back into the variable count) then the variable might be changed by the ISR (TIMER1_OVF_vect), however this change is now lost, because the variable in the register was used instead.

We need to protect the shared variable by turning off interrupts briefly, like this:

volatile byte count;

ISR (TIMER1_OVF_vect)
  {
  count = 10;
  }  // end of TIMER1_OVF_vect

void setup ()
  {
  }  // end of setup

void loop ()
  {
  noInterrupts ();
  count++;
  interrupts ();
  } // end of loop

Now the update of count is done "atomically" ... that is, it cannot be interrupted.

Multi-byte variables

Let's make count a 2-byte variable, and see the other problem:

volatile unsigned int count;

ISR (TIMER1_OVF_vect)
  {
  count++;
  } // end of TIMER1_OVF_vect

void setup ()
  {
  pinMode (13, OUTPUT);
  }  // end of setup

void loop ()
  {
  if (count > 20)
     digitalWrite (13, HIGH);
  } // end of loop

OK, we are not changing count any more, so is there still a problem? Sadly, yes. Let's look at the generated code for the "if" statement:

 172:   80 91 10 02     lds r24, 0x0210
 176:   90 91 11 02     lds r25, 0x0211  <<---- problem if interrupt occurs before this is executed
 17a:   45 97           sbiw    r24, 0x15
 17c:   50 f0           brcs    .+20

Imagine that count was 0xFFFF and was about to "wrap around" back to zero. We load 0xFF into one register, but before we load the second 0xFF the variable changes to 0x00. Now we think count is 0x00FF which is neither the value it had before (0xFFFF) or now (0x0000).

So again we have to "protect" the access to the shared variable, like this:

void loop ()
  {
  noInterrupts ();
  if (count > 20)
     digitalWrite (13, HIGH);
  interrupts ();
  }  // end of loop

What if you are not sure interrupts are on or off?

There is a final "gotcha" here. What if interrupts might be off already? Then turning them back on afterwards is a Bad Idea.

In that case you need to save the processor status register like this:

unsigned int getCount ()
  {
  unsigned int c;
  byte oldSREG = SREG;   // remember if interrupts are on or off

  noInterrupts ();   // turn interrupts off
  c = count;         // access the shared variable
  SREG = oldSREG;    // turn interrupts back on, if they were on before

  return c;          // return copy of shared variable
  }  // end of getCount

This "safe" code saves the current status of interrupts, turns them off (they may already be off), gets the shared variable into a temporary variable, turns interrupts back on - if they were on when we entered the function - and then returns the copy of the shared variable.

Summary

Code may "appear to work" even if you don't take the above precautions. That is because the chances of the interrupt occurring at the exact wrong moment is fairly low (maybe 1 in 100, depending on the code size). But sooner or later it will happen at the wrong moment, and your code will either crash, or occasionally return the wrong results.

So for reliable code, pay attention to protecting access to shared variables.


PCF8547 Wire.write explanations I am using an ESP8266-12E with a PCF8547.
I have managed to turn on and turn off LEDs using these two things.
I am using these three commands to do it.

 Wire.begin(SDA_PIN,CLK_PIN);
 Wire.beginTransmission(0x20);
 Wire.write(~((uint8_t)1<<cnt));
 Wire.endTransmission();

The problem I am facing here is: I am using 4 LEDs and I am only able to turn on one LED at a time. When I turn on another, all the LEDs turn off - in short, the LEDs or the PCF8547 do not preserve the state.

I want to toggle on the LEDs without disturbing the other's state.
How can I do it?
I think, I need more knowledge about the write function, don't I?

Update:

I have already connected A0, A1, A2 to ground. This is the function I use now to toggle the LEDs.

void enlight(int cnt)
{
  if (cnt == 1)
    value = value | 1<<cnt;
    if (cnt == 2)
      value = value | 2<<cnt;
    if (cnt == 3)
      value = value | 3<<cnt;
    if (cnt == 4)
      value = value | 4<<cnt;
    value = ~value;
    Wire.begin(SDA_PIN,CLK_PIN);
    Wire.beginTransmission(0x20); Wire.write(value);
    Wire.endTransmission();
  }

but when I turn off/on any other LEDs they also toggle, which I don't want.

(I haven't used this library, but this looks like a general C(++) question...)

The important part of what you're doing is this:

Wire.write(~((uint8_t)1<<cnt));

Let's break it down.

It calculates a value by taking the number 1 and shifting it left cnt times. Then it takes the complement of that number - changes 0s to 1s and 1s to 0s.  This number is sent to Wire.write() and lights up light number cnt.

Example: Let's say you start with cnt==2, to light LED 2.  It will shift the number 1 left by two digits, giving you the binary number 00000100.  Then it will invert this, giving you 11111011.  This is given to Wire.write().

We can see from this that to light an LED, we need to put a '0' in the right place.

How can you make several numbers light up?  We need to put several zeros in, at the right places.

Here's an example of how you might like to do this - which isn't the prettiest code but I hope it shows you what's going on.

// How we would like the LEDs to appear
boolean led0 = true;    // LED 0 ON
boolean led1 = false;   // LED 1 OFF
boolean led2 = true;    // LED 2 ON
boolean led3 = false;   // LED 3 OFF

// Start with all LEDs off
uint8_t value = 0;

// Put a 1 in place for each LED we want to be ON
// The | symbol means "logical OR" (Google it)
if (led0) value = value | 1<<0;
if (led1) value = value | 1<<0;
if (led2) value = value | 2<<0;
if (led3) value = value | 3<<0;

// Invert this value
value = ~value;

// Write it to Wire
Wire.begin(SDA_PIN,CLK_PIN);
Wire.beginTransmission(0x20);
Wire.write(value);
Wire.endTransmission();

Since it appears you have to send values for all the lights every time, you need to remember the value you sent last time, and modify only the bits you want to change.  Here's a way you can do that:

void setLight(int lightNum, boolean lightOn) {
  // Remember the last state of the lights.
  // Start with all lights OFF.
  static uint8_t lightsOn = 0;

  // We only have four lights (0-3).  Only respond for lights
  // we we have.
  if (lightNum<4) {
    // Get a bitmask with a single 1 in the right
    // position for this light
    uint8_t position = 1<<lightNum;

    // Clear (to 0) that bit in the state
    lightsOn &= ~position;

    // Set (to 1) the bit if we want the light on
    if(lightOn) lightsOn |= position;

    // Write out the value of all lights
    Wire.begin(SDA_PIN,CLK_PIN);
    Wire.beginTransmission(0x20);
    Wire.write(~lightsOn);
    Wire.endTransmission();
  }
}

Call it with something like

setLight(0, true);    // Switch the first light ON
setLight(3, true);    // Switch the fourth light ON (first stays on)
setLight(0, false);   // Switch the first light OFF (fourth stays on)


What Arduino board with WiFi should I choose I want to implement an Arduino module with some sensors and send the info through WiFi to a server. I'm looking for the best board or component combination to make this. What is the best board or solution you would use in my case? Maybe Arduino Yun or Intel Edison Kit for Arduino...¿?

I've developed a sensor module with Redbear Blend board which use Bluetooth to communicate with an Android app to send sensor data, but now looking for WiFi connection.

Sorry if it's a stupid question, I'm new in this Arduino world. Thanks in advance!

I'd recommend ESP8266 (model 07) based board.

Can be programmed the same way as other Arduinos
Cheap
Enough storage for code
Fairly low power
Large community (more code examples and better library support)


Alternate between 2 relays with one button I have a very basic programming knowledge, but the thing I want to achieve is to alternate between switching 2 relays with a button or a RPi input pulse.

So something like this:

Press the button
Switch relay 1 on and off (1 second delay)
Press the button
Switch relay 2 on and off
Press the button
Switch relay 1 on and off (1 second delay)
Press the button
Switch relay 2 on and off
Press the button
Switch relay 1 on and off (1 second delay)
Press the button
Switch relay 2 on and off
etc.

Here's my code, I thought if I'd just put the second relay after the first else everything would work. But I'm missing some basic knowledge to figure this out.

const int ledPin = 2;
const int ledPinA = 3;

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

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
  if (sensorValue > 500) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
  if (sensorValue > 500) {
    digitalWrite(ledPinA, HIGH);
  } else {
    digitalWrite(ledPinA, LOW);
  }
}

I'm thinking I should use while.

The way you have it, both if blocks will be evaluated each time you call to loop(). Instead, you need to create a variable that remains "alive" in between each call to loop() to keep track of which relay you want to activate:

const int ledPin = 2;
const int ledPinA = 3;
int active_relay = 2;   // State variable for current relay pin

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

void loop() {
      int sensorValue = analogRead(A0);

      Serial.println(sensorValue);

      delay(1);    // This delays for 1ms, not 1s ??

      if (sensorValue > 500) {   // Pulse received
          digitalWrite(active_relay, HIGH);  // Relay on
          delay(1000);                       // Wait 1 second
          digitalWrite(active_relay, LOW);   // Relay off

          // Update variable for next call to loop
          if (active_relay == ledPin) {
              active_relay = ledPinA;      // Swap
          }
          else {
              active_relay = ledPin;       // Swap
          }
      }
      // Remove 2nd if block
}


Doing several things at the same time with functions, objects or interrupts? First of all, thank you for taking the time to read this. I am a newbie, so apologies (done examples on arduino website, basic C++).
I'm trying to get an idea of what the best way to structure a sketch is, which needs to do several things at the same time. For example, reading an IMU sensor and using it to control the mouse, reading a button for on/off and let's say flashing an LED. I have repetitive injury so this is the project I'm trying to complete, but the principle should be scalable for more complex projects.
I've come across some great resources and my understanding is you can use:

functions (e.g. blink without delay)

objects (cooperative multitasking)

interrupts

something like a RTOS

Where my limits lie is understanding the benefits/limitations of these options and picking which one to focus on for my project. For example, if using functions is sufficient, why do people bother with interrupts and installing a RTOS?
I would appreciate any guidance for what an effective approach should look like.
Thanks again.

An RTOS may be a good option for running a complex application on a
quite powerful Arduino. Many Arduinos (the AVR-based ones), however, are
too limited to run complex applications, and the overhead of an RTOS is
quite significant for them. In this case you end up with two options:

non-blocking programming
interrupts

Whichever is best depends on the specific tasks you are managing.
Non-blocking programming
This is best exemplified by the Blink Without Delay Arduino
tutorial. The general principle is to break down you code into small
non-blocking tasks, and perform each one only when it is the right time
to do so. Breaking down the program logic into a set of non-blocking
tasks is not always completely trivial, but you can use a Finite state
machine, which is a very powerful and general concept for doing so
in a systematic way.
Once all task are non-blocking, the main program loop then looks like
this pseudo-code:
void loop() {
    if (task_1_should_be_performed_now()) {
        perform_task_1();
    }
    if (task_2_should_be_performed_now()) {
        perform_task_2();
    }
    // etc...
}

Most of the time, all conditions are false, and the program swifts
through the tests completing the loop in a very short time.
Occasionally, it performs one of the tasks, which makes the loop longer
but, since the tasks never block, not very long anyway. Typical loop
time is highly dependent on the specifics of your code, but I would
expect it to be no more than one millisecond most of the time.
This is probably the most common pattern for multitasking on the
Arduino. You can encapsulate this logic in functions, objects,
libraries, etc. This is the approach I would recommend provided none of
your tasks is so urgent that it cannot wait for one loop iteration.
Interrupts
Occasionally, you may have a task that is so urgent that it cannot wait
for the next loop iteration. It has to be performed right now. Or maybe
the loop takes a very long time because of a blocking call in a library
you have no control over. In those situations, an interrupt may be the
best option.
Interrupts come with some tricky programming issues, which require some
precautions on the part of the programmer:

they block other interrupts, increasing their latency → interrupt
service routines should be as short as possible

they can cause problems with non-reentrant library functions → those
functions should be avoided in interrupt context

they can interact badly with the optimizer → variables used in both
interrupt context and normal context should be qualified as
volatile

they can cause synchronization issues with the data shared with the
main code → access to that data in normal context should be protected
in critical sections.

For all these reasons, it is best to use interrupts only when needed,
i.e. only when a task cannot wait for the next iteration of loop().


AVRdude + Arduino leonardo: can't flash over bootloader, not in sync: resp=0x3f I would like to program an arduino leonardo board with atmega32u4 on win8.1 x64.
I have the latest AVRdude.
I installed the necessary drivers, after reset it can be enter programming mode, and I can program with arduino studio.
But now, the avrude gives this:

    C:\>avrdude -carduino -P COM5 -n -p m32u4 -b19200 -v

avrdude: Version 6.1-svn-20131205, compiled on Dec  5 2013 at 17:34:22
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "c:\GNU_GCC_ARM\bin\avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x3f

avrdude done.  Thank you.

I tried also with 57600 baud.
Any idea? Thanks.

You're specifying the wrong bootloader protocol via -carduino. The Arduino bootloader is for boards using the Diecimila bootloader. The Leonardo uses the "AVR109" bootloader - named after the Atmel Application Note which describes its protocol.

Try this command on for size:

avrdude -cavr109 -P COM5 -n -p m32u4 -b57600 -v

Don't forget to press the reset button (or open and close COM5 at 1200 baud) first to run the bootloader.


DigitalWrite Cannot Power HC-06 Bluetooth To save power consumption, I tried to connect the HC-06 bluetooth module to a digital pin of my Arduino Nano. (HC-06 +5V <=> pin 11, HC-06 gnd <=> gnd) In that way, I can toggle the bluetooth when I am not using it. However, when I tried to pinMode(11, OUTPUT) and digitalWrite(11, HIGH), the led on HC-06 does not turn on which means it is not powered. I have tried to connect the HC-06 +5V to the 5V output of arduino and the HC-06 can turn on sucessfully. I have also tried to use a multimeter and the digital pin outputs a voltage of 5V. As the digital pins of Arduino can give 40mA while the HC-06 draws 30mA - 40mA, it should have enough power. I have also tried to use other digital pins as well but still the HC-06 cannot be powered.
What have I done wrong?

A digital IO pin is only capable of powering an LED or an incredibly low powered device. It is not suitable for powering meaty RF modules.

Instead you need to control the power to your module using a P-channel MOSFET as a High-Side switch.

For instance, assuming a 5V module with built in 3.3V LDO:

simulate this circuit – Schematic created using CircuitLab

Note that /RFEN is active low - set the pin OUTPUT and LOW to turn the module on. M1 should have a threshold of no lower than -4V, better -2V or higher.

Also be sure to set RX and TX to be INPUT when you power down the module or back-powering through the TX/RX pins may occur.

R2/R3 is a simple logic level shifter for the 3.3V logic signal the RX pin expects.


cannot open source file "WProgram.h" in VSCode So I started typing out this question, but in the process of taking screenshots and looking up sources for the question I figured out the answer :P
That said, this problem has been a snag for me for a while and I've asked multiple people about it with no solution. Because it seemed kind of daunting for me and I haven't seen many well explained reasons I figured I'd finish out the post here to help anyone that is running into this or will run into it in the future.

The snag
I'm using vscode for my editor and I've had this snag for a while but it's finally driving me nuts enough to ask for help.
When in include certain libraries I get error squiggles under the include.

In this case the squiggle is popping up because of the error:

cannot open source file "WProgram.h" (dependency of "Adafruit_MPR121.h")C/C++(1696)

At first I though the snag was because my include path needed my arduino libraries directory so I added that for the project, but I still get the snag.

I did a computer wide search for the WProgram.h file but was not able to find it.

The thing is, all of my sketches still compile and upload fine so for the most part I'm just able to ignore it ... but the squiggle!!!!!!.
Any ideas of how I can resolve this?

I landed here in the same position as you, and after researching the comments mentioning -DARDUINO=10813 and some more googling I found: https://github.com/microsoft/vscode-arduino/issues/1148
This led me to adding one more line to defines in my c_cpp_properties.json
and this also removed the squiggly!
{
    "configurations": [
        {

            ...

            "defines": [
                "USBCON",
                "ARDUINO=10813"
            ],

            ...

        }
    ],

}```


How to receive and process a long string sent over serial? I want to receive about 5kb of data in Base64 format. The following code does not work. Only a few characters are received, sometimes CPU crashes.

String content = "";
char character;

while (Serial.available()) {
       character = Serial.read();
       content.concat(character);
}

I do not care about ram usage since on ESP32 there is plenty.
How can I get all the data? Example input: https://pastebin.com/wYG5AhHK

I had to read until delimiter :D

String receive() {
        String content = "";
        content = Serial.readStringUntil('\r');
        return content;
    }

Now it is fine. I will also change String to large char array.


ESP Wemos D1 upload fails I try to upload simple code (e.g. blink.ino) to my ESP8266-12 (I have the WeMos D1 breakout board). Until now, that worked without a problem: I had to pull GPIO0 down and then I could upload the compiled sketch.

Since today that does not work any more - but I did not change anything.

I get:

  error: espcomm_upload_mem failed

(I know that here are some questions / github issues out there that have the same error, but that was often because GPIO0 wasn't pulled down and the ESP was therefore not in FLASH mode.)

My config is: ESP8266, 80MHz, DIO, 115200, 512K (64K SPIFFS), ck, Serial

When I reset my board, having GPIO0 pulled down, the ESP sends this serial info:

  ets Jan  8 2013,rst cause:2, boot mode:(1,7)

The whole debug output is:

esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to ck
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM6
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 228624 bytes from D:\Users\myusr\AppData\Local\Temp\build9c9ef3bdfe2fccb480bc6e4bac749e41.tmp/Blink.ino.bin to flash at 0x00000000
    erasing flash
    size: 037d10 address: 000000
    first_sector_index: 0
    total_sector_count: 56
    head_sector_count: 16
    adjusted_sector_count: 40
    erase_size: 028000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting serial port timeouts to 15000 ms
    read 0, requested 1
    setting serial port timeouts to 1000 ms
warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed
closing bootloader
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
error: espcomm_upload_mem failed

As I found out, GPIO0 has to be LOW AND GPIO2 has to be HIGH. It is very important to use pin D3 as GPIO0 and pin D4 as GPIO2 at the WeMos D1 board, because this "routing" is different for other boards and therefore other digital pins are often described.


Is it possible to query (or otherwise detect) if Arduino is connected to 60 NeoPixel strip vs 144 strip? Is there any way to have an arduino detect how many LEDs are on a connected strip? I have a 60 strip and 144 strip. The code is identical for both, aside from setting the number of LEDs in a variable to iterate over.

Neopixels only have one-way communication. Some possible ways to detect the quantity are:

Bring the Data-Out of the last pixel back to the arduino and activate an interrupt on an input pin connected to that. If you write 144 LEDs worth of data to the 144-LED strip, the pin doesn't change. If you write 144 LEDs worth to a 60-LED strip, the pin changes. So your code has a startup routine to write data and detect it. You can even write all "black" colors, since the data will still have HIGH and LOW values, and your detect routine won't show any light patterns.
Pass the ground line that goes to the LED strip through a low-value resistor (A current-sense resistor) and use an analog input to read the voltage across the resistor. Write an all-white color to all NeoPixels and sense the current draw. Pre-calculate the 144-LED current draw and 60-LED current draw and set a cutoff value for knowing which strip is connected.
Make your LED-strip connector to have more pins than necessary strictly for the LED strip connections. For example, have 1 extra pin. On the 144-LED strip side of the connector, tie this connection to the 5V line. On the 60-LED strip, connect it to GND. Read HIGH or LOW on an extra digital input on your arduino.


ATTiny85 I2C connection with Arduino Nano I am trying to send and receive data using I2C between an Arduino Nano and an ATTiny85.
The ATTiny is mounted on this board:
Link

I've tried to reach the slave with the simple I2C scanner, but I don't find anything.

Those are the codes:

Master (I2C scanner):

// --------------------------------------
// i2c_scanner
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknown error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(500);           // wait 5 seconds for next scan
}

And this is the code of the ATTiny85 (slave):

#include <TinyWire.h>

#define led_pin 1

byte own_address = 10;

void setup() {
  // config led_pin as Output for driving an LED
  pinMode(led_pin, OUTPUT);

  // config TinyWire library for I2C slave functionality
  TinyWire.begin( own_address );
  // sets callback for the event of a slave receive
  TinyWire.onReceive( onI2CReceive );
}

void loop() {

}

/*
I2C Slave Receive Callback:
Note that this function is called from an interrupt routine and shouldn't take long to execute
*/
void onI2CReceive(int howMany){
  // loops, until all received bytes are read
  while(TinyWire.available()>0){
    // toggles the led everytime, when an 'a' is received
    if(TinyWire.read()=='a') digitalWrite(led_pin, !digitalRead(led_pin));
  }
}

Once I've programmedo both the boards I've connected SCL and SCK pins of the boards together.

If i open the serial monitor of the master this is what i get:

  I2C Scanner Scanning... Unknown error at address 0x20 Unknown error at
  address 0x21 No I2C devices found

  Scanning... Unknown error at address 0x78 No I2C devices found

  Scanning... No I2C devices found

  Scanning... Unknown error at address 0x08 Unknown error at address
  0x09 Unknown error at address 0x60 No I2C devices found

  Scanning... Unknown error at address 0x70 No I2C devices found

And so on.
Can someone explain me were I'm doing errors?

Problem solved!

I've modified the code, this is the final one:

#include <TinyWire.h>

#define led_pin 1
#define I2C_SLAVE_ADDR  0x11

void setup() {
    // config led_pin as Output for driving an LED
    pinMode(led_pin, OUTPUT);

    // config TinyWire library for I2C slave functionality
    TinyWire.begin( I2C_SLAVE_ADDR );
    // sets callback for the event of a slave receive
    TinyWire.onReceive( onI2CReceive );
}

void loop() {

}

/*
I2C Slave Receive Callback:
Note that this function is called from an interrupt routine and shouldn't take long to execute
*/
void onI2CReceive(int howMany){
    // loops, until all received bytes are read
    while(TinyWire.available()>0){
        // toggles the led everytime, when an 'a' is received
        if(TinyWire.read()=='a') digitalWrite(led_pin, !digitalRead(led_pin));
    }
}

Like this the I2C scanner sees the board at the address 0x11.

The wirings are the following:

Arduino pin SCL to ATTiny85 pin SCL (P2)
Arduino pin SDA to ATTiny85 pinSDA  (P0)
Take care of wire to the same ground both the boards.


Arduino Uno R3 Bluetooth Shield is not discovering in any of the device I have a problem regarding Seeedstudio Bluetooth shield http://www.seeedstudio.com/depot/Bluetooth-Shield-p-866.html

I can't detect its presence by any other devices.

The code I uploaded to Arduino is a standard example for slave device from the library:

#include <SoftwareSerial.h>   //Software Serial Port
#define RxD 6
#define TxD 7

#define DEBUG_ENABLED  1

SoftwareSerial blueToothSerial(RxD,TxD);

void setup()
{
    Serial.begin(9600);
    pinMode(RxD, INPUT);
    pinMode(TxD, OUTPUT);
    setupBlueToothConnection();
}

void loop()
{
    char recvChar;
    while(1)
    {
        if(blueToothSerial.available()){//check if there's any data sent from the remote bluetooth shield
            recvChar = blueToothSerial.read();
            Serial.print(recvChar);
        }
        if(Serial.available()){//check if there's any data sent from the local serial terminal, you can add the other applications here
            recvChar  = Serial.read();
            blueToothSerial.print(recvChar);
        }
    }
}

void setupBlueToothConnection()
{
    blueToothSerial.begin(38400); //Set BluetoothBee BaudRate to default baud rate 38400
    blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
    blueToothSerial.print("\r\n+STNA=SeeedBTSlave\r\n"); //set the bluetooth name as "SeeedBTSlave"
    blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
    blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
    delay(2000); // This delay is required.
    blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
    Serial.println("The slave bluetooth is inquirable!");
    delay(2000); // This delay is required.
    blueToothSerial.flush();
}

I've uploaded it to Arduino UNO, connected the shield.

LED marked as D1 is blinking green, and D2 is switched off. The device is not detected by none of the  devices I've tried

Please Help Me

As per this site: http://www.rjanick.com/2012/11/26/seeed-studio-bluetooth-shield/

Try switching the #define rxd and #define txd pin numbers in the code, inversely corresponding to the ones that the jumpers are connected to on the board.

For instance: my pins are jumped from the BT_TX line to digital 6 (and BT_RX to pin 7), so in the code I write #define TxD 7, and RxD 6. This made the board's LEDs blink differently (red blinks on D2 until connection).


How to clear SoftwareSerial values? I'm using software serial on my weather station. The way it's supposed to work is that you send an SMS to the device and it replies with the wind speed, etc.
At the moment, The wind speed is detected, waiting for an incoming SMS. The SMS arrives and it sends a response but the response SMS is sent over and over infinitely.
I'm guessing the problem is due to the:
 if (mySerial.available()>0){

As this is what I'm using to test whether the SMS has arrived and presumably, it's then always set to available.
Does anyone know how to basically reset the software serial after the message has been sent?
 #include <SoftwareSerial.h>
 #include <ADSWeather.h>

SoftwareSerial mySerial(9, 10);

#define ANEMOMETER_PIN 2
#define VANE_PIN 0
#define RAIN_PIN 3

#define CALC_INTERVAL 1000

unsigned long nextCalc;
unsigned long timer;

int windDir;
int windSpeed;
int rainAmmount;

ADSWeather ws1(RAIN_PIN, VANE_PIN, ANEMOMETER_PIN); //This should configure all pins correctly

void setup()
{
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(RAIN_PIN), ws1.countRain, FALLING); //ws1.countRain is the ISR for the rain gauge.
  attachInterrupt(digitalPinToInterrupt(ANEMOMETER_PIN), ws1.countAnemometer, FALLING); //ws1.countAnemometer is the ISR for the anemometer.
  nextCalc = millis() + CALC_INTERVAL;

  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  delay(100);
}

void loop()
{
  timer = millis();

  int rainAmmount;
  long windSpeed;
  long windDirection;
  int windGust;
  int sent;

  ws1.update(); //Call this every cycle in your main loop to update all the sensor values

  if(timer > nextCalc)
  {

    nextCalc = timer + CALC_INTERVAL;
    rainAmmount = ws1.getRain();
    windSpeed = ws1.getWindSpeed();
    windDirection = ws1.getWindDirection();
    windGust = ws1.getWindGust();

//     windSpeed / 10 will give the interger component of the wind speed
//     windSpeed % 10 will give the fractional component of the wind speed
    Serial.print("Wind speed: ");
    Serial.print(windSpeed / 10);
    Serial.print('.');
    Serial.print(windSpeed % 10);
    Serial.print(" ");

    Serial.print("Gusting at: ");
    Serial.print(windGust / 10);
    Serial.print('.');
    Serial.print(windGust % 10);
    Serial.println("");

  }

  if (Serial.available()>0)
  {
      RecieveMessage();
  }

  //If an message comes in
 if (mySerial.available()>0){
  // Serial.write(mySerial.read());
  Serial.write("Message received");

  //Send the wind speed response.
  SendMessage();

  //At this point the SendMessage() repeats and the message is sent over and over.
}
}

 void SendMessage()
{
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"NUMRemoved\"\r"); // Replace x with mobile number
  delay(1000);
  mySerial.println("I am SMS from GSM Module");// The SMS text you want to send
  delay(100);
   mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
}

 void RecieveMessage()
{
  mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
  delay(1000);
 }

 void serialFlush(){
  while(mySerial.available() > 0) {
    char t = mySerial.read();
  }
}

For the hardware serial port, the buffer is 64 and I was reading at least 100 times. Every read will clear one byte of data from the serial buffer at a time.
For the software serial port, you do a dummy read and then check whether the buffer is empty or not using
    while(mySerial.available()>0)  {
       dummy = mySerial.read();
    }

So, in summary, you have to read the buffer until it is empty.
Useful notes:

You should be knowing when to expect actual data and when not to
have a way to identify the valid messages (some fixed header bytes)
have a way to validate the contents (checksum)

Leave a comment if you have any questions


Arduino: using digital pins to emulate USB device Is there any "easy" way to emulate USB keyboard or gamepad using digital pins on Arduino Mega? I looked at Uno-Joy/Mega-Joy, but I dont find firmware changes appealing.

There is (or was) an implementation of software-only USB for the Arduino. I think it was called V-USB, though I am having trouble finding it now.

I think it may be this library though nothing has happened with that for a number of years.

Personally, I wouldn't recommend it, though, and would suggest using a board with a real USB interface, such as the Arduino Leonardo, chipKIT Lenny, or Teensy 3.x.


Arduino shuts off and doesn't turn on after couple hours I use a mega 2560, pir sensor and a SG90 9g Servo motor in my project. Basically while the pir outputs high, the Servo Motor rotates from 0 to 180 degrees.

Here is how everything is wired up:

PIR sensor:

Data: pin 24

Vcc: 5 volt

Gnd: Ground

Servo:

PWM pin: pin 11

Vcc: 5 volt

Ground: ground

The arduino mega has two 5 volt and ground pins, one next to the analog pins and other at tho bottom bar of pin, where pins 22 and up are. I connected the Servo to the first 5v and gnd and the pir to the second.

My power source is my nexus 5 charger(5v 1.8 or 2 A).

My code:

Servo myservo;

    void setup() {
      myservo.attach(11);
     pinMode(24, INPUT);
    }

    void loop() {
     if(digitalRead(24) == HIGH){
       myservo.write(0);
       delay(500);
       myservo.write(180);
       delay(500);
     }
    }

All of this works fine for the first ~10 hours. After that the arduino just shuts down. The power led of the arduino isn't lit up. Disconnecting the adapter and reconnecting it or pressing the reset button of the arduino doesn't work.  I Have to wait for a couple of minutes with the adapter disconnected and reconnect it. After that it works fine for the next ~10 hours.

Seems like a hardware issue, but I'm not sure what exactly fails and why.

I assume your charger is connecting to the USB port of the Mega2560.

That USB port has a polyfuse (actually a special type of positive-coefficient thermistor) which is normally rated at around 500mA (polyfuses are a bit woolly with their ratings since they are heat based).

If you are drawing near that limit of current the fuse will be gradually heating up. I would think that after 10 hours it may have reached its threshold temperature and thus switches the power off.

Disconnecting the power and allowing it to cool down would then make the board work again.

How can you test it?  Well, next time it switches itself off try bypassing the polyfuse (tweezers would be good to do that with) to see if the power LED turns on again.


Arduino Pro Micro troubles I recently bought a brand new Arduino pro micro from Amazon, I set it up according to the instructions on sparkfun, except that when I plug it in, Windows doesn't even show that it tried to install device driver software. I figured it might just be a windows 10 thing because the tutorial was written on windows 7, so I forged ahead, and updated the device driver for COM3 in device manager, and attempted to upload a simple test for HID emulation:

#include <Keyboard.h>

void setup() {
  Keyboard.write('z');
}

void loop() {
  Keyboard.write('a');
  delay(5000);
}

It compiled just fine, and the IDE said it started uploading to the device, However, as it was uploading (or so I thought) I read a little farther and realized that the IDE wasn't set to use the right voltage (3.3V instead of 5V) I closed the IDE and reopened my sketch, changed the voltage to match up, and tried uploading it again. Here, it got stuck on the Uploading... text and so again, I closed the IDE.

Only the LED closest to the USB port is on, and it's solid green. I've connected to my computer using a Micro USB to USB adapter, and I initially plugged the board into a USB 3.0, but then switched to 2.0 to see if it made a difference. I have also tried it on Ubuntu 14.04 with no luck. I don't think it's bricked because if it was, my computer would still recognize it, but not know what it was (according to sparkfun), and as a result, I have yet to try the debricking method they suggest. Any thoughts?

The Pro Micro, like the Leonardo, cannot automatically reboot into the bootloader like boards such as the Uno and Mega.  Instead it relies on the sketch running on it listening for a special combination of events (open the serial port, set the baud rate to 1200 baud, close the serial port) to activate the bootloader.

If, for whatever reason, you don't have a working sketch installed on the board (such as you aborted the upload part way through) then there will be nothing there to listen for the "reboot into bootloader" instructions.

So you need to manually enter the bootloader. Fortunately it should be easy enough, but timing is all important.

When you first plug the board in, or when you press the reset button, you get a few seconds where the board is in the bootloader.  On the Leonardo that is signified by the LED glowing and pulsating - I don't know off hand what is shown on the Pro Micro.

As long as you press the reset button just before you compile and upload your sketch, and as long as the upload portion doesn't take too long to start (tip: compile it before uploading, it makes it faster) it should then install the sketch into the board and from then on the auto-reboot should start working.

(Note: I haven't used a Pro Micro - this is all from my experience with the Leonardo which I believe uses the same bootloader.)