Serial.parseInt value always goes back to 0

This code will work IF you set the Serial Monitor to "No Line Ending" (OSX 10.6.8. IDE Version 1.0.6.2). parseInt() doesn't like the NL + CR chars.

unsigned int val;

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

void loop(){
  Serial.println("Input ESC Speed between 1000 and 2000:");
  while(Serial.available() > 0){
    val = Serial.parseInt();
  }
  if(val > 0){Serial.println(val);}
  delay(1000);
}

There is another way to get the integer value using this code:

char inputBuffer[16];
unsigned int val;

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

void loop(){
  Serial.println("Input ESC Speed between 1000 and 2000:");
  while(Serial.available() > 0){

    // A function that reads characters from the serial port into a buffer.
    Serial.readBytes(inputBuffer, sizeof(inputBuffer));

    // Convert string to integer
    // cplusplus.com/reference/cstdlib/atoi/
    val = atoi(inputBuffer);

    // memset clears buffer and updates string length so strlen(inputBuffer) is accurate.
    memset(inputBuffer, 0, sizeof(inputBuffer));
  }
  if(val > 0){Serial.println(val);}
  delay(1000);
}

The Binary sketch size is 94 bytes less than the first example using parseInt. The second sketch will work with ANY Serial Monitor Line Ending settings.


Is it possible to disable functions/methods?

If you don't want a function to run you can just return at the start of that function:

void myFunction() {
    if (!myFunctionShouldRun) return;
    ... rest of function ...
}

If myFunctionShouldRun is false the if will be true (due to the !) and the function will return.  If it's true the rest of the function will execute.


Try this:

byte (*sequence[])[4][2] = { lines, circles, squares } ;

Explanation: The identifiers lines, circles and squares decay
to pointers to the first element of each array. Their decayed types are
then “pointer to array of length 4 of array of length 2 of byte”. This
type could be declared as

typedef byte (*pointer_to_2d_array)[4][2];

The sequence is then an array of this type, which can be declared as

pointer_to_2d_array sequence[] = { ... };

or, if you appreciate the obscure elegance of the C syntax, as in the
beginning of this answer.


How does measuring angled surfaces using ultrasonic distance sensors affect the readings?

Speaking form experience: The behavior can be fairly unpredictable and depends on the surrounding objects as well as the texture of the surface.
Ultrasonic distance sensors are just sonars that ping at a higher frequency than humans can hear. They work by bouncing sound off of an object and measuring the amount of time it takes to get back. When an object is slanted or angled away from your sensor, it can deflect the sound rather than bouncing it back toward the sensor, making the object essentially invisible to your sonar. However this can be effected by the texture of the surface.
Rough surfaces can scatter sound, sending it in multiple directions. So an angled rough surface may still be detectable to your ultrasonic distance sensor.
When you get an inacurate reading, one of two things will happen. 1: Your sonar ping will bounce off of a surface, hit another object, and bounce back, returning the distance from your sensor, to the surface to the object.
2: The sound will deflect your sound which will be deflected and absorbed, without returning to your sonar sensor. This will return a distance of infinity or whatever your maximum measurable distance is.
I hope this answers your question!


Serial1 is not reading the Xbee on a Arduino Due

I fixed my problem. I stupidly left the Xbee Shield on DLINE instead of UART. Now there is communication between the radio modules. I have another question. When I type a character into XTCU, it "receives" the exact character from the Arduino Due. I have used this basic code with other Arduinos before and this has never happened.

Extra information: The serial monitor solely prints out received data.

I attached an example.


UART communication - Serial is always empty

There is already an answer and comment about possible hardware / flow control issues, so this answer is only dealing with your Arduino sketch. Iv’e added a couple of print statements and the FreeMemory library to test your sketch.

#include <MemoryFree.h>
String data = "";

void setup() {
  Serial.begin(9600);
  while (!Serial);
  delay(1000);
  Serial.println("REQINFO,4");
  delay(1000);
}

void loop() {
  if (Serial.available())  {
    char c = Serial.read(); // also I tried readString() and readStringUntil()
    if (c == '\n' || c == '\r') {
      Serial.println(data); // jsut to see it in the montor
      Serial.print("freeMemory()=");
      Serial.println(freeMemory());
    } else {
      data += c;
    }
  }
}

When I repeatedly enter the following text in the serial monitor "1234567890", here is the results of the print statements:

REQINFO,4
1234567890
freeMemory()=1770
1234567890
freeMemory()=1770
12345678901234567890
freeMemory()=1760
12345678901234567890
freeMemory()=1760
123456789012345678901234567890
freeMemory()=1750
123456789012345678901234567890
freeMemory()=1750
1234567890123456789012345678901234567890
freeMemory()=1740
1234567890123456789012345678901234567890
freeMemory()=1740
12345678901234567890123456789012345678901234567890

Every time you receive new data, it is appended to the data string, causing the string to grow and available memory to disappear. Using the String object should be avoided.

Here is a simple sketch that uses a char array as a buffer for the incoming data:

// Set the buffer size to accomodate the largest
// "chunk" of data you will be receiving.
const byte bufferSize = 64;
char inputBuffer[bufferSize + 1];

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

void loop(){
  if(Serial.available() > 0){
    Serial.readBytesUntil('\n', inputBuffer, bufferSize);
    Serial.print("inputBuffer=");
    Serial.println(inputBuffer);
    memset(inputBuffer, 0, sizeof(inputBuffer));
  }
}


What is the easiest way to count how many global variables are in your sketch code?

1 - The number of variables is not important, but the number of used memory (in bytes) is important. That is shown at the bottom of the Arduino IDE by the compiler when verifying or uploading a sketch.

2 - It is not possible to go to, for example, the largest global variable. You can use the search function to search for something.

For a small microcontroller, for example a Attiny or Atmega8, every byte that uses memory can be important.

For a Arduino Uno and larger, the optimization is done more globally.

To optimize for ram, look for the hungriest memory eaters:

For the Arduino Uno and other avr microcontrollers, the text with
Serial.println can be put in PROGMEM with the F() macro.
Many String
objects might need a lot of heap memory.
Arrays can get large
quickly.
Arrays of large elements (float, struct) can get large even
more quickly.
The SD library uses a lot of ram memory. There is a small version
of the SD library.
Some graphical libraries for displays use a lot of memory.

Try to avoid to save a single byte, unless you check the resulting memory usage. The compiler can optimize code in a way that conflicts with someone trying to save a byte.

When an integer is changed into a byte,
perhaps all the calculations are still done with integers and the
compiler needs more memory to convert from byte to integer and back.
Perhaps that integer was only used in registers and
did not use a memory location.
A 'const' integer uses probably no ram memory at all.

Final tip: Don't be afraid to upgrade to an other Arduino board with more memory. If you project uses almost all the memory, then it is not possible to add something to your project. When the project runs for a while, you might want to add an extra sensor or extra functionality.


Arduino: Digitally Muti-Switch - What is the proper term for hardware?

The technical term of what you're looking for is demultiplexer. Note that the demux itself will not be enough to activate the zone, it will simply allow you to choose between different zones based on its input. It is still up to you to provide any further electronics required to enable the appropriate zone.


version using String (not recommended, but it makes simpler to understand the following C-string version)

#define LED 2
const char* a = "abcd";

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    String s = Serial.readStringUntil('\n');
    s.trim();
    if (s == a) {
      digitalWrite(LED, HIGH);
    } else {
      digitalWrite(LED, LOW);
    }
  }
}

the version with C-string:

#define LED 2
const char* a = "abcd";
char buffer[32];

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    size_t l = Serial.readBytesUntil('\n', buffer, sizeof(buffer - 1));
    if (buffer[l - 1] == '\r') {
      l--;
    }
    buffer[l] = 0; // the terminating zero
    Serial.println(buffer);
    if (strcmp(buffer, a) == 0) {
      digitalWrite(LED, HIGH);
    } else {
      digitalWrite(LED, LOW);
    }
  }
}


Newbie - What is the Difference Between Power Supply's GND and Arduino's GND?

I would expect there to be no difference between the grounds in your circuit, and after looking over the schematic for the board, it appears that all of the grounds are common.

I think the most likely explanation for what you're seeing is a quirk in the breadboard. It may be that the side busses are split at the middle of the board, or perhaps there was just a bad connection somewhere on the ground bus on that side of the board.

One way you could troubleshoot it further would be by jumping the ground side of the LED to the power supply ground. Start with the ground on the regulator and then work out until you find the spot where you loose continuity.


It is possible to run an entire script on the Linux side? If so, how, what and where to do that?

Arduino Yun ships with python pre installed. You can copy python scripts from your pc to the yun with scp (or WinSCP or putty, if you're on windows). Once copied, just run it using Process from your sketch. As they are scripts, program name is python and the path to your script is its first argument (you can do that in a different way, but that would require some linux magic, which I suggest to postpone if you're new to it).

Other pre installed options include lua and bash. Other languages such as ruby, erlang and php are available as optional packages.


How to connect/call to the PSTN network using Arduino?

As already written in the comments, you may use any RS232 modem you can find. They use the so-called AT commands, which is a very common way to exchange commands with this kind of peripheral. You can check on wikipedia or on google to get more information on it.

The main problem is that this kind of modems are a bit hard to find (or at least, they are a bit harder to find and a bit too expensive for my liking). That's why, for a project of mine, I wanted to switch to a cheaper alternative. Looking on the internet, a lot of people stated that it was much better to have an already approved instrument rather than designing your own. For this reason, I bought a mini-phone like this one:

You just have to open it, wire the keys (or rather, the rows and columns of the keypad) to the arduino and let it do the magic.

This solution is cheaper (I spent 4€ for this, but if you have an old phone it becomes free) than getting a RS232 modem, but needs more work on your side.


Problem with uploading my sketch to my Arduino

This is the relevant bit in your error output:

Caused by: jssc.SerialPortException: Port name - COM4; Method name - openPort(); Exception type - Port busy.

Is your Leonardo on COM4, or some other port? Does some other program have that port open?


Interleave disassembly + source with avr-objdump

The .stabs section contains debugging info, not actual code. There is no
point in trying to “disassemble” it. The -D option of avr-objdump
means “disassemble everything, whether or not you believe it's machine
code”. Not what you want. For your purpose, -S should be enough.

I do not know why your main() is displayed without source code. I
tried your exact same program with the exact same commands and I do see
the source interleaved with the assembly. I am using avr-gcc 5.4.0 and
avr-objdump 2.26.20160125 as shipped on Ubuntu Eoan.


Which Bluetooth Module can I use with Arduino Micro/Mini?

I have had good results using the Bluefruit LE UART Friend module from Adafruit with a 32u4 micro Arduino type module, there are only a few pins to connect up to get things going (do remember to follow the instructions to pull the CTS pin to ground).

As per the previous answer it really does depend on what you want to do with it - but this module does Low Energy, can be configured as a "Beacon" and there is a companion App for Android/iOS.


Can the SPI pins of an Arduino be separated from SPI?

No.  Those pins are not separate on the microcontroller itself.  If you need to use SPI and still need more pins you may use analog inputs as digital inputs or outputs.  Otherwise you'll probably have to use an expander of some sort, or use a Mega or Due for additional inputs or outputs.


is it possible to use I2C and SPI at the same time?

Yes it is. Both are implemented in hardware in the chip. They can operate "in the background" and raise an interrupt when there is something to do.

  Do I have to introduce delays between the I2C and SPI commands?

No you don't.


How do I connect Arduino to a Bluegiga112?

The most popular way to establish communication between an Arduino (I've used a Duemilanove) and a BLE module (I've used BLE113 that's on a DKBLE113) is through UART.

UART is a two wire interface (don't forget the common GND) with one RX and one TX.
You can use the SoftwareSerial library to define your communication object on the Arduino.
In contrast, the BLE113 uses four. The additional two are RTS and CTS (Request To Send and Clear To Send).

However, you can configure the UART in two ways using hardware.xml:

Go to the <usart > tag and set flow = "false". This "disengages" the RTS and CTS allowing a traditional two wire interface.
Had you set flow = "true", you need to connect the RTS and CTS as well, which I had a big problem with, though the two are both digital.

Further, in hardware.xml, you need to disable sleep mode by including <sleep enable="false" /> within the <hardware> tag. This will solve all your problems.
If you intend to use sleep mode, you need to skip the previous step and instead govern the module's mode through the P0_0 pin. Moreover, there are additional definitions to be included in hardware.xml, which are documented by BG. These work nicely for the BLE112 too.

In my exercise, I'd established communication at 9600 baud. It worked the same way when I increased it to 115200 baud (this is a plus in the BLE113).


The Timer1 library only supports... Timer 1! So you only have one
hardware timer available. If you are using an Arduino Uno or anything
similar, you have a couple of other timers. However, unlike
Timer 1, which is a 16-bit timer, the others are 8-bit only. This
means they are very limited in the range and precision of the
frequencies they can generate. If you have an Arduino Mega, then you
have a few other 16-bit timers available. You may want to search for a
library called Timer3, which should work just like Timer1, while using
the 16-bit Timer 3.

If you don't find any suitable library, you may still be able to
generate your two signals using only Timer 1. Here is the trick:

set both PWM outputs to “toggle on compare match”
enable both compare match interrupts
in each of these ISRs, advance the compare match register by half a
period of the corresponding signal.

For doing this you will need to dig into the low-level details of how a
timer actually works. I recommend you start by reading the
Timers and counters tutorial by Nick Gammon.
Take the time to read and
study this. It's not a topic you will be able to master in just a
couple of hours.


Why does command line BOSSA not recognize Arduino Due?

from the IDE's menu you can activate the verbose upload (and compile) mode, that will print all the command executed; Probabibly what you miss is the necessity to open the serial at 1200baud, that will trigger the reboot and consequent bootloader's start ont DUE chip, and bossac need to find the bootloader. see autoReset

edit: i've now a pc with a physical Serial, so i've tryed to upload in verbose mode:

Sketch uses 10,380 bytes (1%) of program storage space. Maximum is 524,288 bytes.
Forcing reset using 1200bps open/close on port /dev/ttyS0
/home/xxx/arduino-1.5.6-r2/hardware/tools/bossac -i -d --port=ttyS0 -U false -e -w -v -b /tmp/build8035422101690460839.tmp/sketch_apr14a.cpp.bin -R

as you can see he is resetting the board by opening the serial at 1200, forcing the bootloader to start. You have to do the same on your script befor launching bossac. How this can be done depends on your OS

Please note that the reset is triggered by the 8u2 chip used as USB to serial adapter on the arduino board, so bypassing it by connecting through tx/rx pin (like using your own conversor, like in my example with hardware serial) won't work unless you do a manual reset at the right time


Reading/Writing Strings with Bluetooth Windows API

Serial is only ever a character at a time. That is what serial is. If you want to impose some structure on top of that then it is up to you to define that structure.


In principle yes, you can use a loop in setup() however this specific code

for (int i = 0; i >= 10; i++) {
  Serial.println(i);
  Serial.println("Pong");
}

will result in the body of the loop never executing, as the loop test i >= 10 is initially false.

You probably meant i <= 10

Generally speaking, it would be poor program structure to use a loop in setup() in place of one in loop(), however if you need a loop to apply similar operations to a range of things, or to briefly busy wait on a condition as part of setting up operation, that kind of thing could be appropriate.


AIN- won't be connected to the ADC mux unless ACME is set and ADEN is cleared. Don't forget to do so.


A Logic Level Converter can step-down incoming voltages for the Arduino inputs and may also work to drive the relay coils. Heres an example of a 4 channel board:

https://www.sparkfun.com/products/12009

and there are also 8 channel boards:

http://www.ebay.ca/itm/8-Channel-I2C-IIC-Logic-Level-Converter-Module-Bi-Directional-for-Arduino-MF-/172424799119?hash=item282551a38f:g:6Q0AAOSwo4pYPDwg.

The boards are small and use BSS138 MOSFETs, which, according to the data sheet: http://cdn.sparkfun.com/datasheets/BreakoutBoards/BSS138.pdf can handle a maximum of 0.22A continuous current and a Drain-Source Voltage of 50V. The SparkFun link has lots of information about these devices. Normally, you would use them to translate between 5V and 3.3V but I don't see why you couldn't power the "high voltage side" with the vehicles 12 - 14V and the "low voltage side" with 5V from the Arduino.


Base64 has nothing to do with audio. It is merely a way of encapsulating binary data into ASCII text so that it can safely be included in text-based structures like JSON, or transmitted over a text-based communication channel.
There is no library to "play" base64 simply because base64 is not something you play.
First you decode the base64 text into raw 8-bit binary. It's then that data that you play through whatever library is most suitable for your hardware.
For example on the ESP32 you have the function base64_decode() available. You can read up on how to use it in this tutorial.


Rectangular Input signal on digital pins

Reading high frequency signals can be done. It's possible to read signals up to about 6MHz or maybe even higher (depending on the system clock frequency).

That is, as long as all you want to know is the fundamental frequency of the signal.

Pin 5 of the Arduino Uno (PD5) is connected to Timer 1 and can be set to be the clock source for that timer.  By connecting that to your signal and allowing the timer to count up from zero using that signal as the clock source, and then waiting for a pre-defined time period, you can easily find how many clock pulses have arrived from your signal in that time. From that, you can calculate the frequency of the signal.

  The Timer/Counter can be clocked by an internal or an external clock source. The clock source is
  selected by the Clock Select logic which is controlled by the Clock Select bits in the Timer/Counter control
  Register B (TCCR1B.CS[2:0]).

Since all you are working with us the number of pulses over a given period you lose any information such as the duty cycle of the signal.

You should read the datasheet section 20: "TC1 - 16-bit Timer/Counter1 with PWM" for more detail about how you can use the timer to count the frequency of a signal.


None of the programs in Arduino example is compiling

A couple of things here look odd – but then I don't use Windows very often – I'd suggest that you download a fresh copy of the stock (not development) Arduino IDE. You can get it here.

What's odd looking too me is:

The double backslashes, they could be causing the file to appear not to exist, and
The arduino-nightly component in the path. That suggests to me that you're using a "bleeding edge" version of the IDE where problems are likely to creep in. These versions are for developers and people who like living on the edge (or who want to help with testing new features and the like).

One thing to do to check out the first oddity is to actually try to follow that path (both with and without the double backslashes). If the file is there (without the double backslashes) then it seems like something is odd with the path construction in the IDE.


From Gerben's link to the googlegroups's thread, Delta robot 3D printers › compiling jcrocholl's Marlin (Ubuntu), as Francis Mallet points out, at the bottom of the thread, it is necessary to change <time.h> to "Time.h":

  I copied the content of the Time library right in the Marlin folder, then changed line 7 of qr_solve.cpp from #include  to #include "Time.h"

  The code compiled and everything seems to be working ok.

So, to iterate, the line in qr_solve.cpp:

#include <time.h>

becomes

#include "Time.h"

Now, Marlin.ino should compile as expected.

Note that the latest version of Marlin, from github.com/MarlinFirmware/Marlin no longer suffers from this issue, but older versions of the software, such as github.com/gpfwestie/kossel_2020_sintron will do, due to line 7, in qr_solve.cpp.


How to connect MPU6050 with Arduino Uno without using A0-A5 pins?

You could use a Software I2C library, like this one on github, which can be used on almost any pin of a board. But keep in mind, that doing such communication in software imposes some limits (for example the linked library can only be a master). Keeping it in hardware is often the better choice, depending on your requirements.


Arduino Ultrasonic Sensor and LCD - Help Needed-

The root of your problem is this bit:

LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters:
(rs, enable, d4, d5, d6, d7)

I think in copying-and-pasting you ended up with a line split across two giving you an error. It should read:

LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)

You have a similar problem here:

lcd.begin(16,2); // Initializes the interface to the LCD screen, and
specifies the dimensions (width and height) of the display

Again that has split across two lines and should read:

lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display

And a third:

lcd.setCursor(0,0); // Sets the location at which subsequent text written to
the LCD will be displayed

which should be:

lcd.setCursor(0,0); // Sets the location at which subsequent text written to the LCD will be displayed

When those three are corrected the code compiles properly.


Cannot obtain reading from meter (Modbus)

You need to stop thinking quite so linearly. You are working with asynchronous systems, so your code has to be asynchronous too.

Something more like this:

#include <SoftwareSerial.h>

#define SerialControl 7

#define RS485Tx HIGH
#define RS485Rx LOW

SoftwareSerial RS485Serial(11, 12);

byte SendKWh[] = { 0x01, 0x03, 0x40, 0x34, 0x00, 0x02, 0x90, 0x05 };

// 0x01: Meter Address, 0x03: Read Function Code, 0x40: Register Address Variable (Start address high bit)
// 0x34: Register Address Variable (Start address low bit)
// 0x00: Register Quantity (High Bit), 0x02: Register Quantity (Low Bit)
// 0x90: CRC check code (CRC code Low bit)
// 0x05: CRC check code (CRC code High bit)

uint8_t window[8]; // Initialising window of 8 bytes

void dumpWin() {
  for (int i = 0; i < 8; i++) {
    Serial.print(window[i], HEX);
    Serial.print(" ");
  }
  Serial.println();
}

void ReadRx() {
  if(RS485Serial.available()) {
    uint8_t b = RS485Serial.read();
    dumpWin();
    // Slide the contents of the array down
    for (uint8_t i = 0; i < 7; i++) {
      window[i] = window[i+1];
    }

    window[7] = b; // Next frame inserted at the top of previous

    if ((window[0] == 0x01) && (window[1] == 0x03) &&
        (window[2] == 0x40) && (window[3] == 0x34)) {
          // Doing something with window[4] and window[5] here
    }
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(SerialControl, OUTPUT);
  digitalWrite(SerialControl, RS485Rx);
  RS485Serial.begin(9600);

}

void loop() {
  static uint32_t ts = millis();

  if (millis() - ts >= 2000) {
      ts = millis();
      digitalWrite(SerialControl, RS485Tx);
      RS485Serial.write(SendKWh, sizeof(SendKWh));
      RS485Serial.flush();
      digitalWrite(SerialControl, RS485Rx);
      RS485Serial.listen();
  }

  ReadRx();
}

Notice how I use millis() to send the command every 2 seconds asynchronously (i.e., without delay()). The RS485 is kept in READ mode except for the brief moment while you send. Also note the use of flush()  to wait until the last symbol has been transmitted by the UART (software in this case) interface. It's important, otherwise you may cut off the transmission part way through (I don't think it's such a problem with SoftwareSerial, but with a hardware UART missing it out would be fatal).

The reading just reads one character and returns to the loop. Each iteration through the loop will (if a character is available) read just one character. Only when all 8 have been received and the contents of the window match up can you process anything (which you would put in place of the comment).

This method also leaves you free to implement other things in loop(), as long as they don't use delay() as well.


You could write a simple program that escapes all the offending characters and use the output of that in your const char libData[]; see here for a list of escape sequences;
You could serve the library directly from a (pseudo) file system on the ESP8266, without having to copy it "manually" into a variable; you just copy the file to the filesystem;
You could Base64-encode the library and manually copy the result into const char libData[], then Base64-decode before sending;
What I like to do, if there is no file system but enough memory:

Gzip the library;
Base64-encode the .gz file;
Copy the Base-64 encoded result by hand into your const char libData[].

Despite the Base64 encoding, the gzipping makes the end result smaller than the original, which helps with memory usage and transfer speed, and it will have no "quote problems".
When the libData needs to be served, Base64-decode it, and send the resulting (gzipped) data to the client; all browsers I know will accept that if you add the Content-Encoding: gzip header.
Example code on a raw client without a webserver library: unsigned int sendBase64Page() (mind the content type).


Problem sending string with Python to Arduino through serial port

The AVR Arduinos (Uno, Nano, Mega) have auto-reset function. At opening of USB connection the circuit around USB resets the MCU. After reset the bootloader waits a second for a new upload. If the upload doesn't happen the bootloader starts the current sketch.

The serial.Serial() command in python opens the USB connection. With that the Arduino is reset and waits in bootloader while you send the data. The data doesn't arrive in your sketch. Add a two seconds wait time after Python's serial.Serial().


You can but keep the I2C wires less then about 30cm. If they are going to be further apart consider something like RS485 or CAN. Are you sure you need three?


Are any Arduino boards especially suited for low-power operation?

Technically you can use any arduino for that purpose with some modifications. I recommend to go with an arduino Pro Mini and remove the LED and the voltage regulator.
But if you don't need so much I/O you can go with a digispark Attiny board.


How to use variables and functions across multiple .ino files

When you compile multiple files in the Arduno IDE the files first get concatenated together.

It happens in alphabetical order, except the main INO file (the one named the same as the folder it's in) is placed first.

In C the order in which things appear in the file matters. Basically you have to make sure that things (like variables, functions, etc) are defined before they are used.

This gets more complex when you have a hidden thing like file concatenation messing things up.

The Arduino IDE tries to hide some of it from you too by making function prototypes, so it doesn't matter what order you define functions in - however that "helpfulness" means you don't learn about the proper structure of a C program.

So what can you do? Well, simply make sure that all your global variables are defined in the main file, unless you know they are only going to be used within the file they are defined in.


Can you pass params to an arduino sketch?

Every ESP8266 has a unique MAC address. You could that information to distinguish between the different units.

Something like if( mac='00:0a:95:9d:68:16' ){ ... }


How is IF( object ) evaluated? Follows from SD card example sketch

There is an operator bool which does the test:

File::operator bool() {
  if (_file)
    return  _file->isOpen();
  return false;
}

When used inside an if the compiler invokes the operator bool() which does the test you see above.


What is the most efficient voltage divider for Arduino?

The most efficient is not to have a voltage divider at all. Or at least to only have a voltage divider when you actually need one.
My preferred schematic is this:

simulate this circuit – Schematic created using CircuitLab
With this M1 is normally kept turned off by R3. When you want to take a measurement you turn on M2 by setting D3 HIGH (or whatever pin you attached it to) which pulls down the gate of M1 turning it on. This then connects the batter to the voltage divider R1/R2 and allows you to read the voltage at A0.
The voltage divider of 20k / 10k allows you to read up to 15V on the battery, and gives you an output impedance of 6.67kΩ which is within the recommended maximum of 10kΩ for the ATMega's ADC.
During "idle" times when M1 and M2 are both off the only current flowing is the minuscule leakage current through M2 tempered by the large 100kΩ resistor R3 (which itself pales into insignificance compared to the "off" resistance of M2 anyway).
Selecting M1 so that the ON resistance is very small (<0.1Ω) allows you to essentially ignore it in your calculations since that will be swamped by the tolerance of R1 and R2 anyway.  M2 needs to be selected so that it is "logic level" (i.e, with a gate threshold V_GS well below 5V).
This double-FET arrangement should be used rather than just using an N-channel FET in the ground connection of the divider because when that simpler arrangement is turned off the Arduino will be seeing 12V directly connected to A0 which really is not good - you will kill the Arduino - so it is important that you switch the "high" side of the network not the "low" side, and to do that requires two FETs.


I didn't try myself, but just by looking at the docs I suggest you try:

Adding

#define ARDUINOJSON_USE_LONG_LONG 1

at the top of the sketch, before including ArduinoJson.h.

Declare CurrentUpdatedMS and CurrentUpdatedMS as either
unsigned long long or uint64_t.

Edit: To answer the question in the comment:

  When you said you looked at the docs where did you check?

I had to follow a (not so simple) path: Deserialization tutorial →
JsonDocument::operator[] → JsonVariant →
JsonVariant::as<T>(). This last page states that the method
as<unsigned long long>() “may require ARDUINOJSON_USE_LONG_LONG”.
Unfortunately, the macro is not linked, so I have to search for it and
found ARDUINOJSON_USE_LONG_LONG.


Is there alternative to arduino IDE program ESP8266 and ESP32 with arduino toolchain?

Not an exhaustive list. Most advantages will be subjective.

UECIDE - Wide variety of boards, not only Arduino, better editor and serial monitor, plug-in based modules.
PlatformIO (Available as plugin for Atom editor, MS Visual Studio and Eclipse IDE) - Automatic library updating, one ini file that defines project settings and external libraries, making projects portable to other users without having to download all external libraries.
Arduino IDE for Visual Studio - For those who like VS?
Arduino Makefiles - More like old-school command-line coding, Linux-style development. Not an IDE.
Eclipse - Another quite popular IDE outside Arduino world.
Atmel/Microchip Studio 7 - Provided by the manufacturer of the AVR chips. "Arduino" sketches may not compile without changes to make them more like standard C++.


Arduino IDE giving a blow to battery back-up of PC

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


Different dht21 readings on different arduinos

Problem solved. Using a ywrobot breadboard PSU and now it works. I haven't tested current in the circuit but looks like it was just too low. I wish I'd had datasheet for the board to look at. In a language different from chinese would have been ok, I guess.


Limiting Data Output Frequency from ADXL345

Everytime you get a value from the sensor (for example with getX() or others) the library communicates with the sensor over I2C or SPI. So you can limit the usage of these function in your sketch. One way is with using delay(), but this is considered unefficient in most cases, since you are basically busy waiting during execution of delay(). You will not be able to do anything else in the future during this time span (if you want to add functionality to your device).

It's better to use non-blocking code, that only checks, if it is time to do something and if not going further through the program. Image like you yourself would bake a pizza. You would not stare at the clock for 20 min, until the time is up. You would periodically check, if the time has come to take the pizza out.

You can achieve this on an Arduino with use of the millis() function, which returns the number of milliseconds since the last powerup/reset. (Note that it overflows after about 50 days). There are plenty of tutorials for that out there. You can start with the BlinkWithoutDelay example from the Arduino IDE, which perfectly shows, how this is to be coded.

Note: If you are using the sensor with a battery, then you might want to limit its power usage. For this the library can set the corresponding registers in the sensor to set the datarate in the sensor (The rate at which the data in the sensor is updated). A smaller rate will lower the power consumption. So you can set the rate at about the rate of the reading in your sketch.


Detect a camera flash? Light sensor, photoresistor?

A photo-resistor would not be recommended to detect a camera flash accurately.  For example, the Jameco Part #202403 (Part PDF) has a response time of 50 to 75 milliseconds.  Photo-resistors are more suitable for general light levels, for instance, like how bright it is in a room.  On the other hand, photo-transistors are suitable for very fast reaction times.  The Jameco Part #2129385 (Part PDF) has a response time of 15 microseconds, which is more than 1000 times faster.  A photo-resistor will be able to respond to the light change, but it will be nowhere as sensitive.As with any product, however, search for the product PDF before buying it.


Send data from one NodeMCU to another NodeMCU using Serial Communication

As already stated, your code uses the I2C interface (via the Wire library) and not the Serial interface (which is an Arduino term for UART). They work fundamentally different.
As you only communicate between 2 devices, which you both can program yourself. I would ditch the I2C interface. It doesn't give you any advantage here, but some disadvantages (for example, that you can't have real bidirectional communication, as the slave cannot do anything by its own, only, if the master asks for it).
Instead you should use a Serial (UART) interface. As the NodeMCU only has 1 full hardware Serial interface, which you already use for debugging, you could use the ESPSoftwareSerial library to create an extra Serial interface via software. It has limitations (in how many interfaces can listen at a time and how fast the communication can go), but most likely this will solve your problem. Also Serial is easier for beginners, than I2C.


Lowering delay when sending multiple SMS

It because a single SMS has 160 character limit. If you send more than 160 characters, those are transmitted by a process called concatenation(just googled out).
You can send at a faster rate by avoiding this process and sending 2 different messages which are of length less than 160. Hope it satisfies your query.


How to read the serial data from a ATMEGA8 on a PC using Arduino?

If you connect the TX pin on your device to the 'TX' pin on the Arduino, then load a sketch such as 'blink' that won't initialize the Arduino's own UART, you can use the Arduino's onboard USB-UART adapter to talk to your device.


What sensor is used to judge transparency?

A light sensor should work. Another option would be an inductive Sensor to detect the Aluminium Can. And if you need to know if there is a Can in your sensor area you can combine it with an IR (or capacitive) Sensor, which should detect both Can types.

So it would be something like this:

if(IRdetect == true){
  if(inductive == true){
    type = alu;
  }else{
    type = plastic;
  }
}else{
  // no Can
}

Some cheap sensors as Example:

Inductive: Banggood
Infrared: Banggood


Thanks to all those who responded. I have a double embarrassment here as I have the answer. Firstly if you can answer your own question there is an argument it should never have been posted, more thought needed first. Sorry everyone. Secondly when the cause is ignoring well known good practice then it is even worse.

So when tying a pin to Vcc (in this case SRCLR) it is known bad practice to hard couple it to Vcc. A pull-up resistor is a much better method. In this case suitable pull-ups were in the next room and I could not be bothered so I just jumpered SRCLR to Vcc. After I had written the post I was staring at the breadboard and thought - I should not have really done that replaced the jumper with a 10K pullup to Vcc. Instantly the SEROUT pin of the TPIC6B595 came to life as it should have. Now I have taken this short-cut before and gotten away with it. But it seems not this time.

Subsequently I have a one chip version of the alternating LEDS running with the SPI interface.

As to the suggestion by dannyf about the datasheet, there is no doubt the datasheet is a good place place to go. Prior to developing my test sketch as per my original post I consulted the datasheet and if you look in Section 8, page 11 of the TI datasheet revised June 2015 there is a Functional Block Diagram. This block diagram clearly shows that the RCK signal is concerned only with the C2 column of D flip-flops which take the output from the shift register and latch it to the output FET through the output enable logic. RCK is independent of the process to clock data through the shift register, controlled by SRCLK. You will note my test did not exercise the transfer function it was just interested in getting data into the shift register and out again.

I stand by my assertion that for the serial shift register function and checking SEROUT, RCK is not relevant. Once you want to start data transfers from the shift register to the output register then it is different matter. No disagreement there. Having that timing wrong will lead to a mess of corrupted data.

Thanks again to all. This is solved and is a lesson to abide by good practice always.

Regards, Fred.


Infra Red sketch "not declared in this scope"

Numeric values in HEX need to be prefixed with 0x:

case 0xE0E036C9: //Keypad button "5"

and

case 0xE0E028D7: //Keypad button "2"


Disabling USB power is slightly tricky, as the incoming USB power is not only used for potentially powering the system, but it is also used by the various USB interfaces to indicate the presence of a connection.

The best way, looking at the schematics of the Due, would be to remove one or both MOSFETs that switch the USB power - that's T1 for the native port and T2 for the ATMega interface.  That will isolate the USB power from the 5V system while keeping it connected to the VBUS pins of the relevant microcontrollers.


Your code is not reading the SoftwareSerial. b is only populated when the Pi sent data. The loop below sends what it reads from the SoftwareSerial, after that is prints a new line println() (only because that's what your code is doing)

The listen() method of SoftwareSerial is only required if you have more than one SoftwareSerial connection.

#include <SoftwareSerial.h>

String b = "0";
SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  portOne.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    b = Serial.readString();
    Serial.println("Data from RPI:");
  }

 //not required with only one software serial connection
 //portOne.listen();

  if (portOne.available() > 0)
  {
   while(portOne.available() > 0){
      byte byteRead = portOne.read();
      Serial.write(byteRead);
    }
    Serial.println();
   }
  }


If you want to get a value from PROGMEM you must read it with pgm_read functions. Read the PROGMEM reference.

for (int i = 0; i < 8; i++) {
  Serial.print(pgm_read_byte_near(pat + i),HEX);
}

pat[0] in Serial.print(pat[0],HEX); is an item in a constant array const uint8_t pat[]. it can't change at runtime so the compiler uses the value 0xFF. that is why it is printed ok without pgm_read_byte_near


Unless you have a really large number of read/write operations and very tight time constraints, I doubt you are going to have any significant advantage in terms of speed.

Accessing the bits in a port together, rather than individually is certainly more efficient, both in terms of time and space, but it might cost in readability, depending on how comfortable you are with leaving the Arduino libraries behind.

You can have also a look at this thread.

Notice that the maximum gain happens only when all the pins you have to read or write belong to the same register.


Can i connect in pin of relay module to Analog pins of arduino instead of digital pin?

Yes, you can  use the analog pins as digital pins.
Quoting this Arduino tutorial:
pinMode(A0, OUTPUT);
digitalWrite(A0, HIGH);

EDIT:
Here is the code snippet for digital input:
pinMode(A0, INPUT);
digitalRead(A0);


The closest I could get to what you are trying to do is this:

template <size_t table_size> struct Ex_class {
  int get_value(int index) const {
    return pgm_read_word(&_ex_table[index]);
  }
  int _ex_table[table_size];
};

void setup() {
  Serial.begin(9600);
  static PROGMEM const Ex_class<5> ex_object = {1, 2, 3, 4, 5};
  for (int i = 0; i < 5; i++) {
    Serial.print(i);
    Serial.print(": ");
    Serial.println(ex_object.get_value(i));
  }
}

void loop() {}

avr-nm and avr-objdump confirmed that the object lives indeed in the
text section of the program. Please note that:

The object is PROGMEM const. It would make no sense to try to put in
PROGMEM anything that is not constant.
The object is allocated statically. It can be either a global or a
static local, but not an automatic local like in your example.
I am using aggregate initialization here. I know no other way to
statically initialize an array of variable length. If you have an
idea, I would be interested to know though.


cant understand how to program it for such purpose so please help me out

it is fairly easy to approach such questions:

1) you can program any?

2) can you program this mcu to blink an led?

3) can you program this mcu to do short time counting?

4) can you program this mcu to do long time counting?

what you help helps you the most depends on your  answers to those questions.


Simple reading and writing on Floppy Disk

for(unsigned index = 0; index<=8; index++)

I think that need to be

for(unsigned index = 0; index<8; index++)

Otherwise you are trying to read the 9th bit in a byte.


How to webClient.write() an image stored on a String?

You should not use String to store binary data.
Instead allocate yourself an array of uint8_t of the right size.
uint8_t *imageData;
size_t len = file.size();

imageData = alloca(len);
file.readBytes(imageData, len);

webClient.write(imageData, len);

With that said, without knowing what the rest of your program is doing I can only surmise that you're just blasting raw data at the web server and hoping it sticks. That's not how web data transfers work. You have to craft the upload page properly as multi-part mime form data. Read this for more information


Sometimes the brute-force way is also the most efficient. Just copy the bits one at a time from the corresponding source variable to the destination variable:

int merge_bits (int old_bits, int new_bits)
{
   int retval = 0;
   if (old_bits & 0x01) retval |= 0x001;
   if (old_bits & 0x02) retval |= 0x002;
   if (old_bits & 0x04) retval |= 0x004;
   if (old_bits & 0x08) retval |= 0x008;
   if (new_bits & 0x01) retval |= 0x010;
   if (old_bits & 0x10) retval |= 0x020;
   if (old_bits & 0x20) retval |= 0x040;
   if (old_bits & 0x40) retval |= 0x080;
   if (new_bits & 0x02) retval |= 0x100;
   if (old_bits & 0x80) retval |= 0x200;
   if (new_bits & 0x04) retval |= 0x400;
   if (new_bits & 0x08) retval |= 0x800;
   return retval;
}

On most microprocessors, this will compile into just a few instructions per statement.

This is also arguably more maintainable than a complex series of shift and mask operations.


Arduino support within MATLAB came with Matlab-2014a onwards, you are using R2013a

Arduino support within SIMULINK came with Matlab-2012a onwards

for your release you can only interact via a simulink model


The datasheet states:
Requires 5-9VDC @ 1.5Amp power supply during print.

In my experience this printer provides best results when operated at its upper limit. I am using a 9V 2A power supply for that. A bettery is definitiverly not enough.


Stepper would be heavy and battery consuming, as Ignacio says.

Pololu makes an encoder for a wheel: http://www.pololu.com/product/1217, but obviously you can implement this in other ways too.


Ok strange, just after posting this the qduino decided to flash a different light on me so I try to upload again and it works... So apperantly just by keeping the qduino connected for some time it will start to work again...


The Arduino Sketch does not save in Arduino folder location

Download the latest IDE from Arduino.cc
Drag your Arduino application icon to the trash.
Open up terminal and type rm -r ~/Library/Arduino15
Delete the Arduino folder in your Documents folder for good measure
Drag the newly downloaded Arduino application to your application folder and see how it goes from a clean install.

Failing that PlatformIO IMO is a much better IDE for developing on these platforms : http://platformio.org/


How can I add additional boards to Eclipse with the Arduino add-on with only a URL, not a zip file

With arduino eclipse plugin 2.4 you simply install the boards with the arduino ide -like you described- and you can use then in the arduino eclipse plugin.

Version 3.0 (that is the nightly as 3.0 still needs to be released) contains it's own boards and library manager in windows->preferences->arduino.


While I'd like to direct you to ways to set up a nice tasking system with a frame counter, your system is likely simple enough that it is unnecessary.  You can likely just replace the delay(1000); of the second program with approximately 5 calls of the first program's loop.  May you instead learn something when cleaning up the following (which is literally a copy paste with minimal changes).

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

#define sensor A0
#define led 13
#define ledd 8  // d out from mq3
#define buz 9
#define motor 10
void setup1()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  lcd.print("ALCOHOL MONITORING");
  lcd.setCursor(0,1);
  lcd.print(" VEHICLE SYSTEM ");
  delay(2000);
  pinMode(sensor, INPUT);
  pinMode(buz, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(ledd, OUTPUT);
  pinMode(motor, OUTPUT);
  lcd.clear();
}

void loop1()
{
  float adcValue=0;
  for(int i=0;i<10;i++)
  {
    float actualanalogReading =  analogRead(sensor);
    adcValue = adcValue + actualanalogReading;
    Serial.println("In loop counter >"); // logging
    Serial.print(i);
    Serial.print(" input reading : ");
    Serial.print(actualanalogReading);
    Serial.print(" cumulative input reading : ");
    Serial.print(adcValue);

    delay(10);
  }
    float v= (adcValue/10) * (3.0/1024.0);
    float mgL= 0.67 * v;
    Serial.println("");
    Serial.print("Post calculation v value >" );
    Serial.print(v);
    Serial.print(" mg/L > ");
    Serial.print(mgL);
    Serial.println("");
    Serial.print("BAC:");
    Serial.print(mgL);
    Serial.print(" mg/L");
    lcd.setCursor(0,0);
    lcd.print("BAC: ");
    lcd.print(mgL,4);
    lcd.print(" mg/L        ");
    lcd.setCursor(0,1);
    if(mgL > 0.8)
    {
      lcd.print("Drunk ENGINE OFF ");
      Serial.println("Drunk ENGINE OFF ");
      digitalWrite(buz, HIGH);
      digitalWrite(led, HIGH);
      digitalWrite(ledd, LOW);
      digitalWrite(motor, LOW);
    }
    else
    {
      lcd.print("Normal ENGINE ON ");
      Serial.println(" Normal ENGINE ON ");
      digitalWrite(buz, LOW);
      digitalWrite(led, LOW);
      digitalWrite(ledd, HIGH);
      digitalWrite(motor, HIGH);
    }

    delay(100);

}

const int LED = A5;
const int DO = 6;
void setup() {
 setup1(); //Serial.begin(9600);
 pinMode(LED, OUTPUT);
 pinMode(DO, INPUT);
}
void loop() {
 int alarm = 0;
 float sensor_volt;
 float RS_gas;
 float ratio;
//-Replace the name "R0" with the value of R0 in the demo of First Test -/
 float R0 = 0.10;
 int sensorValue = analogRead(A1);
 sensor_volt = ((float)sensorValue / 1024) * 5.0;
RS_gas = (5.0 - sensor_volt) / sensor_volt; // Depend on RL on yor module
 ratio = RS_gas / R0; // ratio = RS/R0
//------------------------------------------------------------/
 Serial.print("sensor_volt = ");
 Serial.println(sensor_volt);
 Serial.print("RS_ratio = ");
 Serial.println(RS_gas);
 Serial.print("Rs/R0 = ");
 Serial.println(ratio);
 Serial.print("\n\n");
 alarm = digitalRead(DO);
 if (alarm == 1) digitalWrite(LED, LOW);
 else if (alarm == 0) digitalWrite(LED, HIGH);

 for(int dd = 0; dd < 5; dd++) loop1();
}


How big of a difference is there between an Arduino Uno and the rest?

That program will make the arduino board act like a keyboard to the PC it's plugged in. This can't be done on the Uno, since it doesn't have USB support.


Just inherit Print class and implement virtual size_t write(uint8_t); and you can use all kinds of print/println that Print implements. See Print Class @arduino.cc.

It implements these methods for you:

size_t print(const __FlashStringHelper *);
size_t print(const String &);
size_t print(const char[]);
size_t print(char);
size_t print(unsigned char, int = DEC);
size_t print(int, int = DEC);
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(double, int = 2);
size_t print(const Printable&);

size_t println(const __FlashStringHelper *);
size_t println(const String &s);
size_t println(const char[]);
size_t println(char);
size_t println(unsigned char, int = DEC);
size_t println(int, int = DEC);
size_t println(unsigned int, int = DEC);
size_t println(long, int = DEC);
size_t println(unsigned long, int = DEC);
size_t println(double, int = 2);
size_t println(const Printable&);
size_t println(void);

However you have to implement 2D array print if you really need this, I don't see why do you need it but whatever (you can print each line separately). It just saves you time with implementing everything else.

And for std::ostream like approach I like this (works with anything inherited from Print class):

template <class T> inline Print & operator<<(Print & p, const T & val) {
  p.print(val);
  return p;
}

// ...

void loop() {
  float variableA = 221.23;
  String variableB = "Some string";
  Serial << F("flash string to save some ram: ") << variableA << F(" / ") << variableB << "\n";
}

Then you can implement some commands interface.


No, it's not possible.

AVR chips can only execute code from their internal flash.


Different behavior than in simulator: 5V pin works instead of GND. Why is that?

The RGB LED's are available with common cathode and common anode.  That determines whether you connect the common pin to ground or to +5.

In your schematic you likely mismatched the selected part to what you actually have.  If you have the opposite type of LED as planned, just reverse the connection as you did.  You are not alone in this type of mistake.  see similar whot? here

A digital multimeter with a diode test mode would be very useful here.  The DMM would quickly measure the polarity of the diode tell you which lead connects to positive and which to ground.

But did it really work correctly?  Don't you also see that you have to write LOW to the digital output to make the LED light up?


Arduino Library to make http post request with bearer authentication

The "Authorization" is simply an HTTP header.  So add it in your request like:
http.addHeader("Authorization", token);

The value of "token" is just the string "Bearer " followed by your authorization string.  Don't neglect the SPACE after the word "Bearer".  It will look like:

"Bearer eyJhb......"

On the Arduino MKR WiFi 1010 you use the WiFiNINA library which is slightly different.  Here is some example code:
  if (client.connect(server, 80)) {
    client.println("POST /test/post.php HTTP/1.1");
    client.println("Host: www.targetserver.com");
    client.println(authorizationHeader);
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(postData.length());
    client.println();
    client.print(postData);
  }

The variable authorizationHeader will have the "Authorization: Bearer xxxxx...." authorization string.
Or you can replace the client.println(authorizationHeader); by:
client.print("Authorization: Bearer ");
client.print(token);

to avoid dealing with concatenations, etc.
client can be an instance of WiFiSSLClient which works with both WiFi101 and WiFiNINA.


How to debug Arduino using Atmel studio?

I found another very easy way to debug the arduino board with atmel studio without even using an external debugeer like the atmel ice debugger. It's an extension called vMicro which can be added within atmel studio (visual studio as well) you connect the arduino board over the micro USB to the computer and specify the parameters in the vMicro toolbar in atmel studio and that's it!
 It's ready to debug! Finally I think atmel ice is thought for other boards maybe, since debugging can be done without it easily!


Sometimes you want your callback to be fed some data that you provide
when you register that callback. Here is a very common callback pattern
in plain C that does that:

// The API:

typedef void (*callback_t)(void *data);
void register_callback(callback_t callback, void* data);

// Usage:

typedef struct {
    // stuff only the user of the API knows about.
} my_data_t;

void my_callback(void *in_data)
{
    my_data_t *data = (my_data_t *) in_data;
    // do something with data->foo, data->bar...
}

// ...somewhere else:
my_data_t my_data = { stuff... };
register_callback(my_callback, (void *)&my_data);

The problem is: it's clumsy. C++ classes allow you to pack together the
code (the callback function) and the data it needs. Thus, if in your use
case you need to pass data to the callback, by all means use a C++
class. It will make your life easier and you are unlikely to even notice
the memory overhead.

However, if you only need to pass a function, with no attached data,
then a plain function pointer would be both easier for the API user and
optimal memory-wise.


Connect Arduino to an external microSD card reader

You cannot

SD cards cannot be shared between masters in operation, and it is unsafe to disconnect the card from the camera with an electronic switch when the camera is not expecting that.

Nor is an ordinary Arduino fast enough to passively snoop the data being written to the card by the camera (while a card will let an Arduino write to it quite slowly, any camera would do so far, far faster)

Nor is an ordinary Arduino able to do much of anything meaningful with the image files produced by a typical camera in real time.

Nor can an ESP8266 while running Arduino-based software; it apparently does have some high-speed I/O capabilities but that would require low-level rather than Arduino-port-based programming.

For all practical purposes, you'd need to power off the camera, remove the card, and place it in the Arduino reader.


Like any other I/O pin, there should be no problem driving this pin (and
thus the builtin LED) from an external source, as long as you make sure
it is in INPUT mode. If the pin is set to OUTPUT you will likely
damage the Arduino.

Warning: If you have the Blink example already loaded in the
Arduino, the pin is in output mode. Be sure to upload another program,
that does not set pin 13 to output, before connecting anything that
could drive pin 13.


Opamp for amplifying 1V signal voltage to 2V

A 2mV offset voltage will become a 4mV error after amplification. You haven't shown the schematic for your amplification, but the current bias will also become error after amplification.

That LM324 variant is surface mount, but there are other LM324 variants in a DIP package, which will work fine in a breadboard.


Strange phenomenon when declaring double

OK, this may not be a proper answer. I'm just having a hard time reading
your code, and I cannot understand why you make it so complicated. If
you know the acceleration profile, computing the position profile is
just a matter of integrating twice. Here is an example, not for Arduino
but for a PC. It should not be very different on an Arduino, you just
wouldn't use printf():

/* Compute position for any acceleration profile. */
void compute_profile(float (*acceleration)(int), int max)
{
    float x = 0, v = 0;

    for (int t = 0; t <= max; t++) {
        v += acceleration(t);
        x += v;
        printf("%d\t%f\n", t, x);
    }
}

/* Your particular acceleration profile. */
float VttgJ(int t)
{
    if (t <  7) return t;
    if (t < 13) return 12 - t;
    if (t < 40) return 0;
    if (t < 46) return 39 - t;
    else        return t - 51;
}

int main(void)
{
    compute_profile(VttgJ, 50);
    return 0;
}


Python PySerial with Arduino fails byte check

I think the problem is that you can't count ;)

Spot the difference:

0: [0x01] Frame start
1: [0xMeterValueByte0]
2: [0xMeterValueByte1]
3: [0xMeterValueByte2]
4: [0xMeterValueByte3]
5: [0x04] Frame end

and:

0: Serial.write(0x01); //start frame
1: Serial.write(0x00);
2: Serial.write(0x00);
3: Serial.write(0x02);
4: Serial.write(0x04); //end frame

Your receiver is looking for a pattern of 6 bytes, but your Arduino sketch is only sending a pattern of 5 bytes.

Your check for the start character is simple enough - you solved it fine a few lines above:

print "j= " + hex(ord(j))

But you forgot to do something similar for the check:

if (j == 0x1):

That should really be:

if (ord(j) == 0x1):


char to String conversion in Arduino program

this isn't an arduino specific error what you're trying to do is declare and initialize the variable in one statement which is causing the problem. As you've figured it out already. Declaring the variable first

String s;

and initializing it another statement does the job for you

s=blabla

Hope this helps. PS, try posting the error that you get during build process next time :)

EDIT:
 I think this needs more explanation. Basically why you cant declare and initialize at the same time in this case is because Serial.read is a synchronous request. Declaring an object requires acquiring the space for it, running any constructors and whatsoever, and doing while Serial.read() is an IO blocking operation. You could declare and initialize a String class variable given it was a string constant but not with anything like get_input or Serial.read

EDIT 2:
Further here's what I've found for you.

http://www.cplusplus.com/reference/string/string/string/

Apparently the  String class has a copy constructor which means when declaring the variable you initialize at the same time it uses the copy constructor, and which requires ADDRESS to a valid string(know that you can use a constant because C++ deals with all strings as the address to their first char). In your case the constructor raised an error because you pointed it to an undefined(Serial.read() ).

String mystring=Serial.read(); //error, uses copy constructor

However this would work

String mystring="hey juliet!" ; //uses the copy contructor which takes address to a char

Doing the same thing in two different lines works for the same reasons, it uses a different constructor

String mystring; //uses empty string constructor - okay so far
mystring=Serial.read(); // uses the overloaded = operator  --okay


There's no need for either PHP or JSON. Simply detect when one of two URLs (say, /led/on and /led/off) has been accessed on the Arduino's web server, change the LED state, and return a 204 response.


Counting revolutions of a DC motor with a Photo Interrupter

You shouldn't use an analog pin with a photointerruptor.  The photointerruptor is a digital device.  Connect it to, preferably, an interrupt pin and use an interrupt to count your revolutions at high speed.


Arduino classes, can't get property value

When you put the type there, you are creating new variables.  SO in your constructor:

 MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      int _dirPin = dirPin;
      int _stepPin = stepPin;
      int _enablePin = enablePin;

You start by creating three new variables with the same names as the member variables defined in the class.  Throughout the rest of the constructor those get used instead of the ones that are member variables.

You gotta lose the "int" there.

You also have another bug in there.  The constructor may run before the init function if one of these objects gets declared at global scope.  Things like digitalWite and pinMode aren't going to work yet in that case.  A constructor should just have code to initialize variables, it should never touch hardware.  The stuff that uses hardware should be in another member function (usually called begin or init) that you can call from setup.


I had the same problem, you just have to download the Adafruit Neo Pixel library:


The Arduino IDE does not have a core for the ESP32 installed by default.

The problem was solved by explicitly installing the ESP32-Arduino Core in the Arduino IDE according to their manuals

https://github.com/espressif/arduino-esp32/blob/master/docs/arduino-ide/windows.md
https://www.smart-prototyping.com/blog/How%20to%20Install-ESP32-Core-Arduino-IDE


How do I make a stepper motor compass cross 360° to 0°?

Two options (for starters):

Use the move() class rather than the moveTo() class. This will allow you to do relative moves rather than absolute.
Use setCurrentPosition() (which sets the current position to zero) followed by moveTo() with a destination which is newPos - prevPos.

For either to work you will need to keep track of the current position of the needle.

To work out the relative move you will need to do some kink of modulo arithmetic but this will require some trickery to generate negative values for anti-clockwise moves.

// delta is the angular adjustment required.
delta = (currHeading + 180 - prevHeading) % 360 - 180;
setCurrentPosition();        // Zero the motor.
moveTo(delta);               // Move absolute from the new zero.
prevHeading = currHeading;   // Keep track.

The code assumes that you will never have to make a heading adjustment of more that 180° in one step.
Adding in the 180° before the modulo calculation and subtracting it again afterwards is a trick to allow negative results from the modulo arithmetic.


At what frequency/rate does the digitalRead function read an input?

When I get time, I will provide more definitive answers.

I did follow through with this, and the result is here, towards the end of the page: https://dannyelectronics.wordpress.com/2016/05/01/the-price-of-avr-arduino/

the short answer is: digitalRead() takes 4.9us to execute on a 16MIPS Arduino Uno, or 79 ticks (=instructions).

the fastest you can read digitalRead() is then 200KHz (= 1/4.9us).

Hope it helps.


However, does not work for:
 ADMUX = 0xC0;

See the datasheet:

An ADMUX of 0xC0 will be using a voltage reference of "Internal 1.1V Voltage Reference with external capacitor at AREF pin". Since you are supplying 2.5V that exceeds 1.1V and thus you get a reading of 1023.

  Serial.println((int)sensorValue);

Also, don't do serial prints inside an ISR.


My two ultrasonic sensors are reading inaccurately

I am not sure but may be it helps just by checking principle of working of this sensors as it is depicted for low range distance you must be carefull about reflection from other source of ultrasonic. I think it would be a good Idea to place a delay between these two module so to make sure it get less noise from each other

  FindRange(trigPin1, echoPin1);
  duration1 = duration;
  distance1 = distance;
  delay(1000);//add delay
  FindRange(trigPin2, echoPin2);
  duration2 = duration;
  distance2 = distance;
  delay(1000);//add delay

the other reason for getting zero may be your controller could not measure reflection from wall due to lowspeed sampling (if you are polling) or reading time with low precision so I have a suggestion for you if you are familiar with STM32 there is a built-in hardware implementation for measure time of pulse using timers called one-pulse mode it may helps you get precision you need


The AD7390 data sheet timing diagrams show that /LD is in effect a slave select, but an active high one.

Specifically, it says that while /LD is high, each rising clock edge causes "Shift-Register-Data Advanced One-Bit", while when it is low, the shift register data is transferred to the DAC.

So basically you would need to use SPI in a mode where the slave select is controlled by software and asserted with the opposite of the usual polarity, but the actual shifting of the data can be accomplished with the hardware SPI engine.

It does not seem that you are always required to use the /CLR input - if you don't want to use it, wire it high.  Otherwise, you can connect it to a GPIO, take it low, and then raise it so that the rising edge causes an asynchronous clear.


If your error is intermittent, check all of your wiring to ensure there is nothing loose, and try hitting the 'reset' button the Arduino as the compile message changes to uploading, in case your serial adapter isn't resetting the Arduino properly.


A byte can't be -1. A byte can only store numbers between 0 and 255 inclusive.

Depending on the range of your numbers you could use a char (-128 to +127) or an int (-32768 to +32767).


On your code, you using analogRead but declaring the pin (A3) as output. Change it to pinMode(A3,INPUT);

Aside from that, PWM is basically a digital output which changing (HIGH and LOW) at specified frequency. When the result you got is

  0 0 1022 1021 0 1022 1021 0 0 1021 0 1021 1021 0 0 1021 0 0 1022

There's nothing wrong. 0 --> LOW, and 1021++ --> HIGH
If you want "measure" something from the PWM, use pulseIn() instead, you can check the documentation here.

If you want to measure the PWM value, I suggest you read:
Can I connect a PWM pin on one Arduino to an analog input on another?


You want to import a library not an example.

Arduino Folder
    |-- libraries
        |--HX711
            |--HX711.cpp
            |--HX711.h

ex:

C:\Program Files (x86)\arduino-1.8.5-windows\arduino-1.8.5\libraries\HX711

Put the files in a folder called HX711 to have everything nice and tidy.

I use the standalone version of arduino ide, if you have it installed I suspect the folder would be under

My Documents\Arduino\libraries\

According to the documentation.

You should put the nodemcu_test.ino in your sketchbook folder as I would generally avoid putting non-library files in the libraries folder. If you do want to keep the examples for a specific library close to the library create a subfolder:

Arduino Folder
    |-- libraries
        |--HX711
            |-- examples
                |--nodemcu_test.ino
            |--HX711.cpp
            |--HX711.h

As Juraj pointed out, this has the additional advantage of them being accessable in the examples menu.

If you want the libraries close to your sketch you are actually working on, follow the guide and put the library files in your sketchbook folder for your project. I would not advise for the following reasons:

I read that in newer IDEs 1.8.X you would need to put the files in a /src/subfolder. For me it did work without that, but the main caveat remained:

#include <HX711.h>

means to look in the library folder as mentioned above.

If you want to put the files somewhere else, you have to use

#include "HX711.h"

and specify the path (or in this example it was located where my .ino was). But now I also need to change

#include <HX711.h>

to

#include "HX711.h"

in the HX711.cpp file. What a hassle!

So my takeaway message would be: Stick with Arduino\libraries\.


Text send via HC-05 is broken up by first character on the receiving end?

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


Let's assume you have an Arduino that you have arranged to sample a signal with a sample rate of 1/T that is then processed by your controller. Let's also assume that the processing time for your controller is small compared to T e.g. 0.1/T

Firstly, you need to convert the controller transfer function to discrete time. There are lots of ways to do this. Matlab has a convenient c2d() function. One way you can do it on paper (not the best way), is to use Euler's Method.

s=(z-1)/T   where T is the sampling period.

Converting a transfer function then: (s+a)/(s+b) => (z-(1-aT))/(z-(1-bT))

So now you have a TF in z such as : Y(z)/X(z)=(z-c)/(z-d)  where Y is the output and X is the input.

To implement this in a controller you need this as a difference equation in terms of delays. So convert the equation to a function of (z^-1) which is a delay:

Y(z)/X(z) = (1-cz^-1)/(1-dz^-1)

and re-write as:
Y(Z)(1-dz^-1) = X(z)(1-cz^-1)

Y(Z)-d.Y(z).z^-1 = X(z)-c.X(z).z^-1

and change to sample time treating z^-1 as a delay:
y(n) - d.y(n-1) = x(n) - c.x(n-1)

rearranging:
y(n) = d.y(n-1) + x(n) - c.x(n-1)

You can implement this easily in the Arduino by realising that y(n-1) is the previous value of y(n) and similarly for x(n), and x(n) is the value input to the controller; i.e. the reference minus the output from the ADC.


Yes. The programming of the arduino microcontroller sets the values inside the FLASH. This is non volatile memory and as such won't be erased by taking out the IC.

Please note that this is assuming a DIP package IC as these can be removed without force, heat and stress. A TQFP, and SMT packages like that, IC might get damaged by moving them in such a way. This doesn't mean it has to be erased, it is still non volatile storage, but the moving process is much more dangerous for the chip.

I would recommend connecting the whole arduino or if you really need the whole chip: designing your own board/circuit which allows you to program the chip without moving it around as this is really tedious and not worth the effort. Also moving the chip around is a ESD hazard.

Also please note that you'll need to add a clock source for the chip to work (most of the time). Or you'll need to enable an internal PLL. It will in any case require more effort on your part to make sure that the MCU can work. Therefore using the whole arduino board is preferable.


Stabilizing output values of conductive sheet(Velostat) connected to analog pin A0 of Arduino

You need to use a matching resistance to create a voltage divider.


How can I calculate remaining battery life time with arduino

you may use ADC(analogRead) to measure Li-Ion Cell voltage. unlike Ni-Cd or Ni-Mh batteries, a Li-Ion Cell Voltage is a good measure for battery status. the discharge cycle of an usual Li-Ion cell Starts at 4.2v(full charged, better avoid that!) which quickly comes down to 3.7v. it remains about 3.7 volts most of the cycle and at the end, comes down again to about 2v which battery protector circuit cuts battery off circuit.

but if the Arduino itself is powered from li-ion battery, it can't measure the battery voltage as the ADC Reference is the current varying cell voltage itself. in this case you need to set VREF of Arduino to a lower internal constant reference(1.1v):

https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/

and implement a voltage divider

simulate this circuit – Schematic created using CircuitLab

now you can measure cell voltage compared to a fixed reference. a full battery of 4.2 will be read in ADC as about 1000 (4.2* (1/1+3.3) * 1024). 3.7 should be read about 880 and 2.2v (if the Arduino is still ON!) will be read 500 in ADC unit.


The circuit diagram of a NodeMCU shows that there's a schottky diode between Vusb (the voltage input supplied by USB) and the Vin pin. This has the effect of reducing the approximate 5V voltage supplied by your typical USB jack/outlet/cable to something slightly lower. In my case, the apple USB charger adapter provides 5.1V but this gets reduced to 4.76V on the Vin pin. This Vin voltage is also quite noisy. I don't know if that will affect your servos. I've run one NodeMCU from the Vin pin of another NodeMCU pin without any trouble.
The schottky diode in the NodeMCU is a 1n5819/SS14/S4(SOD_323). I'm not certain, but if this is the correct datasheet, it says it can supply 1 amp, which sounds like enough. If I were you, I'd try and see if I could get power directly from the USB source rather than taking it off the NodeMCU pin. It might work off the pin, though. Try and make sure you get a USB that supplies at least 5.1V, though. It's going to be close.
EDIT: I would also add that the NodeMCU will be drawing power, too. If you are drawing 300mA with your servos and 100-150mA with your nodeMCU, that's cutting it pretty close for most USB power sources. A Macbook, for example, can only supply 500mA via a USB port. This article says a NodeMCU can consume up to 400mA under some circumstances.
Generally speaking, I've been told that it's a bad idea to use GPIO pins to drive anything that draws a significant amount of power. I'm thinking you should maybe consider using some kind of servo driver or relay or something.


Sodaq Moja — Accessing SW2/SW3 user switches

According to the schematics and pictures of the Moja, the Sodaq Moja has no "User Switches".

There are 2 buttons and 1 switch.  The switch is a general power on-off switch.  One button (SW2) is the master reset button for the ATMega328P.  The other button, SW3, is the reset for the X-Bee daughter board.

None of those can be used programmatically.


is PIN To PIN matching mcu against Atmega328P-AU available?

The only other AVR chip with more program memory in the 32/TQFP form factor is the ATMEGA4808 at 48 kB.

Unfortunately, the pinout is not the same compared to the ATMEGA328P-AU:

ATMEGAx8P family datasheet

ATMEGAx08 family datasheet


How do I run a loop for a specific amount of time?

Here is an example that will run for 5 minutes. Note that the loop will begin executing anytime before the time limit is up, including 1 msec before; it can't cut-off something happening at the 5-minute mark, meaning the timing precision will be limited to the duration of the code in the loop.

Update: My first suggestion had a bug related to the 50-some-odd days roll-over period of the millis() clock. This one is more robust:

uint32_t period = 5 * 60000L;       // 5 minutes

for( uint32_t tStart = millis();  (millis()-tStart) < period;  ){
   doStuff();
   moreStuff();
}


Is it possible to use WiFi and Bluetooth / BLE in the same ESP32 project?

Yes. Select a partition scheme that gives you more room. For example "No OTA (Large APP)" gives you 3MB of program space.


Running Arduino with 2 outputs and 2 inputs

First thing: you should call pulseIn() right after sending the TRIG
pulse. If you wait too much, you will miss the start of the echo pulse.
For instance, here:
int distance = pulseIn(ECHO, HIGH, 26000);
int distance1 = pulseIn(ECHO1, HIGH, 26000);

the second pulseIn() is starting too late, because of the time taken
by the first one.
Next, the general approach for doing things is a non-blocking fashion
(and thus being able to handle concurrent tasks) is to program each task
in the form of a finite state machine. Combine this with the
timing technique used in the “Blink without delay” Arduino tutorial if
you need time-triggered actions.
Here I would use one state machine for sending the SMS and another one
for the buzzer. The first one is the most complex:
Edit: I expanded on how I designed this state machine.
In a canonical finite state machine implementation, each action is
associated with a state transition. We then have a transition for each
command sent to the GSM module, and we can label the states according to
which commands have already been sent, like this:
SENT_NOTHING → SENT_CR → SENT_CMGF → SENT_CMGS → SENT_MSG →
SENT_ALL.
All of the above transitions send a string to the GSM module. The first
one (SENT_NOTHING → SENT_CR) is triggered by the distance detected
being less than 25 cm. The following ones are time-triggered one
second after the previous one. We have to add one final transition
(SENT_ALL → SENT_NOTHING) that performs no action but lets the system
“forget” it has sent an SMS and thus makes it ready to send a new one.
This transition would also be time-triggered, after a potentially long
delay (how often would the user like to receive those reminders?). In
the code below, this last delay is one second, which I believe is too
short, but matches the last delay(1000) in the code you posted. The
implementation would be like this:
static enum {
  SENT_NOTHING, SENT_CR, SENT_CMGF, SENT_CMGS, SENT_MSG, SENT_ALL
} sms_state = SENT_NOTHING;
static uint32_t time_last_command_sent;
uint32_t now = millis();
switch (sms_state) {
  case SENT_NOTHING:
    if (distance < 25) {
      Serial.print("\r");
      time_last_command_sent = now;
      sms_state = SENT_CR;
    }
    break;
  case SENT_CR:
    if (now - time_last_command_sent >= 1000) {
      Serial.print("AT+CMGF=1\r");
      time_last_command_sent = now;
      sms_state = SENT_CMGF;
    }
    break;
  case SENT_CMGF:
    if (now - time_last_command_sent >= 1000) {
      Serial.print("AT+CMGS=\"+YYXXXX\"\r");
      time_last_command_sent = now;
      sms_state = SENT_CMGS;
    }
    break;
  // and so on for the cases SENT_CMGS and SENT_MSG...
  case SENT_ALL:
    if (now - time_last_command_sent >= 1000) {
      sms_state = SENT_NOTHING;  // forget we sent an SMS
    }
    break;
}

I have an issue with this implementation though: it is overly
repetitive, as the cases SENT_CR, SENT_CMGF, SENT_CMGS and SENT_MSG
are essentially copies of the same code. In order to make the code
dryer, I prefer merging them into a single state, and splitting
the state information into two variables: sms_state and
commands_sent. The new possible values for sms_state are now:

SMS_READY: the code is ready to send the message as soon as it is
required by the detected distance.
SMS_SENDING: it has started to send the commands to the GSM module,
but is not done yet.
SMS_DONE: the SMS has been sent, but no other one will be sent until
some time has elapsed, after which it will transition to SMS_READY.

The mapping to the “full” machine states is then:
 full state    │ sms_state   commands_sent
───────────────┼───────────────────────────
 SENT_NOTHING  │ SMS_READY         0
 SENT_CR       │ SMS_SENDING       1
 SENT_CMGF     │ SMS_SENDING       2
 SENT_CMGS     │ SMS_SENDING       3
 SENT_MSG      │ SMS_SENDING       4
 SENT_ALL      │ SMS_DONE          5

It could be argued that sms_state is redundant, as all the state
information is contained in commands_sent. I still wanted to keep
sms_state in order to easily switch on it. This is not the only
possible approach though, and it would be perfectly sensible to write
something like
if (commands_sent == 0) {
  // handle the case SMS_READY
} else if (commands_sent < command_count) {
  // handle the case SMS_SENDING
} else {
  // handle the case SMS_DONE
}

For the buzzer, there are only two states: BUZZER_OFF and BUZZER_ON.
The transitions are conditioned by the measured distance and, for the ON
→ OFF transition, also by the time it has been ON.
Here is my tentative, untested implementation of this approach:
#define TRIG A0 //Module pins
#define ECHO A1
#define TRIG1 A2 //Module pins
#define ECHO1 A3
#define Buzzerpin 13

// Commands to be sent to the GSM module.
const int command_count = 5;
const char * const commands[command_count] = {
  "\r",
  "AT+CMGF=1\r",
  "AT+CMGS=\"+YYXXXX\"\r",
  "HELLO There",
  "\x1a"
};

void setup() {
  Serial.begin(9600);
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT_PULLUP);
  pinMode(TRIG1, OUTPUT);
  pinMode(ECHO1, INPUT_PULLUP);
  pinMode(Buzzerpin, OUTPUT);
}

void loop() {
  // Measure both distances.
  digitalWrite(TRIG, LOW);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(20);
  digitalWrite(TRIG, LOW);
  int distance = pulseIn(ECHO, HIGH, 26000) / 58;
  digitalWrite(TRIG1, HIGH);
  delayMicroseconds(20);
  digitalWrite(TRIG1, LOW);
  int distance1 = pulseIn(ECHO1, HIGH, 26000) / 58;

  // Timing for both state machines.
  uint32_t now = millis();

  // Send the SMS.
  static enum {SMS_READY, SMS_SENDING, SMS_DONE} sms_state;
  static uint32_t time_last_command_sent;
  static int commands_sent = 0;
  switch (sms_state) {
    case SMS_READY:
      if (distance < 25) {
        Serial.print(commands[commands_sent++]);
        time_last_command_sent = now;
        sms_state = SMS_SENDING;
      }
      break;
    case SMS_SENDING:
      if (now - time_last_command_sent >= 1000) {
        Serial.print(commands[commands_sent++]);
        time_last_command_sent = now;
        if (commands_sent >= command_count) {
          sms_state = SMS_DONE;
        }
      }
      break;
    case SMS_DONE:
      if (now - time_last_command_sent >= 1000) {
        commands_sent = 0;
        sms_state = SMS_READY;
      }
      break;
  }

  // Drive the buzzer.
  static enum {BUZZER_OFF, BUZZER_ON} buzzer_state;
  static uint32_t time_buzzer_started;
  if (buzzer_state == BUZZER_OFF && distance1 < 25) {
    digitalWrite(Buzzerpin, HIGH);
    buzzer_state = BUZZER_ON;
    time_buzzer_started = now;
  } else if (buzzer_state == BUZZER_ON && distance1 >= 25
             && now - time_buzzer_started >= 2000) {
    digitalWrite(Buzzerpin, LOW);
    buzzer_state = BUZZER_OFF;
  }
}


The speed of a motor is a function of the motor itself and the voltage applied to it. There is no programmatic way of increasing the speed of a motor. You would either need to increase the voltage being applied to the motor (as long as it is within the limits of your motor and speed controller) or find a different motor to use that is faster.

It appears the Adafruit motor shield accepts between 5-12 volts, if you are not already at the maximum of 12 volts, and your motor is rated to allow it, you can increase the voltage you are applying to the shield. All that 255 means in this case is give the motor all the power that is available, so if you are only giving the controller 5 volts, it is only going to give the motor 5 volts.

Also I might recommend instead of using analogWrite() that you use the official Adafruit library to control your shield as it uses its own PWM library which is more performant for motor control than the built-in Arduino one.

EDIT

Actually, with v2 of the shield, it has its own PWM driver controlled over I2C. In which case analogWrite() shouldn't work at all, or at least it doesn't do what you think it does. Instead use the official Adafruit library and I also recommend following the official tutorial as well.


There are newer long range RFID solutions. You can do a google search on "Ultra Long-Range UHF Wireless RFID Sensors" for more information, but almost all of these systems are still proprietary (i.e. I'm not aware of any hobbyist breakout-boards based around UHF tags yet).

The Disney MagicBands are an exact use-case of your question: Their magic bands use a combination of 13MHz RFID tags, and a new UHF active tag (it requires a small battery). They use them to collect data on how people flow through their Walt Disney World facility.  What bathrooms see the most activity, and when, for example.  There is actually a pretty decent amount of information available about the technology used in the Disney Magicbands if you're curious about the technology.


The code you linked to measures the 1.1 V internal reference using
Vcc as a reference. The ATtiny13A cannot do that. It does have a 1.1 V
internal reference, but it can only use it as a reference for the ADC,
not as a measured channel.
What you can do, if you don't mind adding extra hardware, is divide Vcc
with some resistors in order to get a voltage proportional to Vcc but
lower than 1.1 V. Then use the 1.1 V reference to measure that
voltage. In other words, measure a scaled-down Vcc against the
1.1 V reference instead of measuring the 1.1 V reference
against Vcc. The datasheet should help you with the details.


DS3218MG Servo - Not working with power supply

@starcat,  regular  usb cable for  powering  arduino


Ultrasonic distance module works without connecting to gnd

It's not uncommon for part to "sort of" work when one of the supply rails is missing and an input signal of the some polarity somewhat substitutes for it, often through built-in ESD protection diodes.  In this case, the trigger input when idle is low, and there's probably some capacitance on the board that could hold it through the brief trigger pulse.

It's a bad idea to rely on this though, both as it typically means stressing parts by operating them outside of specified limits, and can also produce not-quite reliable behavior.

For example, I once wired an SPI flash chip on a small carrier stuck underneath an MCU eval board, in order to test some software for a board I was designing.  It worked great.  Or I should say, it did right up until I tried to write to it, which would always fail.  Eventually I discovered that I'd forgotten the ground connection when wiring it up.  It was able to return enough current through the I/Os to perform read operations, but not to support a write.


I wouldn't use a servo for this. You don't have very fine control over the angle with a servo. Also with a typical telescope the focus is more on rather slow and precise movements, instead of fast ones.
Instead I would use a stepper motor. Depending on your exact requirements, these can be rather cheap to rather expensive.
Here also the mechanics come into play. The motor should not be attached directly to the axis, but instead through some gears (the axis of the telescope having the larger gear). That will allow for smaller, more precise movements and also lower the needed torque for the motor. Of course this depends on your actual telescope hardware, meaning if you can put a gear right to the axis. If not, you could limit the motor driven movement a bit and install a level, which then could be pushed or pulled by a nut on a threaded rod, which gets driven by the servo motor. This would be rather easy to implement, though you may need to correct for the different rotation behavior, when you get to the outer sides of the movement (for the actuator being linear, while the resulting movement is circular), by some mathematics in your code.
Since you want to keep your costs very low, you might wanna use the 28BYJ-48 stepper motor (including the fitting driver). In terms of stepper motors they are rather bad, but they are really really cheap and - depending on the gear ratio/level length/thread pitch - it might not matter that much for you. You could always update to a better stepper motor in the future.


Use a simple transistor where the Vin (external power) is connected to the base, which switches the transistor. Than connect the collector to +5V, and the emitter to a GPIO input pin and read the status with the Arduino. If it receives a HIGH you know external power (via Vin) is used.

See the useful 'good' answer as comment of Majenko below ... I will leave the answer above as is, to keep his remarks clear.


I've added in a bunch of comments for you:

// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; // declare accellerometer and gyro variables
void setup(){
  Wire.begin(); // initiate i2c system
  Wire.beginTransmission(MPU_addr); // be sure we talk to our MPU vs some other device
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true); // done talking over to MPU device, for the moment
  Serial.begin(9600); // initialize serial port to 9600 bps so you can see your debug messages in Arduino IDE via debug channel
}
void loop(){ // main program loop
  Wire.beginTransmission(MPU_addr); // get ready to talk to MPU again
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false); // done talking to MPU for the time being
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  // all the fancy <<8| stuff is to bit shift the first 8 bits to
  // the left & combine it with the next 8 bits to form 16 bits
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  // the above lines have gathered Accellerometer values for X, Y, Z
  //  as well as Gyroscope values for X, Y, Z

  Serial.print("AcX = "); Serial.print(AcX); // share accellerometer values over debug channel
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX); // share gyroscope values over debug channel
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333); // delay a bit to not overwhelm you the user/programmer as you view the results
}


Handling serial streams biggers than the available ram

You can parse indefinitely large amounts of data with a state machine parser.

General description: State machines

As an example, I wrote recently an HTTP server which parses incoming HTTP data (eg. cookies, parameters, POST data, GET data) on-the-fly.

You need enough RAM for one item of data, naturally. But then you act upon it, and then discard it. In the case of the web server, you could conceivably process a complex form with thousands of actions on it (eg. turn on switch 5, pump 3, heater 22). It parses each action, and then you act on it, then you parse another action.

You can even consider the Arduino bootloader as an example of this. The Optiboot bootloader is 512 bytes on a Uno, but it can re-flash 32 KB of program memory. How? The programming data comes down in bursts (packets, if you like) and it processes each packet at a time, then discards it and reads the next one.


How to establish a connection between an Arduino and a web server via ESP8266

Is this project possible without Arduino and just by programming the
  ESP8266 module?

Yes if you use ESP-12 or an esp8266 dev board like Wemos or NodeMCU. The problem could be the current sensor. I would recommend to read it with I2C ADC module, because the esp8266 A0 can read only to 1 V and is shared with WiFi functions. Wemos boards use a circuit to read analog until 3.3 V, but it doesn't help much.

  How to build web APIS to send and receive data to Arduino UNO via
  esp8266?

Run your Web server in Internet and let the esp8266 and clients communicate over it. But think about security.

For accessing a Web server from Arduino or esp8266 see the WebClient example of networking libraries.

  How to send data and check the received data in Arduino UNO VIA
  esp8266?

For Arduino with esp8266 as network adapter connected to Serial you can use AT firmware in esp8266 and WiFiEsp library in Arduino. Or you can have a sketch for the esp8266 with Arduino esp8266 core package and your own protocol over Serial to communicate between esp8266 and Uno. And there are firmwares for esp8266 written as esp8266 sketch, which you can use with corresponding Arduino library (WiFiLink, WiFiSpi).

  Can I send and receive data in JSON format Arduino UNO?
  How can the Arduino UNO filter required data from the received json?

ArduinoJson library helps with processing the JSON format. Amount of RAM could be a problem on Uno.


How can I save my float 'ave' on the EEPROM continuously?

It's possible, but it's certainly not advised.

EEPROM has a limited number of writes before it's dead. By writing continuously to the EEPROM you will kill it in no time at all.


How can I load fonts into Adafruit GFX for TFT display (ILI9341)

Looking further into documentation on the Adafruit website they indicate that indeed, their GFX library published on GitHub does not handle different fornts.

Case closed :-)


GSM 900A modem not responding to AT commands

The modem library does not communicate on pins 0 and 1. Check the reference library and tutorial. It should be pins 2 (RX) and 3 (TX). Reset is pin 7. The configuration may be found in GSM3IO.h. https://github.com/arduino/Arduino/blob/master/libraries/GSM/src/GSM3IO.h. See also https://www.arduino.cc/en/Main/ArduinoGSMShield


A1-A5 pins not declared in this scope error

If you look at the ESP8266 pinout diagram (for example here), you will only find 1 analog input: A0. This is because the ESP8266 simply just has 1 analog input. The Arduino IDE states A1-A5 being out of scope, because on that board these inputs just don't exist. That is completely correct.

Also: When you try to compile code, that is meant for an ESP, for the Arduino Uno board, it will naturally fail, because it is just different hardware. The ESP basis code just cannot run on the Uno.

You will have to compile the code for the board, that you actually want to use AND you can only use codes/libraries, that are meant for your board. You cannot mix them in general. Only some function might be transferable (if so, it will not be easy) and WiFi is definitely not something to transfer to the Uno, which doesn't have the hardware for it.