I suggest you to try and read the Arduino page about ArduinoISP.

Particularly, you will notice that pins 11, 12, 13 and Vcc and GND are all common, BUT the reset pin is not common to both boards. So I suggest you to detach the pin 5 of ICSP from the ArduinoISP board and connect it to its pin 10. Or, if you prefer, connect

ISP - Target
+5V - +5V
GND - GND
11  - 11
12  - 12
13  - 13
10  - RST

Then try again


Should I use LLC to power sensors on grid pcb at 4mtr wire length distance?

Transmitting power over longer distances requires careful consideration. The actual voltage you will get at the remote end depends on two major factors:

The resistance of the wire, and
The current draw of the remote device

If you regulate your 24V incoming power down to 7V for the Arduino and then send the Arduino's 5V over 4m of wire to power your remote board the actual voltage the board will receive depends on the amount of current the board draws.

If this current is tiny then the voltage drop for the wire will be small and can largely be ignored. For instance, you quote about 3Ω resistance for 4m of wire, which to me seems incredibly high (32AWG which is like hair thin is only ~0.5Ω/m), but anyway.  If your board draws 100mA, over your 4m wire, which is actually 8m when you take into account the length of the ground wire ("There and back again - an electron's tale.") you would drop (2*3Ω)*0.1 = 6*0.1 = 0.6V, so your 5V would turn to 4.4V by the time your board sees it. Not only that but the ground wire would be offset at the board end by 0.2V, which may impact LOW logic level detection.

So ideally you need to both minimise and mitigate that voltage drop. And both can be done using a buck regulator at the board and powering it from the 24V supply instead of 5V.

By using a buck regulator you massively reduce the current over the wire (for 24V to 5V you could be looking at around a quarter of the current or even less, depending on the efficiency of the regulator) which reduces the voltage drop on both the power and ground wires. It also guarantees that the board runs at 5V regardless of the current draw of the board.

Here's a diagram:

For digital sensors this loss of voltage could cause damage if any incoming logic signals are above the absolute maximum for the sensor (which is usually a function of the supply voltage, say Vcc + 0.3V). For analog sensors it will affect the values you are reading, since the voltage emitted from the sensor is often a function of the supply voltage, and if that is not what you expect it to be your calculations from the ADC values will be incorrect.

To answer your original question "can I use a LLC to distribute power" the answer is "no". The LLC can allow you to interface logic signals between two different voltage levels, but not affect power at all. And further more it requires that you have both voltages availabe for the LLC to operate, and you don't have both voltages, you only have the 5V minus the wire's voltage drop available, so you can't use it to mitigate any offset in the logic levels either.


How to eliminate noise from PWM controlled 12V fan at low speed

I had the same problem with a 5V fan.  Something simple worked for me: To decrease the PWM frequency.  You probably want to do this using pin 9 or 10 (for the Uno) as changing the frequencies of other PWM pins messes up the delay and millis functions.  Details on how to do it and a very convenient function are provided in http://playground.arduino.cc/Code/PwmFrequency.  In my case, using the lowest frequency possible (31250/1024 = 31Hz), I completely eliminated the hum for higher speeds and significantly reduced it for lower speeds.  And by the way, I used the PWM pin to drive a MOSFET since the current of my fan was 140 mA, much higher than the 20 mA Arduino pins can safely provide.


If you look at Arduino.h, you'll see true, false and bool defined as:

#define true 0x1
#define false 0x0
typedef uint8_t boolean;

Using a simple test sketch, it appears that comparing true or false to anything besides a 1 or 0 does not "work".

void setup(){

  Serial.begin(9600);

  if(false == 0){Serial.println("false=0");}
  if(false == 1){Serial.println("false=1");}
  if(false == 2){Serial.println("false=2");}
  if(false == -1){Serial.println("false=-1");}
  if(true == 0){Serial.println("true=0");}
  if(true == 1){Serial.println("true=1");}
  if(true == 2){Serial.println("true=2");}
  if(true == -1){Serial.println("true=-1");}

}

void loop(){}


serial communication problem with sim7600 with arduino mega

You have change baud rate by at+iprex=9600 before upload your code, because sim7600 set 115200 by default then save your setting by at&w.

hope this help someone.


RAM memory looses its contents when it's powered off. However, this
natural erasure process is not instantaneous: it can take several
seconds, or even minutes. It has been demonstrated that cooling down a
memory chip can extend its data retention time to hours, which enables
a type of attack known as cold boot
attack.

This type of attack has been studied mostly on DRAM computer modules.
The Arduino memory, however, is based on SRAM, which is physically very
different from DRAM (a transistor feedback loop vs. a capacitor). There
seems to be very little research on cold boot attacks against SRAM. I
found nonetheless a technical report from the computer laboratory of the
University of Cambridge: Low temperature data remanence in static
RAM, by Sergei
Skorobogatov. Quoting from the conclusion:

  Contrary to the established wisdom, there are several chips that
  retain data for dangerous periods of time at temperatures above −20°C.
  The temperature at which 80% of the data are retained for one minute
  varies widely between devices. Some require cooling to at least −50°C,
  while others retain data for this period at room temperature.
  Retention times can be significantly reduced by shorting VCC to ground
  rather than by leaving it floating.

From this perspective I would say that, although the attack seems non
obvious, your secret key is not completely safe even in SRAM. Since the
data retention time varies widely between devices, it could be worth
testing on your Arduino. If possible, I would suggest you overwrite the
key after the signing operation.

Update: I did a quick test on my Arduino Uno, at room temperature,
by just unplugging and plugging back the board. Here is my test code:

// This memory buffer will not be zeroed at startup by the C runtime.
uint8_t __attribute__((section(".noinit"))) buffer[1024];

void setup()
{
    Serial.begin(9600);
    Serial.println(F("Program started."));
}

void loop()
{
    switch (Serial.read()) {
        case 'i':  // Initialize the buffer with pseudo-random bits.
            srand(42);
            for (size_t i = 0; i < sizeof buffer; i++)
                buffer[i] = rand();
            Serial.println(F("Buffer initialized."));
            break;
        case 'f':  // Report number of flipped bits.
            int count = 0;
            srand(42);
            for (size_t i = 0; i < sizeof buffer; i++) {
                uint8_t mask = buffer[i] ^ rand();
                while (mask) {
                    count += mask & 1;
                    mask >>= 1;
                }
            }
            Serial.print(F("Flipped bits: "));
            Serial.print(count);
            Serial.print(F(" / "));
            Serial.println(8 * sizeof buffer);
    }
}

And this is the output, with my comments on the right:

Program started.            ← fresh boot
Buffer initialized.         ← pressed 'i'
Program started.            ← pressed the reset button
Flipped bits: 0 / 8192      ← pressed 'f'
Program started.            ← unplugged and plugged back
Flipped bits: 4166 / 8192   ← pressed 'f'

It appears the RAM is preserved across a warm reboot (pressing the reset
button), but it is completely lost after a power cycle: half the bits
flipped is a total loss of information. I tried to do this as fast as I
could, which is slightly less than one second. It would seem the SRAM in
the ATmega chips decays pretty fast, at least at room temperature.

Update 2: I found an enlightening story about an unpowered AVR
keeping data in RAM for more than 10 minutes, but only on mornings:
The mystery of the Zombie
RAM.


Using multiple sensors on ESP8266 Wifi module

You really need something external to both provide the analog inputs for the force sensors and the serial communication for the GPS module.

The simplest "something" is another microcontroller.  Ideally one with two UART ports.

You can then:

Communicate between the microcontroller and the GPS with one UART
Sample the FSRs with the microcontroller
Format and send the data to the ESP-01 through the other UART

Using SoftwareSerial you chould just about do it with an Arduino Uno (though you'd have to disconnect whatever was on the hardware UART every time you wanted to program it), but ideally something with more UARTs would be better, such as a Mega2560.

A halfway house between the two would be a board based around the ATMega32U2 which uses a direct USB connection for programming leaving the hardware UART free to be used permanently. However you'd still need to use SoftwareSerial to emulate the second UART (maybe best for the GPS since it's then only used for receiving).


How to create TCP server on Arduino UNO WiFi?

For Arduino UNO Wifi, you have to use library "UnoWiFi-Developer-Edition-Lib". You can directly download and install it through library manager or can get it offline through the following link "https://github.com/arduino-libraries/UnoWiFi-Developer-Edition-Lib".

Hope this can help you.


Is it possible to use a USB camera with Arduino?

An Arduino is not a powerful processor and can not do much image processing.  I doubt that there is a USB camera that could be connected to the Arduino.

There are a range of OVO cameras that can connect to the Arduino, but I don't think you will be able to record live video on an Arduino with these, where would you store the file for starters?

There is a PIXY camera system, this has its own microprocessor and interfaces with an Arduino.  It can record video and do object recognition.
http://charmedlabs.com/default/pixy-cmucam5/

Hope that helps.


Soil moisture sensor not working in "pcb"

The answer was, in fact, my poor experience with these boards and how they work.

As you can see in the pictures, wire and connectors are on opposite sides of the board. I was assuming that pads were connected on both sides, which is not true. Therefore, connectors were simply dead.

Soldered again at the wire side and it works like a charm. Thank you all for every suggestion, and the learning experience.


How to power Arduino and shields with 4 rechargeable AA batteries?

Most 5V devices will function fine at up to 5.5V - however, check the datasheets for the major components and modules on the boards.

The main thing to watch though is that a 3.3V device, which can normally communicate fine with a 5V one, may not be able to. The problem is that the logic HIGH signal from the 3.3V device may be below the threshold for a logic HIGH on the Arduino:

V_IH = 0.6Vcc = 0.6 x 5 = 3V

V_IH = 0.6Vcc = 0.6 x 5.5 = 3.3V

Thus a 3.3V device would have to output at the very minimum 3.3V as a logic HIGH in order for it to register as one on the Arduino, which may be a problem...

You can easily drop the battery voltage by 0.7V though by inserting a single silicon diode (such as the trusty 1N4001) in series with the batteries. That will take your voltage down from your measured 5.3V down to 4.6V which will improve matters somewhat.

However, it is important to note that you have so far measured the open circuit voltage of the batteries. That is, the voltage with no load on them. The voltage will most likely be lower once they are actively driving the Arduino etc.

The Arduino itself will be fine running off 5.3V, so I suggest you power just the Arduino direct into the 5V pin from the batteries and measure the actual voltage while powering the Arduino. That will give you a more accurate voltage reading. Then, if needed, you can add the diode to drop it by 0.7V.


Motor not working when connected to motor driver shield?

I cannot tell all of your connections from the photo, but I'm guessing you're supplying power to the Arduino through its power connector and also to the motors, both from the battery. The power connector on the Arduino is specified for 7-12v because the kind of voltage regulator it has needs that 2v difference to operate properly. You're kind of at the edge by supplying 6v, and when the motors come on, their current draw will cause the 6v battery voltage to drop somewhat. It probably drops below the regulator's ability to supply 5v from it, shutting down the Arduino.

Adding one more cell to your battery will give you 7.5v (5x1.5v) and will may be enough to run the Arduino and the motors. Two more cells would work even better. (Don't make the mistake of trying the small 9v batteries with snap-clips on top - their utterly incapable of supply the current your motors need).


How to transmit data from Arduino to Raspberry Pi?

Which protocol to use to transmit data from Arduinos to the Raspberry Pi? Do I have to write code for both Arduino and Raspberry Pi or are there existing solutions which I can use for this purpose?
  Does MQTT, Node-RED or Node.js have any role in the above?

I have searched, explored, read and found that MQTT can be used to send and receive data from Arduinos to RaspberryPi as in [1] and [2]. So, no need to design and develop a new protocol.

MQTT libraries, such as PubSubClient [3] are available for Arduino. So Arduino code can use these libraries and no need to write much code either.

Simple and straight!

A.

[1] https://funprojects.blog/2018/03/04/arduino-talking-mqtt-to-node-red/

[2] https://iotdesignpro.com/projects/interface-arduino-with-node-red-to-send-sensor-data-on-webpage

[3] https://www.arduinolibraries.info/libraries/pub-sub-client


Why adding a LED between Pin 3 and Ground causes LCD display not to show text?

In a typical 1602 LCD pinout, pin 3 or V0 is the contrast setting for the display.  It usually is set to a voltage near ground, often by using a 10K pot with ends connected to Vdd and Vss with wiper to V0.

By putting an LED in series with your resistors (that apparently go to ground) you've either disconnected V0 from ground or have raised its voltage by the LED voltage.  This reduces contrast to the point that characters aren't visible even though they are on the display.

The LED backlight remains on and at the same brightness as before because it is driven via pins 15 and 16, independent of all other display settings.

Edit 1: I haven't duplicated your circuit to take measurements, so at the moment don't know for sure; but (in resistors-only case) V0 from pin 3 on the 1602 LCD board apparently sources some small current through your 1500 Ω to ground.  When you add an LED it can disconnect V0 from ground or can raise its voltage by the LED voltage, as follows:  firstly, if the LED cathode faces V0 and V0 is positive, no current will flow through the diode, thus disconnecting V0.  Secondly, if the LED anode faces V0 and V0 is positive, current will flow through the LED.  If the LED lights at all, most of its Vf characteristic voltage (typically between 3 and 4 volts for a green LED) will appear across it.  Thus, V0 sits at close to Vf plus whatever drops across the resistors.

*The same as for other diodes, LED forward current increases exponentially with voltage (Ref: wikipedia on LED physics) hence voltage change is tiny over large changes in current when an LED is emitting light.  In other words, if the LED is lighting up, its voltage will be close (ie within a few dozen millivolts) to its characteristic band gap voltage.  See petervis.com's led-resistor-calculator for a "Chart by Colour" that shows characteristic Vf forward voltages.


RGB LED using potentiometer and push button

You method sound a bit more complicated that it needs to. What I would do is have the button switch between three colors, and have the potentiometer change the brightness of the currently selected color.
For example, when first starting up, the red led is selected. Turning the potentiometer changes the brightness of the red led (in real time). Let's say you turn it 50%, so the red led is at 50% brightness. When you're happy with that, you press the button, and now green is selected. (Since the potentiometer is still at 50% from the red, the green led will immediately turn on at 50% brightness.) You can then turn the pot to change the brightness of the green led. Let's say you turn it all the way of to 0%. Then press the button to select the blue led. Turn it to 100% and the combined color would be a dark purple. Press the button again to select red again.
Here is some proof of concept code:

byte selectedColor = 0; // 0:red, 1:green, 2:blue
byte oldButtonState = HIGH;

void loop() {
  byte buttonState = digitalRead(buttonPin); // read the button
  if( buttonState==LOW && oldButtonState==HIGH ) // see if the button is pressed, but wasn't pressed the last time
  {
    selectedColor++; // to to next color
    if( selectedColor==3 )
      selectedColor = 0;// after blue, go back to red
  }
  oldButtonState = buttonState; // remember the buttons state for the next loop

  int brightness = map(analogRead(potPin), 0, 1023, 0, 255);

  if( selectedColor==0 )
    analogWrite(redPin, brightness);
  else if( selectedColor==0 )
    analogWrite(greenPin, brightness);
  else
    analogWrite(bluePin, brightness);
}

PS I left out the pinMode stuff in the setup.
PPS make sure the led leads are connected to PWM pin on the Arduino (they have a ~ next to them on the PCB).


Digital read on voltages between 1 and 31 volts?

Using a simple voltage divider (51K / 10K as you have worked out already) fed directly into an ADC input will give you a reading of 32 on the ADC at 1V input. That should be enough to give a reliable threshold detection.

If you want to have higher sensitivity at lower voltages you can increase the output of your voltage divider to more than 5V and then clip it with a zenner diode. For instance if you reduce the 51K to 33K you get 7.2V out of the voltage divider. A 5V zenner diode can then clip it to 5V. Your 1V input (which would be 0.233V on the output of the divider) would now read 47 on the ADC. Anything over 21V would then read 1023.

simulate this circuit – Schematic created using CircuitLab

Theoretically you could get away with not having the voltage divider at all and just using the zenner and one resistor to clip the incoming voltage to 5.1V. That would give you the greatest sensitivity, but also the greatest current flow through the zenner.

simulate this circuit

Size R1 to limit the current at your maximum voltage to within the rating of the zenner.


Arduino Due custom platform for school and library installation

Exit the Arduino IDE.
Create a folder in the Arduino IDE installation folder named portable. This will cause the Arduino IDE to run in portable mode.
Start the Arduino IDE.
Tools > Board > Boards Manager
Wait for the download to finish.
Click on "Arduino SAM Boards".
Click "Install".
Wait for installation to finish.
Make your modifications to the Arduino SAM Boards hardware package installed at {Arduino IDE installation folder}/portable/packages/arduino/hardware/sam.
If necessary, configure File > Preferences to your liking.
Exit the Arduino IDE.
Zip the Arduino IDE installation folder.

When you run the Arduino IDE in portable mode it causes hardware packages installed via Boards Manager to be installed to the portable folder, rather than a folder outside the Arduino IDE installation folder. It also stores preferences.txt in the portable folder. This means you can supply a .zip file that contains a copy of the Arduino IDE with the customized Arduino SAM Boards package already installed.

By default it will also set the sketchbook folder to be there but that can be changed via File > Preferences > Sketchbook location if you like.


In some architectures a "char" is an "unsigned byte". In others it's a "signed byte".  The AVR specification mandates a signed byte for char. Whatever you are compiling on probably mandates an unsigned char.

You cannot assume one or another. If you are working with an array of characters (a "string") you should be assigning it to a char data type. That way the signage of the data type and the "string" content will match.

By using uint8_t you are specifically telling it to use an unsigned byte.

strtoul() expects a char. Since on AVR char is signed, when you try and squeeze an 8-bit value into a 7-bit + sign space it warns you. Which is good. You potentially lose the 8th bit of your data.

The main error, though, is:

error: taking address of temporary array

This is caused by you creating a new temporary array within the parameter list of strtoul.

{byteBuffer[i], byteBuffer[i + 1], '\0'}

Then you take the address of that array and pass it to the function.  That is not good. Imagine the situation where the function returns something that is dependent on that address. For instance a function that returns a pointer to all but the first character of the string.  Once the function returns that returned pointer points to an area of memory that is no longer valid - the temporary array has already been disposed of.

I know that's not the case in your code, but it's a possibility you can conceive.

Yes, temporary arrays like that are perfectly valid in some versions of C++. But those are fairly recent versions, and the Arduino compiler isn't that recent (I don't know which version introduced them as valid off hand, but we're up to GCC version 8 now. Arduino is still down at version 5.something IIRC).

Suffice it to say, don't use temporary arrays like that (which is a shame, because it's damn useful).  Instead you have to assign it to a new array and pass the pointer to that array instead:

char tempArr[3] = {byteBuffer[i], byteBuffer[i + 1], '\0'};
 arr2[i / 2] = strtoul(tempArr, 0, 16);

That way the address you're passing to the function is one that is allocated on the stack and is guaranteed to exist past the lifetime of the function call (right up until the end of the current scope).


You can make the ESP8266 wake from deep sleep by just pulsing RST low briefly. Crudely you can just use your switch to connect it to GND perhaps with a pullup resistor to +v. If you want to be a bit more elegant you could use a small capacitor to smooth out the switch bounce so your code only restarts once. I use this on an ESP8266 that is solar-powered. Most of the time it is in deep-sleep. It wakes up, connects to MQTT and deep sleeps again only when the sensor it is monitoring changes state.


Can I switch a pulse solenoid from the onboard 5V/3.3V power source?

1) Can I send a 3.6V solenoid a 60ms pulse to open/shut it from a 5V
  power source without burning out the coil or causing any other damage?

No. If it's 3.6V then you need 3.6V - 5V will most likely make it smoke. Use a regulator (preferably a buck one, since it is apparently 500mA) to power your H-bridge.

  2) Is 3.3V too low to power a 3.6V solenoid?

Maybe, maybe not. It may be that 3.6V is the absolute maximum and may switch from 3V to 3.6V.

  3) Do pulse solenoids still generate back EMF?

Normally, yes, since they are just a coil like any other inductive load. Your H-bridge should deal with that though if designed right.

To get any meaningful answers you will need a datasheet. Buying such things from eBay is never a good idea unless you have used it before and know what it is, what its specifications are, and how you use it, or they provide a link to a datasheet. Without a datasheet most questions will be answered with a "maybe".


Using Temperature sensor arduino to trip off an ac device

Yes, there are lots and lots of project descriptions similar to yours (if I guesstimate) on the web. Google is your friend.

Here is one link to an interesting project - if you are interested in brewing beer.

Cheers!


The row of white blocks is what you get before the screen's initialized. It's normal.

The shadow behind the characters is because you have the contrast turned up too high. Adjust it down a little.


L239D motor driver not able to drive motors

I guess using 9 Volt battery in parallel will do your work because if the motor is moving as you quoted above means it is getting the voltage but not enough current to drive it, please connect the 9 volt battery in parallel and it will work for you


Adafruit Circuit Playground Express fails to upload

The actual error part of that stack trace is:

Port name - /dev/ttyACM1; Method name - openPort(); Exception type - Port busy.

You have something else using /dev/ttyACM1.  If you don't yourself have something open, such as a serial terminal or the Arduino serial monitor, then the most likely culpret is modemmanager.

https://majenko.co.uk/blog/diagnosing-arduino-problems-linux


Arduino Uno - why doesn't memory leak crash the program?

malloc() by itself generally doesn't crash a program.  It attempts to allocate the requested amount of memory, and if it can it will.  If it can't (there isn't enough memory available) then it won't allocate anything and will just return NULL.

By trying to allocate more memory than you have it will just fail every time and no memory will be allocated - thus you don't actually have a memory leak, so your program doesn't fail.

The main reason for crashing is a phenomenon called stack smashing where the memory area used by malloc() (known as the heap) and the memory area for the stack (used by local variables and for storing the contents of registers during function calls) collide with one another and one corrupts the other.  For instance, if the return address of the current function in the stack is corrupted, when the function finishes it will return to the wrong memory location and who knows what may happen then?  Wrong instructions will be executed for sure.

For instance, try this program out instead:

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

void loop() {
    char *a = (char *)malloc(10);
    if (a != NULL) {
        Serial.println("Allocated 10 bytes");
    } else {
        Serial.println("Allocation failed");
    }
}

If all goes well you should see lots of "Allocated 10 bytes" followed by some "Allocation failed".  Since the memory is now full there is a chance that it may now crash as the stack and heap collide - in which case you would expect to see the "Allocation failed" messages stop.


Problem with serial connection. Data garbled

I think RS232 signals are outside the TTL limits; I don't know if you've done any permanent damage.

On the interfacing itself:

https://www.sparkfun.com/tutorials/215

On the damage part:

https://forum.arduino.cc/index.php?topic=26139.0


You can set addresses using SPI commands.  For example a 5-byte transmitter address could be written as (MSB first):

  digitalWrite(CSN_pin, LOW);
  SPI.transfer(0x30); // write TX_ADDR register
  SPI.transfer(tx_addr[0]);
  SPI.transfer(tx_addr[1]);
  SPI.transfer(tx_addr[2]);
  SPI.transfer(tx_addr[3]);
  SPI.transfer(tx_addr[4]);
  digitalWrite(CSN_pin, HIGH);

where tx_addr is an array of 5 bytes.  Similarly you can write to the RX_ADDR registers, see the nRF24L01+ datasheet, section 9 for the register map.

Furthermore, the following code allows you to read the TX_ADDR register:

  digitalWrite(CSN_pin, LOW);
  SPI.transfer(0x10); // read TX_ADDR register
  data_out[0] = SPI.transfer(0x0);
  data_out[1] = SPI.transfer(0x0);
  data_out[2] = SPI.transfer(0x0);
  data_out[3] = SPI.transfer(0x0);
  data_out[4] = SPI.transfer(0x0);
  digitalWrite(CSN_pin, HIGH);

  Serial.print("TX_ADDR=");
  Serial.print(data_out[0]);
  Serial.print(data_out[1]);
  Serial.print(data_out[2]);
  Serial.print(data_out[3]);
  Serial.println(data_out[4]);


Libraries/classes using other libraries/classes

The Arduino IDE must detect the library to include it in the build process. It is done by matching a library to a header file by searching the libraries in configured library locations. Only the root folder and the src subfolder of a library are searched.

If your library is in the sketch folder's libraries subfolder and it is called customLibs, then only the customLibs folder and the customLibs/src subfolder are searched and the include file LLRelay.h in customLibs/src/relay folder is not found.

reference: Layout of library folders and files


Does any board provide more than 1024 analog input values?

AVR-based Arduinos only have 10-bit ADCs, but the ATSAM3X in the Due has 12-bit ADCs. Additionally, it is possible to interface to higher-resolution external ADCs via I2C or SPI.


I have successfully reprogrammed the UNO's R3 8U2 to support keyboard emulation, as to just this. Making dedicated user inputs for kiosks to Computers. I recommend NicoHood's GitHub as it allows simultaneous Arduino Bootloader and Keyboard functionality, making it easy to reprogram the Arduino.

This along with using Capacitive Touch Sensor connected to Copper tap under clear acrylic protecting printed graphics of buttons is very quick and easy to make. Very little machining.

Example of such code is found at artemis-firmwares it was initially created with a different 8U2 method. Where next time we will use NicoHood's.

Note the stock keyboard send key command for the Arduino is limited. Where the above methods allows the code to send complete virtual keys supporting full emulation.


Working or functionality Serial.begin(9600)

Serial.begin(9600);

What is mean of this line of code?

Serial.begin(9600) doesn't actually print anything.

If you want to print "Hello world!" to the serial monitor then you have to use this line of code. Rather it initializes the serial connection at 9600 bits per second.

It is used for kind of handshaking means both sides of the serial connection (i.e. the Arduino and your computer) need to be set to use the same speed serial connection in order to get any sort of intelligible data. If there's a mismatch between what the two systems think the speed is then the data will be garbled.

Why here, we always write 9600?

And 9600 bits per second is the default for the Arduino, and is perfectly adequate for the majority of users, but you could change it to other speeds: Serial.begin(57600) would set the Ardunio to transmit at 57600 bits per second. You'd need to set whatever software you're using on your computer (like the Ardunio IDE's serial monitor) to the same speed in order to see the data being sent.

And can we write manually number means instead of 9600 let's say 10000?
No, we can't write. There is a specific baud rate available: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200.


sending multiple signals at the same time, with short delay

Yes. Read the BlinkWithoutDelay example and triplicate it.


Every so often ESP8266 hangs... WifiClient seems to be at fault

It is a bug and it was fixed in Arduino esp8266 core package 2.4.2 published 2 days ago.

see first line in ESP8266WiFi section of the changes list

  2.4.2 ESP8266WiFi:
  Fix memory leak when reusing WiFiClient object (#4497, #4516, #4549)


Use state change detection and hysteresis for counting pulses in an analog signal.

const int lowerThreshold = 150;
const int upperThreshold = 200;

const uint8_t analogPin = A0;
const uint8_t ledPin = LED_BUILTIN;

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

void loop() {
  static bool state = LOW;
  static unsigned int counter = 0;

  int analogValue = analogRead(analogPin);
  if (state == HIGH) {
    if (analogValue < lowerThreshold) {
      state = LOW;
      counter++;
      Serial.println(counter);
      digitalWrite(ledPin, LOW);
    }
  } else { // state == LOW
    if (analogValue > upperThreshold) {
      state = HIGH;
      digitalWrite(ledPin, HIGH);
    }
  }
}

This sketch basically applies a software Schmitt trigger to the analog input signal, and increments the counter on each falling edge. (Rising edge of light intensity, because your LDR configuration inverts the signal.)

The red waveform is the analog input from the LDR. The gray rectangular wave is the state (and the state of the LED). The counter is incremented at each black, vertical dashed line.


How to use a push button & transistor as a kickstarter for power supply?

Your idea is sound, but your implementation is flawed.
First, you don't want to bother with "wake" and things like that - when the chip gets power it just starts from scratch - that's your "wake" signal. Your code will just be "Hold it on" and "Make a sound" followed by "Let it switch off".
You only need one IO pin for that - the "Hold it on" signal. The "catch" signal in your schematic is just the chip getting power.
And then there's your schematic.  You should really use a P-channel MOSFET to do the switching of the power, not an NPN transistor. An NPN won't work, and a PNP (which would be what you would use for this if you were using a BJT) would impose a voltage drop, which you don't want.
Your circuit would in fact need to look like this:

simulate this circuit – Schematic created using CircuitLab
When idle M1 (P-channel with threshold voltage well below the battery voltage) is turned off by R1 pulling the gate up to the source voltage. Pressing the button pulls the gate below its threshold voltage allowing M1 to turn on. The chip then gets power.
M2 (N-channel with threshold voltage well below the chip voltage) is then activated by the chip by driving the GPIO HIGH to bypass the switch and connect the gate of M1 to GND.  R2 keeps M2 turned off while idle.
M2 is needed so that there is no current flow between the battery and the GPIO when the power is turned off.  Without it current can flow through R1 into the GPIO, through the ESD protection diodes inside the chip, and potentially break the chip.
Now to help clear up some of your questions:

Truth: Is is possible for a transistor as relay to power a chip on demand?

Yes, it is.

Risks: Is the power going to be stronger due to the amplifying nature of the transistor?

No. Amplification, with a BJT, is really a misnomer. It doesn't "amplify" a signal, it takes one small signal and uses that to proportionally control a larger signal. But that's only in the "linear" portion of the curve. When used in "saturation" like this it's more like a switch - power applied to the base turns on the flow of current from collector to emitter.

What about the chip, I've read that a chip can maintain its code for 20+ years without power supply. Is this true?

Yep. Flash memory typically has a retention time in the order of 10 to 100 years. 20 years is a reasonable ballpark figure.

Goals: Is there a better way to save power? Would it be best for the chip to just have sleep enabled?

Zero power is the best low power there is. Even in the deepest sleep mode the chip will still draw power. But if you do it right there can be little difference between the current drawn by a sleeping chip and the self-discharge of a battery as it sits idle.

Name: If this works, is there a better name than the Startled Monkey?

I like the name Startled Monkey. I think I'll use that in future myself.


How to measure whether air is flowing through a pipe?

Did you consider a barometric sensor deployed inside the pipe?
The pressure should be higher when the pump is active.


Touch Sensor - Determining Pressing/Hold Length and Modifying Program Flow Accordingly

You have to determine, how long a the sensor was pressed until released. When it is released you can take the corresponding steps. If the press was shorter than say 1.5s, you can switch the relay. Else you can do something else.

There are many ways to achieve this. You can program it yourself by using the millis() function. You would have to set a timestamp, when the state of the sensor changes to high, then wait for it to go low and substract the timestamp from the current value of millis(). This would give you the duration of press, which you can use in a corresponding if-statement.

Or you can use the Debounce library for it, which makes it a bit simpler (not a lot, but you should consider debouncing depending on the type of sensor you use). Look at the answer from VE7JRO to this question. The debouncer.update() function checks, if the state of the button changed. If so and the value was LOW (in your case this would has to be changed to HIGH), a timestamp is set with the value of millis(). When an update with LOW occurs, the time difference between the two events is calculated and the corresponding action are taken. I will add the code from the answer for reference here:

// Connect one end of a N.O. push button switch to GND and the other
// end to pin 4 of the Arduino.
// NOTE: If the button is held down for less than the debounce delay
//       time, the elapsed time will display the debounce delay time.
#include <Debounce.h>
const byte SWITCH = 4;
unsigned long startTime = 0;
unsigned long endTime = 0;
unsigned long elapsedTime = 0;
const byte debounceDelayTime = 50;

Debounce debouncer = Debounce(debounceDelayTime, SWITCH);

void setup(){
  Serial.begin(9600);
  pinMode(SWITCH, INPUT_PULLUP);
}

void loop(){
  if(debouncer.update()){
    if(debouncer.read() == 0){
      startTime = millis();
      Serial.println("Button Pressed");
    }
    else if(debouncer.read() == 1){
      endTime = millis();
      Serial.println("Button Released");
      elapsedTime = endTime - startTime;
      Serial.print("Button Held Down For ");
      Serial.print(elapsedTime);
      Serial.println(" ms.");
    }
  }
}


ESP8266 check if TCP client disconnected...informally

You have the inherent problem that a TCP connection is terminated by an explicit "FIN" message from the terminating party, followed by a FIN-ACK and ACK.

Refer to here.

If your client (or server) just powers off without closing the connection properly, that's it. The connection hangs up and no data will be transfered if it is not explicitly handled.

If you must know whether the client is still there, you must use a heartbeat meachanism. That is, after some period time without a response has passed, query the connection party with a "heartbeat" message and see if it responds after a given maximum time. The other way around would be to make the client send a periodic "Keep Alive" message which holds up the connection as long as it is sent repeadetly.

Refer to here and here.


The NRF24L01+ has inputs that are 5V tolerant! So you only need to provide 3.3V on the Vcc pin of the module, which you can do by putting a voltage regulator between it, and the 5V of the Trinket. So there isn't really any need to convert the Trinket to 3.3V.

PS Remember to add some capacitors to the output of the voltage regulator, as the NRF needs a pretty stable 3.3V. Noise in the power lines can cause instability in the operation of the device.


There are three basic ways of creating a DAC.

The simplest, though roughest, is to use PWM, then low-pass filter it.  Not perfect, but rough and ready. Only needs a resistor and a capacitor.

The highest quality way, though slowest for interfacing, is to use an external DAC chip. Fine for low frequency response reproduction, and the linearity is second to none. The MCP4821/2 is a popular choice (SPI connected).

The third option is to build your own DAC using an R-2R ladder. You can make an 8-bit DAC with very fast response by using all 8 pins of a single IO port (such as pins 0-7 on the Uno are bits 0-7 of port D). However the linearity of an R-2R ladder very much depends on how well matched your resistors are.

The R-2R ladder should be buffered with an amplifier of some form before driving a low impedance device like a speaker.

None of them are really great for audio work - for that you need a chip with much more processing power and memory, and a high speed digital audio interface, such as I2S, to interface a proper audio CODEC chip. Personally I use PIC32MZ chips for audio work.


It seems as you are using the delay(); function for your code. The reason that it doesn't run anything is your Arduino does nothing during the function. The easiest option IMHO is using millis();. This will "return" a long datatype. Some example code (modified from example sketches in Arduino IDE):

/*
 created 2005
 by David A. Mellis
 modified 8 Feb 2010
 by Paul Stoffregen
 modified 5/16/14 by Anno. Penguin
 This example code is in the public domain.
*/

const int ledPin =  13;      // the number of the LED pin
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated
long interval = 1000;           // interval at which to blink (milliseconds)

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

void loop()
{
  //Sensor code
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

Obviously, your code will be more complex than that. This one only blinks it, but you'll have to do some creative logic here. I don't know what the animation is, but most likely you'll need to add a few more variables (make sure to declare them outside loop() so they aren't disposed of each iteration!).


How do you know, that there is nothing in the Serial buffer, when you enter the jog() function? You don't check for this.

I think your problem is actually in your getData() function. The for loop

for(int i = 0; i < Serial.available(); i++){

might not work as you think, because i increases in every loop iteration while Serial.available() decreases in every iteration. So you actually read less data, than is available on the buffer. For example let's assume, that you have 2 Bytes on the buffer. Serial.available() returns 2. In the first for loop iteration i is 0, while Serial.available() is 2. When you read from the Serial buffer in the iteration, Serial.available() decreases to 1 (since you removed one byte from the buffer by reading it). At the end of the iteration, the for loop will increase i by 1 (due to the i++). Now in the condition of your for loop, you have 1 < 1 (because both i and Serial.available() are 1), thus the for loop will exit without any further iterations. But you still have 1 Byte left in the buffer, that you didn't read.

As I read from the documentation of Serial.flush() (though the documentation is notoriously bad) and from this question, I see, that it will only wait until the output buffer is emptied by the interrupt routines. It does nothing with the input buffer. So you still have data in your RX buffer after this line.

That means, that you really have data in your RX buffer, when you get into the jog() function. Thus it will directly exit without doing any step.

To solve the issue, you should first correct your getData() function to read all the available data from the RX buffer. You can change your for loop like this:

for(int i = 0; Serial.available() > 0 && i < INPUT_BUFFER_SIZE; i++){

This will loop until the RX buffer is empty (when Serial.available() returns 0) or until your input[] array is full (Please add a constant or a define for the input buffer size. Maybe you already have it. You didn't include the full code. But I guess it is 200).

After the for loop, you can empty the buffer by reading from it, until there is nothing left (Please see the linked question for that). You can even do this at the start of your jog() function. This ensures, mostly, that no data is in the buffer at the start of the jog() function (mostly, because the timing of data reception could be, that you receive a byte between the emptying of the RX buffer and the loop. Little probability, but not impossible).

Though - as Nick Gammon states in the linked answer - it is not the best way to empty the RX buffer and use every serial input as interrupt (sometimes you don't have exact control, when exactly the data is received). A better solution is to implement a message protocol, where the end of a full message is marked with a special character. Then you read from serial, until a full message is received (you can even do this non-blocking, so that you can do other things until the message is complete), and only then act upon the message. This would need bigger changes in your code. You would have to rewrite your getData() function and then remove all blocking code from the sketch (for example all delays) and work with non-blocking code instead (for example using the micros() function. The principle is explained in the BlinkWithoutDelay example, that comes with the Arduino IDE (though it uses millis() instead of micros() it is the same principle). You would call the jog() function repeatedly, which would only do a step, if it is time to do one. In the meantime the rest of the code can receive new messages. This makes you more flexible and independent of the exact timing of data reception. Since this would be a big rewrite of your code, you have to decide yourself, if you want to go this way, or stay with the simpler and more imperfect solution.


There are two methods of doing what you want:

Add more ADC channels
Multiplex the existing ADC channels

SPI or I2C ADC chips are readily available in a range of resolutions, sampling speeds and number of channels.  They are fairly simple to add to any Arduino.

For instance the MCP3208 will give 8 channels of 12-bit resolution on SPI, which means 3 pins (MOSI/MISO/SCK) + 1 per chip (SS). So 1 chip would be 4 pins, 2 chips 5 pins, 3 chips 6 pins, etc.

Adding lots of chips to the SPI bus though can itself be troublesome with the increased capacitance of all those inputs meaning you have to reduce your communication speed somewhat or add extra buffering to drive the bus with more current.

I2C chips can be harder to have lots of them since there are only a limited number of addresses on an I2C bus - plus on many Arduinos the I2C is also two of the analog pins, which you may not want to sacrifice.

The second option involves using analog multiplexers (eg the 4051) to switch different sources in to the existing analog inputs.

A third option which you probably haven't considered is to have multiple arduinos (or other low-cost microcontrollers) each doing some of the sampling and then implementing some kind of communication method between them (or to a single master). This has the added advantage that it's then possible to sample multiple channels at once (one per microcontroller) speeding up your operation somewhat.


Why is my boards.txt file not being found?

I got a hack to work  (macOS) by symlinking the files to where ino expected them to be.  But now I'm running into this issue: https://github.com/amperka/ino/issues/149

FWIW:

cd /Applications/Arduino.app/Contents/Resources;
ln -s Java ../Java;
cd /Applications/Arduino.app/Contents/Resources/Java/hardware/arduino;
ln -s boards.txt avr/boards.txt;

Did it for me as far as finding boards.txt goes.

Still Broken otherwise. (Not marking as answer)


Why have resistor at end of circuit cycle if GND dissipates final energy?

Roman, As I understand your question you have a resistor, an LED and a switch in "series". It makes no difference in which order these are connected. It may help to think like water flowing through a hose, with a tap being a switch - it can be at either end.

"Current" flows through each in turn. As others have mentioned current conventionally is considered to flow from + to - (even though in most, but not all, cases electrons flow from - to +).

In practical circuits it is usually more convenient to select one configuration over another. An Arduino digital pin can be considered as a switch which is either connected to + or -. You could connect a LED (with a current limiting resistor) to either + or -, either is valid it just changes the logic controlling the switch.


You have to change F_CPU only - You can add new board into the boards.txt with correct clock speed.
EDIT: Aparently millis counter will be drifting much more then expected due to "rounding" errors.

The bootloader on the other side needs to be recompiled with correct F_CPU and  reflashed, if you want it working at the same baud rate (plus it's possible to change fuses to use external clock source instead of crystal). Otherwise you have to try reduced speed (also configured in board config).

You can use MCUdude/MiniCore as inspiration. It supports many clock speeds (but 10MHz doesn't)


How to programmatically upload an Arduino sketch generated by node.js (electron) or from browser?

There are two things you need to do:

Compile the sketch into a .HEX file
Upload the sketch to the board

The first part can be done with arduino-builder which is part of the IDE since 1.6.6, or you can use one of various Makefile projects on a platform that supports make, or you can manually script it yourself calling the correct avr-gcc and avr-g++ commands. You can check the output of the IDE for what those are.

The second part is done, usually, using avrdude - again see the output of the IDE for the correct command format.


Adding external power supply to any arduino connected component

You can use an NPN transistor for this purpose.

All you have to do is connect it this way

Obviously use a buzzer instead of the motor and pin 9 instead of 4 :D

Arduino (pin 9)==>1k-10k Resistance==>Transistor base

Buzzer +ve ==> + 9V

Buzzer -ve ==> Transistor collector

Transistor Emitter ==> battery -ve ==> Arduino GND.

So now whenever you set the pin 9 to HIGH the transistor would allow current to pass through it from collector to emitter and your buzzer would work just as you wanted.


Reading pressure sensor using Arduino analog

You can use map, ref. : https://www.arduino.cc/en/Reference/Map

  Re-maps a number from one range to another. That is, a value of
  fromLow would get mapped to toLow, a value of fromHigh to toHigh,
  values in-between to values in-between, etc.


NodeMCU run sensor code while listening for wifi input?

The problem is that at

while (!client.available()) {
  delay(1);
}
// your wifi code

you wait for a wifi event and in that time you obviously can't read the sensor. Just poll for incoming requests by doing it like

if (client.available()) {
  // your wifi code
}

This way your loop skips the wifi-routine if there is nothing to do and proceeds with reading the sensor.

As mikrocontrollers usually don't run a OS, you don't have multitasking which you have to implement yourself.
Generally you have to avoid using delay loops when you want several tasks being executed "parallely".


How can I programming detect that a Bulb/LED is ON/OFF or a circuit is working as expected using Arduino?

This can be done using a few methods.  The simplest and least expensive option is to measure the current consumption of the device you want to verify correct operation of, and see if it's using enough, but not too much, current.

For instance, the following would work well in the arduino case of using an LED:

simulate this circuit – Schematic created using CircuitLab

Connect the Power to 5V or to the pin you're controlling the LED with. Connect the Sense to an analog input such as A0.

If the LED isn't installed, or is broken as an open circuit, the sense would register 5V.  If the LED is broken as a shorted element, the sense would register 0v. If the LED is operating correctly, you would sense the voltage drop of the LED (which varies according to the LED's design), but it would be well above 0V and well below 5V.

For bulbs and other loads, use a much smaller resister for R1 (so the resistor doesn't affect the load as much) and it would be considered a current shunt.  Knowing the resister value, and the voltage at the Sense location will give you a current value using Current = Voltage / Resistance. Again, the load should be drawing current within an acceptable range during proper operation.  If it's not drawing enough current, or too much current, it may not be operating correctly.

This won't tell you if the LED is on, however it's a very reliable method to discover if it's working correctly, and you'll probably never run into a situation where the correct LED is installed and in the right current range, but not emitting light.


Does the atmega8 arduino NG have interrupts?-

Page 1 of the datasheet:

Yes, it has interrupts.

  just need one interrupt.

Page 46 of the datasheet:

It looks like you have 19 of them.

  regarding interrupts atmega8 is different168 there-so that may imply the the same code wont work -and I couldnt find any examples when searching

Try using the Arduino libraries. If that doesn't work post your code.


Measure different Vcc using 1.1V bandgap

The internal reference won't change much. That's why it's a reference.

Running this code on my Atmega328P:

void setup ()
{
  ADMUX = bit (REFS0) | bit (REFS1);  // Internal 1.1V reference
}
void loop () { }

That outputs the reference voltage on Aref. I measured it as follows with different values for Vcc:

Vcc     Aref
------------
5.00   1.085
4.00   1.081
3.30   1.080
3.00   1.079

So you can see that it retains, more or less, the same voltage regardless of Vcc. In any case, there is no way of measuring Aref, unless you have another reference voltage around to compare it to.


The problem is that (255/1023) is being treated as an integer calculation, meaning the result gets truncated to 0. You can make the compiler promote it to a floating-point calculation by explicitly making at least one of the values floating-point. For example:

pwm = xPos*(255.0f/1023.0f);


Uno pin 13 LED mysteriously always ON at 0.14V unless pinMode OUTPUT

The LED is driven by an op-amp (see the schematic). When the pin is configured as input the op-amp has an undefined input (floating input). Thus it may or may not turn on the LED. If you configure it to an output the op-amp is driven in a known way.

  Why is the LED on unless I set pinMode to output? Have I broken my UNO or is this normal?

It's perfectly normal.

I think they did this to stop the LED "loading" the SCK pin (pin 13), particularly if you have it configured as an input and are trying to measure something, the 1k resistor and LED would throw out the measurement.

You could conceivably have a pull-down resistor from SCK to GND, but that would load the pin as well.


How to define and use a list/array of chars using `Serial.print`

You are almost there:

Use a char* instead of char, a char can only contain one character
Use " instead of ' (Thanks Juraj)

Then you get:

const char* months[] =
 {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};


The fix ended up being to use a 220ohm resistor between D3 and GND (It has been pointed out, though I haven't tested it, that just wiring D3 to ground on startup should have the same effect). Then unplugging the USB cable, plugging it back in, then flashing the blink program to test. That got it going. I tried a 10kohm resistor too per some documentation I read but that didn't end up working. Wanted to post in case someone else stumbled on this issue.

Source

GitHub Issue

Helpful Articles:

ESP8266 bootloader modes

NodeMCU Pinout


915Mhz vs Wifi (speed impact of duty cycle limitations)

300kbps is the data transmission rate. Not the throughput rate.
That means that yes, if you only transmit for 1% of the time then for 1% of the time you are getting 300kbps - i.e., 3kbps as you correctly surmised.


Didn't have MAC address on Wiznet based ethernet shield (cloned)

Ethernet will work as long as two different machine in the LAN don't have the same MAC address, as @Nathan wrote in his answer.

The MAC address is built by two parts, a prefix which are given to manufacturers of network devices and is called OUI, and a suffix that is the node part that manufacturers can use as they wish.

If you want to build an MAC address yourself, use a Locally administered address.  Universally administered and locally administered addresses are distinguished by setting the second-least-significant bit of the most significant byte of the address.
That will make this address to not use any OUI prefix, as that bit is zero on OUI, which minimize the risk of two or more devices have the same MAC address in same LAN.

If you get the same MAC addresses you will get very strange results if they happen to be in the same LAN, I tell you.  Been there, done that, and it wasn't fun to debug.

Here are a site that looks up MAC addresses (and generate random ones).  But if you want to see which manufacturer have that MAC address, you read it from IEEE and their list.


Digital pin output voltage, not triggering 71mA relay coil

The digital output pin cannot output sufficient current to drive the relay directly. Iirc this question was already asked. You need to add between the Arduino and the relay a driving stage, for example with a FET. Or you can use a shield that already has this additional circuitry.

Just google for "Arduino relay driver circuit" and you will get various options.

This is pretty close to your setup.


Is it possible to use extra AVR Flash memory as non-volatile EEPROM-like Flash memory storage?

Yes you can. This Arduino IDE add on lets you make calls to code store in the bootload of memory so you can make changes to the flash memory.
https://majek.sh/en/writing-to-internal-flash-on-arduino/

The number of times you rewrite a cell are limited.
I'd suggest you are better off with adding a FRAM memory chip.
Get a 5V part with SPI interface. Fast reads, virtually unlimitless writes (trillions)
https://www.digikey.com/products/en/integrated-circuits-ics/memory/774?k=fram+memory&k=&pkeyword=fram+memory&pv276=15&FV=ffe00306%2C1f140000%2C1fec000b&quantity=0&ColumnSort=0&page=1&stock=1&pageSize=25


Where can I get a high-quality ADC (audio digitizer) for Arduino?

You are going to need a bigger board.

(96000000 samples/second) * (32 bits / sample) ~= 3 Gigabits/second

A poor little Arduino Uno only runs at 20MHz and can process 8 bits bytes at a time, so even if it could somehow read and store a byte every cycle, it would still be orders of magnitude too slow for your purposes.

While I guess is might be possible to build a shield with an ultra high speed ADC and on board memory to directly store the captures samples to, you probably would bother making it since the Arduino would struggle to do anything useful with the captured data even after the fact.

The highest quality audio recording shield for Arduino I've seen is a modified Wav Shield that can record 8-bit mono files at 44,100 samples per second using the waverp library.


Sorry I don't have reputation for a comment but this might be of help.

You didn't specify if the sensor was a breakout board. If it is then the board may already have the resistor in place, which is why removing it worked.

Now if you had the resistor in place when it was also connected to the nodeMCU, then perhaps power from it was high enough to still generate a stable operating condition (not familiar with nodeMCU) but more likely you have a power supply issue.

Is it a module and does it have resistor on board.
was the 27k resistor only in circuit on external power.

If the answer was yes to the above that is probably the issue.

If they are not the cause, my next check would be your external power. It could need calibration, power spikes/ripples etc but the easiest thing to do is put in a smoothing capacitor in circuit after your power supply.

Probably about 20-30% of my sensor issues are resolved by this. Another 60% are solved by fixing my screw ups and assumptions.


If you provide a password for you network, it will be encrypted. Thats the point of the password. When you look at the function description in the WifiAP.cpp file of the Wifi class for the ESP32, the description suggests, that it will be encrypted with WPA2, which is currently the standard in Wifi encryption. (Though that can depend on the actual library, that you are using)

do I have to worry about HTTPS?

That depends on your needs. In IT security is a scale, not a binary. Using HTTP on a WPA2 protected network can be considered safe on the one side and unsafe on the other. You need to thing about, if your project needs that additional layer of encryption through HTTPS.
For example: If you control your Smart Home with that ESP32, which may be able to open your windows or even the door, I would consider that critical. Then I would take every bit of security, that I can get, as there are ways to break into a WPA2 protected wifi network.
An example in the other direction: I'm currently building a game, which gets configured on a smartphone via the Wifi network of an ESP32. The network is encrypted to prevent casual attackers from messing with my current game run, but the project has so low security needs, that I will not bother with HTTPS. It's just a game, that will not that often being used, and the possibility of an attack on it is very low.
So it's about risk assessment (as with all security in IT).

if I connect from my computer instead than my phone via wifi to the ESP32 and send UDP packets will those be encrypted

The mentioned types of encryption (WPA2 and HTTPS) happen on two different layers of the network communication. With WPA2 your complete wifi data of that network is encrypted. So the UDP packet is also encrypted, but only in that wifi network, and it can be read by any authenticated user of the network. HTTPS works in a layer above that, so that your packet would be encrypted, even if it would move out of that Wifi network. For learning more about network layers, refer to the OSI model.

Apart from the security perspective: When you use HTTPS you also need to think about the certificate, that you are using. If you use a self-signed one, your browser will present you a warning about that, everytime you open that site. To prevent that, you either need to trust that certificate on all your devices, or you need to use an officially signed certificate (which might be a problem for a pure local project).


Problem with reading series of bytes over serial port

So, as result of Edgar Bonet's good remark, change

int i=0 , j=0;

to

int j = 0;

and define

int i = 0;

Outside the loop (as a global variable).

Also it is quite dangerous to define the length of the array as 10, while not checking for writing over the boundary of the array. What if you receive more bytes? The application might crash or give unpredictable behavior.


Once a message has passed through an MQTT broker there is not a way to retrieve it from the broker.

Consider instead deciding upon the action at the time the message is received by the subscriber.  If this decision needs to be made at a later time consider storing the state in the of the payload of the message on the subscriber.

Also consider running Node-RED.  If the platform running the MQTT broker can support Node-RED (such as a Raspberry Pi), it turns out to be convenient to run both on the same computer.  Node-RED contains nodes (graphical programming blocks) which can subscribe to and publish to MQTT topics.  By connecting other nodes to these, the topic and payload can be manipulated.  Of interest is an option within the Output MQTT node.  Here you can select Retain True.  This page explains how this option works:

  Once you have sent a retained message to a topic, all subscribers will
  receive that message when they subscribe.

  To clear a previously retained topic from the broker, send a blank
  message to that topic with the retain flag set.


can I design a User Interface to run on the arduino and display it with VGA?

Forget VGA. Arduino is not capable of that.

For display you can use a 16x2 LCD (only chars, not graphics) or an OLED display, which have graphic capabilities. There are in size from 0.96". There BW, but alse color models and touch sensitive ones. For input you use push buttons, or keypad.

Today best option for display is some model with I2C or SPI interfaces (to minimize wiring).

There thousand of projects in Internet. Search "Arduino OLED keypad" and you will find projects like http://www.instructables.com/id/Arduino-OLED-Calculator/:

This hardware impose some limits in the UI (thank god). What you have is a tradicional menu system: you present a menu, user choose an option, Arduino execute it. No help, no dropbox, no autocompletion, nothing, only the most basic "Press 1 for ..."

EDIT:

As Nick Gammon stated, it's possible to drive a VGA display from an Arduino, like this post and this other shows. The resolution are  20 characters wide by 30 characters deep (160 x 480 pixels) for the monochrome version and 120 x 60 pixels for the four colors version.

However, that capabilities doesn't match any of the standard VGA capabilities:

  The VGA supports both All Points Addressable graphics modes, and
  alphanumeric text modes. Standard graphics modes are:

640×480 in 16 colors or monochrome[2] (the latter matching IBM's lesser Multi-Color Graphics Array standard)
640×350 or 640×200 in 16 colors or monochrome (EGA compatibility mode)
320×200 in 4 or 16 colors
320×200 in 256 colors (Mode 13h)

The proposed alternatives achieves less resolution than a 1981 Sinclair ZX-81 (24 lines of 32 chars), takes two timers and half of Arduino RAM minimum (the color example left you with 200 bytes RAM and takes a third timer with it).

So, in practical terms, VGA is not an option.


how to send data to 15 meters with KY-005

In the emitter breakout board there is only a LED, nothing more. Comments in the linked page of the supplier states, that the 5V pin of it is not connected to anything. This means you are driving the LED directly from the Arduinos pin, which cannot provide more than 40mA. The supplier states a forward current from 30 to 60mA. You can use a small MOSFET in combination with a resistor, that limits the current to maybe 55mA, to drive the LED indirectly.

With this you won't fry the pins hardware and can provide more current, which means the LED can shine brighter. If you can find out, what LED is actually used for this board, you can refer directly to its datasheet. I couldn't find a part number at the site.


You can't.  Not without physical modification to the PCB itself (remove the chip, scratch off a pad and trace, replace pad with fine enamelled copper wire tinned at the end, replace chip).  All you can use is whatever firmware is currently installed in the module.


Arduino Uno pin dead for no reason. Why?

I have quite a few Arduinos lying around and only one has failed completely, which I think is because I "zapped" it with static electricity, which is a problem, as Chris Stratton suggested.

Make a habit of grounding yourself before handling electronics, for example by touching some metal (earthed) part before reaching for your Arduino. Don't work while standing on a synthetic carpet, for example.

  but what causes my pin 5 to be dead?

Possible reasons:

static electricity
accidentally shorted an output pin to ground, which could damage the output driver if you are outputting HIGH
accidentally connected an output pin to +5V, which could damage the output driver if you are outputting LOW
connected the pin to a negative voltage
connected the pin to more than +5V
powering the board "parasitically" which means connecting power to the data pins before connecting power to the main power input
tried to "sink or source" more than 40 mA which is the absolute maximum rating. For example, connecting an LED directly to the pin without a current-limiting resistor

The other link he refers to: Bad LCD? Bad microcontroller? Or what?


Get TSOP1738 or any good IR receiver to decode. Above code is appropriate and does not need any changes. you will surely get some fluctuations and different decoded hex codes but it would provide only 2 different values for single button so that while controlling any device using ir , you can use 'or' operator in conditional statement and hence you will get desired results.
Getting absolute results from a cheap IR receiver is a myth.But it will work well for your project at lower level.I had worked with that and my device is working in my room with no difficulty.


Most likely a short between VCC (5 volt) and GROUND. When there is a short the fuse will kick in after a second, and disable the whole board, including the ON-led.

When you disconnect the board, the fuse will reset.

So either the board is faulty of the connection you made to it are.


A fixed sampling window can be hard to manage, especially if you want the calculation to be recursive, for space and speed considerations.

You can achieve similar results via exponential smoothing.

Yn = (1−α) Yn−1 + α Xn

Where Yn is the smoothed outcome, Xn is the current measurement, and α is the weight.

With some thoughts, it can be done with integers and without loss of precision.

edit: i ran a comparison of exponential smoothing vs. (fixed window) moving average. The moving average algorithm was written to be recursive for maximal speed.

the sampled data is a simulated sine wave:

1000 * sin(2pi*n/100) + 100 * noise. n = 0..19999, and noise = -0.5...+0.5.

So snr = 1000 / 50 = 20:1, or about 5 digits. far worse than what you would encounter in a 10-bit adc.

the window I picked is 4.

As you can see, both approaches closely resemble each other. exponential smoothing uses much less ram and is also much faster. older data has lower weight on the output, something generally desirable in most applications.


Is it possible to upload a file with GPS values onto my arduino?

The Arduino does not have a file system per-se, to which you could upload files, unless you create the code that does that. There is "EEPROM" space on the Arduino processor that can hold 1024 bytes of data and survives power-cycles. That should be sufficient to hold 20 lon/lat pairs of sufficient precision.

As for how to get the waypoint data onto the Arduino, you could transfer them over the serial port from your computer, either by manual entry from your computer over the serial monitor of the Arduino IDE or by writing a script in Python or some other language to read the waypoint file and transmit the data according to the protocol you invented.

There are are also SD Card peripherals you can add to an Arduino, so you could potentially just load the waypoint file onto the SD Card from your computer, and then insert the card into the SD Card reader on the Arduino and have it read the data from there.


How to include userid, pass to WifiClient connect() api

WifiClient provides low level tcp connection. Your server seems to be implementing a REST API interface. Thus you need to construct HTTP headers (GET, POST, etc.) manually as a string. Then you can add your credentials. Before doing so, try to use your server, I mean call api's with the program named Postman. Postman runs on Chrome browser. Postman can compose such headers for you. Then you can insert them into your arduino code.


Digispark / DigiKeyboard change keyboard layout

You can edit the file scancode-ascii-table.h in your DigiKeyboard library.
It basically states which ASCII code corresponds to which keyboard scancode.

So if you try to print the ':' character but get a '>' instead, you know that in the above mentioned file at the ASCII position for ':' is the scancode for a '>'.

Using this, you can swap the scancodes around and basically create your own 'mapping'. For example, if you swap the values at ASCII 89, 90 and 121, 122 you for example solve the Y/Z switch.

However, I have not figured out how to correctly print a backslash. You might have to map that do a different ASCII character you don't need.

To add to this answer, there exists a workaround using mame82's duck2spark:
https://github.com/mame82/duck2spark


You need to send two bytes - a high byte and a low byte.

There are two things you need to know with SPI:

You must wait for one byte to finish transmitting before you send the next
The whole transaction needs to be wrapped with a digital chip select signal.

So you have:

Chip Select idles HIGH
You lower Chip Select
You send one byte
You send the other byte
You raise chip select

At the receiver you:

Wait for chip select to go low
Receive one byte
Receive a second byte
Chip Select rises
You combine the two bytes together into one integer.


Not sure if programmer or ATMega is burned

The Arduino IDE ships with a built in ArduinoISP sketch, and there is a very detailed tutorial with wiring diagrams etc on the Arduino site.


Read time digits from DS1307 and run code based on return

You can set up an array containing the bit patterns to turn on different digits, and then use code that sends the bits for the high digit of now.hour()/12 and the bits for the low digit of now.hour()%12.  For example:

const byte digiBits[] = { B0000, B0001,
// and so forth for all the digits ...
};

void send1Digit(byte digiVal, byte whichDigit) {
  // somehow use whichDigit to direct the bits someplace...

  // To send the bits:
  byte bits = digiBits[digiVal];
  for (byte i=4; i<8; ++i) {
    sr.set(i, bits & 1);  // Set a bit in SR to 0 or 1
    bits >>= 1; // shift out the used bit
  }
}

void send2Digits(byte numVal, byte whichDigit) {
  send1Digit(numVal/10, whichDigit);
  send1Digit(numVal%10, whichDigit+1);
}

void loop() {
  // other stuff, then:
  send2Digits(now.hour(), HourSpot);
  send2Digits(now.minute(), MinuteSpot);
  send2Digits(now.second(), SecondSpot);
  // other stuff ...
}

Note 1:  If your sr.set() routine is doing any complicated masking or shifting, you may be able to avoid some of that by ORing digiBits[digiVal] with whatever number sr.set() might be building up to shift out.

Note 2:  If the numerical value of digiBits[digiVal] is equal to digiVal, then don't bother defining digiBits[], but instead in send1Digit() just say byte bits = digiVal, or use digiVal directly in place of bits.


Number of digits setting for serial printing the sensor output value

You can use the C function sprintf:

char text[5];
sprintf(text, "%04d", number);
Serial.println(text);

The leading 0 in 04d will add zero's for the length (4) is met, so 1 will become 0001, 10 will become 0010, 100 will become 0100 and 1000 will stay 1000.


How do I connect a vibration motor to Arduino?

Lets break down the circuit and have a look why everything in that circuit is there and what it does.

First we have the 33R resistor before the motor which limits the current to the motor. This particular motor is rated at 75mA and has a starting of 85mA. The 33R resistor limits the current to 130mA maximum through the motor. If the risk of the motor pulling too much current is an issue then stick a fuse in-line

Then there's the motor, not much to say here really. It's whatever motor you're using.

We then have both a diode and a capacitor across the motor. I find this a bit strange, I've seen the use of flyback diodes, I've seen the use of snubbers, but both? The purpose of the diode is to allow a return path for any spikes caused by switching off power to the inductive load (the motor) which stops them from damaging the transistor. For the capacitor, just remove it, it's not got any use here really.

Then comes the transistor, it might be easier to think of a transistor as a switch (especially in this example). When you put a little bit of current on the base, the transistor 'opens' allowing the motor to connect to ground. The reason we have to use a transistor is because the outputs of an arduino are only able to supply a maximum of 40mA, we need more than that to run our motor. Fortunately, the transistor is not going to need any more than 5mA on it's base which is why we use it to 'switch in' components that require more voltage/current. The 1K resistor on the base is to limit the current coming from the arduino and preventing it from killing our poor transistor.

tl;dr - You need everything except the capacitor


How to prevent the garbage data when the serial port is initialised?

There are probably a number of reasons that might contribute to the problem that you are observing:

You are trying to send the string "Text" within the main loop without any delay between println calls. So the microprocessor is running at full speed and trying to send the string "Text" much faster than the baud rate can accommodate. The serial interface has a finite I/O buffer, which is probably filling very fast and overwriting old values in the middle of serial transmission. Hence potentially garbage characters.
Even when HyperTerminal is not running, the PC and Arduino are exchanging serial messages. So when you start HyperTerminal at some arbitrary time, the data in the serial buffer might not correspond cleanly to the start or end of a transmission.

As an alternative, you may want Arduino wait for a serial command from the PC before starting to send the serial data. For example, when using the Serial Monitor, you may send a key press to Arduino, which would then start sending data so that no data is lost while there is no body listening on the PC side or while a terminal program is not running.

Finally, flushing the serial buffers on either side of the serial connection might help you clear partial serial messages.


Uploading/Flashing different programs to two different Arduino uCs, using one USB

Provided that you are okay with producing a customized PC side tool (which you would probably want anyway for user convenience) automated target selection should be far superior to manual.

You should be able to use one ATmega16u2 with a  minimally customized firmware as a front end to program two distinct ATmega328p's.  This could be as simple as selecting the target based on the baud rate, having it hold the de-selected one in reset the whole time, and using some resistors on the shared TX lines for safety.  Last I checked the stock firmware used a soft serial at some rates, and that can be put on different pins, so it could be another way to de-conflict and select targets.

Your idea of using a 32u4 both as a functional part and as a buddy-programmer for another part is perfectly valid too - you can do that programming to a serial bootloader (it should be a simple matter to port the 16u2 firmware, or find another example), or via the ISP pins.

Now that I think about it, there's been a version of this question here before, as I remember writing about an idea for using two ATmega328p's permanently wired to a stock USB-serial, but with their bootloaders customized to use unique baud rates, and a little logic added so that on reset each would leave its serial TX pin tristated if it didn't detect bootloader traffic at its individually unique baudrate, thus allowing the other to be programmed without interference.


Arduino Due Digital Inputs without Response

A good practice is to set the pin mode for all the pins used by the sketch.

void setup() {
    Serial.begin(115200);
    while(!Serial);
    pinMode(34, INPUT);
    pinMode(35, INPUT);
    pinMode(36, INPUT);
    pinMode(37, INPUT);
    pinMode(LED_BUILTIN, OUTPUT);
    Serial.print("Test");
}

The Arduino AVR core does set the pin mode to INPUT by default but the Arduino SAM core does not. The SAM MCU is much more advanced and allows turning on and off the ports, and a lot of other functionality.

Cheers!


can i use bluetooth from a speaker as a bluetooth module?

Bluetooth actually uses many different protocols to support many different Bluetooth applications.  For 2 channel good fidelity music with high latency and a very low bandwidth return only suitable for short infrequent commands like PAUSE and PLAY, most use A2DP or Advanced Audio Distribution Profile.
As most Arduino platforms use very low powered processors, good fidelity sound manipulation is not possible or is very difficult.  This only leaves the very low bandwidth return channel only suitable for short infrequent commands.  If you can imagine a use case for this channel it may be possible to use a low powered Arduino to send these PAUSE, PLAY, STOP type commands.
That said, you may want to buy a new well supported (in the Arduino community) Bluetooth module which uses the HID (Human Interface Device) protocol so you can build a keyboard for example or which uses the SPP (Serial Port Profile) protocol so you can build something that sends arbitrary data.
Added later...
I see in the diagram that there may be an "microphone in pin".  If true this hints that the module also supports the Bluetooth HFP (Hands Free Profile) protocol.  This is a lower fidelity 2 directional low latency audio channel with a very low bandwidth return only suitable for short infrequent commands like ANSWER and HANGUP.  Instead of music this is used to make phone calls.  This might be of more interest to Arduino project builders as this might be made into an intercom.


It's basically a push button. Possible examples depend on what you want to do. As it seems, you simply want to start interfacing it with Arduino, just use it as a normal push button. Use the DigitalInputPullup example, that comes with the Arduino IDE:

Middle pin to pin 2 on the Arduino
One of the other pins to ground (depending on which state you want to be reflected with a HIGH in the Arduino)
The other pin unconnected

Look at these two schematics. The left one is a normal push button. It connects, when pressed and disconnects, when released. The right one is your button. When pressed it disconnects the upper  pin and connects to the lower pin. When released vice versa.  When you don't use the upper pin, your button behaves just like the push button on the left.

simulate this circuit – Schematic created using CircuitLab


You are trying to use millis() exactly like delay().  The method delay() stops the program from progressing forward.  It blocks the program.  This is frowned upon as the processor could be doing something useful during this time.

The method millis() does not stop the program.  Instead it is like telling you what time it is.  It is your code that then need to know at what time you want to do something.

But in your code, you are doing something odd.  You are switching the brightness of the LEDs then IMMEDIATELY switching them back.  You are using the same time for the two things you want to do.  Instead try to initialize previousMillisLED4 to 500, intervalLED3 to 1000 & intervalLED4 to 1000.


RadioHead Library custom configuration for RFM96 LoRa

Parameter in RH_RF95.h

const RH_RF95::ModemConfig myProfile =  {
  RH_RF95_BW_62_5KHZ | RH_RF95_CODING_RATE_4_5,
  RH_RF95_SPREADING_FACTOR_1024CPS};

rf95.setModemRegisters(&myProfile);


How to read incoming HEX values from Serial.read() method?

Your problem is, that you try to provide a HEX value, but you are actually providing a decimal value.
When you just write a whole number like 32, it will be interpreted by the compiler as a decimal number. The decimal number 32 is equal to HEX 20, which is a space character in ASCII.
Solution: Write your number as decimal value like this:
int i = 0x32;

The 0x preceding the value will mark it as a hexadecimal representation.


Broadcasting parallel data from Arduino using router

Use a NodeMCU (ESP8266 based) because it have WiFi included. It can work as a light web server. You can serve HTML, but not large files (like many .js).

Instead of HTML you can use websockets to get only data from NodeMCU and all the other files (html, js, images) from another bigger server. Websockets is fast, but you still have to deal with .html, .css, .js and other files in your webserver.

If you want something even easier and lighter, take a look at MQTT, which was developed with IoT in mind.

There is lot of MQTT client for Android/Iphone/PC/Mac. You use your client to send data and commands to your NodeMCU. No need to program anything here; you simply construct a visual interface by adding controls (buttons, meters) to a blank slate. No brains job.

You will need a broker, a server that acts as a relay, receiving commands/data from your Android and resending it to your NodeMCU. And your NodeMCU can publish temp, humidity, light levels and other data to your broker. You can use multiple client at once. There is no limit.

Your broker can be an public Internet broker (many) or a private one in your LAN. There is many brokers available for different platforms. You can run one in your smartphone or any old PC. Mosquitto is a free one.

Depending on your configuration, you will be even able to access your green house from Internet and look at your girls from far away.


Help with multi function momentary buttons

Don't act immediately when a button gets pressed, instead when a button is pushed all you do is set the timestamp on that button and set a flag.

Then when it is released or the time elapsed is large enough do the appropriate thing.

void loop(){
    int btn1State = digitalRead(btn1);
    static bool button1 = false;
    static unsigned long time1 = 0;

    if (btn0State == LOW && !button1) {
        button1 = true;
        time1 = millis();
    }

    if (btn0State == LOW && button1) {
        if(millis() - time1  > SHORT){
            //do long action
            time1 = millis(); //reset timer
        }
    }

    if (btn0State == HIGH && button1) {
        button1 = false;
        //do short action
    }

}


As Jaromanda X pointed out in the comments, sizeof(array[0]) (size of first element) will not return the size of the literal strings, but the size of a char pointer.

It doesn't work (whatever that means for you), because sizeof(devices) doesn't return the number of entries in the array, but the size of the array in bytes, e.g. something like (following is wrong: 24 (1 byte per character plus 1 byte with the concluding null character for each string) ) 6 (The size of a char pointer is 2 bytes on most microcontrollers; I'm not sure, if this is the same for Node MCU). So after 3 iterations (which can use the string literals in the array) currentDevice doesn't go back to zero, but counts further. With the access to the array with exceeding index you are accessing memory, that doesn't belong to the array anymore (e.g. random data).

There is no native function, that gives you the length of an array. But it can be calculated with sizeof(array)/sizeof(array[0]), which is the size of the array in bytes divided by the size of one element in bytes. In your case you would have an array size of 6 and an element size of 2, resulting in a calculated element count of 3, which is correct.

Another simple solution, which is easier to understand for beginners, but not as flexible, is to set a constant or define, that contains the size of your array. You can then use it in your code, whenever you need the size, including, when you define the array.


SparkFun BasicAHRS_I2C giving unstable readings

If you haven’t noticed the difference in the two is minuscule.
For example, the change in degree is <1. Also the acceleration is measured in g’s which is acceleration due to gravity. The data says the measures are in mg which is 0.01g.
This is normal with accelerometers and all sensors when they pick up residual voltage from random vibrations or other sources of noise. It also could be with the error margin within SparkFun’s product since the product is more on the lower end of quality which once again is normal.
TLDR: everything is working fine.


Inheritance: error in calling the constructor of the base class?

#include "../Adafruit_NeoPixel/Adafruit_NeoPixel.h"
#include "../IRremote/IRremote.h"
#include "../DS3231/DS3231.h"

What you're doing there is telling the compiler where, relative to where it's performing the compiling (or one of its include directories), the header files you list are.

What you're not doing is telling the IDE where the CPP files are to compile and link with your sketch.

When including anything external to the sketch folder that is more than just a header file you must treat it as an Arduino library - that is, place it in one of the standard library folders and name it properly (libraries should be named LibraryName/LibraryName.h).

Then you include the libraries properly:

#include <Adafruit_NeoPixel.h>
#include <IRremote.h>
#include <DS3231.h>

You must do that in both your sketch and your custom library.  That way the IDE knows where to look for the files to compile - the compiler doesn't understand the concept of an Arduino library (and thus the CPP files associated with a header file) - that is purely down to the IDE gathering the data by examining your sketch and locating the right files to then pass to the compiler.


Yes, it is possible, and you've done it almost right. I made a minor correction in the toMove() function ("int" instead of "var"), and supplied the setup() function which you didn't show. It compiles without error. I didn't check it for correct operation as it looks like you had reduced your code to the minimum example necessary to demonstrate your question -- and thanks for that! Here is what I compiled:

#include <Servo.h>

#define SERVO1      9
#define SERVO2      10

/*****< External and Global Declarations >*****/
Servo s1, s2;
void toMove(Servo obj, int inPosition, int forPosition);

/*****< Local Function Prototypes >*****/

void toMove(Servo obj,int inPosition, int forPosition){
int i = 0;
  for(i = inPosition; i<forPosition; i++){
    obj.write(i);
  }
}

void setup()
{
    s1.attach(SERVO1);
    s2.attach(SERVO2);
}

void loop() {
   toMove(s1, 0, 180);
   toMove(s2, 0, 90);
}


The voltage regulator on the Arduino is designed to power the logic circuits, and perhaps a few LEDs and other digital devices. It is not designed to power 5 motors.

You haven't specified what current they draw - that is the important question, not the voltage.

As the comments under your question have said, you need to power the motors separately from the Arduino, not through it. However, connect the ground wires, and use the Arduino to control the signal wire to the servos.

The graphic below shows the general idea. For 5 servos even those batteries are probably not enough.

Notice that the power for the motor does not go through the Arduino.


connection for hall sensor 4 pin and arduino nano

The board you have has two outputs - AO and DO (note, those are the letter O not the number zero - for output).

You can connect AO to any of the analog inputs on your board if you want to read a discrete analog value from the sensor.

You can connect DO to any of the digital inputs (or analog ones since they are also digital inputs) if you just want a simple "Something is there" signal.

The sensitivity of the "something is there" is controlled by the trimmer on the board.

The simplest way of doing what you want is to use DO and adjust the trimmer to suit. Then the sensor looks, to all intents and purposes, like a switch or a button (but you don't need the pull up / pull down resistor).  So you can leave AO disconnected.

Note that using D0 (zero) and D1 (one) on the Arduino is discouraged since they are connected to the USB interface and using them can affect your ability to upload sketches. It also means you cannot use any serial communication in your program.


Maybe doing 100kHz PWM with timer2 instead of timer1 would be good.  The registers look similar to timer1, but they are only 8 bit, so you can't go bigger than 255 in the compare and count registers. The prescaler would be the same, and the timer controlled pins would be D11 and D3:

  //// pwm settings for 100kHz on Timer 2
  //// Toggle OC2A/D11/PB3 at 50kHz, PWM OC2B/D3/PD3 at 100kHz:
   DDRB |= bit(DDB3); //Enable output
   DDRD |= bit(DDD3); //Enable output
   // WGM2x=0b111 for fast PWM with TOP=OCR2A
   // COM2Ax=0b01 for toggle OC2A at OCR2A
   // COM2Bx=0b10 for set@bottom-clear@match_OCR2B PWM
   TCCR2A =   bit(WGM21)  | bit(WGM20)
            | bit(COM2B1)  // PWM on OC2B
            | bit(COM2A0); // Toggle OC2A
   TCCR2B =   bit(WGM22) | bit(CS20);  // Set /1 prescaler
   OCR2A  = 159;       // 16000000/(PreScaler *Ftimer)-1
   OCR2B  = 10;        // 6.25% PWM
   TCNT2 = 0 ;

I haven't tested this on an Uno/Atmega328P, but it looks reasonable per the datasheet (p153-157).

If you don't want both the 50kHz toggle and 100kHz PWM outputs, (as in your posted code,) you could disable one or the other and adjust the frequency as needed.


Arduino Pro Mini maximal and recommended current per pin

It is the amount of current the pin can source or sink when in OUTPUT mode.

That is, the amount of current that can flow from the pin to ground, or can flow from VCC into the pin.

You can understand it better if you learn how a GPIO pin works.


Because you have an Arduino Mega, you can set it up to use it like a USB-to-UART adapter by using the following code (source):

void setup() {
  // initialize both serial ports:
  Serial.begin(9600);
  Serial1.begin(9600);
}

void loop() {
  // read from port 1, send to port 0:
  if (Serial1.available()) {
    int inByte = Serial1.read();
    Serial.write(inByte);
  }

  // read from port 0, send to port 1:
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial1.write(inByte);
  }
}

Basically what this does is it takes the data it receives from the USB port via Serial and transmits it to Serial1 and then also reads from the UART port via Serial1 and transmits it back to the computer via Serial. With this code running you should be able to hook up the XBee to RX1 and TX1 and communicate to it using the Serial Monitor.


What does it mean in I2C, "NACK received"?

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

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


Communication between IC and microcontroller (Teensy 3.2)

You seem to be overlooking (or at least mishandling) the fact that these parts are built with a bus interface where the /OE and SEL signals as well as the internal position data latch are sampled synchronously with a clock input which you do not seem to be driving.

You need to generate a low-to-high transition of the CLK signal to latch the count into the readout
You need to generate a high-to-low transition of the CLK signal to latch in chosen values of the /OE and SEL signals.

On second examination of your code, perhaps you are trying to use a free-running clock asynchronous to your reading.  That, however, is extremely unwise.  First, you don't know that a suitable clock edge will happen between when you set the /OE or SEL and when you try to read the data.  Next, you do not know that an undesired clock edge will not happen in the midst of reading data, causing you to end up with a corrupted value that contains some "old" bits from before the clock edge and some "new" bits from after.  This would be particularly bad if it happened across a transition such as 0b01111111 to 0b10000000 or similar...

You may have other problems as well - your question is not complete without a schematic diagram of how you have wired up this chip.


Can someone help me figure out why only one wheel is spinning?

Firstly, the 9V batery is going to struggle with driving two motors. Change this 9V battery out with another power source.
As @timemage points out in his comment, you are using a PWM command on a non-PWM pin. For the Arduino Uno, the PWM pins are: 3, 5, 6, 9, 10, 11. Move the wiring and change the code so that it is using pin 9, 10 or 11 instead of pin 4.
It sounds like you are trying to test your hardware setup and your firmware at the same time. It is much easier to test your hardware first and make sure that works as expected before testing your firmware. I suggest writing a simpler program (the simpler the better) that just drives the motors full forward - one at a time and then together. Verify that it works and then change your test program so the motors spin in (full) reverse. Then change your test program so it changes the speed of the motors. Then with known working hardware test your firmware.


You can build your project on stripboard (aka Veroboard, which is a particular brand). The wiki page at http://en.wikipedia.org/wiki/Stripboard covers most of the salient points - it is essentially a generic PCB. You can cut tracks, either with a knife, or a specialized tool, and you can solder your parts on to the tracks.

They come in various configurations - my personal preference is just straight strips - and you can cut them to size with a hacksaw.

If your project is non-trivial, you might still like to spend some time working out a decent layout. There are free, and not quite free, products to help you - I use Kicad, which is free & opensource, there are many others.

I have also used stripboard to group a few components together - for example, 2 7-segment displays and two SIPO chips to run them - this can then be a "component" for future bread-board projects.


Arduino Mega vs. RasPi Pro Cons in 3D Printing

A mutli-tasking operating system such as the Linux normally run on the pi is not particularly suited to doing hard real-time control such as coordinated pulse generation for multiple stepper motor axis trying to move as quickly as the rigidity and motor power will permit.

It is possible to use realtime extensions to the Linux kernel to get reasonable performance.  And it is also possible to run something simpler than Linux on the pi.

However, it is also possible to use a far cheaper processor to get the actual G-code execution done (you don't really pay the Arduino cost premium when buying an ATmega on a dedicated board, so it's only a  dollar or three more expensive than it "should be").  If one were to design printer electronics from scratch today, there are probably better choices, such as as ARM Cortex M0, M3 or M4 - but most of the printer designs came out of the same community where Arduino was a familiar choice, and there are probably more people willing to try to make small personal customizations to an Arduino codebase than there are willing to install the toolchain for a perhaps technically better, but less familiar solution. .

People do use Raspberry Pi's with 3d printers quite frequently though - they just use them for a different job: that of slicing and motion planning and potentially functioning as a network print server, which then drip-feeds the G code to the simpler (ATmega or whatever) based realtime executive.  In effect, they use a pi as a cheap PC to host the ATmega-based printer, rather than dedicating an old PC to that job.

Ultimately, the rarely taken alternative of using a realtime Linux kernel extensions to control motion directly from a pi, vs the more common one of using an ATmega as a realtime motion delegate for the pi, are conceptually similar - it's just that in one case the realtime executive engine is a highest priority task on the main processor, and in the other it runs on a dedicated motion co-processor.