When the wires to the DS18B20 are short, you can use a 10k resistor as well.

The DS18B20 is accurate. If you have connected it wrong and it became very hot, then it might be damaged. But normally it is always accurate.

Many report that the DS18B20 returns a high temperature, and the cause is often something nearby that makes the DS18B20 warmer. For example an Arduino board (with a hot voltage regulator) or a computer screen or a certain air flow of warm air or even very dim sunlight. A normal thermometer does not do that, but the DS18B20 is highly influenced by warm things nearby.

Some temperature sensors have a problem with self-heating. You could add a delay of 5 seconds in the loop function, to see if that makes a difference.

To be sure you can put it in distilled water at sea level at 0°C (water and ice cubes) and 100°C (boiling water).

The picture uses pin 2 and the sketch uses pin 10. I assume that is a mistake.


How can I power a servo and Arduino from the same power supply?

Wire the +5 and Ground from the supply to both the ESP's Vin & Ground and the servo's Vin & Ground. The only thing you have to avoid is trying to power the servo through the ESP.


In addition to Majenkos answer:
A float cannot take any decimal number. It has a limited change and a limited resolution in that range you could say. So if often happens, that the flat (rounded) value is not a valid float. This is the case for 26.05. There is no valid float value, that is exactly 26.05. So the nearest valid float value is chosen. The following code would always print 26.059999:
float i = 26.05;
Serial.println(i);

since the variable i contains the float number 26.059999 (nearest valid float value to 26.06). That is the reason, why mostly the rounding of floats is only done directly with the outputting/printing. In that stage the number is not longer bound to the limitations of the float type (since it is internally not again saved in that type).


What happens when I call exit() from my program?

My initial guess is wrong. I would have thought it would simply return from loop and the core library would just call loop() again. However, I see the following code was created. Noticing that __stop_program is a hard loop...

An extract of Blink.ino's listing, with exit(0) added:

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
  exit(0);
}

The disassembly of the above:

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
 100:   80 91 00 01     lds r24, 0x0100
 104:   61 e0           ldi r22, 0x01   ; 1
 106:   0e 94 ca 01     call    0x394   ; 0x394 <digitalWrite>
  delay(1000);               // wait for a second
 10a:   68 ee           ldi r22, 0xE8   ; 232
 10c:   73 e0           ldi r23, 0x03   ; 3
 10e:   80 e0           ldi r24, 0x00   ; 0
 110:   90 e0           ldi r25, 0x00   ; 0
 112:   0e 94 f7 00     call    0x1ee   ; 0x1ee <delay>
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
 116:   80 91 00 01     lds r24, 0x0100
 11a:   60 e0           ldi r22, 0x00   ; 0
 11c:   0e 94 ca 01     call    0x394   ; 0x394 <digitalWrite>
  delay(1000);               // wait for a second
 120:   68 ee           ldi r22, 0xE8   ; 232
 122:   73 e0           ldi r23, 0x03   ; 3
 124:   80 e0           ldi r24, 0x00   ; 0
 126:   90 e0           ldi r25, 0x00   ; 0
 128:   0e 94 f7 00     call    0x1ee   ; 0x1ee <delay>
  exit(0);
 12c:   80 e0           ldi r24, 0x00   ; 0
 12e:   90 e0           ldi r25, 0x00   ; 0
 130:   0e 94 1e 02     call    0x43c   ; 0x43c <_exit>

...

0000043c <_exit>:
 43c:   f8 94           cli

0000043e <__stop_program>:
 43e:   ff cf           rjmp    .-2         ; 0x43e <__stop_program>

Note that if _exit had not called cli, interrupts would be able to do stuff. But that is not the case.


How to add extra USB port to Arduino Nano?

USB is deceptively simple.  The underlying protocol is very complex. So a complete answer to your question requires some USB background.

USB is divided into 2 types.  USB Hosts and USB Devices. We are not concerned about USB Hosts here.  USB Devices only need to know about their own functions / features.  If they are a serial port device, like the FTDI chip on the Arduino Nano, they only need to "speak" basic USB protocol and the serial CDC USB protocol.  If the USB Device was a keyboard, it only needs to know the basic USB protocol and the HID USB protocol.

In order to offer up a USB port the Arduino Nano uses an FTDI chip FT232RL.  This chip supports a Serial Port USB Device.  It does not appear to support HID USB Devices.  So your decision to use V-USB is necessary not because of power but because the Arduino Nano's built in USB port supports a protocol other than USB CDC.

  What circuit I should use and how to add extra USB port to Arduino
  Nano.

The circuit suggested is on the V-USB web page appears to contain the necessary information:

Of course you will have to do some research into V-USB software to see which are the appropriate pins to use on your Arduino Nano.


What are the units of output of soil moisture sensor?

Those sensors have no units. If you can find a schematic you could possibly relate the value to the resistance of the soil, but you'd need to know the resistance that the soil is paired with to form the resistive divider.

All you can say from the numbers is "This is wet" or "This is dry". Normally you would use trial and error to determine what the values roughly relate to, and say that "Anything under X should trigger watering. Anything over Y should stop watering."


Is this example for playing music without delay correct?

There's a variable called "pauseBetweenNotes". Try modifying that and see if the pause between notes becomes smaller.

Regarding your counter question, the way the counter is set up looks fine to me.


Sometimes my system hangs in the way you describe  ("hanging as soon as the Arduino usb cable connected")  if I mistakenly connect  the +ve and -ve supply lines to an i2c device the wrong way round.


How to send the MFRC522 RFID module into sleep mode?

http://www.nxp.com/documents/data_sheet/MFRC522.pdf

Look at section 8.6.2   Soft power-down mode.


reading pwm signal doesn't work correctly

check if the problem is the fact you have set 9700 baud rate on your sketch while the commonly used 9600 is supported from arduino IDE.

I slightly modified your code and it works for me. Check if this works for you:

#define Pin 3
#define Source 5
unsigned long  pwm_value;

void setup() {
    pinMode(Source,OUTPUT);
    pinMode(Pin, INPUT);
    Serial.begin(9600);
    analogWrite(Source,500);
}

void loop() {
    pwm_value = pulseIn(Pin, HIGH);
    Serial.println(pwm_value);

}

when you connect pin3 with pin 5 you should get a consistent value on Serial(=967).

About getting signal on floating pins

Getting a signal on a floating pin is normal.
When you have a cable attached it acts like an antenna. When you touch it, you are the antenna!


I highly recommend reading the datasheets for any electronics because they have an incredible amount of information.

Short Answer, No

If you read the datasheet for the Particle Photon, it recommends no less than a 1A power supply. Unfortunately, the datasheet for the AC/DC Converter you found shows it has a maximum output current of 30mA, which is nearly 30x smaller than you would want for the Photon.

How to Make This Work

Because you're trying to get ~1A @ 5V and you're working with 120VAC, you don't have to reinvent the wheel--or in this case, the USB Charger Brick!

Literally any off-the-shelf USB charging brick for a phone or tablet will work. I can't think of any that are less than 1A-rated anymore, but if you want a hobbyist-level supply, something like this one may be right for you (not to plug for Adafruit, though they are a great learning resource).

Basically, you'll have a box that houses the Photon and the relay. You simply put this in the box with it, and voila! you have 5V power for the Photon.

Bonus Points

You can even go nuts and remove the device from its housing (DISCLAIMER: This may void the UL listing and any warranty) and just grab the innards to package neatly in a nice enclosure.

EDIT:

Easiest Solution
Just install one of these at the receptacle you intend to use.


How to power board plus module with one battery pack

you can use a breadboard and jumper cable. connect the VCC and GND of battery to a breadboard, do this for your Arduino and sim card module too. just remember they should be in a one row. GND with GND row, and VCC with VCC row
note: this way is okay just for debugging


How might the SD library be reading phantom files?

How large is the file when it is deleted in Windows? I can imagine what you describe happening if there's a bug in the Arduino File System (see below) - but that requires relatively small files (less than 4K or so).
I assume that the SD card has zero or more "static" files, that don't change; and then the log file, that grows. That is, when the log file is deleted, the newly-freed blocks get re-used again for the new log file?
I also assume that you're using Windows' "Safe Removal" mechanism - giving it a chance to tidy up the SD Card before you yank it out.

To delete a file in FAT, the file system needs to do two steps:

Unlink the used blocks from the File Allocation Table (the eponymous F.A.T.).
These should be set back to zero - making it hard to accidentally re-use them again unless they're the same blocks again (which, for SD Cards, is unlikely due to wear levelling!)
Mark the directory entry as available again.
This is done by merely overwriting the first character of the directory entry with 0xE5. When FAT needs a new directory entry, it will use entries with either 0x00 or 0xE5. If the deleted file is being "resurrected", then a bug could be that it re-uses the directory entry but doesn't zero the existing contents, allowing the existing block number and length to be appended to.

Rather than deleting the file in Windows, try renaming it to something else entirely. That way the Arduino will create a new file, and you shouldn't have the problem. If you still do (worse: if the renamed file gets corrupted) then it's a caching problem. If you don't, then it's a bug in the file system.


Make one Arduino fire interrupt on another

You should not do delay() or Serial.print() inside an ISR. That would cause it to hang. For more information see my page about interrupts and also How do interrupts work on the Arduino Uno and similar boards?


How much ohm resistance I should put between tp120 base and uno?

To calculate you need to know the maximum current the solenoid uses. The TP120 has a gain of around 500-1000. So the current going into the base needs to be 1/500th of the current going through the solenoid.

So now you know the current needed. Then you can calculate the resistance value you need with R = V/I. So R = 5 / ( <solenoidcurrent> / 500 ).

So with e.g. a 2A solenoid, you get a value of 1.2kOhm.


Choose the correct solar panel and battery for solar use

I won't be able to tell you which solar panel or battery to use, but I can tell you how to figure that out.

Battery

For the battery there are a few different ways to figure this out:

The most common way to do this at the professional level is to build the device and run it attached to an energy meter and measure it for an hour or two performing its usage, and use that to calculate how much it will use over a 48 hour period. That being said that type of test equipment is not really a hobbyist piece of equipment and probably not something you are wanting to obtain for this project.
You can try and use the datasheets for all of your components to determine their idle and active current draw is, add them up for idle and active, adjust the values based upon the efficiency of your step up converter (so if it only 75% efficient, divide them by .75), guesstimate how long your sensor read process will take, multiply your active current draw times the voltage and times the time it will take (in hours, so if this is a few seconds, it will be a really small decimal), multiply your idle current draw times the voltage and times .083 hours (5 minutes), add those two together multiply it times 12 (12 - 5 minute periods per hour) and then by 48 (two days) and that will be an estimate of your energy usage for two days. Now this will be a very rough estimate as the datasheets only provide nominal values, and their actual usage in practice may be different, which leads me to the final option...
A hybrid between the two above solutions. Set up your device and have it read the sensors and transmit continuously. Then use a multi-meter to measure the current usage of it actively being used. Repeat the measurement again but this time with it running on an indefinite timer to simulate being idle. Then take those two numbers and use the above formula substituting the datasheet estimates with your actual measurements to get a much more accurate picture of what your energy usage will be.

Once you have your energy usage (this will be in milli-Watt-Hours or mWH) pick a battery voltage you will be using (this is based on the charge circuit you are using, typically, single cell lithium ion batteries are 3.7 or 4.2, with multi-cell batteries being multiples of those), divide your energy by the voltage to get the power (in milli-Amp-Hours or mAH) and you'll want to pick a battery greater than that. You'll also want to double check the data sheet of your step up converter and see what the drop out voltage is, and then compare that to the datasheet for the battery and see at what capacity it hits that voltage. You'll want to make sure that it is at least 80%. Otherwise you'll have to pick a different battery with a larger capacity, or a different step up converter with a lower dropout voltage.

Solar Panel

For the solar panel, what you will want to do is get a battery charger designed specifically for use with solar panels. This is because when it says 5.5v solar panel, that is it's nominal voltage in full sunlight, however, it most often will not be that and will vary greatly throughout the day. What this means is that solar panels are basically on unregulated power supply, and most battery chargers require a regulated power source. With a solar specific batter charger, it is designed such that it can handle voltage variation and sudden dropouts. Usually these chargers come with a recommendation as far as voltage and current requirements and those specifications should form the basis of your solar panel selection.

So for example, if you have a battery, on the datasheet it will list what its charge current is, and you'll want to make sure you have a charger circuit that can supply that amount of current. Then you'll want to take a look at the datasheet for the charger circuit, see what current it requires and then make sure that the solar panel can provide that current.


How to modify Arduino boards.txt to support new MCUs

Please, Note that the Arduino IDE is behind on many of the tools. In this case avrdude and its conf file, along with avr-gcc

First:

.\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf

needs to support the m328 in addition to m328p. This can be done by either updating

.\arduino-1.5.6-r2\hardware\tools\avr\bin\avrdude.exe

to something like avrdude-6.1-svn-20131205-mingw32. along with replacing the conf file with the new one

.\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf

file that has both m328 along with the m328p. Note 6.1 supports a parent method, making it easy to duplicate chips with different signatures. Or use existing 5.11 and add to its

.\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf

file by duplicating the entire m328p section and renaming the new entry to "m328" along with the correct signature.

Second:

avr-gcc need to be updated to support compiling both the m328p and m328. Yes, it just a semantic thing. But the next part will send either ATmega328p or ATmega328 to both gcc and dude. which both need to support it. One can simply copy over

.\arduino-1.5.6-r2\hardware\tools\avr\

with the new tool chain. I used avr-gcc-4.8_2013-03-06_mingw32

Third:

replace the following line in boards.txt

uno.build.mcu=atmega328p

with

## Arduino ATmega328P
## ---------------------------------------------
uno.menu.cpu.atmega328p=ATmega328P
uno.menu.cpu.atmega328p.build.mcu=atmega328p

## Arduino ATmega328
## ---------------------------------------------
uno.menu.cpu.atmega328=ATmega328
uno.menu.cpu.atmega328.build.mcu=atmega328

This will add an option to the IDE when UNO is selected for either chip. And subsequently send the correct MCU to both the compiler and avrdude.

Proof:

Below are the verbose output of the IDE with the above changes. Note the -mmcu and -p for both options. As a real unit is was not connected it yielded the "not in sync" error. Where this shows it all works.

C:\projects\Arduino\arduino-1.5.6-r2\hardware\tools\avr\bin\avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\variants\standard C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp -o C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp.o
...
C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
C:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/bin/avrdude -CC:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex:i

avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
...
avrdude: stk500_getsync(): not in sync: resp=0x00

avrdude done.  Thank you.

C:\projects\Arduino\arduino-1.5.6-r2\hardware\tools\avr\bin\avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -MMD -mmcu=atmega328 -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\variants\standard C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp -o C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp.o
...
C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
C:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/bin/avrdude -CC:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328 -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex:i

avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
...
avrdude: stk500_getsync(): not in sync: resp=0x00
avrdude done.  Thank you.


How to actually concatenate two Strings?

Your lambda is capturing arg by copy, which is most certainly not what
you want. And since it doesn't have the mutable qualifier, the
captured parameters are not modifiable. Hence the compiler error.

You could get rid of the error by qualifying the capture as mutable,
but you would then be modifying the captured copy of arg, not the
original one. The correct solution would be to capture the String by
reference instead of capturing by copy. See Lambda
expressions.

But then, I concur with Michel Keijzers that avoiding Strings altogether
is a better option.


Connecting CAT5 robustly between portable Arduino and more portable sensors

Certainly go for RJ45 sockets.  Not only does it help protect the wire, but it gives you a really easy way of swapping the wire for different lengths should you want to.

You can't solder an RJ45 socket directly to a normal prototyping board. The pins aren't in the right pattern.  So, you could go for something like this

That can then either be soldered to wires or, since the pins are now in a normal 0.1" pitch, solder the whole module to a prototype board or shield.

Be sure you get a vanilla RJ45 socket, not a "MagJack", which contains extra Ethernet-specific electronics inside it.

If you do want to solder the wires directly to a PCB simply drill a couple of holes just in from one edge of the PCB, run the cable between them, and strap a cable tie around it.  Here's an example:

That PCB has specially shaped slots designed into it for the cable tie.

Also, for soldering, you want a good quality cable. A cheap one from eBay will most likely be made of aluminium with a thin plating (if you're lucky) of copper. A better quality one will be made entirely of copper. Aluminium cables don't solder well. Fine for crimping to an RJ45 plug, but rubbish for soldering.


Unable to power an Arduino Pro Mini through the RAW pin

I am not completely familiar with that specific board, but according to the schematic there is a solder jumper which is used to isolate the RAW voltage regulator from the rest of the system "for low power applications".

I don't know off hand if that comes pre-soldered or not, but check it to make sure it is connected, otherwise the RAW input will do nothing.


expected primary expression before ')' token

Why are you putting byte there? That isn't in the Serial.print reference page.

This compiles OK:

#define ANALOG_IN 0

void setup() {
  Serial.begin(19200);
  analogReference(INTERNAL);
}

void loop() {
  int val = analogRead(ANALOG_IN);
  Serial.print(0xff);
  Serial.print( (val >> 8) & 0xff);
  Serial.print( val & 0xff);
}


Did you follow that manual?
https://lastminuteengineers.com/esp32-ntp-server-date-time-tutorial/
The printLocalTime(); function does all you ask for.
void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

getLocalTimereturns false on failure. Let the printLocalTime do the same.
boolean printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return false;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
  return true;
}

Now the print function tells you if it failed (returns false) or not (returns true).


If the Analog input of your Arduino Uno is damaged, then unfortunately you have damaged the pins on the ATMEAGA328P chip directly.

As per the schematic below of Arduino Uno R3, the pins A0 to A5 are connected directly on the Pins 23 to 28 of the ATMEGA328P chip.

Therefore if you say that the 2 out of 6 Analog pins have been damaged then the only way to fix that is to replace the ATMEGA328P chip with a new one.

More can be read here about the UNO's hardware design.

PS. When replacing the ATMEGA328P chip, be sure to program the new chip with the Arduino Bootloader so you can upload sketches to it, otherwise it won't work ;)

Cheers!


Problem with simple sound detection circuit using a microphone

I plotted the values you got in a spreadsheet:

You must admit that looks a bit like a sound wave! If you want to know if it is a soft sound or a loud sound you really need to see the maximum values (1023 in your case). If the maximum was 512 then clearly the incoming sound isn't as loud.

An alternative, if you just want loudness would be to filter the incoming signal, eg.

simulate this circuit – Schematic created using CircuitLab

This would smooth the incoming voltage so that consecutive readings would be in a narrower range.

Warning: Judging by the graph, you may be getting negative input into A0. The Arduino pins are not designed for negative voltage. You may want to use a diode to eliminate the negative component.


Can't Upload Sketches to Arduino Nano Every

Here is a trick I use on some boards but first be the baud rate is the same in the terminal as in the sketch (Serial.begin(115200). If so then remove everything then put a jumper between ground and reset. Then put a jumper between TX and RX (pin o and pin 1 on uno). launch the IDE and what you type in the console should be echoed back to you. If this works the hardware is connected fine.


Arduino Micro draws too much power from iPhone. How can I change that?

The power consumption is part of the exchange with the PC when it is plugged in. You can change that. Find the file USBCore.h in your Arduino install directory. In my case (under Linux) it was:

./hardware/arduino/avr/cores/arduino/USBCore.h

Inside that file, at around line 269 (depending on the distribution) you should see these lines:

#define D_CONFIG(_totalLength,_interfaces) \
    { 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED | USB_CONFIG_REMOTE_WAKEUP, USB_CONFIG_POWER_MA(500) }

On the right of the second line is the requested power consumption in milliamps (currently 500). Change that to (say) 100:

That is, change USB_CONFIG_POWER_MA(500) to USB_CONFIG_POWER_MA(100).

Save and recompile.

You may find that the bootloader initially requests 500 mA even with this change (as it initially runs the bootloader). However when the sketch starts it should re-establish a USB connection and only request 100 mA. To fix that you would need to recompile the bootloader with the same fix, and reinstall it, a somewhat more complex task.

Another possible approach would be to tweak the fuses so that it doesn't run the bootloader, if you have finished debugging your code. Only do that if you are confident with playing with the fuses.


Is the DigitalWriteFast library still needed?

I just tried to time digitalWrite() against direct port access with
the following code:

void setup()
{
    uint16_t overhead, start, end;

    Serial.begin(9600);
    TCCR1A = 0;
    TCCR1B = 1;

    // Time digitalWrite().
    overhead = 7;
    cli();
    start = TCNT1;
    digitalWrite(2, HIGH);
    end = TCNT1;
    sei();
    Serial.print("digitalWrite(): ");
    Serial.print(end - start - overhead);
    Serial.println(" cycles");

    // Time direct port access.
    overhead = 4;
    cli();
    start = TCNT1;
    PORTD &= ~_BV(PD2);
    end = TCNT1;
    sei();
    Serial.print("direct port access: ");
    Serial.print(end - start - overhead);
    Serial.println(" cycles");
}

void loop(){}

The result was:

digitalWrite(): 78 cycles
direct port access: 2 cycles

I used an old Arduino core (1.0.5), but that function has not changed
since. You can try with your current core and see.

PS: In this program, the correct value for overhead can only be
determined by examining the generated assembly. It's a count of the
cycles you are measuring but do not directly belong to the operation you
really want to measure.


You cannot. You will need an Arduino at the servo end to generate the PWM signal from serial instructions sent over Bluetooth.

Since PWM is (typically) 8-bit and serial is (typically) 8-bit you could simply have each byte as a 1:1 mapping to a PWM value.

One the transmit end:

bluetoothSerial.write(pwmValue);

On the receive end:

if (bluetoothSerial.available()) {
    analogWrite(9, bluetoothSerial.read());
}


Arduino / BitVoicer Sending IR code on loop

Taking a quick look at the Documentation on page 22, it looks like you need to use your bvSerial.strData calls within a function called void serialEvent() rather than inside of your loop.  I would recommend trying out their tutorial on that page just to make sure you get BitVoicer to work properly before scaling it for your application.

Hope that helps!


Can I use a PIR sensor to turn on an arduino?

Yes you can.

It all depends on how you are turning the power on.  You sensor needs to flip a 'switch' rather than actually power the Arduino directly.  (I'm sure you know that but just in case).

So you need a normally open relay in between you power source and you Arduino.  Normally open because you don't want it powered unless you 'turn it on'.  Your relay might be able to be switched by your PIR sensor's data output, but if you need more current then you are going to have to use a transistor and draw more power from the power source.

You have the PIR sensor, so now find the relay capable of carrying the maximum current you need for the Arduino.


I'm dealing with the exact same thing right now trying to get mine to work. The only help I can give so far is that that avrdude error was solved for me when i stopped trying to upload code to the uno with the a7 powered. think it has to do with the programmer using the same RX/TX ports.


Wemos D1 mini freezing after a few minutes

I doubt this is the problem, but this code looks wrong.

  int redval = red_val.toInt();
  analogWrite(D5, redval);
  redval = redval >= 1023 ? 1023 : redval <= 0 ? 0 : redval;
  if (redval == 0)
    analogWrite(D5, 0);

I think it should be more like this:

  int redval = red_val.toInt();
  if (redval > 1023)  // If its =1023 you do need to set it to 1023.
    redval= 1023;
  else if (redval < 0)
    redval = 0;
  analogWrite(D5, redval);

The inline if statement is too ugly and doesn't really add anything.

To be honest I would look at pulling this code into functions to make it easier to read and I suspect you will find the problem.

When these microprocessors stop after a while its usually memory, heat or electrical.  If you have checked the electrics and its stopping quite quickly its probably a memory leak.  So refactoring your code might help people spot the problem easier.

You might want to replace you call to setColour()  with a call to Serial.println() and see if that cure the problem.  If it doesn't then your problem is with the way you are calling client.


Depends on the pin you used for the PWM.

Arduino UNO/NANO specs say following things:

The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.

The base frequency for pins 5 and 6 is 62500 Hz.

The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64, 256, and 1024.

The divisors available on pins 3 and 11 are: 1, 8, 32, 64, 128, 256, and 1024.

PWM frequencies are tied together in pairs of pins. If one in a pair is changed, the other is also changed to match.

Pins 5 and 6 are paired on timer0.

Pins 9 and 10 are paired on timer1.

Pins 3 and 11 are paired on timer2.

Changes on pins 3, 5, 6, or 11 may cause the delay() and millis() functions to stop working. Other timing-related  functions may also be affected.


why my arduino uno r3 restart when plugged in to a battery(9v)

Let me guess: the Arduino resets just as one of the motors starts (or should start) right?

The 9v battery is incapable of supplying enough current for much of anything but a few LEDs. When the Arduino first turns on a motor, it needs, and tries to draw, more current than the battery can supply, resulting in the battery voltage dropping below the Arduino's voltage-regulator's minimum input voltage, and the Arduino is shut off. That stops the current draw, the battery voltage recovers, power up the Arduino, which resets (as they always do on power-up), and the cycle keeps repeating.

Try powering it from a more capable battery of greater than 7 volts. 5 AA cells in series, for example would provide 7.5 volts. This won't last terribly long but should work for a while. A second (third, ...) string of 5 in parallel with the first should double the life. Using C or D cells instead will increase the life a lot more.


Why do you need so many Arduinos, Nanos and a Mega?  You want to read/control 2 joysticks, some switches and some LED.  If you do this using a multi-processor environment then you are adding a significant overhead to the processing and the development time which you can probably do without.

So, could you connect everything to a Mega, do you have enough IO pins?  If not would the use of GPIO expander ICs, I2C devices, etc help solve this issue.

Connecting the joysticks via interrupts will allow a more responsive system, can you do this?

Is an Arduino even the best platform for this?  What about an ESP32 or PI?

You want to minimise the comms overhead, so a star network would be better than a ring.
Serial is going to be the lowest programming overhead solution, but by far the slowest.  Using WIFI via an ESP8266 is going to be the simpelist and you can hand off some of the processing to the ESP.


Using an Arduino Nano, how many LEDs can I safely power?

If you are running the LEDs from shift registers then the power rating of the Nano is irrelevant.

If you are wanting to use the Nano as the power source (not recommended) then you would need to know both your expected current and what the regulator on the Nano would be able to supply.  My immediate guess is "not enough".

64 LEDs at full brightness would be expected to use a maximum of say 20mA each, so 1.28A just for the LEDs.  That's a huge amount, and way more than any linear regulator can be expected to supply without melting everything around it.

So you can reduce your current requirements by not having the LEDs as bright.  Half the current does not equate to half the apparent brightness. In fact at half the current you probably won't notice much difference at all.  At a tenth of the current you will see them a bit dimmer, but not as much as you would expect.

So you can come up with a compromise between the brightness you desire and the current consumed by each LED.

Say you end up deciding on (as Gerben has suggested) a current of 5mA per LED.  When all LEDs are on that would be (5 × 64) 320mA.  That's reasonable for a linear regulator, but still will generate more heat than is really advisable.

So you should, for this project (assuming you aren't going to be using multiplexing, which is a whole other ballgame), investigate using a switching (aka "buck") regulator.  You can pick these up on eBay for just a couple of dollars and can quite happily supply amps as opposed to milliamps and will allow you to run far more LEDs without going into thermonuclear meltdown.

Another important consideration to think about is how much current an individual shift register can provide - both through its output pins and in total for the whole chip.  There are special constant current LED driving shift registers that remove the need for individual resistors on each LED and give much better control over the LEDs than traditional logic output shift registers.


time should be an unsigned int.  As soon as millis reaches 32768, it will be stored as -32768 in time, and your comparisons will not work. This happens after 32.768 seconds.  Here's a short sketch to illustrate:

int time = 0;

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

void loop() {
    time = millis();
    if (time % 1000 == 0) {
      Serial.println( time );
      delay( 2 ); // let millis() increment
    }
}

To see the difference, just change the first line to

unsigned int time = 0;

Note how time rolls over to 0 after 65535 (well, only 65000 is printed).

I would recommend using unsigned constants by adding a "U" after the digits: 1000U.  In your if statements, you must cast the millis to the same (smaller) type: (unsigned int)millis().  Also, parentheses make the expression more clear:

      else if (((unsigned int)millis() - time > 1000U) && ((unsigned int)millis() - tempo < 2000U)) {digitalWrite(led_2, HIGH);}


Alternative for IRF520 mosfet in Arduino shutdown schema

For what you are trying to do, any transistor, bjt or MOSFET, would work. 2n2222 or 7000 for example. Irf5x0 is actually a poor choice here. It only worked due to the low load being switched.


They are transparent bridge modules that are designed specifically to work together. It's intended to be kind of like a wireless UART.
This AliExpress Seller details how to use them.
You need one UART and one USB module. You plug the UART module into the USB module and plug the USB module into your computer. After about 10 seconds the modules are paired together.
You then separate them, and you can connect the UART module to your Arduino or other board.
Now you have a wireless UART between your computer and your Arduino.
Alternatively, since they have an STM32F0 chip controlling them you could hack them to do other things using stm32duino.


I found it! I was returning an int8_t variable from my mod function, causing me to not be able to iterate over more than 126 LEDs. Now this little Arduino Uno is maxing out it's RAM at 409 LEDs!


Is it possible to read the value of the switch in the analog in pins on the board??

Yes. Analog input pins are also digital IO pins. You can use them exactly the same way as all the other pins on the board.


How do I execute some code at a certain time without RTC module?

If you start with the "BlinkWithoutDelay" sketch that comes with the Arduino IDE, you can execute your code alternating between 11 hours and 13 hours.

// Power up the circuit at exactly 06:00.
unsigned long delayInterval = 0;
unsigned long previousMillis = 0;
bool twoHoursAdded = false;

void setup(){

}

void loop(){

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis >= delayInterval){

    // previousMillis = currentMillis;

    // Use this "method" of incrementing the previousMillis variable
    // instead of the code used in the BlinkWithoutDelay sketch.
    previousMillis += delayInterval;

    if(twoHoursAdded == false){
      delayInterval = 1000UL * 60UL * 60UL * 13UL;
      twoHoursAdded = true;
    }
    else{
      delayInterval = 1000UL * 60UL * 60UL * 11UL;
      twoHoursAdded = false;
    }

    // Your code here that is run at 06:00 and 19:00.

  }
}

"Down sides" to using this code.

If there is a "power failure", the timing will be off, WAY off until you reboot the Arduino at exactly the right time.
You have to power up the Arduino at exactly the right moment for "it's" timing to match your "clock" timing.

If it's within your budget, have a look at the DS3231 modules available on aliexpress.com / ebay.com. They have a lithium battery backup incase of power outage and are really easy to connect to your Arduino using I2C. There are several libraries on Github that simplify using the DS3231 modules.


Looking for Power Bank with "Always-On-Feature"

Lithium cell based powerbanks use a boost converter to boost the voltage from the Cell to the 5V for the USB. They turn off because keeping the voltage boosted when not used wastes quite a bit of power.

If all your devices can run straight on 3.3V you can use a Lithium cell directly with a voltage regulator (and with the normal protection circuitry).

Otherwise you can simulate a button press on the on button with a gpio pin to activate the boost circuitry when you are ready to take your measurements; let he voltage stabilize; use transistors to connect the components to power; take your measurements; disconnect the components and then let the timeout expire after which the voltage will drop again.


IR Receiver interrupt and arduino sleep mode

This is what I have managed to achieve ...

Library

IRLib - GitHub

  Version 1.51 March 2015
  Copyright 2013-2015 by Chris Young http://tech.cyborg5.com/irlib/

  This library is a major rewrite of IRemote by Ken Shirriff which was covered by GNU LESSER GENERAL PUBLIC LICENSE ...

Code

Modified code (from the demo IRrecord example):

/* Example program for from IRLib – an Arduino library for infrared encoding and decoding
 * Version 1.5  June 2014
 * Copyright 2014 by Chris Young http://cyborg5.com
 * Based on original example sketch for IRremote library
 * Version 0.11 September, 2009
 * Copyright 2009 Ken Shirriff
 * http://www.righto.com/
 */

/*
 * IRrecord: records IR signals
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Record a value by pointing your remote at the device
 */

#include <IRLib.h>
#include <avr/sleep.h>
#include <avr/power.h>

const byte LED_PIN = 8;
const byte RECV_PIN = 11;
const unsigned long BAUD_RATE = 115200;
const unsigned long NO_ACTIVITY_TIMEOUT = 2000;  // milliseconds

IRrecv My_Receiver(RECV_PIN);
IRdecode My_Decoder;
IRsend My_Sender;
/*
 * Because this version of the library separated the receiver from the decoder,
 * technically you would not need to "store" the code outside the decoder object
 * for this overly simple example. All of the details would remain in the object.
 * However we are going to go ahead and store them just to show you how.
 */
// Storage for the recorded code
IRTYPES codeType;          // The type of code
unsigned long codeValue;   // The data bits if type is not raw
int codeBits;              // The length of the code in bits

// These values are only stored if it's an unknown type and we are going to use
// raw codes to resend the information.
unsigned int rawCodes[RAWBUF]; // The durations if raw
int rawCount;                   //The number of interval samples

bool GotOne, GotNew;

// added by Nick Gammon
EMPTY_INTERRUPT (PCINT0_vect);

void setup()
{
  GotOne=false; GotNew=false;
  codeType=UNKNOWN;
  codeValue=0;
  Serial.begin(BAUD_RATE);
  while(!Serial);//delay for Leonardo
  Serial.println(F("Send a code from your remote and we will record it."));
  Serial.println(F("Type any character and press enter. We will send the recorded code."));
  My_Receiver.enableIRIn(); // Start the receiver
}

// Stores the code for later playback
void storeCode(void) {

  // added by Nick Gammon
  pinMode (LED_PIN, OUTPUT);
  digitalWrite (LED_PIN, HIGH);

  GotNew=true;
  codeType = My_Decoder.decode_type;
  if (codeType == UNKNOWN) {
    Serial.println("Received unknown code, saving as raw");
    // To store raw codes:
    // Drop first value (gap)
    // As of v1.3 of IRLib global values are already in microseconds rather than ticks
    // They have also been adjusted for overreporting/underreporting of marks and spaces
    rawCount = My_Decoder.rawlen-1;
    for (int i = 1; i <=rawCount; i++) {
      rawCodes[i - 1] = My_Decoder.rawbuf[i];
    };
    My_Decoder.DumpResults();
    codeType=UNKNOWN;
  }
  else {
    Serial.print(F("Received "));
    Serial.print(Pnames(codeType));
    if (My_Decoder.value == REPEAT) {
      // Don't record a NEC repeat value as that's useless.
      Serial.println(F("repeat; ignoring."));
     }
     else {
       codeValue = My_Decoder.value;
       codeBits = My_Decoder.bits;
     }
     Serial.print(F(" Value:0x"));
     Serial.println(My_Decoder.value, HEX);
  }

  // added by Nick Gammon
  pinMode (LED_PIN, INPUT);
  digitalWrite (LED_PIN, LOW);

}

void loop() {

  // added by Nick Gammon
  static unsigned long lastActivity;  // when we last woke
  // sleep if no activity for a while
  if (millis () - lastActivity >= NO_ACTIVITY_TIMEOUT)
    {
    Serial.flush ();  // wait for Serial to finish outputting
    Serial.end ();    // shut down Serial
    noInterrupts ();  // timed sequence coming up

    // pin change interrupt for D11
    PCMSK0 |= bit (PCINT3);  // want pin 11
    PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
    PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13

    set_sleep_mode (SLEEP_MODE_STANDBY);
    sleep_enable();

    byte old_ADCSRA = ADCSRA;
    // disable ADC to save power
    ADCSRA = 0;
    power_all_disable ();  // turn off various modules
    interrupts ();
    sleep_cpu ();
    sleep_disable();
    power_all_enable ();   // enable modules again
    ADCSRA = old_ADCSRA;   // re-enable ADC conversion
    Serial.begin(BAUD_RATE);
    lastActivity = millis ();
    }  // end of no activity for a couple of seconds

 if (My_Receiver.GetResults(&My_Decoder)) {
    My_Decoder.decode();
    GotOne=true;
    storeCode();
    delay(500);
    My_Receiver.resume();
  }
}

Explanation

Main changes are in loop (near the bottom) where it sleeps if there is no activity for two seconds. This "no activity" test gives it time to catch an incoming pulse stream.

Before sleeping it turns off Serial (to save power), and sets up to detect the pin-change interrupt. It also turns off the ADC, and calls power_all_disable to disable various internal modules.

Note that it uses pin-change interrupts on Arduino pin D11 (pin 17 on the chip). For a different processor than the Atmega328P, or a different input pin, you would have to change which pin-change interrupt is used.

I found that I had to use SLEEP_MODE_STANDBY rather than SLEEP_MODE_PWR_DOWN, otherwise it seemed to take too long to wake up and handle the incoming pulse.

For testing, I flashed D8 pin to make sure it was working when hooked up in low-power configuration.

Power consumption

I tested with an AX-1838T IR-receiver that I had to hand (same pin-outs as in the Adafruit article).

Measured stand-alone (ie. not connected to the Arduino) it consumed 630 µA, so therefore we could not expect lower power consumption than that.

Connected up to a "bare-bones" board (ie. just the Atmega328P chip, decoupling capacitors, etc.) I measured 1.158 mA when idle.

My tests on my page about power indicate that SLEEP_MODE_STANDBY uses 480 µA more power than SLEEP_MODE_PWR_DOWN, so this sounds about right.

630 + 480 = 1110 µA

You might be able to save more power by operating at a lower voltage. This particular receiver can operate at a lower voltage. As an indication, I tried the setup at 3.3 V (which is out of spec for the processor, but whatever, I was just testing) and it consumed 978 µA when idle. This is a modest saving over the 5 V test.

References

Power saving
Interrupts
Adafruit IR library
IR library source


How can I interface HMC5883L compass board to a smartphone with OTG?

A cheaply available USB OTG adapter cable (ask eBay) will connect the Arduino to the phone.

You can then connect the compass sensor to your Arduino and write a sketch to retrieve the data from it and send it through the USB serial connection.

Then you need to write some software for the phone to receive and interpret the serial data and display it as a compass.  That is unless you are happy just to have a simple text display (like the Arduino's Serial Monitor) with the compass information showing in it, in which case there is off-the-shelf software that would do that (search Play)


Try commenting out the serial in your sketch. In my experience serial communication takes time, and I assume you have a short window where the voltage peaks at more than a volt. Or initialize the serial with a stupidly high baud rate.
Edit: even better, you could try this for a faster response time:

void setup(){
  digitalWrite(13,0);
  pinMode(13, OUTPUT);
}

void loop(){
  if(analogRead(A0)>204){ //at ~1V the ADC will read between 204 and 205
    digitalWrite(13,1);
    delay(100);
    digitalWrite(13,0);
  }
}


Connection of serial pin on ATMEGA328P to connector B type(female) D+ and D-

The Arduino Uno (and similar boards) have a chip on them that does serial communication via a dedicated USB chip (the ATmega16U2 chip). You can't just connect pins 2 and 3 to D+ and D- and turn that into USB.

You can conceivably do it using V-USB which does USB in software in conjunction with a few extra components.

You can also buy external serial to USB adapters which do the conversion externally. If you Google serial to usb adapter you will find quite a few for around $3.


Alternative IDE for compiling and running arduino code?

You can use any C++ IDE you like, best when bundled with a compiler, for example Code::Blocks. Assuming you're using Windows: A combination of a decent editor like Notepad++ and some good compiler chain like MinGW will do, too. If you absolutely have to you could also use MS Visual Studio, I don't bother.

Then create standard console programs with this main():

void setup();
void loop();

int main()
{
    setup();
    for (;;)
    {
        loop();
    }
}

And append your hardware-less Arduino code.


How can I use attached interrupt on my project?

If you can't rearrange the pins like Majenko suggests in the their comment, something you can do is is use pin change interrupts rather than the regular "external" interrupts.  On the UNO, these are available on all of the "digital" capable pins, which also includes most of the "analog" pins if you have an SMT UNO, or all of them if you have a DIP model.
NiceHood's PinChangeInterrupt library is modeled after the regular attachInterrupt function, so it should be familiar looking to you.  It's in the library manager; you don't need to get it from github.
NOTE: The O.P. opened a another question which seems to be this same thing, only with different context and specific code.  There I've given more details on what's outlined above but in relation to that that specific code in an answer there.


Attiny85, high output impedance, dim leds

You already found your problem. I am answering only to provide some
insight on why you were experiencing the symptoms you had.

pinMode() takes two integer arguments (two uint8_t to be precise).
The names INPUT, OUTPUT and INPUT_PULLUP are just macros for 0, 1
and 2 respectively. This is why the compiler accepts your code with the
arguments swapped.

On the AVR microcontrollers, setting a pin's output register to HIGH
on a pin that is configured as input has the effect of turning on the
internal pullup. Thus

digitalWrite(pin, HIGH);

has the same effect as

pinMode(pin, INPUT_PULLUP);

on an input pin. When you do this, the pin will source (not sink) a very
small current. The pullup resistance is typically of the order of
30 kΩ, and this is why you get such a small current.


Sometimes Tx and Rx are connected directly despite the fact, that it works on different voltages, sometimes resistor dividor is used, sometimes it goes through resistor. Why no consensus? What are differences?

There is some uncertainty as to whether the ESP8266 has 5V tolerant inputs or not.  This uncertainty stems from differences in an early Chinese datasheet translated by the community, and the current English datasheet.  It's better to err on the side of caution though and translate your 5V signal from the Arduino to a 3.3V one with either a proper logic level translator or a resistive divider (note that the latter can limit the maximum baud rate you can use).

You can read more here:

https://hackaday.com/2016/07/28/ask-hackaday-is-the-esp8266-5v-tolerant/

  Why contributors are so stubborn to use software UART? Is there any reason I can't understand, that should stop me from using built in UART?

Bad information begets bad information. People copy poor quality examples and tutorials and pass that bad knowledge on to others1.

Many Arduino boards only have one hardware UART port, and that is shared with the USB connection to the PC.  It is hard to reliably use that UART for other serial communication, since doing so will break your ability to upload code while your hardware is connected.  So it's simpler in that case to use SoftwareSerial (or one of the better implementations).

However, I would never advocate using SoftwareSerial unless you absolutely have to.  It barely functions at 115200 baud (one of the common default ESP8266 baud rates).  If you have a convenient hardware UART then really you must use it, for the sake of your sanity if nothing else.

1: Even worse though are the examples where people use SoftwareSerial to communicate over the pins of a hardware UART... that's just plain stupid...


What's with the debug error messages, like VMDPE_1|1_VMDPE?

Your incoming buffer is not big enough to handle the data that you're giving it. Cutting away the comments from your code:

char incoming[3];

This declares a buffer for two characters, allowing for the (required) 0 on the end. println() needs to know when to stop printing characters: it does this when it sees a NUL (0) character.

Serial.readBytesUntil(',', incoming, 3 ) ;

You're passing in that you want to read 3 characters - but that completely fills incoming, leaving no room for the trailing NUL (0).

Serial.println(incoming);

This then prints the first character, the second character, the third character... then the 4th, 5th, 6th, 7th etc. in memory until it finally reaches a NUL and then quits.

What you call "debug messages" are actually printed gibberish in memory... To fix it, you need to make incoming larger.

Also, it's a good idea when using buffers like this to use the sizeof() function, as follows:

Serial.readBytesUntil(',', incoming, sizeof(incoming)-1 ) ; // Note the -1!


The problem is here:

ISR(TIMER3_COMPB_vect) {
  TCNT3 = 0;
  ...

If you want to get anything that vaguely looks like accurate timings,
you should never reset the timer. The MCU needs time to process an
interrupt: it has to save the program counter to the stack, load the
address of the interrupt vector, execute it (it's typically a jump),
save all the registers it needs to the stack, and only then can it start
executing the code you wrote in the ISR. From your experiment, it looks
like all this process takes about 1 µs. But don't take this delay
for granted: from time to time the interrupt will fire while the MCU is
processing another interrupt, and this will increase the latency.

You have two options:

Update the compare registers in order to program the next interrupts
some time in the future. In this case, the COMPB ISR would do
OCR3A = OCR3B + 160; OCR3B += 1600;. Do not worry about the
overflows: they do the Right Thing.
Let the timer reset itself to zero: it will then do so without
loosing a single cycle. See the CTC and fast PWM modes of the timer.

For your specific use case, PWM seems like the obvious choice. Not only
will the timer handle the resetting itself, it can also generate the
output signal without requiring you to write any ISR. Beware that in
this case the period of the signal is whatever you load in corresponding
compare register plus one, and the duration of the pulse is another
compare register plus one.

As a side note:

  // Reset Timer 3 Control Register to 0
  TCCR3A = 0;

I would also reset TCCR3B. The Arduino core configures both registers
for it's own purposes, so it would be safer to clear them both.


Count HIGH values read for example in 2 ms. It should be zero if the LED is not lit and more then zero if it is lit.


What's the most efficient implementation of map(x,0,1023,50,250)?

The screenshot shows a base-2 (i.e. binary) result of calculating the constant part of a mapping. You can approximate this multiplication by a constant by a number of shifts added together. You need to break down each multiplication in the result first:

x * 0.0012 = x >> 3

x * 0.00012 = x >> 4

x * 0.00000012 = x >> 7

Then add these together. You are essentially breaking it down into convenient base-2 multiplies (which can always be represented by shifts) and adds - nearly always more efficient.

This doesn't get you right to 250, but pretty close:

>>> for i in range(0, 1024, 34):
...   print (i >> 3) + (i >> 4) + (i >> 7) + 50
...
50
56
62
   [snip]
235
241
247
>>> print (1023 >> 3) + (1023 >> 4) + (1023 >> 7) + 50
247

Do all your processing with a left-justified int (ADLAR=1) though, to minimize errors. The ADC returns a 10bit result, and ADLAR choses if this is aligned to the left or right of the two result registers.


is any windows application available for accelerometer based computer mouse

try "remotemouse.exe"
its a open source application you can modify the codes according to your requirement


How to read shiftOut function using arduino

You are right that you can't read the data fast enough with your method there. What you really need is the opposite of "shiftOut" - which happens to be called "shiftIn".  You use it just like shiftOut, but instead of you sending it a value to send it instead returns a value that it reads.

You trigger it using the "STB" pin:

if (digitalRead(STB) == LOW) {
    uint8_t val = shiftIn(dataPin, clockPin, LSBFIRST);
    Serial.println(val, HEX);
}

But the protocol you describe is simply SPI.  There is hardware within the Arduino to handle it for you.  A little harder to work with, but it's capable of working at much higher speeds and is more likely to be able to read your incoming data fast enough.

Resources:

https://www.arduino.cc/en/reference/SPI
http://www.gammon.com.au/spi

The latter includes how to configure an SPI "Slave" which is used for receiving data that is sent out from elsewhere.


Dynamically modifying the call stack using pointers

I am answering in the context of the AVR calling conventions, as they
are the only ones I know well enough to be able to answer here.

  Can we use this to, for example, change what function is "calling"
  FooBar() by replacing the function pointer of the calling function
  on the call stack to another function?

That will probably be impossible in C++. Let's say you have the
following call chain: main() → f() → FooBar(). In the body of
FooBar(), the stack will look like this (oldest stuff at top):

return address from f() to main()
registers saved by the f() prologue
return address from FooBar() to f()
registers saved by the FooBar() prologue

Getting the stack pointer is easy. No need to declare a dummy variable,
just:

char *stack_pointer = (char *) SP;

Now, to change the required return address, you need to skip over the
registers saved by the FooBar() prologue. And this is the big problem:
you do not know how many registers were saved there. Function prologues
are written by the compiler, and whatever they save depends on how many
registers are needed within the function, which in turn depends on the
complexity of that function. Even minor changes to the function can
modify the number of registers its prologue saves.

The only solution to this problem I can imagine is to forego the
compiler-generated prologue and write FooBar() in assembly. If you
wish to do it within a C++ file, you can attach the "naked" attribute to
the function and write its body using inline assembly.

  Or can we change the values of function variables in the calling
  function in mischievous fashion?

No need to tamper with the stack for this. The compiler strives to store
as many local variable as possible in CPU registers rather than the
stack. The caller's local variables are most likely still in those
registers and you can modify them at will (in assembly). That's why you
have this register-saving prologue and register-restoring epilogue in
the first place. Indeed, if you make the function "naked" and don't do
the saving/restoring yourself, you will very likely end up corrupting
the caller's locals.


How to build a robot that can stop at a certain point using an altimeter

have fun playing with the Arduino and some sensors! It is a great platform to learn. For your task, look into the Bosch sensor modules BME280 (pressure with temperature and humidity) or BMP280 (just pressure). You can expect maybe +-1 meter of accuracy. Or check the precision version BME388 that could give you +-50cm. Go to the adafruit shop and try a few of the breakout boards. They provide great library and documentation support.

In order to get absolute altitudes, you need to factor in ambient air pressure. A good source for that are METAR reports issued for aircraft. There are many online sources where you can get the so called altimeter setting for an airport close to you. Airplane altimeters actually just show the altitude above a standard pressure plane, so you need to compensate for whatever pressure the current weather gives you.

For higher precision, you pretty soon have to integrate barometric pressure, GPS altitude, and maybe other sensors, with some serious math. This is where MATLAB fits in.


How to stop Arduino from reseting after serial connection lost

There is a link on the Uno marked RESET-EN which links the Atmega16U2 (or 8U2) which handles incoming serial data to the main chip, the Atmega328P. If you cut that link (eg. with a knife) then it won't reset. However uploading new sketches will be harder because you will have to manually press the Reset button when the IDE starts to upload a new sketch.

Board:

Schematic:

One thing that people do is put a 10 µF capacitor between RESET and GND. That holds enough current to "weather" the reset pulse, and that stops the board resetting. You can always remove the capacitor to reprogram the board.


If you clone my fork of the code, I have got this working.
https://github.com/mwr9uk/mocolufa

I have generated a pull request to merge it with mainline.


Has any part of it ever worked? What have you done to it since?
My approach to debugging this would be to
 - Temorarily replace the Bluetooth with wired serial communication;
 - Comment out, or stub out(*), anything you aren't utterly and completely confident in.
 - Get some minimum amount of hardware and software working.
 - Add back one piece of hardware or one section of code at a time, fixing whatever you have to to get it working again.
 - Repeat, until everything is back together and playing nicely.

(*) Stubbing is the technique of replacing a function or a section of code with something trivial (and therefore hard to get it wrong!) that lets the rest of the code mostly work.
Suppose you had written a digitalRead() function. (I know it's a library function and we have total confidence in it, but for a moment, just suppose....) You might replace the contents of your digitalRead() with a single statement:

int digitalRead(uint8_t pin){
   // untested code commented out here
   // ...
   return(4);  // any value that means something to the calling code
}

Now you can work on the code that calls your digitalRead() without having a working digitalRead(). The caller will only ever get the same value every time it calls, but that may be enough get some part of it working until you can come back and fix your digitalRead() function.


First, a general remark: most of your variables are never used. You
should get rid of them, as they only serve to make your code more
obscure.

Then, the reason for the observed behavior is that you are comparing the
entered code with 4 predefined codes. Whatever the user enters, there
will be at least 3 non-matches, hence 3 times the program prints “not
eligile”.

To get the behavior you expect, I would get rid all all those boolean
variables that make the logic hard to follow, and instead break down the
problem into smaller chunks, each implemented in its own small function.
This makes it easier to write code that is easy to understand.

First, how do you tell whether two 4-character codes are the same? Like
this:

// Do codes a and b match?
bool match(char a[4], char b[4]) {
    for (int i = 0; i < 4; i++) {
        if (a[i] != b[i])
            return false;
    }
    return true;
}

Then, given a code entered by the user, tell whether it matches
adhaar[0] or adhaar[1] or... or none of them:

// Return the adhaar index matching the given key,
// or -1 if there is no match.
int matching_idx(char key[4]) {
    for (int i = 0; i < 4; i++) {
        if (match(key, adhaar[i]))
            return i;
    }
    return -1;  // no match
}

Now your checkkey() function can be rewritten as follows:

void checkkey() {
    if (i != 4) return;  // should never happen
    if (matching_idx(num) == -1)
        Serial.println(" not eligile");
    else
        Serial.println(" cast your vote");
    i = 0;
}


Yes and no.

To elaborate, the sketch you downloaded to the chip has been flashed to internal non-volatile memory. So if you were to move it to another Arduino board or other device with the appropriate support hardware, then it should work just fine.

However, if you're intending to directly hook-up speakers to it and a power source, then I highly doubt it's going to work. You really need some support hardware for the chip (such as an external clock - though I think the Atmega328 has an internal clock, decoupling capacitors, amplifiers for the spearkers, etc.).


Reading from software serial with an interrupt

You can't do it directly with an interrupt. SoftwareSerial already uses an interrupt to do the actual reception - the received byte being placed in a circular buffer.

The only thing you could do would be to modify the source code for SoftwareSerial so that instead of storing the byte in the buffer it calls your custom code instead.

Ok, so you're NOT using SoftwareSerial, you're using (something which I have never heard of) "NeoSWSerial". That has the ability to attach an interrupt (by adding it to the reception interrupt ISR), and the README.md file with that library gives you an example of how to use it:

#include <NeoSWSerial.h>
NeoSWSerial ss( 4, 3 );

volatile uint32_t newlines = 0UL;

static void handleRxChar( uint8_t c )
{
  if (c == '\n')
    newlines++;
}

void setup()
{
  ss.attachInterrupt( handleRxChar );
  ss.begin( 9600 );
}

So just read the character in there, set a flag to say you have a new "mode" arrived, and in your loop react to that flag and run the right function for that mode.

If you want to terminate a mode early you will have to program your modes to also react to the "new mode" flag and terminate. The interrupt cannot do that for you.


C strings need to be NUL-terminated.

char strcode[5];

 ...

 ...
     ...
    strcode[4] = '\0';
     ...


D1 mini esp8266 error: esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

I'm not sure if this will help EVERYONE, but I hope it at least helps someone.  I had the same issue with several different boards (3 Nano's, 2 NodeMCU ESP8266's, and 1 Uno).  I searched and searched for an answer and I kept reading about this pin or that pin being "pulled low" or "pulled hi" interfering with uploading sketches.  Well, since I couldn't find a solid answer anywhere I decided to disconnect all of the peripherals hooked to my board (except for powers and grounds) and Wah Laa!!!  The sketch uploaded like it was supposed to.  So, I believe if you just unhook all of the sending and receiving pins from all of your peripherals during upload, the sketch should upload just fine.  I hope this helps you.


Is it as simple as just adding the optocoupler between the switch and ground with the necessary resistor for it?

Probably not, because of two issues.  First, adding circuit elements between the switch and ground raises the voltage the pin will see when the switch is closed, which might keep a switch closure from registering as a low pin voltage.  For example, with Vcc=5V, table 30.2 DC Characteristics in the Rev. 8271J 11/2015 ATmega328P datasheet shows the guaranteed maximum input low voltage as 0.3 Vcc and the guaranteed minimum input high voltage as 0.6 Vcc; that is, 1.5 V and 3 V if Vcc=5V.  If the voltage drop across the optocoupler is between 1.5 and 3 V then the pin might register high or low with no guarantee which.

Second, if the pullup is large, not enough current will flow to trigger the optocoupler.  For example, at Vcc=5V if the internal pullup is used and the optocoupler drops two volts, I/O Pin Pull-up Resistor Current will be about 80 μA, too little to trigger a typical optocoupler.  (See figure  35-17, ATmega328P: I/O Pin Pull-up Resistor Current vs. Input Voltage (Vcc = 5V) in datasheet.)

What you might do instead is use two optocoupler channels in parallel or series, one for each of the Arduinos.  The switch lets current pass through an appropriate resistor or resistors and the optocoupler inputs;  optocoupler outputs go to  Arduino inputs.

Or, tie one side of the switch to +5V and the other to a resistor in series with an optocoupler input.  Connect the first Arduino's input pin to the low side of the switch.  I think that input will register low when the switch is open.  It will register high when the switch is closed.


"write" function in sd card is not working

The problem is that print() and write() behave differently when you give them numerical data, such as a byte.

When you pass your byte to print(), it converts it to text which is convenient for humans to read. For example:

byte b = 10;
dataFile.print(b);

This will result in the following ASCII characters being written to the file:

10

That's actually two bytes: one byte with the value 49, which represents ASCII character 1, followed by a byte with the value 48 representing character 0.

However, write() does not convert numbers into text. It writes them in their raw binary form. For example:

byte b = 10;
dataFile.write(b);

When you do this, it doesn't write a "1" and a "0" to the file. It literally writes a binary byte with the value 10. When you try to open this as a text file, your computer interprets that byte as a single ASCII character. It so happens that ASCII value 10 is the newline character, meaning your file basically contains a blank line.

For comparison, try this instead:

byte b = 65;
dataFile.write(b);

ASCII value 65 corresponds to the letter A (uppercase), so that's what you should see in the file.

The write() functions are useful for writing raw data to file in the most efficient form for another machine to read (as opposed to being human-readable). This is why they allow you to write arrays -- it acts like one big block of raw data with a fixed format.

In your case, print() is more appropriate. That means for outputting arrays of numbers, you will need to use loops. That functionality isn't built-in to the print() functions because different projects might need different formatting. For example, some people might want one number per line, whereas others might want numbers separated by commas, and so on.


Arduino stops loop randomly whenever a button is pressed

A 10 Ohm resistor when switched to ground can cause the power supply to drop below the operating voltage of the Arduino. If you mean to have a pulldown resistor to ground use a 10K value instead.

Note that a 10 Ohm resistor across a 5V supply draws 0.5 Amps of current.


Where is the positive and negative holes on the arduino mini breadboard?

Does anyone know what to do?

Do whatever you want to do.
There's nothing special about the +/- rails of a breadboard - they're just chunks of metal that go along instead of across, and are longer, with more holes, and someone has helpfully coloured them red/blue and added some symbols.
If you want a common place for + and - then just choose a common place for + and -.


ESP32: How to run two independent PID controllers, one per core?

esp32_technical_reference_manual_en.pdf
Page 620
As mentioned before, only an elevated process with PID of 0/1 can initiate a process switch. The new process
may have any PID from 0 ~ 7 after the process switch. The key for successful proactive process switching is that
Espressif Systems 620
Submit Documentation Feedback
ESP32 Technical Reference Manual V4.3
29. PID Controller
when the last command of the current process switches to the first command of the new process, PID should
switch from 0/1 to that of the new process.
The software procedure for proactive process switching is as follows:

Mask all the interrupts except NMI by using software.
Set register PIDCTRL_NMI_MASK_ENABLE_REG to 1 to generate a CPU NMI Interrupt Mask signal.
Configure registers PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG.
Configure register PIDCTRL_PID_NEW_REG.
Configure register PIDCTRL_LEVEL_REG and PIDCTRL_FROM_n_REG.
Set register PIDCTRL_PID_CONFIRM_REG and register PIDCTRL_NMI_MASK_DISABLE_REG to 1.
Revoke the masking of all interrupts but NMI.
Switch to the new process and fetch instruction.
Though we can deal with interrupt nesting, an elevated process should not be interrupted during the process
switching, and therefore the interrupts have been masked in step 1 and step 2.
In step 3, the configured values of registers PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG will
affect step 6.
In step 4, the configured value of register PIDCTRL_PID_NEW_REG will be the new PID after step 6.
If the system is currently in a nested interrupt and needs to revert to the previous interrupt, register
PIDCTRL_LEVEL_REG must be restored based on the information recorded in register PIDCTRL_FROM_n_REG
in step 5.
In step 6, after the values of register PIDCTRL_PID_CONFIRM_REG and register
PIDCTRL_NMI_MASK_DISABLE_REG are set to 1, PID Controller will not immediately switch PID to the value of
register PIDCTRL_PID_NEW_REG, nor disable CPU NMI Interrupt Mask signal at once. Instead, PID Controller
performs each task after a different number of clock cycles. The numbers of clock cycles are the values specified
in register PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG respectively.
In step 7, other tasks can be implemented as well. To do this, the cost of those tasks should be included when
configuring registers PIDCTRL_PID_DELAY_REG and PIDCTRL_NMI_DELAY_REG in step 3.
Espressif Systems 621
Submit Documentation


NodeMCU serial port - use with computer and device at the same time

Yes, it is the same as Arduino. The TX and RX pins connect to a CH340G chip to convert the serial into USB. If you use USB serial you can't use the pins for anything else.


Arduino IDE in conflict with pyserial for use of serial port in OSX Yosemite

Ok, I solved it. First I stopped using the IDE serial monitor as Majenko suggested, and focused on getting the Arduino readings within the python code. Besides trying to use the python code and the IDE monitor at the same time (which apparently you can do in Ubuntu but not in OSX), the original problem was that my python code was not clearing the serial buffer in the r/w process. In order to do this, I wrote the following function to be called before and after a serial write:

 ser = serial.Serial('/dev/cu.usbmodem1421', 9600)

 def readarduino(ser):
    did=True
    while ser.inWaiting(): # Check number of characters left in buffer
        if did and ser.inWaiting() < 490: # Select last 500 characters in buffer
            for i in range(6):
                print ser.readline() # Print 6 lines in buffer
            did = False
        ser.readline()  # Clear buffer line by line until ser.inWaiting goes to 0

This ensures that the buffer is clear whenever I am writing to the Arduino.

This solution works for OSX Yosemite and Ubuntu 14.04


I have seen a lot of variations with the 6050.  Code I know works fine for me, will not run on someone else's system.  Code fixes suggested by others has zero effect for me.  My understanding is the DMP code is a reverse engineered sample that the manufacturer will not release actual documentation on. So it is a gamble to begin with.

That being said, I usually reset the FIFO buffer after every read.  I get an occasional over flow (1-2 per minute) with a lot of other code running at the same time, and NOT using interrupts.  The resulting AHRS data is reliable and solid (UNO) at default rate (100hz).  Ive lowered the AHRS rate (you have to modify data tables in a .H file) and I get the same error rate, it seems to have no effect.

As far as line lengths go, it is I2C. It is some magical combination of wire size and length, internal pull up resistors plus external ones.  I have usually heard people have success adding some pull-up resistors  I2C is a ground sink signal - so it doesn't care if it is 5 volts or 3.3 - only that everything on the bus be the same.  Obviously you will do better at 5V on a longer line vs 3.3V.  Some will argue the pull ups need to be at termination, some say it doesn't matter. I don't know anything other than the spec is very hard to understand and I have not had problems, especially the kind that require some of the elaborate schemes some people come up with (replacing caps and resistors).

Anyhow, 2 meters would seem to be pushing an Integrated circuit to Integrated circuit spec beyond what it was intended for, communication within a board. You might get it to work, but you also might rethink it.


How to interface with a mobile phone LCD?

How could I interface with this LCD with an AVR microcontroller?

Mobile phone manufacturers do not usually release information about the hardware they use. The first step would be looking if it has a controller on-board. Without a controller board you can't use the LCD, an Arduino can't handle being a controller. If it has a controller you have to update your post with pictures of the screen then we can help you a bit more.

  Also, why are there articles on websites showing only interfacing of Nokia LCD?

Nokia LCD's are easy to interface with, they're cheap and really good quality that's why they're popular that means there are more websites showing how to use them. As a beginner it is a good idea to use popular things, people can then help more.


How can I run Hello World using Serial Monitor in Tinkercad Arduino simulator?

I mean where would you expect it to print Hello World ... On the Serial Monitor, right? So first open it by clicking on the Serial Monitor button at the bottom of the code tab in Tinkercad.
I tried your code and it works perfectly fine.


seeeduino can-bus shield v2: can't read can bus and write on SD card

Despite the "the library example must be correct, It's work for other people before you", I'm not sure a lot of people make it works.
I've seen that even when the mcp2551 don't receive anything on can bus, the SPI bus is saturated by the mcp2551.
The solution was to use a simplest library make for 8MHz cristal chip. Modify it to works with standard 16MHz and use the interrupt pin (pin 2 on board) as interrupt.
If anybody got the same issue, just post a comment here and I'll do a better and more complete response.
Thank you very much @Timemage for your help


Connecting a push button to a stepper motor problem

Your code makes no sense at all.  Let's break it down. First we'll reformat the code using the auto-formatter (AStyle) in UECIDE:

const int buttonPin = 7;

int buttonState = 0;
int serialData = 0;

#define IN_1 8
#define IN_2 9
#define IN_3 10
#define IN_4 11
#define DELAY_TIME 30
int i = 0;

void setup()

{
    Serial.begin(9600);
    pinMode(IN_1, OUTPUT);
    pinMode(IN_2, OUTPUT);
    pinMode(IN_3, OUTPUT);
    pinMode(IN_4, OUTPUT);
    pinMode(buttonPin, INPUT);
    Serial.print("start");
}

void loop()

{
    buttonState = digitalRead(buttonPin);

    if (buttonState == HIGH) {
//delay(1000);
        for (i = 0; i < 4; i++) {
            Serial.println("pressed");
        }

        switch (i) {
            case 3: // ASCII  value for '1'
                digitalWrite(IN_1, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_1, LOW);
                break;

            case 1: // ASCII  value for '2'
                digitalWrite(IN_2, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_2, LOW);
                break;

            case 0: // ASCII  value for '3'
                digitalWrite(IN_3, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_3, LOW);
                break;

            case 2: // ASCII  value for '4'
                digitalWrite(IN_4, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_4, LOW);
                break;

            default:
                Serial.println("Not a valid case");
                break;
        }

        if (i == 4) {
            i = 0;
        } else {
            i = 5;
        }
    }
}

Now that we have fixed the formatting we can see some very strange things:

if (buttonState == HIGH) {

First we're doing this for every loop iteration where the button is pressed. That means we're doing it over and over again until you release the button.

    for (i = 0; i < 4; i++) {
        Serial.println("pressed");
    }

Now we're printing the word "pressed" four times.  After this i will be set to 4.

The switch will now take an input value of 4, which is "Not a valid case". So nothing will happen.

Then:

    if (i == 4) {
        i = 0;
    } else {
        i = 5;
    }

i is always 4, so it will always set it to 0.  Quite what this block is supposed to achieve I have no clue. If it were supposed to be inside the for loop above then it would just kill the loop on the first iteration, since i, when 0, would not be 4, so would be changed to 5, which is > 4. It makes no sense and can achieve nothing of value.

As for the switch: if it were inside the for loop and able to get some varying values of i, it would just make each output briefly activate in turn. If that's what you need to drive your motor, then fine. However, it's never going to run since the rest of the program is just nonsense.


How do I use the timers on an Arduino Uno R3?

Your question is probably not as simple as it may seem.

One approach I would use if I was to address this same problem would consist in:

converting the analog output of the mike into a digital value (based on a threshold to determine)
connect this digital signal to one Arduino pin that can trigger an interrupt when its level changes

Let's first start with the easy part: Arduino program.

Let's say we have a digital signal that raises to 1 as soon as a sound of too high amplitude is captured by the mike; it shall stay 1 as long as the sound does not reduce amplitude enough. We will connect this signal to Arduino pin 3; then we can use attachInterrupt() to have a function called whenever this pon level raises to 1:

volatile static bool started = false;
volatile static unsigned long timing = 0;
volatile static bool finished = false;

void loud() {
    if (started) {
        timing = micros() - timing;
        started = false;
        finished = true;
    } else {
        timing = micros();
        started = true;
        finished = false;
    }
}

void setup() {
    pinMode(3, INPUT);
    attachInterrupt(1, loud, RAISE);
}

void loop() {
    if (finished) {
        // Do something with timing
    }
}

Now the hardest part: electronics!

A first issue we have to deal with is related to the fact that the raw mike signal will have same wave shape as the sound it captures, this wave has a frequency that can vary between 10Hz (bass) and 20KHz (treble).

Indeed, if we convert the mike analog output to a logical value (1 when the analog value is above a threshold we'll call Vt, 0 when it is under Vt) fast enough, then, if the environmental sound as an amplitude above Vt, the logical input connected to your Arduino will oscillate at the same frequency as the sound! This would make our efforts pointless as you would measure the period of the sound wave instead of the elapsed time between two distinct sound bursts.

That means that we should probably first "smoothen" the analog sound signal in order to avoid disturbance of its frequency.

Hence point 1 will have to deal with these 2 aspects:

smoothen analog input value
compare smoothened value with Vt threshold and provide a logical value from this comparison

Comparison can rather easily be performed by an op-amp used as a comparator.

However, the main difficulty you may have with an op-amp is the need for a symetric voltage supply (e.g. +5V/-5V) although it is possible to use a single supply but that raises further limitations (outside the scope of my answer).

Smoothening the signal is potentially more complex, although it can be done with a simple capacitor, because smoothening the signal generally means weakening it, thus you would lose the initial amplitude of the sound signal.

So how can we deal with that?

A Schmitt trigger is probably a good solution for this problem but further experiment will be needed to confirm that.


Change Arduino Uno clock from 16MHz external to 1MHz internal

That will not work. To change the clock source, you'd need to change the fuses. I don't know of any way to do this while the chip is inside the UNO.

Secondly, a factory fresh 328P won't work in an UNO board, because it doesn't have the correct fuses, and doesn't have the bootloader programmed.

I'd suggest placing the 328P chips in a breadboard; connect the ISP pin to the UNO, and use the Arduino-as-ISP to change the fuses, and upload your program.

PS why run at 1Mhz. The internal oscillator runs at 8Mhz. By default the divide-by-8 fuse is set, so it runs at 1Mhz out of the factory, but you can unset this fuse.

PPS use this website http://www.engbedded.com/fusecalc/ to generate the right fuse settings for your project.


Ok, so... I can see your question is a bit obscure, so I'll try to cover a generic approach.

Power If you need to power the arduino, you can get a cheap car USB adapter. If you want a "solderable" solution, I'd avoid linear regulators (such as a 7805)and go with a cheap switching module. For low power applications I usually buy some modules called mini360 (for instance here is a link from aliexpress) which are cheap and ok for even some hundreds of milliamps. You FIRST turn the potentiometer to set the output voltage (checking with a multimeter) and THEN connect the arduino to it.
Get status If you need to get the status of something (e.g. whether the lamp is on or off) you have to analyse the circuit. If you have to detect if either 12V or GND are applied, you can solve the problem with a voltage divider. But if the lamp is always connected to 12V and then the GND side is he controlled one then you will always force a (small) current inside it. If this is the case, maybe an optocoupler is the best solution. If the signal is a PWM maybe you need some filtering, if it is a digital wire maybe it is already at the correct voltage, .... You have to figure out what is the best solution for you
Set status If you need to control something (e.g. turn on a light) your best bet is to use a 5V relay. There are plenty of them, even modules with the transistor and diode necessary to control them with an arduino.

Here are some ideas and rough schematics for the three points

simulate this circuit – Schematic created using CircuitLab

Just one very big WARNING: you have to carefully double check that the modification does not blow something up (for instance, you can make a short circuit if the body computer tryes to force a wire to 12V and you close the relay to ground). So... Be very careful, since what you do can break a lot of things, and if you are very lucky the bill can be only some couple of thousand dollars (I'll let you figure out what happens if you are not lucky enough)


How to indicate an End of a stream on USB

LoRa has a moderate data rate and typically substantial gaps between packets, so a simple thing you can do is send the data as printable ASCII hex with newlines or other terminators.

This will just short of double the amount of data you have to move, but do so in a very simple and deterministic way, and you can crank up the serial baud rate to handle it, especially as the baud rate only actually "exists" between two ATmega chips within the Uno.

Another plus is that the data becomes human readable, which is handy for debugging, especially if you might want to intermix advisory messages and data.


Your last two lines are not in any function. This confuses the compiler. You need to move those two statements inside a function.

Because those statements refer to RawValue, I'm guessing you want to put them in loop(), where RawValue is being updated.

Also, remember that the IDE will tell you on which line the error is, which is helpful when debugging compilation errors.


What type of connector does the GROVE system use?

It looks like the Grove connector is proprietary. I emailed Seeedstudio, and they directed me to this datasheet. Unless I'm reading it incorrectly, it doesn't appear to correspond to any type of JST connector, although it's similar. It has 2mm pin spacing, which would make it closest to the JST-PH type, but all the other dimensions are slightly different.


Pulldown resistors and multiple switches

Call the resistors R1 and R2, the negative terminal Ground, and the positive terminal V+.  The junction of R1 and R2 is connected to Ground.  This holds the resistor ends at the junction to zero volts relative to ground.  Ignoring P2 for the moment, the other end of R2 is open circuit to V+ when S2 is open.  Applying Ohm's law, we have a finite resistance in series with an infinite resistance, so zero volts across R2 when S2 is open.  Thus one sees that voltage across R2 is not affected by voltage changes across R1.

P2 as an input is not completely an open circuit; typically its effect is similar to a multi-gigaohms resistor to some voltage between Ground and V+.

Edit:
More directly, observe that the voltage at the Ground ends of R1 and R2 is zero and remains at zero no matter what S1 and S2 do.  Thus, operation of S1 does not affect voltage at P2, and operation of S2 does not affect voltage at P1.


Alternatives to read mp3 without using an sdcard as source for the files?

The problem of all alternatives I can think of is a commercial one:Its more expensive than to waste space. So if you look up your facvorite online dealer you will quickly find out that e.g. buying the cheapest 1GB SD card costs double than buying the cheapest 32GB card (6$). So the more space you waste the cheaper. Get an used 512MB or 1GB card (cost in my country around 1$) and be happy with the space reserve.
Of course if saving space is a topic and not money get 20 x 1MB eeprom I2C boards (20*3$ from china), solder the hardware (you'll need some more parts to manage the board addresses), get a power source, write a library for managing the memory and after spending around 100$ and a lot of time you saved up to around 15.98 GB of free space but not the environment.


You can't put 12 volts into a Uno input pin in any case.

You could run it into a voltage divider and divide it down to somewhere on the range 0 to 5 V, and then do an analogRead to see exactly (or almost exactly) what the resulting voltage is.

I don't really see where comparators come into it in this particular case. I mean, you could use a comparator to turn the LED on, but then where does the Arduino come into it?

  I've actually tried with voltage divider, I went pretty high on my resistors, taking the 12V source and hooked in 4x1M resistors but the 12V never came down significantly.

You need a voltage divider like this:

Those values give you 4 V on the Arduino pin if there is 12 V on the input.

Vout = (R2 / (R1 + R2) ) * Vin

So:

(1000 / 3000) * 12V = 4V


Converting Random Binary Data to PWM Signal

So, if you simplu has to convert the binary data to PWM signal there are few things you need to cover:

If the binary data that you are receiving from the sensor is linear or non linear.
What is the size of binary byte. Ex: int(16 bits),char(8 bits),long (32 bits).
If it is linear, then if the data is multiplied by some number it will output a value betwen 0-255.
If the data is not linear than you just need to create an giant array with the pwm intensite value direct without any particular mathematical function. Ex: array[1024] = {0,1,1,2,3,4,5,5,6,6,10,9,...}; (1024 values because if you are using analog input. Then you can direct output the values from array:

analogWrite(3,array[x]); //x being your data

Here's the linear Example:

   //map(value, fromLow, fromHigh, toLow, toHigh);
    y = map(x, 0, 1023, 0, 255);

Doing this, y will receive a value from 0 to 255. You just need to first do a simple serial program that prints you through arduino serial window the binary data and see if the data increases or decreases conform your light project.

I don't know about your programming levels or if you are using a digital sensor or analog sensor, but if you are using a digital sensor, so you are probaly using SPI communication or i2c. Then you just need to read that binary data and take where the values bits are with bit wize manipulation.

y=(x & (0xfff<<3))>>3;

Tell me more about the source of data, how this data is and how is the behavior of the data so i can help you a lot more. Thanks


Header files are part of your source code. The result of a build is a set of ones and zeros which are sent to your arduino and written in its Flash memory (the program space). The way you put these zeroes and ones together is completely up to you. You could write C and/or C++ code (where you have header files), you could write assembly code or you could write the zeroes and one directly on the disk, if you are crazy enough.
Header and Source files live only in the world of the developer and its toolchain, Arduino doesn't know they exist at all.

That being said, if you want to store log data you could use a SD card like you said, or send it over the network, or you could use a serial connection. But I'm sure there are plenty of other options.


Is it possible to use AWS and Arduino Uno to upload data from Arduino to a website running on my localhost?

No, it is not (easily) possible.

AWS has no access to your localhost - you are (most likely) behind a NAT router.

You could possibly open up port forwarding on your router and then ensure that AWS knows always what the IP address of your router is so it can connect (using some dynamic DNS service maybe).

However, that is not secure, and dynamic IP address assignments makes it a real pain. It opens up your computer to hacking from the internet.  A more secure method is to use AWS as the "central point" and have your computer go and fetch data from there rather than having it send data to your computer.


lastButton1State is not initialized and therefore has no strictly defined value. In your case, it appears to have a value of 0 (which is random, it's not due to implicit initialization, which is only done for global variables). The condition if(button1State != lastButton1State) becomes true only if the button is released.
You can check that by changing
if(button1State == LOW){
  Serial.println("button1Pushed");
}

to
if(button1State == HIGH){
  Serial.println("button1 released");
}

The following should work:
int last_button_state=HIGH; // initialize to HIGH, so the button does not teigger on very first iteration
void setup () {
  // whatever you want to do here
}
void loop() {
  int button_state=digitalRead(button1);
  if (button_state!=last_button_state && button_state==LOW) {
    Serial.println("button pressed");
  }
  else if (button_state!=last_button_state && button_state==HIGH) {
    Serial.println("button released");
  }
  last_button_state=button_state;
}


Sharp GP2Y0A710K0F IR sensor behaving strangely

I suspect you have it wired wrongly.

You need to consult the outline diagram in the datasheet and work out which colour wire is which function. It's this bit:

By your wiring description it sounds like you may be powering it through Vo and reading the result through VCC, which won't work - and at worst may damage it.


How to Create a water screen with solenoid valve in arduino

You can refer to this page for the generic actuation (iow Arduino board + relays shield + power supply for the valves), but that leaves one problem open: timing.

To draw something on a wall of water, you need to make sure that the water flows with a known, constant speed (unless your wall is very tall, I would ignore the effect of gravity, if the initial speed is high enough).

Maybe it can be achieved without this extra step, but to play it safe, I'd also add a pump that feeds all the valves.

This will ensure that you will have a known pressure/speed of the water, thus being able to calculate the timing of the valves.

You can use one of the relays to control also the pump.
Notice also that most likely an arduino UNO/Nano or equivalent will not be sufficient, as you will get relatively few lines.

An ArduinoMega2560 or DUE have far more GPIOs.


Controlled power-down for automotive application

Consider a battery backup for low power devices.  This article from allaboutcircuits.com discusses how to build a 12 to 5 volt power supply with its own battery backup.

In your specific case, run a second 12 to 5 volt regulated signal to one of the processor's digital inputs.  When the 12 volts shuts off, the signal to the processor's digital input will go low.  Poll this input and when you see it go low shutdown the processor or put the processor into a deep sleep mode to draw as little current as possible from the back up battery.

The ATmega2560 processor may not be the best chose for this. There are processors that can drop down into the nA range and still wake up periodically to check if they should be powered all the way back up.