Reproduce simulated temperature data with Arduino I'm starting a test using Arduino to reproduce a set of temperature values in water each three hours and need some help with it.
I will use two ds18b20 sensors to control two thermostats connected to relays. The idea is that Arduino could access the data from a file in which there are simulated data for each day in the future. Something like this:
Date,Time,Temperature
01/01/2070,00:00:00,27.229211807251
30/12/2070,21:00:00,24.6133060455322
01/01/2070,06:00:00,22.1697025299072
01/01/2070,09:00:00,20.3209171295166
01/01/2070,12:00:00,27.7610721588135
01/01/2070,15:00:00,33.6277084350586
01/01/2070,18:00:00,34.5402450561523
01/01/2070,21:00:00,31.9973392486572
02/01/2070,00:00:00,26.2283573150635
02/01/2070,03:00:00,21.5823612213135
02/01/2070,06:00:00,18.6461429595947
02/01/2070,09:00:00,17.2126712799072
02/01/2070,12:00:00,24.8096561431885
02/01/2070,15:00:00,30.6440677642822
02/01/2070,18:00:00,33.8463973999023
02/01/2070,21:00:00,31.3529300689697
03/01/2070,00:00:00,25.2961673736572
03/01/2070,03:00:00,20.8135623931885

Based on this info the sensor will control the thermostat to decrease or increase the temperature within three hours (8 different temperatures by day). I'm going to start with 1 week (7 day x 8 temperatures = 56 simulations), but want to increment it till 3 months (720 simulations).
Considering the use of if/else if, it seems that would be a massive amount of conditionals.
Does anybody have a good solution to run this temperature simulation based on predefined data?
Thanks in upfront.

You can use an array to go through the times.
Create a struct with the fields time and temperature (you should think about saving time as unix epoch, meaning seconds since 1970, so that you save memory).
struct SetPoint {
    unsigned long time;
    float temperature;
};

Then you can declare an array of type SetPoint to hold the tubles of time and temperature:
#define DATA_SIZE  720
SetPoint data[DATA_SIZE] = {
    {<time1>, <temp1>},
    {<time2>, <temp2>},
    ...
    };

In the above, you need to replace <timeX> and <tempX> by your data. Then declare a position variable, which the element index, which will be invoked next:
unsigned int pos = 0;

We are starting with the first element (index 0) and compare its time to the current time. If it is equal (or current time is after the elements time), we will set the thermostat to the elements temperature and increment the position variable. Something like this:
if(pos < DATA_SIZE && current_time >= data[pos].time){
    set_thermostat(data[pos].temperature);
    pos++;
}

Note: I used the variable current_time here as standin for your way of getting the current time, and the set_thermostat() function as a standin for your way of setting the thermostat. Also I inserted a check into the if statement, to prevent the code going further, when it reached the data array end.

That said, depending on the used board you can easily get into memory trouble here. An Arduino Uno does not have enough memory to save 720 of the data points above. float and unsigned long both take 4 bytes each, so 8 bytes per element, which makes 8*720 = 5760 bytes. The Uno only has 2048 bytes total in RAM. There are enough boards, which have more RAM. The ESP32 for example would have way enough (though there are many others; the ESP32 is just the first to get into my mind here).
Or you can add an SD card module to your build and save the data points in a file. That would also make it way easier to get the data in your project or change the data. It would just involving writing the corresponding file on your SD card.
Then the workflow would be a bit different. Lets assume you save one data point per line as text:

Open file and read one line. Close file.
Parse read text into 2 variables (time and temperature)
Use these variables for the if statement from above
if the time of the loaded data point was reached, open the file again, read the next line and parse it into the variables
The if statement now uses the next datapoint

and so on. If there is no line left to read, you could go into an infinite loop, stopping the code from running further than your data.
There are ready to use SD card modules to buy out there, and you can find many tutorials about how to use them online.

As Edgar Bonet correct stated in the comments, you can greatly reduce the needed RAM, when assuming regular intervals (3h in your case). Then you don't need to save the time for each data point. You only need the one start time for the series. Also above I used float for the temperature (as I assumed, that at this point it would be the easiest for you). But since temperature settings for thermostats are mostly working only down to the 1 digit after the decimal point, you can save memory space by using a different representation. For example you could save the temperature as a single byte signed integer with the unit of 0.1°C and a reasonable offset (for example 25°C being zero). So some example values would be:
Temp | value
------------
18°C | -70
20°C | -50
22°C | -30
25°C | 0
27°C | 20
35°C | 100

That would give you the precision of one digit after the decimal point and a range from 12.3°C to 37.8°C. When changing the factor of 0.1°C, you can also change the range (and precision with it) as you really need it.
So with the above you would only need 720 byte for the actual data, which is good for the Uno.
BUT: I would still suggest looking into the SD card reader. You will have more work building the project, but you won't have the same hassle with including or updating the data. That can come in especially handy, if you want to use to further use the device after the 3 months. Just loading new data on it (maybe even way more data, like for a full year) is easier with an SD card.


Dallas Temperature Sensor DS18B20 not showing correct Result with Ethernet Shield I am using Arduino Uno R3 board and a wiznet W5100 ethernet Shield. The temperature from the One wire sensors before using Ethernet Shield was showing correct. However later after connecting the shield, the temperature is showing to be 85. The server and everything else works fine, but the data is all wrong. Now I am pretty sure the connections are correct and it is not in parasite mode. Any suggestions of how I might get the accurate reading ?

/*
  Web Server

  A simple web server that shows the value of the analog input pins.
  using an Arduino Wiznet Ethernet shield.

*/

#include <SPI.h>
#include <Ethernet.h>
#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 2

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
            0xF0, 0xBF, 0x97, 0x67, 0xF6, 0x98
        };
IPAddress ip(192, 168, XXX, XXX);

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
EthernetServer server(80);

void setup() {
    // Open serial communications and wait for port to open:
    Serial.begin(9600);
    sensors.begin();
    while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
    }
    // start the Ethernet connection and the server:
    Ethernet.begin(mac, ip);
    server.begin();
    Serial.println(sensors.getTempCByIndex(0));
    Serial.print("Siddhartha Temperature ");
    Serial.print("server is at ");
    Serial.println(Ethernet.localIP());
}

void loop() {
    // listen for incoming clients
    EthernetClient client = server.available();
    if (client) {
        Serial.println("new client");
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {
                char c = client.read();
                Serial.write(c);
                // if you've gotten to the end of the line (received a newline
                // character) and the line is blank, the http request has ended,
                // so you can send a reply
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    client.println("Content-Type: text/html");
                    client.println("Connection: close");
                    client.println("Refresh: 2");
                    client.println();
                    client.println("<!DOCTYPE HTML>");
                    client.println("");
                    // output the value of each analog input pin
                    for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
                        float sensorReading = sensors.getTempCByIndex(0);
                        client.print("Temperature ");
                        client.print(analogChannel);
                        client.print(" is ");
                        client.print(sensorReading);
                        Serial.println(sensorReading);
                        client.println("
");
                    }
                    client.println("");
                    break;
                }
                if (c == '\n') {
                    // you're starting a new line
                    currentLineIsBlank = true;
                }
                else if (c != '\r') {
                    // you've gotten a character on the current line
                    currentLineIsBlank = false;
                }
            }
        }
        // give the web browser time to receive the data
        delay(1);
        // close the connection:
        client.stop();
        Serial.println("client disconnected");
    }
}

The Solution was actually much simpler. Apparently the Ground on the voltage I/O ports wasn't the right place to connect the ground terminal of the sensor. rather The Ground of the Digital I/O should be connected. Mistake retrieved by trail and error!! Its working just fine now.


Uno - ESP32 SoftwareSerial communication won't work I have two boards, Uno and ESP32 and my goal is to send data from the Uno to the ESP. I made a voltage divider so my ESP doesn't get fried and I use the communication only in ONE way, strictly UNO -> ESP32. I use PIN 9 from my UNO to send data and RX2 (16) from my ESP to receive the data. How ever, I get errors and can't make it work.
This is my Uno code:
#include <SoftwareSerial.h>

SoftwareSerial softPort(-1, 9);

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

void loop() {
softPort.print("100");
delay(2000);

}

and my ESP code:
#include <SoftwareSerial.h>

#define RXD2 16
#define TXD2 -1

SoftwareSerial Serial2(RXD2, TXD2); // RX, TX

void setup() {
Serial.begin(115200);
Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);

}

void loop() {
Serial.println("Data received:");
Serial.println(Serial2.read());
delay(200);

}

I'm getting an error that says

no matching function for call to 'SoftwareSerial::begin(int, int, int, int)'

On the ESP32 you would never use SoftwareSerial except under exceptional circumstances.
The ESP32 has three hardware UARTs that can be mapped to any pin combination on the board.
The general usage is:
HardwareSerial Serial2(1); // Use UART channel 1

void setup() {
    Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
}

UARTs are numbered 0-2 where 0 is pre-assigned to the TX/RX (USB connection) pins and is used for debugging and programming.  UARTs 1 and 2 are not normally assigned to anywhere and you can use them as you see fit.


Stepper Motor Direction via Flow Amps I have a problem with stepper motor direction.

I want to change the direction of the stepper motor rotation, when the stepper motor shaft is stuck.

For example, when I hold the shaft of the stepper motor with my hand, the direction should change.

How can I do it?
Someone told me you should calculate the current, but I don't know how to do this?

My material components:

Arduino
stepper motor gearbox 12 V
ULN 2003A

When motors stuck their current draw increases, you can sense that increase in the current and then change the rotation of the motor. The simplest way to measure current is with using a shunt resistor, for sensing high currents, current sensors based on hall effect sensors is usually used. ACS712 is one example.

How to sense current using a shunt?

Basically we're measuring the voltage drop over a resistor (RS), but the voltage drop is too small for Arduino to measure so we need an opamp to "amplify" the input:

simulate this circuit – Schematic created using CircuitLab

The schematic above is the simplest way to measure the voltage drop at "LOW SIDE", there is differential mode and "HIGH SIDE" measurement methods.

The gain of opamp can be set with resistors and this formula:

VOUT = (1 + R2/R1) * V1

The output of opamp then can be calculated to get current using ohm's law:

I = V / R

A simple code to calculate current:

int rawAnalog;
float voltageDrop;
int resistor = 0.1;
float current;

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

void loop() {
  rawAnalog = analogRead(A0); // Read A0 input
  voltageDrop = (rawAnalog * 5) / 1024; // Convert the raw value to voltage
  current = voltageDrop / resistor; // calculate the current
}

Bonus: INA219 is an easy to use high-side I2C module which can measure both current and voltage.


Two SD card interfaces on one ESP8266? I know it's possible to hook up multiple SPI devices, but how can one access the second drive from a sketch?

Looking at the SDWebServer.ino example, my doubt is with the SD.begin(SS); part. If I call begin() again with the other CS pin, it seems that I would lose a reference to my first volume, or maybe it won't work at all. I would instantiate another SD instance, but the sketch never seems to instantiate that object, it first appears in setup() with SD.begin(SS);

If I copy the lib (sd.h+sd.cpp) and replace all literal instances of SD with SD2, can I then include and use SD2 just like the original (provided the different .begin(pin))? Is there a less hacky way of using two SD cards in ESP8266 Arduino?

In case anyone's wondering, it's for a crypto project where one card will contain one-time-pads of plaintext length and the other contains the XOR'd ciphertext, both are fed by wifi upload, and the max file size must be bigger than SPIFFS, so I really need two SD cards...

Not possible without changing the library code. Because the current library code is written intended for only one SD card, ie not intended for multiple SD cards because it will be complicated to do so. The SPI library also uses FatFS library, which is a bottleneck in this scenario.

Worth a try.

sdfatlib is library written for Arduino. I have never used it, but you can give a try on ESP.

Let us know if it works.


Baud rate Arduino/Linux I'm trying to communicate some numbers between a Linux program and my Ardunino Uno. To this end I wrote a C++ program which somehow contains:

#include <stdio.h>

int a,b;
a = 1;
b = 2000;

File* serial = fopen("/dev/ttyACM0","w");
fprintf(serial,"%d,%d\n",a,b);
fclose(serial);

Now out of standards I guess, the baud rate is 9600 bit/s. If I use stty -F /dev/ttyACM0 115200 I can change the baude rate of that port to 115200 bit/s. However the communication does not work anymore. My arduino program waiting for number,number does not show any action to the same code as before. Oh, and in the Arduino program of course I changed the code to serial.begin(115200);.

How can I change the baude rate in such a setup? If it is a concern, I'm using Ubuntu and an Arduino Uno.

Setting baud rates in a C program isn't a trivial task. You need to use the low-level open() instead of fopen() and act on the returned file descriptor with ioctl() or tcsetattr() / tcgetattr().  The former method allows the setting of non-standard baud rates while the latter only allows specific baud rates to be used.

I wrote a C++ class to deal with it all for me a while back. You are welcome to examine the methodology and/or steal whatever bits of it you like to use in your own program.

https://github.com/majenkotech/SerialPort


Can batteries be damaged? I have some questions when it comes to draining batteries with low power projects.

I have been making a few low power projects with Arduino Pro Minis running on batteries. Some run on single non-recharchable CR123As while others run on two or three recharchable AAAs. I have removed the regulator and the power led on the Pro Minis, and I have changed the fuses making them run as low as 1.8v (or according to my measurements 1.7v). This way they consume a few µA and should be able to run for years on those batteries.

Now, what started to concern me is that this setup will be able to run the batteries very low. According to the voltage curve of a CR123A, it will be practically drained when reaching 1.7v. The same goes for two or three recharchable NiMH AAAs, that will have an individual voltage of 0.85v or 0.55v. Unless the batteries themselves have a discharge protection built in. In that case there might be no problem at all; I just don't know if batteries such as Eneloops have that.

So my questions are:

1) Do batteries such as CR123As and Eneloops have built in discharge protection so that they stop supplying power when the voltage is too low?

2) If no, will draining a non-rechargable CR123A be dangerous or problematic in any way? And will draining MiMHs down to 0.85v/0.55v hurt the batteries?

3) And, a question that I suppose applies to any battery powered Arduino project: When the supplied voltage drops below the Pro Minis BOD limit, will the Arduino stop using any power, or will it continue draining the batteries until they are completely empty? (In the first case I guess I could stick with the factory set BOD at 2.7v to protect the batteries.)

4) Finally, relating to the first question: Should I try to construct some kind of battery protection in the circuit, or is unnecessary when using CR123A and NiMH batteries?

1) Do batteries such as CR123As and Eneloops have built in discharge protection so that they stop supplying power when the voltage is too low?

No, they don't.  They just run till there is nothing left.

  2) If no, will draining a non-rechargable CR123A be dangerous or problematic in any way? And will draining MiMHs down to 0.85v/0.55v hurt the batteries?

A single cell can be run completely flat without problems. NiMH may need some "recovery" to wake them back up again, but shouldn't suffer serious problems (and no safety issues).  However, batteries are a different matter: see below.

  3) And, a question that I suppose applies to any battery powered Arduino project: When the supplied voltage drops below the Pro Minis BOD limit, will the Arduino stop using any power, or will it continue draining the batteries until they are completely empty? (In the first case I guess I could stick with the factory set BOD at 2.7v to protect the batteries.)

It will continue draining power. The BOD is a reset circuit - designed to recover the system into a known good state after a dip in the power. A permanent decrease in the input power is beyond the scope of the BOD system.  It will just get stuck in a BOD reset loop and consume all your remaining power.

  4) Finally, relating to the first question: Should I try to construct some kind of battery protection in the circuit, or is unnecessary when using CR123A and NiMH batteries?

For a single non-rechargeable cell you can just let it run flat. For NiMH you need to protect them.  Here's why (and what I was alluding to above):

When you have two or more cells in series (a battery) the current flows through all the cells of the battery equally. That is all fine when the cells are all fully charged - however no two cells are precisely the same.

As the battery runs down each cell will approach "empty" at a different time. With a single cell that's not really a problem, since it will just stop providing enough current to run.  However, with multiple cells one cell will run flat before the others. At that point the current provided by the other cells which still have some charge in them will be pushed through the flat cell backwards.  It is at that point that the flat cell becomes irrevocably damaged.  Current flowing backwards through the cell will try to reverse charge the battery and mess up the internal chemistry beyond recovery.

In the best case scenario, your battery will now have a much lower capacity and need recharging far more often. Worst case scenario: that damaged cell overheats and explodes.

The most prevalent problem that is caused by reverse charging is the depositing of metal crystals on the dielectric (the separator between the two electrodes) in the cell which grow and pierce the dielectric causing short circuits within the cell. There is no way back from that happening.

So you should protect your NiMH batteries from over-discharge by cutting the power to your circuit when the voltage drops below a specific threshold.  You should also recharge all the cells individually, not together in series, or they will end up unbalanced and the same problems of over-discharge can occur.

As a side note: I use the terms "cell" and "battery" with their "proper" usage: A cell is a single power-producing unit, such as an AA "battery".  A battery is a collection of cells.  This is the proper usage of the words, not the common usage where battery can also be taken to mean cell.  I use these terms specifically to differentiate between a single unit and a collection of units because of the major differences in how you need to handle them. It helps prevent confusion if you know that I am talking about just one AA (a cell) or a collection of three AA in series (a battery), for example.


How to prevent shoot-through when swiching a motor with a bridge? Ideally, when wiring a motor with an H-Bridge one would ensure that all "open" operations are performed before and "close" operations in order to prevent a short circuit. How does one ensure that these operations are performed in order when using a bridge?

I see on some forums that the L298 IC is a recommended bridge for controlling motors with the Arduino, but this condition is seemingly never discussed. It is not an issue with the speed of modern ICs or are the common tutorials overlooking shoot-through in the interest of simplicity?

You only get this kind of problem when you are manually controlling the high- and low-side switches manually.  Bridge chips seldom make you do that and include the logic and drive circuitry within them so that you just control a HIGH or LOW to a "leg" and it switches the two transistors properly for you.

You normally get an "enable" and a "direction" input.

For instance, take the L298 internal circuit:

If we look at the left-most transistor pair you can see they are driven by a pair of gates. One has an inversion on the input.  The gates are mainly there to AND the enable signal in, but the inversion on the upper input of the lower gate is the vital thing. That makes sure that one transistor is on when another is off. You can't turn both on, or both off - you only have a single signal that indicates which should be on.

Of course, that circuit is very simplified, and there is additional circuitry that ensures that during the switching period one transistor switches off before the other switches on.  Matched transistors with known switching characteristics, adding offsets to the base voltages with diodes, etc are all methods that are used internally.

With MOSFET based bridges it's less of an issue since gate threshold (VGS) come into play and choosing and matching the transistors correctly automatically creates a "dead zone" in the switching input voltage range.


Greyed out port for Raspberry pico in Arduino IDE - Ubuntu 20.04 I'm trying to figure out how to program my new Raspberry Pico with Arduino, but don't see a port to select so I can't upload the blink sketch.
Here's what I've done:

The Pico is working, I can program it with micro Python.
Just in case, I brought the Pico back to factory settings with the nuke file.
Installed support for the Pico in Arduino IDE. Version 2.1.0 of Arduino MBed RP2040 is installed.
While keeping BOOTSEL pressed, I plug in the Pico to my laptop (Ubuntu 20.04)
The board selected is "Raspberry Pi Pico"
But the option to select a port is greyed out :-(

It seems that I am omitting some step during the installation, but can't figure out what it is.
Any ideas?
Thanks!

I've come across this and this is how I worked around it (on Windows, but I suspect the problem and solution is the same).
A brand new Pico or one not programmed by the Arduino IDE does not have a serial port, which is why you can't see one. Arduino sketches are compiled with a serial port automatically, so once a serial port exists, it can be used for future uploads.
The Arduino solution is to use the 'Export compiled binary' option (for any sketch) and upload the UF2 file (which should be generated into the sketch folder) using virtual USB drive interface. When the sketch starts, the serial port will be available and can be used for future sketch uploads.
Another solution is to use an alternative Pico core. This one does not need the port selected, but will find and upload to a Pico in bootloader mode via the virtual USB drive.


Using 18650 batteries with a 3.7v to 5v boost converter I'm looking to set up a 1-meter strip of WS2812B LEDs (60 LEDs) with an off-the-shelf RF LED controller with a remote. The LEDs want a 5V supply - I've tried running them off 3.7v but the colour accuracy goes out the window and they start flickering and doing all sorts of other nonsense.

To work around that I'm considering using a DC boost converter like one of these pololu ones. I'll wire up a couple 18650 batteries in parallel to supply the voltage and my plan is to hook them up to the LEDs via the boost converter.

Idiot question time: is it safe to wire the boost converter directly to the output terminals of the battery/batteries and take the 5V off the +5v pin using a common ground? Or am I doing something dumb?

Also, I'm not 100% sure how to go about charging this setup. One option would be to put the batteries in cases and use an external charger with replaceable cells.

Would it make more sense to get one of these? This should be able to handle both charging AND stepping up the voltage, am I right?

is it safe to wire the boost converter directly to the output terminals of the battery/batteries and take the 5V off the +5v pin using a common ground?

Yes. That is the normal way of using them.

  Also, I'm not 100% sure how to go about charging this setup. One option would be to put the batteries in cases and use an external charger with replaceable cells.

That is the simplest option, yes. You shouldn't charge Li-Poly / Li-Ion batteries whilst using them - the load messes with the charge termination detection and can cause your batteries to over-charge and explode.

  Would it make more sense to get one of these? This should be able to handle both charging AND stepping up the voltage, am I right?

That gets around the problem of charging while running, yes. A proper charger like that should bypass the battery when charging so the load is running from the incoming charge power rather than the battery.

One option you haven't considered though is to not use step-up.  Step-up is harder to manage with heavy loads. As you can see that first step-up module you link to has an upper limit of only 1.2A.  If you have 60 LEDs per meter, and 1 meter of LED strip, that's a maximum of 3.6A (60 * 0.02 * 3) which is 3x what that module can provide.

A better solution would be to use two batteries in series, not parallel, to give you about 7.2V. Then you can use a step-down switching regulator to give you your 5V and have far higher current limits.  Looking for a "UBEC" or "SBEC" in a model RC supplier shop is usually a good bet. For example:

Turnigy 5A (8-26v) SBEC for Lipo

HobbyKing™ HKU5 5V/5A UBEC

These are all designed for use with two or more LiPoly batteries in series.


Transmit/Receive data Nodemcu(V3) + Bluetooth Module HC-05 I am trying to communicate with the HC-05 Bluetooth module for quite long time now, but with no success.

I am using the Nodemcu(V3) ESP8266 module.

I connect the HC-05 to Nodemcu in following sequence:

HC-05             Nodemcu
-----             -----------
RX       -->      Pin 1 (Tx)
TX       -->      Pin 3 (RX)
Vcc      -->      +3.3V
GND      -->      GND

For starters, i want to check if my Nodemcu is communicating properly with my HC-05 module.

I have written the following code to read the response of AT commands:

#include <SoftwareSerial.h>
SoftwareSerial BTserial(3, 1); // RX | TX
char Bluetooth_Name = ' ';

void setup()
{
    // Arduino IDE serial monitor
    Serial.begin(115200);

    // HC-05 default serial speed for AT mode is 38400
    BTserial.begin(38400);

    // Wait for hardware to initialize
    delay(1000);

    // Print debug string
}

void loop()
{

   // Keep reading from HC-05 and send to Arduino Serial Monitor
   if (BTserial.available())
   {
      reading = BTserial.read();
      Serial.println(reading);
   }

   // Keep reading from Arduino Serial Monitor and send to HC-05
   if (Serial.available())
   {
      reading = Serial.read();
      BTserial.write(reading);
   }
}

However, i do not get response for any AT command at all. The serial monitor just shows blank.

Thanks in advance

EDIT:- I connected the "EN" pin on the HC-05 to Vcc. Now, the led on the HC-05 blinks slowly, which means that the HC-05 is configured in command mode. However, i am still not able to receive the response for any AT commands. I have also selected "Both NL & CR" in the serial monitor, configured the baud rate correctly and double-checked the hardware connections.

Everything seems to be correct except that i don't get response for the AT commands.

Please help!!!

I had the exact same problem and got it to work doing these changes:
I had to add this under my library include statements
#ifndef D5
#if defined(ESP8266)
#define D5 (14)
#define D6 (12)
#define D7 (13)
#define D8 (15)
#define TX (1)
#endif
#endif

and changed
SoftwareSerial BTserial(3, 1); // RX, TX
to
SoftwareSerial BTserial(D5,D6);
I used D5 and D6 on my esp8266 instead of D1 and D3 but shouldn't matter


How to calibrate MPU 6050 thermometer? I'm using MPU 6050 and there's a thermometer onboard. However, I looked through the chip set data sheets but could not find the instruction for temperature sensing.

Could you tell me how to calibrate the data string from the two address started from 0x41?

The temperature sensor is likely included to keep the gyroscope and accelerometer better calibrated over the specified temperature range.  The temperature may not be the ambient temperature should the chip warm up.

The temperature sensor specifications are in section 6.3 on page 14 of the specification sheet indirectly pointed to in the question.

TEMPERATURE SENSOR
Range -40 to +85°C
Sensitivity Untrimmed 340 LSB/ºC
Temperature Offset 35ºC -521 LSB
Linearity Best fit straight line (-40°C to +85°C) ±1°C

So, when the chip is at 35C the chip temperature register is supposed to read about -521.  To convert that into C you need to make a calculation:

  chip_temperature = ((value_read + 521) + (35 * 340)) / 340

Simplified:

  chip_temperature = (value_read + 12421) / 340


Where to get the potentiometer that comes with Arduino kit Does anyone know where I can get the potentiometer that comes with the Arduino kit? You can see them here.

They are sold out on their website.

It's just any old trimmer pot. It's nothing special. Why do you feel you need that specific one? Any pot (of the right value) will do.  What value is it? (That datasheet is a generic one for all values).

Visit your favourite electronics retailer (IRL or on line) and pick a pot that is a suitable value and jiffles your tipples.


Make a Robotic Arm move straight not curved I am planning on a project that includes a robotic arm controlled by Arduino. A simplified program of this would be:

A robotic arm picks up an object
The robotic arm then moves the object in a straight line
The robotic arm releases the object

The problem with this is that every robotic arm that I have seen works with servos, which rotate precisely within 0 and 180 degrees. But, because the robotic arm moves with servos, it then moves in a curved path, rather than the desired straight path.

The two paths in this problem appear in this image. The one on the left is the desired, but the one on the right is the one that occurs when using any robotic arm.

Is there any way to make the robotic arm move in a straight path? Is there a specific robotic arm that moves in straight lines rather than curved lines?

Thanks for any help!

Here is the link to an example of a robotic arm picking up an object and moving in a curved path, and not a desired straight path.

It requires doing some geometry.  Think about how you would do that with your arm.  You'd have to move more than one joint at a time.  So you have to define the line you want to follow, and back calculate from each point on the line what the angles of all the joints need to be in order to put the end there.  This will require a bit of trigonometry.  Is that something you've studied before?


Programming Arduino via RX/TX I can't access my Arduino Micro's USB programming port when it's in my project. I want to reroute the RX and TX pins outside to a serial-to-usb adapter.

I have this on hand from a while ago. I found the RX and TX pins in the serial connector and I connected them to the RX and TX pins of the Arduino as well as GND but when I try and program the device nothing happens. I usually get an open port error or something like that but the programming LED on the adapter doesn't light up. Conversely if I try using the Basic Stamp software I at least get a programming LED to light up on the adapter.

Do I need an FTDI breakout instead? Or am I wiring something wrong?

RS-232 logic uses a negative voltage typically from -3 to -25V to represent a logical high and a positive +3 to +25V to represent a low. On the flip side TTL used on the AtMega uses +5V or +3.3V as a high (or VCC) and 0V as a low. Read more

Other than that the signals are the same logically so all that is needed is to invert the RS232 from -/+ ~12V to 0-5V using a simple converter.

Possibly the easiest approach is to use another Arduino Uno as a programmer, which needs 3 pins, TX, RX, and RESET. This tutorial seems to have some success. Check out "programming an Arduino with another".


How to make battery last for months? I have a simple circuit: detect that a person is walking towards the circuit (with HC-SR04), measure distance, light diodes (a wave effect) according to that distance – the closer, the faster the led wave.

When no person detected, sleep longer:

LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);

When person detected, sleep shorter (so that diodes can be often turned on/off):

LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF);

Without LowPower use – delay() used instead – the current taken is 15 mA. This is with diodes off. After using LowPower – it's still ~15 mA. This is very disappointing. I've expected the battery to last at least for 3 months, but it (9V) was drained within hours. Am I missing something?

Also a curiosity: the execution was fully blocking itself on LowPower calls, I've had to add short delay() before the calls, then they don't block execution.

#include <LowPower.h>
#include <NewPing.h>

#define trigPin 13
#define echoPin 12

NewPing sonar(trigPin, echoPin, 250);

// Defines speed of LEDs traversal
int delayTime = 40;

// Current led
int currentLED = 0;

// Direction of travel over LEDs
int dir = 1;

// Stores the last time LEDs were changed
unsigned long timeChanged = 0;

// Stores the last time sensor was read
unsigned long timeOfQuery = 0;

// LEDs
byte ledPin[] = { 4, 5, 6, 7, 8, 9, 10, 11 };

// Stores if any diodes are on
int leds_used = 1;

// Stores if wave is active
int off = 1;

// 5 last distances, circular buffer;
long distances[7] = { 400, 400, 400, 400, 400, 400, 400 }, currentDistance = 0;

// Last chosen distance
long distance = 400;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  for (int x = 0; x < 8; x++) {
    pinMode(ledPin[x], OUTPUT);
  }
  timeChanged = millis();
}

void loop() {
  long duration, cur_time, cm;

  cur_time = millis();

  /* Read distance when off, or when some time passed */
  if (off || (!off && (cur_time - timeOfQuery) > 100)) {
    timeOfQuery = cur_time;

    cm = sonar.ping_cm();
    if ( cm == 0 ) {
      cm = 400;
    }

    distances[(++currentDistance) % 7] = cm;
    // At least 1 proper distance?
    off = 1;
    for (int i = 0; i < 7; i++) {
      if (distances[i] <= 200) {
        off = 0;
        // Remember minimum distance
        if (distances[i] < distance) {
          distance = distances[i];

        }
      }
    }
    delayTime = distance;
  }

  if (!off) {
    // Check whether it has been long enough
    if ((cur_time - timeChanged) > delayTime) {

      // Turn off all of the LEDs
      for (int x = 0; x < 8; x++) {
        digitalWrite(ledPin[x], LOW);
      }

      // Turn on the current LED
      digitalWrite(ledPin[currentLED], HIGH);

      // Mark that diodes are being used
      leds_used = 1;

      // Increment by the direction value
      currentLED += dir;

      // If we are at the end of a row, change direction
      if (currentLED == 7) {
        dir = -1;
      }
      if (currentLED == 0) {
        dir = 1;
      }

      // Store the current time as the time we last changed LEDs
      timeChanged = cur_time;
    }

    // Shorter delay when sleeping
    delay(5);
    LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF);
    //delay(50);
  } else {
    if (leds_used) {
      // Turn off all of the LEDs
      for (int x = 0; x < 8; x++) {
        digitalWrite(ledPin[x], LOW);
      }
      currentLED = 0;
      dir = 1;
      leds_used = 0;

      // Store the current time as the time we last changed LEDs
      timeChanged = cur_time;
    }

    // Longer delay when sleeping
    delay(10);
    LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);
    //delay(200);
  }

  /*
    if (distance >= 200 || distance <= 0) {
      Serial.print(distance);
      Serial.println(" Out of range");
    }
    else {
      Serial.print(distance);
      Serial.println(" cm");
    }
  */
}

Update: The board is Arduino UNO.

The Arduino UNO always consumes current mainly because:

it has 2 MCU, the ATmega328 which you can power down, and an ATmega16u2 for USB communication which is never powered down.
in addition, the voltage regulator is permanently leaking some current

To be honest, I am surprised your UNO consumes only 15mA, on my boards, it is rather near 40-50mA.

Also, a 9V battery is probably the battery with the smallest charge capacity.

I would suggest you:

work on a breadboard with just the ATmega328,
power it with two 1.5V batteries (AA or AAA)
and run @8MHz

That should already reduce current consumption.

You may even try smaller MCU (e.g. ATtiny84A) which consumes less current than the ATmega328 in the same conditions.

Finally, I highly recommend Nick Gammon's blog on that topic. It includes many good tricks to help you with current consumption.


If your IR library does not support sending signals stored in PROGMEM,
then you will have to provide the data in RAM. However, you do not have
to keep both signals in RAM permanently: only the one you are about to
send needs to be there.

I suggest you keep all the IR signal data in PROGMEM while not sending
them. Whenever you want to send a signal, you copy it to a RAM-based
buffer and give the address of that buffer to the library. The same
buffer will be reused for any signal you are sending. This will cost
you some CPU time for the copy, and save 394 bytes of RAM. The savings
will scale up if you add more signals to your sketch.

const size_t signal_size = 197;

static PROGMEM const uint16_t irSignaloff[signal_size] = { ... };

static PROGMEM const uint16_t irSignalon[signal_size] = { ... };

/* Send an IR signal from PROGMEM. */
void send_signal(const uint16_t *signal) {
    static uint16_t signal_buffer[signal_size];
    memcpy_P(signal_buffer, signal, signal_size * sizeof *signal);
    irSend.sendRaw(signal_buffer, signal_size, FREQ_KHZ, false);
}

//...
send_signal(irSignalon);
send_signal(irSignaloff);

Here I am assuming that all your signals have the same length, which is
true for the example you show, but may be false if you add more signals
later. You may then need to size the buffer as the longest of all your
signals, and provide the signal length as an extra parameter to
send_signal().

Note that the RAM buffer does not need to be static. I chose to make it
static here only in order for avr-size to give you a good estimate of
the memory requirement of the program.


i2c scanner stuck on scanning for my 0.96in OLED screen with my Arduino Nano My pins are connected as follows; vcc-3v3, gnd-gnd, sda-A4, scl-A5.

Is it a 3.3 V only OLED? I suppose its vcc(OLED)-3v3(Nano).
Most OLEDs use 3.3V -5V where sometimes the 3.3V from the Arduino is not sufficient.If its a 3.3V only OLED could you give the make of the OLED (does it have jumpers to change I2C address). Normaly the I2C scanner should return at least with nothing found.


Does Arduino.cc sell the Ethernet Shield? I can't find more information on the Ethernet Shield. Arduino.cc has docs about it but where do I buy it? Is Arduino.org the sole provider? I've read about the political schism between the two companies and I'd rather not buy from them.

ebay is overflowing with ethernet shields/modules.

Alternatively, if you trust Wikipedia, you can form your own opinion about from which of the parent stores to buy.


How to restart a counter in a program using a push button in a LDR Tripwire setup So, trying to configure this code so that when I push the button, the person counter will go to zero and just as it goes, the counter will increase when the LDR will get tripped and again when the button is pressed, the counter will go to 0.

#include <LiquidCrystal.h>

int laser=8;
int pushbutton=12;
int flag=0;
int myCounter = 0;
LiquidCrystal lcd(7,6,5,4,3);

void setup()
{
    pinMode(laser,OUTPUT); pinMode(pushbutton,INPUT);
    lcd.begin(16, 2);
    lcd.print("Person Counter:"); lcd.setCursor(0,1);
    lcd.print(0);
}

void loop()
{
    lcd.setCursor(0, 1);
    digitalWrite(laser,HIGH);

    if(analogRead(A0) < 600) //A0= LDR
    {
        flag = 1;
    }

    if(analogRead(A0) > 600 && flag == 1)
    {
        myCounter++;
        delay(200);
        lcd.print(myCounter);
        delay(20);
        flag=0;
    }
}

Try out this code. I made some modification and also comment out that things.

#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 6, 5, 4, 3);

int laser = 8;
int pushbutton = 12;
int flag = 0;
int myCounter = 0;

void setup()
{
  pinMode(laser,OUTPUT);
  pinMode(pushbutton,INPUT_PULLUP); // Provide pull-up

  lcd.begin(16, 2);
  lcd.print("Person Counter:");
  lcd.setCursor(0,1);
  lcd.print(0);
}

void loop()
{
  lcd.setCursor(0, 1);
  digitalWrite(laser,HIGH);

  if(analogRead(A0) < 600) //A0= LDR
  {
    flag = 1;
  }

  if(analogRead(A0) > 600 && flag == 1)
  {
    myCounter++;
    delay(200);
    lcd.print(myCounter);
    delay(20);
    flag = 0;
  }

  if(digitalRead(pushbutton) == LOW) // When button pressed
  {
    myCounter = 0; // Set counter to 0
  }
}


Power supply for Seeeduino Xiao The Seeeduino Wiki claims that it can run on 3.3V/5V. It doesn't specify if it can step down higher voltages. I am looking to power the XIAO using a battery. It usually uses a USB-C cable which can provide 5V. Will I need to step the voltage down, or does it behave like a normal Arduino Nano and automatically step down the voltage?

If you scroll down on that page you link to you can see the power circuit. It uses an XC6206 voltage regulator which has a maximum input voltage of 7V and a dropout voltage that could be as high as 680mV.
So you can feed between about 4V and 7V in to the VIN pad and it will step it down to 3.3V. Anything below 4V and you will go "out of regulation" though the system may still run down to lower voltages. If you go above 7V you will blow it up.


What does display.setSegments(&segto, 1, 1); do? I am using a TM1637 display for my Arduino Uno. The goal was to just light up one point of the colon in the middle - what seems to be kind of impossible to accomplish. During research I stumbled over the following snippet, which I dont fully understand:
  uint8_t segto;
  int value = 1244;
  segto = 0x80 | display.encodeDigit((value/100)%10);
  display.setSegments(&segto, 1, 1);

Ok line 1 seems to declare s.th. like a char, an unsigned 8bit integer. Line 2 should be clear.
Line 3: The pipe symbol seems to do a kind of addition - never seen this before. The rest here is also not clear to me - why these strange calculation to pass a value (here 2) to .encodeDigit() ?
Finally line 4: Why is the adress of 'segto' passed to the function instead of just the value?
This all ends up showing a "2:" on the display. I got the snippet from this 'manual': https://robojax.com/learn/arduino/robojax-TM1637_display_manual.pdf
Maybe s.o. can help to light things up a bit

Let's take the hardest line first.  We'll start from the "inside" outwards.
segto = 0x80 | display.encodeDigit((value/100)%10);

The innermost bit is:
value/100

That gives you 12 from 1244.
Then there's modulus 10.
12%10

That gives you 2 (divide by 10 and return the remainder - 12/10 = 1.2, or 1 remainder 2)
That is then passed through a function that calculates what segments need to be turned on to represent the digit 2. Let's say that's 00110111 in binary, where each bit represents a segment to display.
To that you want to add the colon, which is in the most significant bit's place.  So you set that bit. That's done with the OR operator, which in C is |. 0x80 is 10000000 in binary.
OR the two values together:
00110111
10000000
========
10110111

That value is then assigned to the segto variable.
I am not familiar with that library, but I would assume that the setSegments function is expecting an array of segment settings, a number of digits to apply it to, and maybe a digit offset in the display (at a guess).
In C there is no real difference between using a 1 element array and using a variable and taking its address.
You could just as well have used:
uint8_t segto[1];
int value = 1244;
segto[0] = 0x80 | display.encodeDigit((value/100)%10);
display.setSegments(segto, 1, 1);

If you were doing more than one digit you'd be wanting to use an array anyway.


Arduino Modbus Master code to read data using arduino uno from EB meter I am using DC energy meter as slave.When I am testing DC energy meter using Modbus tester tool,its showing value from 1 to 24 register.I am using my own atmega328P with on board RS485 as a master device.I have connected A,B from slave to mater board.Now,I want to read slave outputs using my master.For that I have written below mentioned code.when I am serially printing array,its showing 00000000000000000000000000000000769.I am not getting full data on my master.

#include <ModbusRtu.h>

// data array for modbus network sharing
uint16_t au16data[64];
uint8_t u8state;

int i;

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus master(0,0,1); // this is master and RS-232 or USB-FTDI

/**
 * This is an structe which contains a query to an slave device
 */
modbus_t telegram;

unsigned long u32wait;

void setup() {
  master.begin( 9600 ); // baud-rate at 19200
  master.setTimeOut( 2000 ); // if there is no answer in 2000 ms, roll over
  u32wait = millis() + 1000;
  u8state = 0;
}

void loop() {
  switch( u8state ) {
  case 0:
    if (millis() > u32wait) u8state++; // wait state
    break;
  case 1:
    telegram.u8id = 1; // slave address
    telegram.u8fct = 3; // function code (this one is registers read)
    telegram.u16RegAdd = 1; // start address in slave
    telegram.u16CoilsNo = 24; // number of elements (coils or registers) to read
    telegram.au16reg = au16data; // pointer to a memory array in the Arduino

    master.query( telegram ); // send query (only once)
    u8state++;
    break;
  case 2:
    master.poll(); // check incoming messages
    if (master.getState() == COM_IDLE) {
      u8state = 0;
      u32wait = millis() + 100;
    }
    break;
  }
 //au16data[4] = analogRead( 0 );

 for(i=0;i<=64;i++)
 {
  Serial.print(au16data[i]);
 }
 Serial.println("\n");
 Serial.println("\n");
 delay(1000);
 }

The response is received when ModbusRtu library object is again in the IDLE state after a request was sent. In your code based on the example from the library, the response is ready in state 2 which follows state 1 where the request was sent. If in state 2 when the master object state changes to IDLE, you can use the response in array au16data.


MPU6050 Accelerometer freezes/glitches after acceleration I am trying to do rotational vector calculation using a MPU6050 chip which actually work really well with not too much drift when I rotate the MPU slowly. However, when I accelerate too much, e.g. change direction in my slow rotations or just slightly tap the breadboard with my finger, the values completely go nuts.

I am using an ESP8266 chip to control the chip and I have tried multiple libraries for reading the Gyro/Accelerometer values which all have more or less the same behaviour.

My accelerometer readings from the Serial plotter, before and after the light tap to the breadboard:

Gyroscope does the same thing. The MPU is new (just arrived in the mail few hours ago), I power it using 3.3V and use 3.3V GPIO logic from the ESP chip.

Does anyone know what could be causing this?

Your problems are (most likely) related to loose connections in the breadboard. Sudden movements can cause power to be interrupted briefly, or data signals to become corrupted.

Breadboards aren't great for prototyping anything that moves, even slightly.


How do I connect a vibration sensor/switch to a breadboard? I have the following vibration sensor:

It has one short/firm-er terminal and one long/flimsy terminal.  Now the shorter terminal slides easily into my breadboard but the flimsy one clearly does not.  A few related questions:

1) How do I go about connecting this to my breadboard (simply plugging it in doesn't work)?  Do I have to solder a wire onto the flimsy end?

2) Why is this switch manufactured this way (with a flimsy end)?

3) Is it right to assume that the longer end is positive (+) and the shorter end is negative (-)?

Thanks!

It appears from this information source:
http://www.electrodragon.com/product/vibration-switch-sensor-sw-18020p/
that the sensor is an electrical contact on the firmer side surrounded by a very sensitive spring within the enclosure. The coil spring is by design made of a smaller diameter wire to provide sensitivity to movement. Rather than manufacture a translation to a heavier piece of material, the thinner lead is brought out of the enclosure.

I suspect that it will not work on your breadboard, due to the flimsy end being too small to make solid contact within the breadboard. You could resolve that aspect by soldering on a heavier segment.

Because it is designed as a simple switch, there is no plus or minus.


How often can I ping an HC-SR04 ultrasonic sensor? In my current project, I want the sensor to be continuously scanning for a value of less than 30cm. I was wondering how long of a delay I need (if any) between each call of the ping function. It currently works at 150ms between each ping call with no problem. The less the delay, the better for my project. This is the ping function:

void ping() {
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
}

For example, would having a delay of only 5ms be sufficient?

How often can I ping an HC-SR04 ultrasonic sensor?

This ping() function is vulnerable to interrupts during the pulseIn(). This implies that a delay needs to wait for queued interrupts as from, for instance, Serial output. Input interrupts may still affect the results. This function only works in very simple sketches.

Possible solutions are to 1) disable during the pulse measurement (not the wait for pulse start), 2) use a more advanced method to allow concurrent events (such as timer capture).

Cheers!


Wired serial connection between two Arduinos - do they need a common Ground (GND)? I would like to connect two Arduinos by a serial connection. Is it sufficient to connect TX1<-->RX2 and RX1<-->TX2 or do I also need to connect the GND of the two Arduinos?

Short answer: Yes.

Rx/Tx is referenced with a logic ground. Without ground being common, there is no way to determine what is high or low.

(Sorry I don't have a more technical explanation)

Edit: I thought I would add, if you are using the same power source, then they probably have a common ground. In this case, a common power source doesn't mean the wall side of a wall adapter, but the SAME wall adapter.


Arduino 1.6.4 not showing any /tty/ options in Serial ports hej guys,

recently I upgraded to Arduino's 1.6.4 IDE just to find out, that I can't seem to upload anything to my board. More specifically: The 1.6.4 IDE is not giving me the option to select the /tty/ board from the serial port list. I am avid Sublime Text 2 user, so obviously I tried to select the port in Stino and voilá: I was able to upload it to my boards.

Since I wanted to sort out if this is a software or hardware problem, I started to experiment with all my boards:

(all of them official boards, no clones)

2 x Arduino Micro
1 x Arduino Uno r3
1 x Arduino Duemillanove
1 x Arduino Mega 2560 r3
12 x Teensy 3.1
a bunch of different USB cables.

none of these boards were registered by the Arduino 1.6.4 IDE, even after restarting the software and the computer several times. i'd only get this in my port selection:

funny enough, my terminal told me the /tty/ device was there. here with the uno connected:

Dash:~ julianh$    ls /dev/tty.*
/dev/tty.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/tty.usbmodemfa131

I also tried to re-install FTDI drivers, with no results.

only when I installed the old (trusty) 1.6.1 version, I was able to upload again.

all of the boards are also working fine. I just used my uno and mega another machine a few days ago for some side projects.

can someone confirm this problem with the new IDE 1.6.4 on OSX Yosemite 10.10.3? or is there any solution available online?

thanks!

I had the same problem when updated to 1.6.4, but with a Spark fun Pro micro.
Did a "reset to bootloader" on the pro micro, and hit upload, and it worked
 out nice and it still does!


Doubt using character array I'm trying to make a led sign with a WS2812b ledstrip, using the FastLed library (by the way, this is a great library!), I'm already able to show a text (so far only one, which I leave saved in an array of characters at the beginning of the program), but I would like to be able to change this text using the serial port of the Arduino, and here is the problem:

When setting the text to be displayed in the array of LEDs, the function that I should use is:

ScrollingMsg.SetText ((unsigned char *) TxtDemo, sizeof (TxtDemo) - 1);}

Where TxtDemo is a variable type char array.

Until here all is right, as I commented I can show the text, but at the time of receiving the data from the serial port and save them in the char array TxtDemo, when I use the function sizeof(TxtDemo), the value I get remains with the original size (quite understandable) of this array.

For example: If the initial text was (saved in TxtDemo):
"Hello world", the sizeof() function, returns "11",
But when I pick up what I want to show on the serial port and store it in the variable TxtDemo, there's no way I can alter the size of that array. So ... what can I do? What do you recommend me to do?

Arrays in C are fixed. sizeof() will always give the amount of allocated memory for the array.

Instead, you should be using strlen() to get the number of characters up to (but not including) the terminating NULL character at the end of the string.

ScrollingMsg.SetText ((unsigned char *) TxtDemo, strlen(TxtDemo));

Make sure that you have enough space in your initial array to store the longest string you will want to send - it will not grow beyond your initial allocation. Also be sure to get the NULL character at the end of your valid text. It's too easy to forget you need to insert that after your last received character.


trying to switch input on my speakers via infrared using web browser but i have issue getting it working ived tested the IR code with
https://github.com/wemos/D1_mini_Examples/blob/master/examples/04.Shields/IR_Controller_Shield/IRsend/IRsend.ino

and it works that way, but when i try to code it together with the web server, i get nothing, can someone explain to me what's wrong in my code? the webserver works fine, its the IR part i dont fully understand why its not working

#include <i18n.h>
#include "ESP8266WiFi.h"
#include "ESP8266WebServer.h"
#include <IRremoteESP8266.h>
#include <IRsend.h>
ESP8266WebServer server(80);

void setup() {
  Serial.begin(115200, SERIAL_8N1, SERIAL_TX_ONLY);
  WiFi.begin("net", "pass");  //Connect to the WiFi network

  while (WiFi.status() != WL_CONNECTED) {  //Wait for connection

    delay(500);
    Serial.println("Waiting to connect…");

  }

  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //Print the local IP

  server.on("/on", []() {   //Define the handling function for the path

    server.send(200, "text / plain", "Switching to USB input");
    #define IR_LED D3
    IRsend irsend(IR_LED);  // Set the GPIO to be used to sending the message.
    uint16_t rawData[71] = {8992, 4494,  574, 558,  572, 558,  574, 558,  574, 558,  574, 558,  572, 558,  572, 556,  572, 1660,  572, 1658,  574, 1658,  574, 1658,  574, 1660,  574, 1660,  574, 1660,  574, 1658,  602, 528,  574, 558,  574, 1658,  576, 556,  574, 556,  574, 1660,  574, 556,  574, 554,  574, 554,  574, 1658,  574, 556,  574, 1656,  576, 1658,  576, 556,  574, 1658,  576, 1656,  576, 1658,  576, 39978,  8994, 2256,  578};
    irsend.begin();

  });

  server.on("/", handleRootPath);    //Associate the handler function to the path
  server.begin();                    //Start the server
  Serial.println("Server listening");

}

void loop() {

  server.handleClient();         //Handling of incoming requests

}

void handleRootPath() {            //Handler for the rooth path

  server.send(200, "text/plain", "NinjaLights");

}


Is it safe to short two pins together for conditioning a sketch? I want to make a sketch which behaves differently, i.e.:

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

pinMode(pin2, OUTPUT);
digitalWrite(pin2, LOW);

pinMode(pin3, INPUT);
// And a user decides to short pin3 with pin1 or pin2

if (digitalRead(pin3) == HIGH) {
  // behavior 1
} else {
  // behavior 2
}

But, I wonder whether shorting two pins with/without a resistor safe or not. If it is dangerous, what is an alternative way to do such a thing?

Firstly, why would you?

All you are doing is connecting the input pin 3 to either VCC or GND, since that is what setting a GPIO to HIGH or LOW gives you - why would you waste two GPIO pins for that purpose?

"shorting" an input pin with VCC or GND is what you do with a button or switch anyway. The resistor in that case is used to hold the pin in the opposite direction when the button isn't being pressed. The same effect can be created using a two-way switch connecting the pin to either VCC or GND with no resistor required.

So yes, you can "short" the input pin with an output pin safely - as long as that input pin never becomes an output pin at any time (hint: never use pin 13 on an Uno for this - it becomes an output to flash the LED during the bootloader over which you have no control. The same goes for the TX pin.)


If - else statement in Arduino I'm starting to learn how to use Arduino and I tried to make this code, which is just a simple if else statement; what I want to make is when the input is LOW, LED 1 is HIGH and LEDs 2,3 are LOW, and when the input is HIGH, the LEDs 2,3 are HIGH and LED 1 is LOW. I wrote this code but when I put the switch in LOW, instead having just like what I intended, all the outputs are HIGH.

I try changing the output and I checked all the wiring to the LEDs so my mistake is in the code.

Could you guys tell me what's wrong with the code?

int switchstate = 0;
void setup() {
  pinMode (13,OUTPUT);
  pinMode(12,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(3,INPUT);
}

void loop() {
  switchstate = digitalRead(3);
  if (switchstate == LOW) {
    digitalWrite(11,HIGH);
    digitalWrite(12,LOW);
    digitalWrite(13,LOW);
  } else {
    digitalWrite(11,LOW);
    digitalWrite(12,HIGH);
    digitalWrite(13,HIGH);
  }
}

Your code doesn't seem to be the problem. Contrary to what you are saying I think your problem is most definitely in your hardware setup.

Most likely, your digitalRead doesn't register a HIGH input, so it doesn't get 5V. Instead of digitalRead, go for analogRead(A0). So change your circuit and attach it to pin A0.

Use serial.println(switchstate) to print the results to the serial monitor and then decide what your top value (HIGH) and bottom value (LOW) for detection will be. Perhaps include a pull down resistor as well on the A0 pin.


Arduino Pro Micro clone not recognized, flickering RX LED I have an Arduino Pro Micro clone that seems to be in some sort of reset loop. The RX LED is flickering very fast and very dim. The power LED also seems to flicker at the same frequency but has normal brightness.

The Arduino is not recognized by the PC at all anymore. It was working fine before. It doesn't matter if I try to go into the bootloader, by pressing reset twice, or not. Nothing happens. It feels like it is constantly resetting. The flickering stops if the reset pin stays connected to GND.

Another clone from the same shipment is still working fine. Both running the blink sketch. Just this one started to malfunction all of the sudden - after probing the pin I set in the blink sketch with my multimeter to see if the flashing was a success.

If your pro micro does not have a reset button, wire one between reset and ground.

Press reset twice, quickly, and immediately hit upload on the IDE.

Secondly, make sure you've downloaded and installed the Sparkfun board files for the pro micro.


LCD Clock Millis Code Issue I am trying to create a clock on an LCD when I upload the code below, all it displays is a very rapidly flashing 0:00 PM. Please help. This is my first time using Millis.

#include <LiquidCrystal.h>   //includes LCD display library in sketch
LiquidCrystal lcd(27,26,25,24,23,22);   //determines pins of the LCD display
int seconds = 0;    //generates integer storing seconds
int minutes = 0;    //generates integer storing and showing minutes
int hours = 12;      //generates integer storing hours in 24 hour mode
int displayHours;      //generates integer displaying hours in 12 hour mode
unsigned long previousMillis = 0;   //creates a variable to store the amount of milliseconds since last update
const long interval = 1000;    //generates integer to find 1 second interval

void setup()
{
  lcd.begin(16,2);  //determines size of the LCD display
}

void loop()   //runs code repeatedly
{
  updateSeconds();   //runs the updateSeconds function
  clockShown();   //runs the clockShown function
  clockConversion();    //runs the clockConversion function
}

void updateSeconds()   //check to see if it's time to update the seconds integer
{
  unsigned long currentMillis = millis();  //generates the number of milliseconds program has been running
  if (currentMillis - previousMillis >= interval)
    {
      previousMillis = currentMillis; //updates the last time seconds was updated
      seconds = seconds ++;   //adds a second to the counter
   }
}

void clockShown()   //displays the time on an LCD display
{
  lcd.clear();   //resets screen on LCD
  lcd.setCursor(0,0);    //sets the place to start writing at the top left corner of the LCD
  lcd.print(displayHours);  //displays hours
  lcd.print(":");   //displays colon
  if(minutes <= 9)  //if the minute is 1 digit
  {
    lcd.print("0"); //displays 0
  }
  lcd.print(minutes);  //displays minutes
  if(hours < 12)lcd.print(" AM");  //displays AM in the morning
  if(hours >= 12)lcd.print(" PM");   //displays PM at night
}

void clockConversion()  //runs math to convert seconds minutes and hours
{
  if(seconds == 60) //when seconds is 60
  {
    seconds = 0;  //set seconds back to 0
    minutes = minutes ++;  //and add a minute
  }
  if(minutes == 60) //when minutes is 60
  {
    minutes = 0; //set minutes back to 0
    displayHours = displayHours ++; //and add an hour
    hours = hours ++; //and keep track of AM PM
  }
  if(displayHours == 13)  //if the hour being displayed is 13
  {
    displayHours = 1; //make it 1 instead
  }
}

Problem 1

seconds = seconds ++;   //adds a second to the counter

This command grabs the value of seconds, increments the value of seconds, and then assigns the previously grabbed value to seconds. Or rather, it does nothing to change the value of seconds.

This mistake is repeated for minutes, hours, and displayHours in the clockConversion() function.

Instead

seconds++;

That was the main problem. The other problems described below are just for efficiency.

Problem 2

void loop()   //runs code repeatedly
{
  updateSeconds();   //runs the updateSeconds function
  clockShown();   //runs the clockShown function
  clockConversion();    //runs the clockConversion function
}

Why would you display the clock with clockShown() before you run clockConversion() to nice-up the minute and hour carry-over? Since you are running both clockShown() and clockConversion() at a high frequency, it doesn't matter much, but from a program flow point of view, I think it makes more sense to do the conversion before you display the values.

Problem 3

You are only updating seconds every 1000 milliseconds, using the millis() function. This is good.

However, nothing at all changes during the 1000 milliseconds between the incrementing of seconds. Why not pull the millis() parts into loop() and call all 3 functions only once per second?

void loop()   //runs code repeatedly
{
  unsigned long currentMillis = millis();  //generates the number of milliseconds program has been running
  if (currentMillis - previousMillis >= waittime)
  {
    previousMillis = currentMillis; //updates the last time seconds was updated

    updateSeconds();   //runs the updateSeconds function
    clockConversion();    //runs the clockConversion function
    clockShown();   //runs the clockShown function
  }
}


Using Arduino as Keylogger Is it possible to use arduino uno r3 as USB keylogger by connecting the usb male pin to CPU and keybord cable to female USB pin of arduino.
So that the keystrokes are stored in EEPROM. Without using an external storage modules or other components?

I am new to arduino, even suggestions are appreciated.

Thanks in advance.

USB-host is hard if not impossible to implement on an UNO.

Though I believe most USB keyboards support PS2 as well (normally done with a USB-to-PS2 plug). So you should be able to talk to the keyboard using the PS2 protocol, which is a lot easier. There are libraries to do this for you.

Next you could use V-USB to emulate a keyboard to the PC. For that USB connection you need to add some resistors and zener diodes, to stay withing the usb specification. This is all explained on the V-USB website.

Using a different Arduino that has real USB support might be a better option. Also the UNO is rather large, so not that easy to hide.


LEDs on Arduino WiFi Shield I would like to know the purpose of the LEDs on top of the Arduino WiFi Shield: L9/Link/Error/Data (left in the picture). What do they indicate?

The web page on the Arduino site for the board tells you in plain words what they mean:

  On board indicators The shield contains a number of informational LEDs:

  L9 (yellow) : this is tied to digital pin 9
  LINK (green) : indicates a connection to a network
  ERROR (red) : indicates when there is a communication error
  DATA (blue) : indicates data being transmitted/received


What if I have burnt my atmega328p? Actually I am facing a big problem while programming my atmega328p using an arduino uno as ISP.
I followed a video on youtube  "Arduino as ISP" by Notes and Volts. Which look doing the same steps that the majority followed. For the blinking LED sketch the µC worked very well and it did not show any troubles.
So I  decided to carry on , and at this point I needed to upload a new program but this i wanted to upload my program using "avrdude" command line because my code was written with MikroC pro for avr, and here is the command line :

"avrdude -p atmega328p -b 19200 -C arduino -P COM7 -U lfuse:w:0xf7:m -U
 hfuse:w:0xc9:m -U efuse:w:0xff:m -U flash:w:LED.hex:i "

But unfortunately it did not work well and I have got the following error :

avrdude : invalid byte value <ff> specified for immediate mode
 avrdude : write to file 'ff' failed
 avrdude : safemode : Fuses OK

Seeing that error paniced me , that's why I decided to retry the programmation with an arduino sketch and then happened the big issue when the arduino generate an error message about finding a bad microcontroller [error about the device signature] []2.
My last try to find out if I ruined my µC is with switching the µCs; the arduino original and the one that I had to program and unfortunately It was not a good result :
"avrdude : stk500_recv() : programmer is not responding
 avrdude : stk500_getsync() attempt 1 of 10 : not in sync : resp=0x85"
Looking for more than day on the internet and I could not find a valid solution , except the possibility that I really BURNT my µC and I have to buy another one. And this is specifically why I am asking for your help; I need  to know if SO could figure this trouble out.Otherwise, could somebode confirm to me that there is no hope with my µC and it's gone and I have to stop trying to make it works .
Thank you
Regards

Trying your fuse settings on an
AVR fuse calculator shows that you
have selected an “external full-swing crystal” as the clock source.
Now your ATmega won't work unless you connect it to an external crystal.
Or you could try just sending a square wave into the XTAL1 pin. Then
you can try to reprogram it.


Using UART to Set RTC I'm using an Adafruit NRF8001 Low Energy Bluetooth module and a Real Time Clock module with my Arduino board. I want to connect to the BLE module using UART to set the clock. I'll also be using UART to set alarms.

I'm not sure which is the best way to take a string from the UART receiver and pull it apart into the hours, minutes, second, etc.

Any ideas? I did look at the Arduino JSON library but it seems a little buggy, and possibly overkill.

Any help would be very much appreciated :)

The simplest method is to keep it as a fixed format string with line termination.

Read one line in from serial into a character array (aka C string) and then chop it up.  As long as the string is in the correct format you can easily chop it around.

For instance, assume you chose the format YYYY-MM-DD HH:MM:SS\n which is quite common and easy to use, you may have data like this:

char *indata = "2015-08-22 17:23:48\n";

(\n is the new-line character)

Using simple char pointers you can get each substring quite easily:

First slice the string up into the component parts by replacing the separator tokens with character 0:

indata[4] = 0;
indata[7] = 0;
indata[10] = 0;
indata[13] = 0;
indata[16] = 0;

Then you can assign pointers to each segment:

char *year = indata;
char *month = indata + 5;
char *day = indata + 8;
char *hour = indata + 11;
char *minute = indata + 14;
char *second = indata + 17;

Or if you want it as integers, you can pass it straight to atoi:

int year = atoi(indata);
int month = atoi(indata + 5);
int day = atoi(indata + 8);
int hour = atoi(indata + 11);
int minute = atoi(indata + 14);
int second = atoi(indata + 17);

In fact, if passing it direct to atoi() you shouldn't need to even do the first stage, since it will stop parsing at the first non-numeric character.

There are more flexible ways of parsing the string too, using strtok(), but that is somewhat more advanced.

Note that this method is highly intolerant to invalid strings being passed, so you may want to first ensure that a) the string is the right length, and that b) there are the right separator tokens in the right placed, to validate that the string is properly formatted before proceeding.


How to connect a digital sensor through SPI I want to connect a ADXL355 development board accelerometer to an Arduino. I cant get any data form the sensor. The data_ready pin is never high and I can't read the registers.
The connections (user guide):

I connected VDD and VDDIO to 5V, ground to ground, DRDY to the correct pin, CS, SCLK, MOSI and MISO all to correct pins.

Code:

//modeled on https://www.arduino.cc/en/Tutorial/BarometricPressureSensor

#include <SPI.h>

const int ID = 0x00;
const int FIFO = 0x11;
const byte READ = 0b11111100;
const byte WRITE = 0b00000010;

const int dataReadyPin = 6;
const int chipSelectPin = 7;

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

    // put your setup code here, to run once:
    SPI.begin();

    // initalize the  data ready and chip select pins:
    pinMode(dataReadyPin, INPUT);
    pinMode(chipSelectPin, OUTPUT);

    delay(100);
    readRegister(ID);
}

void loop() {
    if (digitalRead(dataReadyPin) == HIGH){
        Serial.println("data ready");
        delay(500);
    }
}
void readRegister (byte thisRegister){
    byte inByte = 0 ;
    Serial.println(thisRegister, BIN);

    thisRegister = thisRegister<< 2;
    byte dataToSend = thisRegister & READ;
    Serial.println(thisRegister, BIN);
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(dataToSend);
    inByte = SPI.transfer(0x00);
    Serial.println("data: ");
    Serial.println(inByte);
}

You're shifting your address too far.

Read should be 0b00000001 not 0b00000010.
Your address should be shifted one bit not two.

Also you need to turn it on. By default the device is in standby mode. You need to enable it by setting bit 0 of register 0x2D to 0.

byte readRegister (byte thisRegister){
    byte inByte = 0 ;
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer((thisRegister << 1) | 1);
    inByte = SPI.transfer(0x00);
    digitalWrite(chipSelectPin, HIGH);
    return inByte;
}

void writeRegister (byte thisRegister, byte value){
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(thisRegister << 1);
    SPI.transfer(value);
    digitalWrite(chipSelectPin, HIGH);
}


Writing to serial LCD seems to interfere with servos I have an OBD-based Arduino project (OBD adapter link below) which uses two servos and a serial LCD from Sparkfun (link below). My problem: writing to the LCD seems to interfere with the servos. Details:

1) When all LCD-related code is excluded, the servos work smoothly.
2) When LCD-related code is included, but the servos are not hooked up, the LCD displays everything OK.
3) When the LCD-related code is included, even if the LCD itself is NOT hooked up, the problem occurs. There's a brief noise from the servos every time I write to the LCD (the servos don't move much, they just make a brief noise).

Any idea what's causing this? Below are the relevant parts of the code (OBD, servo, LCD):

#include <Arduino.h>
#include <Wire.h>
#include <OBD.h>
#include "MPU6050.h"
#include <SoftwareSerial.h>
#include <Servo.h>

int servoPin1=13;
int servoPin2=12;

Servo servo1;
Servo servo2;

COBDI2C obd;
SoftwareSerial lcd(2,3);

void clearDisplay() {
  lcd.write(0xFE);
  lcd.write(0x01);
}

void setLCDCursor(byte cursor_position) {
  lcd.write(0xFE);
  lcd.write(0x80);
  lcd.write(cursor_position);
}

void Show() {
  setLCDCursor(0);
  lcd.print("Test");
}

void setup() {
  lcd.begin(9600);
  clearDisplay();
  setLCDCursor(0);
  lcd.print("OBD");

  pinMode(servoPin1,OUTPUT);
  pinMode(servoPin2,OUTPUT);
  servo1.attach(servoPin1);
  servo2.attach(servoPin2);
  servo1.write(0);
  delay(200);
  servo2.write(100);
  delay(200);

  obd.begin();
  conn=obd.init(PROTO_AUTO);
  lcd.print("Connected");

  Wire.begin();
}

void loop() {
  conn=obd.readPID(PID_RPM,rpm);
  if (condition) {
     servo2.write(50);
    delay(500);
    servo1.write(100);
    delay(500);
  }
  Show();
  delay(1000);
}

OBD adapter
Serial LCD

You are using SoftwareSerial which turns interrupts off when sending/receiving in order to precisely time gaps between bits. The Servo library may use hardware timers, but to work on pins 12 and 13 would require interrupts to "copy" the pulses to those pins. Thus the copies will be distorted when writing to, or reading from, SoftwareSerial.

I suggest using hardware serial (pins 0 and 1) for talking to the LCDs, which does not turn interrupts off. Alternatively, implement the servo positioning using the hardware timers yourself, which (once set up) won't change the pulse widths if interrupts are turned off.


How do I install the latest Arduino IDE on Ubuntu 14.04LTS? What I've tried:

I downloaded the package for 1.6.7 on Ubuntu 14.04 LTS but when I open it no matter what I try it will not start.
I installed 1.0.5 from the Ubuntu Software Center. I tried to update it but found no solution.

UPDATE: I found my answer in talamaki's answer on that other question linked above.

Follow the following step to download, install and run Arduino IDE on Ubuntu

First Download the Tar (tar-bal) from this link http://arduino.cc/en/Main/Software (download the correct 32 / 64 bit linux version ) depends upon your Ubuntu version.
Then goto download folder using terminal (shell) or the folder where you downloaded the tar and unpacked that tar using the following commands
like
cd /Downloads
tar -zxvf arduino-1.6.7-linux32.tgz
where 1.6.7 is the version of ide
you also need java runtime environment for arduino IDE download and install it using the following command
   sudo apt-get install openjdk-7-jre
you also need to provide the UART permissions for your hardware using following commands
sudo chmod a+rw /dev/ttyACM0
where ACM0 is the port number if you are using multiple or many arduinos just give permissions using the above commands by replacing the ACM0 to ACM1 to ACMN

then create a shortcut of arduino ide from the folder where you extract the tar
cd ~/Desktop
ln -s /Downloads/arduino-1.6.7/arduino

and then double click the shortcut to run arduino if it gives permission error then right click the shortcut and in file preferences gives permissions to the shortcut


Trying to move servo motor via 3 buttons I am having some difficulties in trying to make my servo motor move to a specific angle based on the button pressed.

For example, having the motor start at 0 degrees and then having it move to 180 when the 3rd button is pressed, have it return to 0 degrees when the first button is pressed, and have it go to 90 degrees when the second button is pressed, etc, etc.

I can't tell if I am going about this all wrong or not with my code, so if anyone could provide some assistance with this it would be a great help

EDIT: Added the wiring as a just in case

#include <Servo.h>

Servo myservo;
int angle = 0;
int anglestep = 10;

#define FIRST 2 // pin 2 is connected to 1st floor button
#define SECOND 3 // pin 3 is connected to 2nd floor button
#define THIRD 4 // pin 4 is connected to 3rd floor button
#define SIGNAL 10

void setup()
{
Serial.begin(9600);
myservo.attach(10);
myservo.write(angle);
pinMode(2,INPUT_PULLUP);
pinMode(3,INPUT_PULLUP);
pinMode(4,INPUT_PULLUP);
Serial.println("Lift/Descend");
}

void loop()
{
while (digitalRead(FIRST) == LOW)
    {
    if (angle > 0 && angle <= 90) //2to1
        {
        angle = angle - anglestep;
            if (angle < 0)
            {
            angle = 0;
            }
            else
            {
            myservo.write(angle);
            Serial.print("Moved to: ");
            Serial.print(angle);
            Serial.println(" degree");
            }
        }
    else if (angle > 90 && angle <= 180) //3to1
    {
        angle = angle - anglestep;
            if (angle < 0)
            {
            angle = 0;
            }
            else
            {
            myservo.write(angle);
            Serial.print("Moved to: ");
            Serial.print(angle);
            Serial.println(" degree");
            }
    }
    else //1on1
    {
        angle = 0;
    }

}
while (digitalRead(SECOND) == LOW)
    {
    if (angle > 90 && angle <= 180) //3to2
        {
        angle = angle - anglestep;
        if (angle > 90)
            {
            angle = 90;
            }
        else
        {
        myservo.write(angle);
        Serial.print("Moved to: ");
        Serial.print(angle);
        Serial.println(" degree");
        }
    }
    else if (angle > 0 && angle < 90) //1to2
        {
        angle = angle + anglestep;
        if (angle < 90)
            {
            angle = 90;
            }
        else
        {
        myservo.write(angle);
        Serial.print("Moved to: ");
        Serial.print(angle);
        Serial.println(" degree");
        }
    }
    else
    {//2on2//
    angle = 90;
    }
}

while (digitalRead(THIRD) == LOW)
{
    if (angle > 0 && angle <= 90) //1to3
    {
        angle = angle + anglestep;
        if (angle > 180)
            {
            angle = 180;
            }
        else
        {
        myservo.write(angle);
        Serial.print("Moved to: ");
        Serial.print(angle);
        Serial.println(" degree");
        }
    }
    else if (angle > 90 && angle < 180)
    {//2to3
        angle = angle + anglestep;
        if (angle > 180)
            {
            angle = 180;
            }
        else
        {
        myservo.write(angle);
        Serial.print("Moved to: ");
        Serial.print(angle);
        Serial.println(" degree");
        }
    }
    else
        {
        angle = 180;
        }
    }
}

You are really overthinking things there. A servo will move to an angle if you just give it the final angle to move to. You don't need to nudge it to the final angle by visiting every angle in between, and you don't need to know what angle it's at currently.

You can simply do:

if (digitalRead(FIRST) == LOW) {
    myservo.write(0);
}

if (digitalRead(SECOND) == LOW) {
    myservo.write(90);
}

if (digitalRead(THIRD) == LOW) {
    myservo.write(180);
}

However if you wanted to slow the movement down, which would entail moving the servo in smaller steps, I would separate out the current angle and positioning from the buttons, which would set a desired angle.  Something more like:

static uint8_t desiredAngle = 0;
static uint8_t currentAngle = 0;
static uint32_t timestamp = millis();

// Choose a new desired angle
if (digitalRead(FIRST) == LOW) {
    desiredAngle = 0;
}

if (digitalRead(SECOND) == LOW) {
    desiredAngle = 90;
}

if (digitalRead(THIRD) == LOW) {
    desiredAngle = 180;
}

// Every 10ms "tick" the servo towards the desired
// angle by 1 degree
if (millis() - timestamp >= 10) {
    timestamp = millis();
    if (desiredAngle > currentAngle) {
        currentAngle++;
        myservo.write(currentAngle);
    } else if (desiredAngle < currentAngle) {
        currentAngle--;
        myservo.write(currentAngle);
    }
}


Is it possible to run 2 functions, that communicate with 2 different serial devices, in parallel using FreeRtos library? This might seem like a very broad question but that's what i want it to be for multiple ways of implementation.

I've an Arduino UNO communicating with 2 Serial devices interfaced using SoftwareSerial flawlessly. I've used [SS_Object].listen() function to switch between the two. Right now, the entire code works sequentially meaning that, once it's work with the 1st Serial device is done, only then it will switch to the 2nd Serial device and work with it. Can i communicate with the 2 in parallel (Multitasking) using FreeRtos? I've heard that the scheduler switches between tasks when it encounters a delay. So may be a small useless delay is required, only for the scheduler, to switch between the two. May be! or May be things will be better if i use more advanced Arduino like Mega or Due.

Thanks for taking your time to read this. Please answer the question the way you've understood it as i am sure different people with different experiences will interpret this differently.

Thanks in advance!

It is unlikely that FreeRTOS will allow you to do that. SoftwareSerial uses busy loops with interrupts disabled, which means it cannot be interrupted or preempted by the RTOS (or by anything for that matter).

If you want two serial connections in parallel, at least one of them should be done in hardware.


Connection Pro-Mini & ESP8266 using Serial I wish to create a system consists of WEMOS mini & Pro-Mini sharing info using Serial ( one MCU is dedicated to react input-output, and second for MQTT commands ) sharing same Power input. From what I read in tutorials, at boot Serial wires have to be disconnected, in order to accomplish boot.
A) is that true that at boot Serial has to be disconnected?
B) is there a way that 2 MCU can be connected at all times, including reboot when needed ( such as power failures ) ?

A) is that true that at boot Serial has to be disconnected?

No, that is not true. However if you are using Serial to communicate on the Pro Mini you will need to disconnect the ESP8266 in order to program the Pro Mini as it will interfere with serial communication to the PC.

B) is there a way that 2 MCU can be connected at all times, including reboot when needed ( such as power failures ) ?

Given that A) is a no, then B) is irrelevant. It will just boot.
The only caveat is that the ESP8266 will squirt some boot messages out of serial as it boots at 74880 baud, so you have to be able to cope with that noise in whatever protocol you design between the two boards.


What is the best serial communication method between an Arduino and a spectral sensor? I have an Adafruit AS7262 visible spectral sensor. I want to receive the data of the sensor with an Arduino.
The sensor has two serial communication options: UART(asynchronous) or I2C(synchronous). I want to know which method is more suitable for the sensor to communicate with the Arduino microcontroller. I was thinking that UART is more suitable, because the sensor has his own master clock, in other words if I choose I2C then the Arduino needs to work as the "slave" and I dont think that is very suitable, because the Arduino has its own master clock also. For this reason I think that asynchronous method is more reliable, but I am not sure about this.

The I2C on this device is slave, not a master. Even though it has its own clock, it is designed to operate as a slave being read by a master.

You will have no issues using the I2C interface - in fact Adafruit uses it for their own software library.

Since there is already a I2C-based library available from the manufacturer I would use that, unless there is a good reason to use the UART instead.


Arduino I2C external 32Kb fram data organization Hey guys I am a noob when it comes to data structures and storing types of data, I have been recently working on a project where I needed to store long term data for later retrieval. I decided to buy a Adafruit 10$ 32kb i2c fram Which works, it can store a byte Of data per address which I can successfully do, I can also read those bytes on any address no problem.
One issue I first came across was storing floats into the chip which only took bytes, After googling I managed to spit a float using a union successfully and also storing those in a 4 byte array. Now I did this with 3 different float values which means every 4 bytes stored is basically one split float value.
The second issue is how do I retrieve this data in an organized way and also as a float. I found out you can use a union to do the opposite as well. But how do I tell my code to read every 4 bytes and convert back to float?
Is there a system that can allow me to store data in a structured way using the arduino? Like a time stamped data using an external rtc? Such that when I click retrieve it will print that data in an organized fashion.

It'll be easier if you use a struct, not a union. Store all the data you want to preserve in a struct, then cast a pointer to it to be a byte pointer and just treat it as an array of bytes and read and write those bytes to the FRAM.
The union you were using explicitly did the same thing, but it's not easy to scale to multiple items.
Some caveats about what you can safely keep in the struct:

do not store pointers in it. A char array is fine because the entire array will take up space in the struct. A char * is not because all you'll save is the value of the pointer, not what it points at.

do not store objects (like String) in it. You don't know (and shouldn't know) how the object is composed internally. If need to use objects, they should have serialize and deserialize methods which would store or restore the contents of an object into an array of bytes which you could then store or restore with the FRAM.

Also remember that the C/C++ sizeof function (used below) tells you the size of thing at compile-time. So if you use it on a struct it will tell you the number of bytes it takes to store the struct. If you use it on a char *, it will tell you the number of bytes in a pointer to a char, not the number of bytes in the C string that the char * points at. If you use it on an object - like String str; sizeof(str); - it will tell you how many bytes it takes to store the String object, which will include the length of the string it stores.
Psuedo-code follows. There are more compact ways to write this; I'm aiming for clarity here.
#include <Arduino.h>

struct program_data {
  float first_thing;
  unsigned long second_thing;
  char third_thing[55];
  char fourth_thing;
  uint16_t fifth_thing;
} data;

void save_data(struct program_data *data_ptr) {
  byte *ptr = (byte *)data_ptr;

  for(size_t i = 0; i < sizeof(struct program_data); i++)
    store_byte_in_fram(ptr[i], i);
}

void restore_data(struct program_data *data_ptr) {
  byte *ptr = (byte *)data_ptr;

  for(size_t i = 0; i < sizeof(struct program_data); i++)
    retrieve_byte_from_fram(ptr[i], i);
}

// call when you want to save your data
  save_data(&data);

// call when you want to restore your data
  restore_data(&data);


Trouble reading analog (PWM) I'm trying to test my analog signal before I send it to an actual analog device. I've written some code and considering the analog square I have expected to see a digital ON or OFF during a single duty cycle but I'm either seeing all OFF for analog values 0-127 and all ON for values 128-255.

My expectation is that I would see 51 ON and 49 OFF thus getting a value closer to 128 of 255.

What am I missing? Is this even possible?

int OUTPUT_PIN = 2; // digital 2 (PWM)
int INPUT_PIN = A0; // analog 0

void setup() {
  pinMode(OUTPUT_PIN, OUTPUT);
  pinMode(INPUT_PIN, INPUT);

  Serial.begin(9600);
}

void loop() {

  analogWrite(OUTPUT_PIN, 128);

  float j = 0;
  for(int i = 0; i < 100; ++i) { // get 100 reads per duty cycle
    float v;
    v = digitalRead( INPUT_PIN );
    if(v >= 1) Serial.println("ON");
    if(v <= 0) Serial.println("OFF");
    j += v;

    delay(12); // trying to match the duty cycle
  }
  j /= 100; // average out the 100 reads

  Serial.println(j);

}

Seeing all on for 128+ and all off for 127- is indicative that you are using a pin that can't do PWM.

If you use a non-PWM pin with analogWrite it goes "Is this less than 128? Yes? Then I will turn it off. Otherwise I will turn it on.".

case NOT_ON_TIMER:
default:
    if (val < 128) {
        digitalWrite(pin, LOW);
    } else {
        digitalWrite(pin, HIGH);
    }

Since you don't mention what board you are using I can only assume that you have picked a pin that can't do PWM. Change to a pin that can do PWM and you should get a PWM signal.


Arduino std::map returning random values I'm working with an arduino UNO. I would like to be able to send it set and get commands over serial and have it update class data class members accordingly by key value pair. I spoke to users in the cpp room, and they suggested I try using map to map every key to value.

command structure
command:key:value

ex. set:key1:20
ex. get:key2

I created a class called Uno, assigned all my keys to private data members, and defined set and get functions. However, I am experiencing unintended behavior.

Unintended behavior
The set function ends up setting key1 and key2 to the same value, and the get function returns a random integer value that wasn't assigned.

  #include <ArduinoSTL.h>
  #include <string.h>
  #include <map>

class Uno{
  //private
    int key1;
    int key2;
    std::map<String, int Uno::*> keys;
  public:
  //Constructor
    Uno(){
      key1 = 0;
      key2 = 0;
      keys["key1"] = &Uno::key1;
      keys["key2"] = &Uno::key2;
    }
    bool setKey(String key, int value){
      if (keys.count(key)) {
          this->*keys[key] = value;
          return true;
      }
      return false;
    }
    int getKey(String key){
      if (keys.count(key)) {
          return this->*keys[key];
      }
    }
};

String inputString = "";      // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete
bool scan = false;            // whether a scan is in progress
Uno myMS;                      // global declaration of Mass Spec Class

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

void loop() {
  if (stringComplete) {
    t(inputString); // tokenize and process string

    //RESET STRING
    inputString = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

void t(String inputString) {
    //get command
    String command = getValue(inputString, ':', 0);

    if(command == "set"){
      // get key, get value
       String key = getValue(inputString, ':', 1);
       int value = (getValue(inputString, ':', 2)).toInt();
       Serial.println(myMS.setKey(key,value));
    }
    else if(command == "get"){
       String key = getValue(inputString, ':', 1);
       int value = myMS.getKey(key);
       Serial.println(value);
    }
    else if(command == "stop"){
       scan = false;
    }
    else if(command == "scan"){
       scan = true;
       while(scan){
//        Serial.println(myMS.scan());
       }
    }
    else{
       Serial.println("not recognized");
    }
}

String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length()-1;

  for(int i=0; i<=maxIndex && found<=index; i++){
    if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
    }
  }
  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}

EDIT: Here is a REPL IT working demo of concept provided by nwp.
https://repl.it/repls/AntiqueProductiveMineral

Sample output

set:key1:10 ===> 1 (GOOD)
get:key1 ===> 32512

You get random values because if the key is not found in getKey, then there is no return statement.

You attach the \n to the key in serialEvent(), then the key for getKey is "key1\n" and it is not found.

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    if (inChar == '\n') {
      stringComplete = true;
    } else {
      inputString += inChar;
    }
  }
}

If you have CR/LF set in Serial Monitor, then the \r character is send too and the parsed key is "key1\r\n".

There are obsolete things in your code, like the this->* or Uno::. Make the map std::map<String, int> keys;, because now you mix pointers and ints.


Adding Attiny to Arduino IDE - attiny\variants\platform.txt file missing I followed this guide to program AtTiny using Arduino as ISP. The problem is that it has some file missing:

java.io.FileNotFoundException: C:\...\arduino-1.6.8\hardware\attiny\variants\platform.txt

The attiny directory is clone of this repository. How do I make it work?

Open the "Preferences" dialog in the Arduino IDE.
Click on the symbol next to "Additional Board Manager URLs"

Paste the following into the box (possibly on a new line under any existing URLs), then click OK.

https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json

Note that you can click on the circled link for a list of boards. This will open in your web browser. You may have to switch to your browser to notice it.

Click OK to close the Preferences dialog box.
In the Tools menu / Board select the Boards Manager:

Scroll down until you see the Attiny entry (or the one for the board you want), click on it to select it, and then click "Install".

Once done, close the Board Manager dialog box.
You should now be able to select Attiny from the Boards menu:

Now in the Tools menu you can select which Attiny you want to use:

Notice you can also select the appropriate clock speed in an adjacent menu item.
To program the Attiny you will need a suitable ISP (In System Programmer) such as the AVRISP programmer, or the USBtinyISP programmer.