Can you fry an arduino with nothing plugged in to it?

Although the controllers on an Arduino are pretty well protected, they can still be damaged by ESD (Electro Static Discharge). The same effect that makes a crispy sound when you pull off your woolen sweater in the winter, or after walking with rubber shoes on a carpet and you touch someone else or a metal and grounded object and you feel a pick. Static electricity can damage the controller. It may get completely broken, or it may function 'most of the time' or lifetime may be shortened.

An Arduino is also easily killed with an piezo gas lighter, just make the spark near the copper traces that feed directly in the controller. This is largely the same effect as above.

Again, the controllers themselves are pretty well protected, don't worry too much about them. But with kids running around (on their rubber shoes) better make sure they don't accidentally draw a spark from their little finger to your Arduino. The protective metallic bag is best, but putting it away in a cupboard or box should do the trick equally well.

As a general rule of thumb, the faster the electronics, the more sensitive it is for ESD. A Due is probably more sensitive than a UNO or a MEGA. But with normal, avoiding static electricity, use you should be OK.


In Linux, how do I get this Arduino library to work

What's causing the problem is that the folder name inside the zip has a hyphen in it, just extract the folder from this zip and rename it to timer instead of timer-master. I just imported it on Fedora 20.


Can we control an Arduino with voice commands?

Yes possible on some of the high end Arduinos, but I know of no example where it has been done. The quality of recognition will be proportional to the processing power provided. In the case of an Arduino, probably not at an acceptable level.

You would be much better off looking at the multitudes of PC solutions, and using the Arduino as an interface to what ever it is you plan on controlling.

FYI: https://www.sparkfun.com/products/13316


NodeMCU (ESP8266) Defining static IP, stops Firebase processing

You have wrong DNS server IP address. In your sketch it is the same as the static IP address you assign to esp. Then the name of the firebase host can't be resolved by DNS.

The DNS server is usually the router/gateway.

IPAddress dns(192,168,1,1)


Atmega2560 USART UDR r/w conflict possible?

Is there any possible way that data written to the UDR register could somehow be read out again?

No, there is no possibility. The datasheet says:

  The USART Transmit Data Buffer Register and USART Receive Data Buffer Registers share the same I/O address
  referred to as USART Data Register or UDRn. The Transmit Data Buffer Register (TXB) will be the destination for
  data written to the UDRn Register location. Reading the UDRn Register location will return the contents of the
  Receive Data Buffer Register (RXB).

Further on it says:

  The transmit buffer can only be written when the UDREn Flag in the UCSRnA Register is set. Data written to UDRn
  when the UDREn Flag is not set, will be ignored by the USART Transmitter. When data is written to the transmit
  buffer, and the Transmitter is enabled, the Transmitter will load the data into the Transmit Shift Register when the
  Shift Register is empty. Then the data will be serially transmitted on the TxDn pin.

And for reception it says:

  The receive buffer consists of a two level FIFO. The FIFO will change its state whenever the receive buffer is
  accessed. Due to this behavior of the receive buffer, do not use Read-Modify-Write instructions (SBI and CBI) on
  this location. Be careful when using bit test instructions (SBIC and SBIS), since these also will change the state of
  the FIFO.

So the only thing it is possible to read is data that has been received via the RX pin (and then once and once only). All written data (assuming there is room in the TX buffer) is sent out of the TX pin.

If you are getting TX data appearing in the RX buffer then somewhere there must be some kind of connection between the TX and RX pins - either in software at the remote end (the remote device echoing everything it receives, which is perfectly possible depending on what the remote device is), or though a fault in the cabling or circuit design.


Reading values from the register of a slave

For reading non-consecutive bytes, the “normal” way would be to do a
one-byte request and a one-byte read for each byte you want. However, if
the bytes you want are close enough (e.g. you want every other byte), it
would be faster to do a contiguous read and just ignore the bytes you do
not want. E.g.:

byte data1 = Wire.read();  // read first byte
Wire.read();               // read and ignore second byte
byte data3 = Wire.read();  // read third byte

For your question regarding the meaning of
Wire.read()<<8|Wire.read();:

Wire.read() return a 16-bit integer, where the 8 most significant
bits are zero and the 8 least-significant bits contain the actual
data. In binary, it's something like 00000000xxxxxxxx, where x
are the data bits.
<<8 means “shift left by eight positions”, where the missing bits
are replaced by zeros. Thus Wire.read()<<8 is xxxxxxxx00000000
in binary.
The second call to Wire.read() return another 16-bit integer in the
form 00000000yyyyyyyy.
The vertical bar | is the bitwise-or operator: each bit of the left
operand is or-ed with the corresponding bit of the right operand to
give one bit of the result: x or 0 is x, 0 or y is y.
Then, the whole expression gives xxxxxxxxyyyyyyyy, where xxxxxxxx
comes from the first Wire.read() and yyyyyyyy from the second.

The problem here is that the “first” and “second” Wire.read() in the
sentence above refer to the position of the call in the line, not to the
actual order in which the calls are performed. Thus you may be lucky and
get the the correct byte order... or not. You should instead do a single
read per statement if you want to control the byte order. For MSB first:

AcX = Wire.read() << 8;  // read most significant byte first
AcX |= Wire.read();      // then least significant byte

And for LSB first:

AcX = Wire.read();        // read least significant byte first
AcX |= Wire.read() << 8;  // then most significant byte


Failed to read DHT22 sensor using Intel Galileo Gen2 board

The article link by Nick is the same that I found, so it must be a well search problem.
What is described on the Intel forum is that the Galileo is not capable of direct communication with the sensor as it is a computer and not a microcontroller, so therefore lacks the ability for accurate timing required by the sensor and also the DHT* is considered a peripheral and would thus require a way to interface with the "PC".
What is described in the post is to use two pins to create the proper digital signal for the DHT.
The circuit makes use of a diode to protect the output pin.
The OP on the forum describes the connections like this:

Pin 2 of Galileo is connected to the data pin of the DHT11.
Cathode of the diode is connected to pin 3 of the Galileo.
Anode of the diode is connected to the DHT11 data pin.

The diode would be a standard diode, possibly a fast switching signal diode as the 1N4143. The resistor would be the standard pull up resistor of 10K Ohms.
Here is the OPs schematic:

(source: intel.com)
You will also need to make use of the code linked to by the OP in the linked post as it was modified to work with the workaround.


Not with the Serial Monitor built into the Arduino IDE. It is possible to use an external terminal program with buffering disabled though.


Difference between Ultrasonic sensor and Distance Sensor?

An ultrasonic sensor can usually develop and receive high frequency sound waves.  They can be used to measure distance by measuring the time of flight of the sound wave.

distance(meters)  = [speed_of_sound(meters/second)][1] x time_of_flight(seconds)
distance(meters) = 343(meters/second) x time_of_flight(seconds)

For example, say the time of flight was 0.01 seconds.

distance(meters) = 343(meters/second) x 0.01(seconds)
distance = 3.43 meters

This is just one way distance can be measured by a processor.  Other ways use different types of radiation such as electromagnetic radio and light radiation.  Some of these use time of flight. Others use more exotic phase techniques.  These types of detectors can be very accurate over long distances.  But are usually very costly.  They are commonly used for automated car driving.

A completely different approach uses triangulation or parallax of a light beam and a focused linear array light sensor.

These types of detectors normally operate over short distances and are cheap to make.  They are commonly used in places like copier machine to detect objects and paper.  Or in automated vacuums cleaners to detect floor edges such as stair drop offs.


How to Specify Array Length during Object Construction within Arduino IDE?

Another way is for the caller to provide the memory as a pointer to enough bytes for 'N' objects (cast, if necessary, as a pointer to the required type), and the number, 'N' of such objects. This gives the caller the choice of whether to allocate statically or dynamically.

It looks like you want an array of ints. So you'd allocate an array (statically, in my example, but you could choose whichever best fits your application):

int memArray[N];
// ...
myClass(N, memArray&);

I avoid allocating memory from the heap, but someone else might have a different preference or a situation that requires it; this technique lets the library work for either.


Sense distance with Bare Conductive's Touch Board

As a member of the Bare Conductive team, I can tell you that looking at the grapher will be helpful to you. The grapher is a processing sketch that requires the Touch Board to be running the Datastream code. Datastream will give you the sort of raw electrode data that you're looking for.


The series resistance is 220 Ohms (Red, Red, Brown).

You also need to take into account the thermistor resistance at 25C. Assuming its 10K. Hence choosing a 10K series resistance will make the calculations easier.

     int THERMISTORNOMINAL =  10000;
     int SERIESRESISTOR = 10000;
     int TEMPERATURENOMINAL = 25;

     a = 1023 / a - 1;
     a = SERIESRESISTOR / a;
     tempC = a / THERMISTORNOMINAL;     // (R/Ro)
     tempC = log(tempC);                  // ln(R/Ro)
     tempC /= Beta;                   // 1/B * ln(R/Ro)
     tempC += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
     tempC = 1.0 / steinhart;                 // Invert
     tempC -= 273.15;                         // convert to C


Record video with CMOS camera using Arduino

Arduinos have two major drawbacks:

Not enough memory.
Way too slow.

There's a shield to help you do that:

http://nootropicdesign.com/ve/
http://blog.arduino.cc/2011/03/24/arduino-computer-vision-with-video-experimenter-shield/


ATtiny84A support with "Attiny" board manager installed to Arduino IDE

According to the PDF ATTiny24/44/84 to ATTiny24A/44A/84A Migration AppNote it should be pretty easy as there are only some differences in electrical specifications. No changes in registers or so.

The signature bytes are the same too, so it should be posible even without adding another boards.


I understand your question to be :  you want to latch (and indicate) whenever an external watchdog timer has reset your Arduino.

D type flip flop (latch) can be used.  You would use the clock input as the trigger. However, most D types clock on a rising edge. You could use an inverter on the input to the clock to get the D type to clock on a falling edge. You would also connect the D (Data) input high (logic 1). Then when your input (event) goes low, the Q output will latch high.  The 200 mS is irrelevant because the latch ocurrs at the change from high to low (low to high on clock input).

You would also need a means of resetting the latch, which many D types have a reset input or a clear input.

You could also use a more simple SR latch (set reset latch) using 2 Nand gates.  SR latch changes state when the “set” input goes low (providing that R input was high).  Make the R input go low to reset the latch.

POSSIBLE ALTERNATIVE :  If you have some means of operator intervention (or even a switch).  You could have your program light an LED at startup.  Operator (person) could reset LED.  Then afterwards,  any reset (restart of program) would light the LED.


need to make my partners pill box turnover sensitive

I wouldn't go with a "turn-over" sensor, but would just use a (big) button. I'd go with something like an ESP8266/ESP32. Those can connect to WiFi. Then have it send a push notification when being pressed (that is; the pill has been taken). Maybe light up an LED to also indicate the pill has been taken. Turn off the led at midnight. Also send a different notification when the button hasn't been pressed before, say noon.
For push notifications, you can use PushSafer, PushBullet, or Prowl (which I had most success with).
Have a look at Kevin Darrah article, and youtube channel. He uses it's own boards, but most of the code will work on any ESP board.
But try to imaging how the system would work, in your head first. Just throwing technology at a problem isn't always the best solution. My grandma has 7 pill boxes, one for each week. Which helped to keep track of whether a pill was taken that day.
Best of luck.


Disclaimer: I know nothing about this media player except what's in this question.  I'd never heard of it before.  The following is simply from observation of the code you posted.

Look at your play_pause() function where the meanings of all the elements are described.

Data[0] = 0x7E;          // START
Data[1] = 0x02;          // Length
Data[2] = 0xA3;          // Command
Data[3] = 0x7E;          //Mode parameter
Command(Data,4);

It seems a message starts with 0x7E, followed by the length , followed by a command and whatever else, followed by another 0x7E.

The length field is 1 less than the total length, so I guess it doesn't include the 'start', or whatever - there are various equivalent ways you could look at it.

In playTrack() you set 6 elements, but with the length element set to 4. You then tell Command() there are 5.  So the last element (0x7E) won't get sent, and the length element which you have sent is wrong anyway.

The receiver is going to get into some weird state, I presume. Perhaps that explains the problem you're seeing.


I found the issue!
There is a bug in the Arduino hardware:
https://ketturi.kapsi.fi/2014/04/how-to-fix-moody-arduino-nano/

You need to bridge pins 25 and 26 of the FTDI chip (located at the back of the Arduino) to ground the pin 26 TEST signal.
If I connect these pins then it works just fine!


3.3v Arduino I2C communication with motor controller powered at ~6v

will the varying voltage of the battery cause the communication to be unstable?

No. As the battery voltage drops the input HIGH threshold (which is a function of VCC) also drops. If anything as the battery voltage drops the communication becomes more stable.

Since I2C is an open drain protocol the voltage makes no different for sending data - that voltage is set by the pull-up resistors to 3.3V.


What am I missing? Send data from Matlab to Arduino to Micro SD

The board resets on new USB connection with fopen. Wait 2 secs between fopen and fprintf in Mathlab code.


The source code for the 1-Wire protocol is a great place to start when learning how to use a single pin for both input and output.

See also chap. 18. I/O-Ports in the ATmega328p datasheet.

Cheers!


Why doesn't my 1602A LCD display text with this code?

Pins number 12, 11 are used by some other library in your code. And that's the reason there is no LCD output. Change pins/connections from 12, 11 to 7, 6.

Then your code uses lcd.clear() too often, so whatever data you display vanishes before you were able to read. Don't clear the display unnecessarily.


As stated in my comment, your code is kind of fine. Id mostly works,
but it looses a few microseconds on each iteration. If you are looking
at multi-kHz frequencies, you probably want to avoid loosing
microseconds. The solution is simple: never reset the counter. I
changed you ISR as follows:

uint16_t previous_counter;

void pin_ISR(){
    uint16_t counter = TCNT1;
    f = 2000000/(counter - previous_counter);
    previous_counter = counter;
}

and now it gives the correct frequency... on average. There are some
variations though, dues mostly to delays caused by other interrupts.

Edit 1: If you want to avoid the fluctuations caused by other
interrupts, your best bet is probably to use the input capture feature
of Timer 1.

Edit 2: Here is why your measurement was somewhat off. Your original
ISR essentially does something like this:

void pin_ISR() {
    uint16_t temporary_value = TCNT1;
    loose_some_time();
    TCNT1 = 0;
}

The time you loose in the ISR is the part of the signal period you are
not measuring, which means you are underestimating the period by that
much. In the ISR you posted, this is mostly the time taken by a 32-bit
division, which is quite significant. A simple improvement would be to
clear TCNT1 right after reading it:

void pin_ISR() {
    uint16_t temporary_value = TCNT1;
    TCNT1 = 0;
    loose_some_time();
}

and now the average period you measure is almost right. It is not
perfect though, as the whole reading and writing of TCNT1 takes
8 CPU cycles.

The alternative I am suggesting, where you never clear the timer, is
the correct way of measuring a period with a timer interrupt: you don't
loose a single CPU cycle. The best way is to use input capture: you get
rid of the software-induced jitter.

Note: You should also take care of the very valid points raised in
Jot's answer, about making f volatile and reading it with interrupts
disabled.


Highly sensitive light sensor to calculate number of times each color LED blinks

Like the OP wrote, you can use very simple sensors, like a phototransistor.
Even simpler, if you can somehow isolate each pair LED-phototransistor, you don't even need to care about the color of the led, just use some bluetac to stick one phototransistor on top of each LED and only measure the brightness.

edit:

A quick check on ebay shows the 3DU5C as good candidate: it has a metallic container, so it is more directional than one with full plastic body.

3DU5C ebay link  and  datasheet

It is shown to have a peak response at 880nm (red light), so you might not be able to use it directly as digital input for the other 2 colors you want to monitor and instead have to treat it as analog reading.

OTOH if you use them all as analog inputs, you will not have to add the resistor that would be required for binary mode.


Given that most likely the Arduino code is accessing AVR specific registers, probably not, unless you have some compatibility library that redefines all the low level stuff.

I also wonder if you have the same set of peripherals available on the PI (ex: PWM generators and ADCs).

I would rather follow the "spirit" of the code you already have and re-implement it natively in you language of choice.


How to receive data from my server database to a variable in my Arduino?

After you send the GET request, you read the response to fill the char result [20] variable you declared:

int i=0;
...
if (client.connect(server, port))
{
  client.print("GET /locator.php?");
  ...
  Serial.println("\nCOMPLETE!\n");

  // Read response from server
  i=0;
  while (client.available())
  {
    result[i] = client.read();
    Serial.print(result[i]);
    i++;
  }

  client.stop(); // disconnect
}

This is an example, result will contain the text output by locator.php. You will need to tweak this code to apply to your case. The above code has no error checking of any kind. Also, you should perform a check and only make the web call one time.

In locator.php you should replace echo "<br/>"; with echo "\n";. And for good measure, make sure there is no white space before <?, and remove the trailing ?>.


cant figure out how to fix this compile error

You call function num_Write a lot, you create a forward declaration:

void num_Write(int);

But you forgot to create the implementation.

If you would have forgot the forward declaration the function would not be known at all (and you would get a compiler error). But with the forward declaration you let the compiler know the signature of num_write (so the return value and argument types).

When the linker wants to link all object (.o) files together it cannot find an implementation of the function num_write and you get this error. Hence ld is the linker.


LCD write a line at bottom without lcd.setCursor and without deleting any char above already there?

I do not really understand what you mean by your first sentence. Did you succeed in getting a "hardware" cursor to display together with a character or not? And if you do, why doesn't this fulfill your requirements?

You have to realize that your LCD cannot display partial characters, like a line at the bottom, leaving the rest of the character that was already there intact. An exception is a hardware generated cursor.

You also have to realize that createChar always expects a full character with 8 rows.

Your code examples

In your first example, starting with byte line[8] = {, the first 7 "empty" B, lines actually produce a value of (binary) zero. So here you create an empty character with a line at the bottom, exactly like you said you see on the display.

In your second piece of code, you define characters byte line[1] = and byte noline[1] = consisting of just 1 byte. createChar expects 8 bytes. createChar will fill the characters with the single byte defined in your character definition, plus whatever it finds in the 7 memory locations following your actual definition (which will probably contain some random data). This explains the "garbage" you see on the screen.

Possible solution

One solution would be to re-create each character you want your cursor to display under, on the fly. I.e. if you want your cursor to be displayed under the letter "A", you create a complete custom character which contains "A", plus a cursor underneath and you display it in place of the real "A" at this location. When you move the cursor, you replace the "custom" A with the real "A" again.

This will be cumbersome in code complexity as well as code size (you'd have to create a complete character map for every character you wish to display), but should be a feasible solution.


RS485 Multimaster Communication with collision avoidance

There is a ready out the box solution documented in https://github.com/MichaelJonker/HardwareSerialRS485/wiki (This wiki describes the library you referred to).

The problem is quite complex: collision avoidance, collision detection and message retrial, message priority and message filtering. But the library solves it all. The software even provides a solution to interface a host (PC or Android) to the RS485, providing the same features.

In ‘understanding the library’ there are two aspects: how it works, and how to make it work.

The library itself is non-trivial (because the problem is also non-trivial), so to understand how it works is also non-trivial (Majenko, in his answer, gave a nice functional description of some of the features that are implemented by the library. The actual implementation has additional complications due to the direct interaction with the USART at interrupt level.). I guess you do not want to know (in first instance) how it works in such details.

However, the author (me) went to quite some detail to document how to make it work. But I reckon that documentation may be difficult to follow if the documentation does not match the expectations of the reader.

So I would be very interested to improve the documentation and to match the expectations of new users. However, here I need your help (or anyone interested) in pointing me out what and where I can improve.

The preferred way to contact me on these matters is by creating an issue on my Github project page:

https://github.com/MichaelJonker/HardwareSerialRS485/issues

BTW one of the issues addresses the same topic.

I guess that you need to create Github account in order to submit issues. Alternatively, you can contact me through this site (However, I might be less reactive through this channel).

Best regards

MichaelJonker


From the docs:

  Reads a pulse (either HIGH or LOW) on a pin. For example, if value is
  HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then
  waits for the pin to go LOW and stops timing. Returns the length of
  the pulse in microseconds. pulsein

So, in this case, pulseIn(echoPin, HIGH) starts counting the number of microseconds until echoPin goes HIGH and stores that in duration.

It starts and ends on that line, it's what is known as a blocking function. It will really sit there until echoPin goes high and tells you how long it took (unless you specify a timeout).

That also means that any delays you have before or after the pulseIn call don't affect it in any way.

The way you get distance from this time is by the following equation:

distance = (duration/2) / 29.1;

You divide by two because it goes out and back so the time would be double that of a one-way travel. The 29.1 is the speed of sound (which is 343.5 m/s => 1 / 0.03435 = 29.1). So note the result is in CM's, not inches. You could probably figure it out by looking at the data sheet of the sensor or just get a lot of samples relating duration to distance (you would measure the distance manually) and get an equation that is very similar.


Why is no PWM signal generated using Timer 2?

The output compare unit of timer 2 is connected to pins PB3 (OC2A) and PD3 (OC2B). So you have to configure those as outputs.
Keep in mind that you can't choose any pin when using hardware pwm, this hardware feature is linked to specific pins.

You also have to set COM2A1 in TCCR2A. Otherwise OC2A is disconnected from the output compare unit (ref: Table 17-3 in datasheet).
The effect of COM2A0/1 depends on the configuration in WGM20-WGM22.
The same applies to OC2B respectively.


My method makes use of the __FlashStringHelper class:

// For convenience:
typedef const __FlashStringHelper *FlashString;

FlashString reverseEnum(int val) {
    switch (val) {
        case 0: return F("Option zero");
        case 1: return F("Option one");
        case 2: return F("Option two");
        default: return F("Invalid Enum");
    }
}

Printing now is as simple as:

Serial.println(reverseEnum(2));

Because it's a "flash string" the print function is overloaded properly and it performs the proper PROGMEM reading.

You can, of course, assign to a FlashString:

FlashString myString = reverseEnum(2);
Serial.println(myString);

Or if you don't want to use a typedef you can use the raw type:

const __FlashStringHelper *myString = reverseEnum(2);
Serial.println(myString);

It's just much cleaner to use a typedef.


CC3000 - Send GET request to an app on heroku

Have a look at this code:  https://github.com/adafruit/Adafruit_CC3000_Library/blob/master/examples/SendTweet/SendTweet.ino

There is a delay after cc3000.connectTCP to wait for connection. Your code does not wait for the connection and thus gives 'connection failed' straight away.

Serial.print(F("OK\r\nConnecting to server..."));
t = millis();
do {
    client = cc3000.connectTCP(ip, 80);
} while((!client.connected()) &&
    ((millis() - t) < connectTimeout));

if(client.connected()) { // Success!

etc

Edit based on comment:

getHostByName returns positive value on success and negative on failure. Therefore the check should be

if (cc3000.getHostByName(WEBSITE, &ip) < 0)

Also try putting http:// in the website address


Curious: What would happen if you connect 5V and GND port directly with a wire

There is some protection.

When powered from the USB port, the UNO has a 0.5 A fuse.  This is a self resetting fuse that will trip when the current is high, and reset when it cools back down.  These fuses are great for peripherals that might be exposed to occasional "oops".  See the data sheet for more details of the part on the UNO.

When powered from the PWRIN plug, the voltage regulator provides some protection.  The device on the UNO contains over current and over temperature protection, which is common for regulators such as this.  The device will get very hot, and the protection will activate to limit the current (see datasheet for details).  By design, the regulator chip should protect itself from being destroyed.

So to first order, if you by mistake connect the +5 on the header to GND, all that will happen is Vcc will be reduced to near zero Volts.

The caveat is that a small spark can be generated when you make this short to ground, especially if you have a bunch of capacitors on Vcc.  That spark may cause a voltage transient that could damage a pin.


You can have high-speed debugging by utilizing either I2C or SPI to send to a second Arduino. That second Arduino can be devoted to receiving debugging information and passing it on (via serial to your PC).

I describe the process here.

The general idea is to add some stuff to the DuT (device under test) to output via SPI/I2C.

Example code:

// make true to debug, false to not
#define DEBUG true

#include <SPI.h>

// conditional debugging
#if DEBUG

  #define beginDebug()  do { SPI.begin (); SPI.setClockDivider(SPI_CLOCK_DIV8); } while (0)
  #define Trace(x)      SPIdebug.print   (x)
  #define Trace2(x,y)   SPIdebug.print   (x,y)
  #define Traceln(x)    SPIdebug.println (x)
  #define Traceln2(x,y) SPIdebug.println (x,y)
  #define TraceFunc()   do { SPIdebug.print (F("In function: ")); SPIdebug.println (__PRETTY_FUNCTION__); } while (0)

  class tSPIdebug : public Print
  {
  public:
    virtual size_t write (const byte c)
      {
      digitalWrite(SS, LOW);
      SPI.transfer (c);
      digitalWrite(SS, HIGH);
      return 1;
      }  // end of tSPIdebug::write
  }; // end of tSPIdebug

  // an instance of the SPIdebug object
  tSPIdebug SPIdebug;

#else
  #define beginDebug()  ((void) 0)
  #define Trace(x)      ((void) 0)
  #define Trace2(x,y)   ((void) 0)
  #define Traceln(x)    ((void) 0)
  #define Traceln2(x,y) ((void) 0)
  #define TraceFunc()   ((void) 0)
#endif // DEBUG

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced device-under-test debugging!"));
  TraceFunc ();  // show current function name

}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

The other Arduino (which receives the debugging information) simply echoes it to Serial:

char buf [1000];
volatile int inpoint, outpoint;

void setup (void)
{
  Serial.begin (115200);   // debugging

  Serial.println ();
  Serial.println (F("Commencing debugging session ..."));
  Serial.println ();

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // now turn on interrupts
  SPCR |= bit (SPIE);

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register
int next = inpoint + 1;  // next insert point

  // wrap-around at end of buffer
  if (next >= sizeof buf)
    next = 0;

  if (next == outpoint)  // caught up with removal point?
    return;  // give up

  // insert at insertion point
  buf [inpoint] = c;
  inpoint = next;  // advance to next

}  // end of interrupt routine SPI_STC_vect

void loop (void)
{
  // insertion and removal point the same, nothing there
  noInterrupts ();  // atomic test of a 16-bit variable
  if (outpoint == inpoint)
    {
    interrupts ();
    return;
    }
  interrupts ();

  // display anything found in the circular buffer
  Serial.print (buf [outpoint]);

  noInterrupts ();
  if (++outpoint >= sizeof buf)
    outpoint = 0;  // wrap around
  interrupts ();

}  // end of loop

SPI is quite fast, so the overhead of doing the debugging should be slight. The receiving end can batch up the debugging information (up to a point which is about 1000 characters) and then send it to your PC via Serial.

I made a library out of the relevant code. The library is available from:

http://gammon.com.au/Arduino/SPI_Debugging.zip

Example using the library:

// make true to debug, false to not
#define DEBUG true

#include <SPI.h>
#include <SPI_Debugging.h>

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced device-under-test debugging!"));
  TraceFunc ();  // show current function name

}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

There is a similar library for I2C debugging:

http://gammon.com.au/Arduino/I2C_Debugging.zip

Example of doing I2C debugging:

// make true to debug, false to not
#define DEBUG true
const byte SLAVE_ADDRESS = 100;  // which address debugging goes to

#include <Wire.h>
#include <I2C_Debugging.h>

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced device-under-test debugging!"));
  TraceFunc ();  // show current function name
}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

All of the examples illustrate using a #define to turn the debugging output on or off, so you can leave the debugging prints there in case things go wrong, but with debugging disabled they won't have any penalty.


Some guidelines for programming:

Start each statement on a new line

int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup() {
Serial.begin(9600);
pinMode(6, OUTPUT);
pinMode(9, OUTPUT);
} void loop(){
sensorVal = analogRead(A1);

Serial.print("Sensor Value: "); Serial.print(sensorVal);

float voltage = (sensorVal*5.0)/1024.0; Serial.print("Volts: "); Serial.print(voltage);

float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
float pressure_bar = pressure_pascal/10e5;
Serial.print("Pressure = ");
Serial.print(pressure_bar);
Serial.println(" bars");
Serial.print("Pressure = "); {
for(int a = 255; a>=0;a--) {
analogWrite(6,a);
if (pressure_bar = 1600){
analogWrite (6, a);
if (pressure_bar > 1600){
analogWrite (6, a); }
for(int a = 0; a<256; a++) {
analogWrite(6, a); {
if(pressure_bar < 1600){
analogWrite (6, a); }
for(int b = 255; b>=0;b--) {
analogWrite(9, b); {
if (pressure_bar == 1600){
analogWrite (9, b);
if(pressure_bar < 1600){
analogWrite (9, b); }
for(int b = 0; b<256; b++) {
analogWrite(9, b); {
if (pressure_bar > 1600){
analogWrite (9, b);
} }

Use brackets and align them

.. so each pair of { and } is on the same column and align code with brackets to be indented 2, 3 or 4 spaces

int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup()
{
  Serial.begin(9600);
  pinMode(6, OUTPUT);
  pinMode(9, OUTPUT);
}
void loop()
{
  sensorVal = analogRead(A1);

  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal*5.0)/1024.0; Serial.print("Volts: ");
  Serial.print(voltage);

  float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
  float pressure_bar = pressure_pascal/10e5;
  Serial.print("Pressure = ");
  Serial.print(pressure_bar);
  Serial.println(" bars");
  Serial.print("Pressure = ");
  {
    for(int a = 255; a>=0;a--)
    {
      analogWrite(6,a);
      if (pressure_bar = 1600)
      {
        analogWrite (6, a);
        if (pressure_bar > 1600)
        {
          analogWrite (6, a);
        }
        for(int a = 0; a<256; a++)
        {
          analogWrite(6, a);
          {
            if(pressure_bar < 1600)
            {
              analogWrite (6, a);
            }
            for(int b = 255; b>=0;b--)
            {
              analogWrite(9, b);
              {
                if (pressure_bar == 1600)
                {
                  analogWrite (9, b);
                  if(pressure_bar < 1600)
                  {
                    analogWrite (9, b);
                  }
                  for(int b = 0; b<256; b++)
                  {
                    analogWrite(9, b);
                    {
                      if (pressure_bar > 1600)
                      {
                        analogWrite (9, b);
                      }
                    }

Remove superfluous brackets

As you can see, you are having some superfluous/missing brackets. What you want is probably something like:

int scvVal = 6;
int drvVal = 9;
int sensorVal = A1;
void setup()
{
  Serial.begin(9600);
  pinMode(6, OUTPUT);
  pinMode(9, OUTPUT);
}
void loop()
{
  sensorVal = analogRead(A1);

  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal*5.0)/1024.0; Serial.print("Volts: ");
  Serial.print(voltage);

  float pressure_pascal = (400.0*((float)voltage-0.5))*1000000.0;
  float pressure_bar = pressure_pascal/10e5;
  Serial.print("Pressure = ");
  Serial.print(pressure_bar);
  Serial.println(" bars");
  Serial.print("Pressure = ");

  for(int a = 255; a>=0;a--)
  {
    analogWrite(6,a);
    if (pressure_bar = 1600)
    {
      analogWrite (6, a);
    }
    if (pressure_bar > 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int a = 0; a<256; a++)
  {
    analogWrite(6, a);
    if(pressure_bar < 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int b = 255; b>=0;b--)
  {
    analogWrite(9, b);
    if (pressure_bar == 1600)
    {
      analogWrite (9, b);
    }
    if(pressure_bar < 1600)
    {
      analogWrite (9, b);
    }
  }
  for(int b = 0; b<256; b++)
  {
    analogWrite(9, b);
    if (pressure_bar > 1600)
    {
      analogWrite (9, b);
    }
  }
}

Remove duplicate code

In the if statement, you perform twice the same code (both you send an analogWrite with the same value, so the code (from the for loops can be reduced to:

  for(int a = 255; a>=0;a--)
  {
    analogWrite(6,a);
    if (pressure_bar >= 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int a = 0; a<256; a++)
  {
    analogWrite(6, a);
    if(pressure_bar <= 1600)
    {
      analogWrite (6, a);
    }
  }
  for(int b = 255; b>=0;b--)
  {
    analogWrite(9, b);
    if (pressure_bar <= 1600)
    {
      analogWrite (9, b);
    }
  }
  for(int b = 0; b<256; b++)
  {
    analogWrite(9, b);
    if (pressure_bar >= 1600)
    {
      analogWrite (9, b);
    }
  }
}

Unclear

What is unclear why you first write an analog value, and directly afterward (in each if) you write the same value. I'm not sure what you really want here. Either you want to write to a different pin, or you want a delay (to have the value having some effect), I'm just not sure.


Understanding global variables on Arduino

I suggest you take a look at https://stackoverflow.com/questions/16274451/operator-new-for-arduino the new operator is not coming from the c++ libraries, it is coming from the Arduino libraries.  It's a wrapper for malloc Is using malloc() and free() a really bad idea on Arduino?


In this article the following steps are used when using an LED as a light detector:

Light up the LED by making the anode positive (logic one) and the
cathode negative (logic zero) - this fully discharges the LED as a
capacitor.
Charge up the capacitor by making the anode negative and the cathode
positive, as this is a small capacitor it will take no time at all
in other words for as short a time as you can.
Put the diode into the measurement mode, by making the anode
negative (it already is) and the cathode connected to an analogue
input.
Make a measurement of the analogue voltage, this is a reference
level to be used later.
Wait while the photon current is integrated - the longer the more
sensitive but too long and effects other than photo current
dominate.
Measure the voltage again and subtract it from the reference value
you took before the integration time. This figure is your light
reading.

Looking at the code in the above question it is not apparent where you switch from forward bias to revers bias.  Also, it does not appear there are two samples taken and the difference between the two samples is found.


In theory, this particular device should work on its own.  However you should search for and read the datasheet for it. (I'll leave you to do that yourself, just to make sure you really do read it.)

You should consider a heatsink too by the way, and provision for things like a fuse on the power, and whether you will be using a separate 5V for the logic (again you need the datasheet for that).


Why does the battery eliminator connected to the wall provide a better spin to my dc motors than my battery of the same voltage?

First off, never use 9V batteries to power motors or any device that consumes more than a few hundreds mA. Those batteries are just too weak.

Now a battery eliminator is not a pure equivalent as it can typically supply 800 mA or more, depending on the model you get.

The only commonalities between the battery and the eliminator are the 9V voltage and the socket.

If you want to power DC motors with batteries then rather use several 1.5V batteries in series.


Pins 4 and 5 are the I2C pins that belong to the built in I2C peripheral on the Arduino. You have to put your CS line for the SPI SD card on a different pin.

EDIT:
The answer above is relevant to the Arduino ATMega328-based board, not ESP8266-based NodeMCU board. This answer is not relevant to ESP8266 or NodeMCU with regard to hardware I2C, as the ESP8266 does not have a dedicated hardware I2C peripheral.


As shown in the detailed information for the ADMUX register in the ADC section of the datasheet, the ATtiny88 has no external voltage reference. Consider using a ATmega8 or ATmega88PB instead.


How do I use a 5v/120v relay that is not mounted on a board

What I did with a similar looking 'module' (An AC/DC converter), was to use a protoboard/perfboard. Some holes fitted in the existing holes, others I drilled with a small drill.

On the back you can solder the wires you need, so for the 110V wires you might use thicker wires than for the controls.

Than if you want to make it fancy, you add some terminal blocks to connect the external wires too. Terminal blocks looks like this:


The NodeMCU uses the SPX3819 3.3v voltage regulator.

That regulator, according to the datasheet has a dropout of maximum 700mV, but much less at lower currents.

Taking the maximum, that means that you need to supply 3.3 + 0.7 = 4V to the board for the regulator to regulate properly. However, it is doubtful you will be using that much current, so probably nearer a 350mA dropout - which means 3.3 + 0.35 = 3.65V.

However, the ESP8266 itself will work down to 2.5V - so if you operate the board with the regulator out of regulation (not recommended, but it should work fine), you could probably go as low as 2.8 to 3V without problems.


2.8 Touchscreen does not work with Proto Screw Shield

You are set to use the ICSP header for communication with the screen. That is good, when you are directly connected to a Mega.

However that is bad when you are going via a shield that doesn't have an ICSP header.

The ICSP header is the 6-pin (3x2) header in the right of your picture. It has SPI signals that the screen needs. Your screw shield lacks those pins.

You need to pass those signals through. The simplest way would be to add a 3x2 stackable header (or two 3x1 stackable headers) upside down through the correct holes to line up with the ICSP header.


I want to run jvm on arduino.What minimum configuration do I need?

Search for "embedded java". Oracle supports it for ARM cores, which is what some of the arduino-like boards such as the Teensy 3.X have, but I doubt they have enough resources to support it.

There is haiku-vm (google it!) that's designed with AVR processors in mind, but I don't know how actively it is being worked on.

Googling "embedded java avr" yields a tremendous amount of results; did you even try that?


Found <TinyDHT.h> and all works ok, just what I wanted.


Is there a way to play sounds from an Arduino without using a sound shield?

I helped someone with a similar question. The results are in my github repo at https://github.com/linhartr22/count. This example uses the PWM library and includes a reference to the article I used to learn how to convert audio files to MP3 with proper settings for the PWM libary. It plays audio through an 8 ohm speaker or a piezo buzzer connected directly to the Arduino.


Few months ago I tested successfully I2S with this library, I used the default pins:

bck_io_num = 26
ws_io_num = 25
data_out_num = 22

which are available on many boards such as Lolin D32.


Adapt a differently pin-interspaced chip to be used with an Arduino

Adapters from 2mm to 2.54mm (0.1") spacing exist.

Here is
an example and another example.

Alternatively you could make up a little PCB or, as suggested by @jfpoilpret, solder wires on.

A further option is to cut a piece of stripboard, score down the middle to break the tracks, stick your chip on, and run wires from the 2mm-spaced pins to the 2.54mm-spaced pins.  Off-cut resistor legs work fairly well, in my experience.  Here's one I made (fairly clumsily) earlier.  Your soldering skill may be better than mine. .


How can an Arduino do multiple actions in parallel without interfering with each other?

The root of this behavior is that when the program runs delay() function - nothing else could run (digitalwrites, checks, conditions, etc.) until the delay() time is passed.

The effective solution for this is avioding the delay() function, and getting the same results (without the side-effect) using timers (like millis()) or other ways.

Googling "How to avoid delay()" will give you lot of information about how-to do it, one example can be found here:
Arduino Playground - How and Why to avoid delay() function.

Good luck with that, and enjoy your programming experience!


How to get ip information of arouter/AP with ESP8266

All you can do is get what DHCP gives you.

Connect to the AP
Use DHCP to get an IP address
Store the IP, netmask and gateway in variables
Use the netmask to determine the "fixed" bits in the IP address.
Replace the "unfixed" bits of the IP with your own chosen IP portion
Re-set the IP information with your static information.

What you cannot do is determine what the DHCP range is. Only the router knows that, and it doesn't broadcast it.

The proper way of handling it, though, is to get the router to provide a fixed DHCP IP address for the MAC address the ESP8266 has. Most routers have this functionality available.


1000 measurement for 10 sensors per seconds, it means there are 10000 measurement per sec with 0.1 mS time slot for each measurement.
According to SRF-04 Documentation,
(1)

If nothing is detected then the SRF04 will lower its echo line anyway after about 36mS.

So, time slot for each reading is 36 mS ("if" nothing is detected), which means for 10 SRF04 x 1000 reading, it will take 360000 mS = 360 Sec.
(2)

I would want all 10 sensors to send a 40kHz pulse at the same time, and then when a return signal is recorded, another 40kHz pulse is sent out.

Its seems reasonable. But,

According to the timing diagram, 1 cycle minimum period consist of :

100 us Trigger pulse ==> 0.0001 s
8 Cycle burst at 40 kHz = (1/40000)*8 s ==>  0.0002 s
100 us Echo pulse ==> 0.0001 s
10 ms delay time ==> 0.01 s

Total for 1 cycle is 0.0104 s, so for 1000 readings x 10 sensors (object to detect is present) will be 104 s.
All sensor burst at the same frequency, great idea. However it's not advised (or rather not possible) because that will disturb each sensor reading unless you successfully change each sensors frequency or doing sound modulation. Even if you success in modulating 10 sensors frequency, the needed time is still not met 1 s interval

100uS for 10 sensors trigger pulse at once ==> 0.0001 s
8 Cycle burst at 40 kHz = (1/40000)*8 s ==>  0.0002 s
100 us (minimum) Echo pulse --> 0.0001 s x 10 sensors ==> 0.001 s, because Arduino does not support threading, which mean there is no way you can read all at same time
10 ms delay time ==> 0.01 s

Time for 1 cycle (10 sensors reading): 0.0113, 1000 readings : 11.3 s
(3)
"How about changing the beam pattern?"

Changing beam pattern and beam width
You can't! This is a question which crops up regularly, however there is no easy way to reduce or change the beam width that I'm aware of. The beam pattern of the SRF04 is conical with the width of the beam being a function of the surface area of the transducers and is fixed.

So, rather than trying to modify the ultrasonic, more reasonable solution is changing the way you do elevation measurement.


How to stop extra LEDs from lighting in LED cube

Your circuit design has to be used with multiplexing. Multiplexing introduces flicker. Since you seem to be wanting to move the grid of LEDs rapidly that flicker will translate into a very undesirable effect.

So you have a number of choices:

Re-design your system so that you don't use multiplexing. With each LED directly driven you get zero flicker, but you end up with as many wires and GPIO pins needed as you have LEDs (although shift registers could be used to move the bulk of the wiring closer to the LEDs). That's impractical.
Use multiplexing but have the frequency so high that flickering is no longer noticeable. We're talking thousands or millions of loops per second to keep it looking smooth (depending on how fast you are spinning the grid). You would need a high speed multiplex driver chip for this.
Time your multiplexing to the spinning of the grid.

The third option relies on quite a high rate of spin, since your multiplexing increments one column or row for each revolution. With 5 columns to work through it would take 5 revolutions to work through the entire grid.

You need some way of identifying the start of each revolution (e.g., a hall-effect sensor), and each time you start a new revolution you illuminate just one column of LEDs. The faster you spin the smoother the effect will be.

If you want to have LEDs on or off for just part of the revolution it's then down to you to work out when to turn them on or off for that one specific column. That's when the fun really begins.


Seven-Segment Display doesn't work on two lights

As jwpat7 states, you need a current-limiting resistor for each segment, between the data pin (on the Arduino) and the segment pin (on the display). Your Fritzing diagram only shows one resistor in the circuit, from the common cathode to GND on the Arduino.

You can not, or should not, share one resistor to ground (assuming that you have a common cathode seven segment display). You need a current-limiting resistor on each anode (again, (assuming that you have a common cathode seven segment display).

If you are sharing the current-limiting resistor between all segments, and then try to light more than more segment, at a time (which it sounds like you are doing ("when I plug the red cable to 4 and 5"), then the current through the current-limiting resistor will increase, and as a result, the voltage will change significantly enough, such that there is not sufficient voltage drop across the LED in order to make it light up.

Remember, 0.7 V is dropped across the LED.

Test each on the segments, one at a time, to make sure they all work, as Ignacio states in his comment.

Also, your sketch should be more complete, along the lines of:

void setup() {
    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
}

void loop() {
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);
    digitalWrite(8, HIGH);
}

Connect up all of the pins, using a current-limiting resistor on each anode, and then try it programmatically.

If your seven segment display is a common anode, then, again, you need a resistor between each cathode and the data pins, and bring the pins LOW to light the corresponding segment, i.e.

    digitalWrite(8, LOW);


Arduino reads hc-05 device connecting status

In hc05 there is led that shows you Bluetooth is paired or not. In datasheet it says that connected the PIO9 pin. You can connect this pin to arduino's digitial input pin. After that you can understand is it paired or not.

AT+BIND? gives you which device you currently paired.


That's not a good choice of MOSFET I'm afraid.

The on resistance is quoted as 14Ω when the gate is at -10V - however, you are only able to get -5V, so it will be considerably worse.

That massive on resistance will be causing a massive voltage drop, which is what you are experiencing.

You should find a MOSFET with an on resistance that is in the milli-ohm range when the gate is between 0V and -5V.


Why does Arduino Due Native Port change serial ports after every reset? (Linux)

It happens because of Linux, not because of the Arduino.
Since you unplug/reset the DUE while the port is still open, when it's back online, the old file name is still in use, so a new one is created.
Just close the port before resetting the DUE and you will see that after the reset it will have the same one.

You can easily reproduce the same issue with a serial to usb adapter (/dev/ttyUSBS0,1,2,etc) and screen or minicom.

To make your program more robust, you should listen for kernel events and open the port accordingly.


Which arduino should i use for a very simple one pin "blinking led" type project?

For beginners, use an Arduino Uno. It is ready to use and quite expendable with shields. They have the USB to SERIAL chip on the board. Only week point is that it is sometimes large from space sensitive projects.

For more advanced users, I would suggest the Pro Mini (my personnal favorite). It is small, powerful and even has more pins then the UNO. The main disadvantage is that it requires an FTDI connector for the USB to SERIAL. Note that this NOT recommended if you use a lot of I2C.

Finaly, there is the overkill option. Only use this if you are considering to get one Arduino to rule them all!. It's the Arduino Mega 2560. It is the overkill of the overkill. So many GPIOs and ANALOG inputs. It is also unique for its core which is different the then normal ATmega328.

Then finaly there is the most easy to use one, the Red Board by Sparkfun. It combines the best of each Arduino in one. Note that this one is not manifactured and backed by Arduino.

That is pretty much a summary of all of the most popular types of Arduino that there is.

[EDIT]

Note that none of them has an included case and a circuit that can reduce 220V to 5V. If you really want a case, get an UNO. There are many cases for it. For transforming 220V to 5V, use an 5V wallplug. If you have something like a 12V wallplug, you can also connect it to the Arduino but you have to make sure you connect it to the Vin port.


Arduino communication to Raspberry Pi using HC-05

port_2 = serial.Serial(" is most likely a copy and paste error on your part, but needs to be fixed if you want 2 serial ports to deal with
You only read from port in your Python while loop without touching port_2. This is the reason you only see output from one serial port
You should use a robust serial data packet-system. Right now you have no way of ensuring that the data received in Python is corrupt or not. You can easily use the pip-installable Python package pySerialTransfer and compatible Arduino library SerialTransfer.h (installable via the Arduino IDE's Libraries Manager).

For theory behind robust serial communication, check out the tutorials Serial Input Basics and Serial Input Advanced.


What happens if I don't use a relay for 5V pump

You should put a resistor in series with the led to limit the current.

The IO pins cannot source enough current to run the pump without damaging themselves. That's why you need a buffer of some kind.

The extra components in the relay module are a transistor to do the actual switching and a reverse-biased flyback schottky diode in parallel with the relay coil. The flyback diode is required to absorb the voltage spike generated by the coil getting switched off and acting like an inductor.

You can use a transistor to switch the motor directly assuming you can find one that can handle the current draw. If you do then you absolutely will need a flyback diode on the motor to avoid damage to the transistor.


Arduino Fio: Battery/Solar Powered Weather Station

You have a LiPo charger module. It's meant to charge single LiPo cells. It is therefore, the intended safe use that you can connect any single LiPo cell to it. All single cell LiPo batteries are nominally 3.7V. The only real question might be -- does the charging circuit try to charge too fast?

A 2000mAh pouch LiPo can safely be charged at 1X the capacity. So a maximum current of 2000mA for an hour in this case. The battery management chip has a maximum charge current of 500mA, so there's no way it can reach over 2000mAh of current while charging.

The datasheet for the battery management chip shows a R_PROG resistor that basically sets the maximum charge current.  Section 5.1.2 shows the formula for charge current regulation at:

I_REG [mA] = 1000 [V] / R_PROG [kΩ]

The schematic for the Fio shows they have used a 2k ohm resistor.

Thus: I_REG [mA] = 1000 [V] / 2 [kΩ] = 500 [mA] (the maximum the chip can operate)


Programmatically Change Arduino Com Port Name

On Windows you can change the "Friendly names" assigned to devices and COM ports are devices.  The process is basically open the device manager, open the device properties, find the 'Device Key' and then locate that in the registry and change the 'Friendly Name' value.

See this page for more details:
https://www.eightforums.com/customization/15321-tutorial-how-change-device-names-device-manager.html


Yes, it is defined in the FastLED library.  It is a preprocessor macro which is replaced by a block of code when compiled:

It is a very convoluted bit of preprocessing code that is difficult (even for me) to follow through with lots of concatenations and multiple layers of definition, so my advice is to just not worry about it and just use it.

If you want to try and decypher it all it's in the file lib8tion.h in the FastLED library.


Solar powered ESP8266. WiFi module usage optimizations

As described here the ESP8266 can be waken up using Timer Wake Up or external interrupt. The idea is simple: almost everything inside the ESP is powered down (including Wi-Fi and/or System clock or even the CPU) with only a timer running which was told when to activate before the ESP went to sleep. After the desired amount of time has passed the timer triggers GPIO 16 or D0 and if that is connected to the reset pin of the ESP is resets and starts executing code again until it goes to sleep again. For your case you can configure your motion sensor to output a LOW when motion is detected and connect is to a GPIO pin and the reset pin, so it will trigger a restart when motion is detected and in the startup sequence you look at the pin where the sensor is connected and do what you have to do. For the keyboard to work you can have the timer set to reset every 5 seconds, so you would have to hold a button for 5 seconds waiting for the ESP to wake up and accept your input or you could make a dedicated button for waking up the ESP if you want to enter the code. In that case the you don't need a timer, since as you described the ESP only has to do anything if the keyboard is activated or if the motion sensor is triggered and since they can be connected as external interrupts they will wake up the ESP if needed. I would recommend to check out this link for further details about the code and hardware.


Why not use I2C slave-master between arduinos?  You can hook up other arduinos or devices on I2C simultaneously (as long as each uses a distinct address).

And you still keep the SPI for a microsd card adapter, for example.

Follow this official tutorial:

MASTER ARDUINO 1

// Wire Master Writer
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Writes data to an I2C/TWI slave device
// Refer to the "Wire Slave Receiver" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop() {
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting

  x++;
  delay(500);
}

SLAVE ARDUINO 2

// Wire Slave Receiver
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Receives data as an I2C/TWI slave device
// Refer to the "Wire Master Writer" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

This is an alternative example of a setup using a nodemcu (which doesnt function in slave mode, btw).


You mean that the STK500 v2 programmer uses an emulated serial port
rather than direct USB? Then I guess there is a bug in the Arduino IDE.
The file programmers.txt contains the following lines
describing the programmer:

avrispmkii.name=AVRISP mkII
avrispmkii.communication=usb
avrispmkii.protocol=stk500v2
avrispmkii.program.protocol=stk500v2
avrispmkii.program.tool=avrdude
avrispmkii.program.extra_params=-Pusb

You may locate this file in your Arduino installation and replace the
last line from this snippet by

avrispmkii.program.extra_params=-P{serial.port}

If that works, it would be a good idea to submit a pull request with the
fix to the Arduino team.

Alternatively, you may try selecting “Atmel STK500 development board” as
a programmer. This is supposed to autodetect the version of the STK500
protocol, and uses the correct serial port.

Edit: you may also have to replace

avrispmkii.communication=usb

by

avrispmkii.communication=serial

C.f. this bug report, which seems to cover the exact issue you are
facing.


Global variables use to much space in the dynamic memory

When you write a program, some memory can be determined in compilation time, due to it's predefinition, (float and double in Arduino - not Due model - use 4 bytes each - in Due, double uses 8 bytes for 64 bit precision).

But there is some memory that only can be known at runtime; where we are talking about objects (or arrays determined by user input). In these cases, programs need to dynamically allocate memory, for which the C++ language integrates the operators new and delete. More info at: Dynamic memory.

You should control the creation of objects and arrays (those are created with new and then deleted with delete).

If your requirements are greater than the resources of any Arduino (except Arduino Due), you should change to the Due model, which has more memory space and computing power (but changes the 5 V to 3.3 V, be careful).


You're only reading from the serial port every GPSSearchPeriod milliseconds. That gives plenty of time for the small serial read buffer to overflow and lose the data.

Instead you should be reading all the time regardless of your desire to only do things periodically. Sure, report the data periodically, but you must read all the time as well.


Getting an Arduino Uno and MKR zero to communicate

Let the MKR Zero play the wav files. It has DAC on A0 and AudioZero library to play wav files from SD card.

You can use Serial communication to command the Zero from Uno. In Uno use hardware Serial or create SoftwareSerial to send commands to Serial1 of MKR Zero. You can then test the MKR first with commands sent from Serial Monitor.


How would you send clock impulses to a camera with an Arduino Mega?

It depends on the camera that you're using but you send in impulse just sending digital write signal, waiting a little bit and then turning it off. You do this over and over again until you have all the pixels. Here is an example where I send 128 impulses:

  for(int i = 0; i < 128; i++)
  {
    digitalWrite(CLK, HIGH);
    delay(1);
    digitalWrite(CLK, LOW);
    delay(1);
  }

Depending on the hardware you are using you might have to send a SI (signal impulse) prior to the CLK impulses and the delay in between them will vary. The best thing to do is to read the documentation to find these figures.


Why do some pins have a different PWM frequency?

Those aren't the only frequencies available for the PWM signals. However, they are the frequencies as determined by the applied prescaler (which you can readily change as detailed below).

Each of the 3 pairs of PWM pins is tied to one timer, each of which has its own base frequency, as follows:

Pins 5 and 6 are paired on timer0, with base frequency of 62500Hz
Pins 9 and 10 are paired on timer1, with base frequency of 31250Hz
Pins 3 and 11 are paired on timer2, with base frequency of 31250Hz

Then each set of pins have a number of prescaler values that can be chosen, that will divide the base frequency of that pair of pins. The prescaler values available are:

Pins 5 and 6 have prescaler values of 1, 8, 64, 256, and 1024
Pins 9 and 10 have prescaler values of 1, 8, 64, 256, and 1024
Pins 3 and 11 have prescaler values of 1, 8, 32, 64, 128, 256, and 1024

The different combinations yield different frequencies in a given PWM pin. Notice that timer 2 (tied to pins 3 and 11) have more prescaler values available, resulting in more frequencies available.

Now, why timer 2 is different, that's a separate question.

Edit: Here's a list of possible PWM frequencies per pin (from this article):

  For pins 6 and 5 (OC0A and OC0B):

  If TCCR0B = xxxxx001, frequency is 64kHz
  If TCCR0B = xxxxx010, frequency is 8 kHz
  If TCCR0B = xxxxx011, frequency is 1kHz (this is the default from the Diecimila bootloader)
  If TCCR0B = xxxxx100, frequency is 250Hz
  If TCCR0B = xxxxx101, frequency is 62.5 Hz

  For pins 9, 10, 11 and 3 (OC1A, OC1B, OC2A, OC2B):

  If TCCRnB = xxxxx001, frequency is 32kHz
  If TCCRnB = xxxxx010, frequency is 4 kHz
  If TCCRnB = xxxxx011, frequency is 500Hz (this is the default from the Diecimila bootloader)
  If TCCRnB = xxxxx100, frequency is 125Hz
  If TCCRnB = xxxxx101, frequency is 31.25 Hz

TCCRnB is where you set the prescaler bits for timer n, replacing n by 0, 1 or 2, depending on the timer you want to set. If you are still unsure about bitwise operations, read this bit math tutorial.

My sources:

http://playground.arduino.cc/Code/PwmFrequency
http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM
http://arduino.cc/en/Tutorial/PWM
http://arduino-info.wikispaces.com/Arduino-PWM-Frequency

Note that there seems to be divergence in those sources about whether pins 9 and 10 have the same behavior as 5 and 6 or 3 and 11, but you get the idea anyway. I'm reading the datashet to try and figure out which is correct, or whether this is a difference between boards.


So you leds are connected to "pins" not "ports." Since each of the buttons will turn on only 1 led we need to keep track of which button pairs with which led. To do this we can use a struct like this one:

struct ButtonLed{
        int buttonPin;
        int ledPin;
};

You declare a ButtonLed like this: ButtonLed button1 = {1, 0} where the first parameter is the button's pin and the second is the led's pin. (All of the led pins are set to 0 since I don't know which pins you have them connected to.)

And the array will hold the button/led pin pair like this:

ButtonLed questionNumberArray[] = {button1, button2, button3, button4, button5, button6};

Since there are 6 leds you know that your array is size 6 so use this declaration instead

const int n = 6;

I fixed you range for the random number generation. Look at the documentation for random() here https://www.arduino.cc/en/Reference/Random. We can use this function for shuffling the array.

void shuffleArray (ButtonLed arr [], const int size){
    for (int i = 0; i < size - 1; i++){ // iterates through array except last element
        int j = random(0, size); // generates a random index from (0 to n-1) inclusive

        // swap current index with random index
        ButtonLed t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }
}

We will use this function to wait until the user enters a sequence of button presses:

ButtonLed getButtonPress (ButtonLed arr [], const int size){
    bool pressed = false;
    ButtonLed  pressedButton;
    while (!pressed){ // loops until a button was pressed
        for (int i = 0; i < size && !pressed; i++){ // !pressed allows early out
            if (digitalRead(arr[i].buttonPin)){ // one of the six buttons was pressed
                pressed = true; // exit both loops
                pressedButton = arr[i]; // stores which button was pressed
            }
        }
    }
    return pressedButton; // return the pressed button
}

Essentially it gets stuck in a loop and reads each of the 6 buttons until one of them is pressed and then records which one was pressed.

Try using the code below and read the comments the only thing you need to do is change all the zeros in the ButtonLed declarations to whatever pin the leds are connected to. Also the struct above needs to go into it's only file called "ButtonLed.h" It must be called that.

#include "ButtonLed.h"

// These are ButtonLeds our newly created data type
// they hold both an led's pin and the pin for the button
// that turns it on
ButtonLed button1 = {1, 10};
ButtonLed button2 = {2,  8};
ButtonLed button3 = {9,  7};
ButtonLed button4 = {11, 6};
ButtonLed button5 = {12, 5};
ButtonLed button6 = {13, 4};

// This function will randomly shuffle an array of ButtonLeds
void shuffleArray (ButtonLed arr [], const int size){
    for (int i = 0; i < size - 1; i++){ // iterates through array except last element
        int j = random(0, size); // generates a random index from (0 to size-1) inclusive

        // swap current index with random index
        ButtonLed t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }
}

ButtonLed getButtonPress (ButtonLed arr [], const int size){
    bool pressed = false;
    ButtonLed  pressedButton;
    while (!pressed){ // loops until a button was pressed
        for (int i = 0; i < size && !pressed; i++){ // !pressed allows early out
            if (digitalRead(arr[i].buttonPin)){ // one of the six buttons was pressed
                digitalWrite(digitalRead(arr[i].ledPin, HIGH); // turns on the led the user chose
                delay(200);
                digitalWrite(digitalRead(arr[i].ledPin, LOW); // turns it back off
                pressed = true; // exit both loops
                pressedButton = arr[i]; // stores which button was pressed
            }
        }
    }
    return pressedButton; // return the pressed button
}

void setup() {
    randomSeed(analogRead(A0));
    // This is how you set up the leds for output
    pinMode(button1.ledPin, OUTPUT);
    pinMode(button2.ledPin, OUTPUT);
    pinMode(button3.ledPin, OUTPUT);
    pinMode(button4.ledPin, OUTPUT);
    pinMode(button5.ledPin, OUTPUT);
    pinMode(button6.ledPin, OUTPUT);

    // This is how you set up the buttons for input
    pinMode(button1.buttonPin, INPUT);
    pinMode(button2.buttonPin, INPUT);
    pinMode(button3.buttonPin, INPUT);
    pinMode(button4.buttonPin, INPUT);
    pinMode(button5.buttonPin, INPUT);
    pinMode(button6.buttonPin, INPUT);
}

void loop() {

    // This array is of type ButtonLed our newly created data type
    ButtonLed questionNumberArray[] = {button1, button2, button3,
                                       button4, button5, button6};
    const size_t n = 6; // array's size

    shuffleArray(questionNumberArray, n);

    numLeds = 1;
    bool guessCorrectly = false;

    // this while loop allows the user to keep trying until they get it right
    while (!guessCorrectly){

        // This loop displays the correct sequence to the user
        for (int i = 0; i < numLeds; i++){
            digitalWrite(questionNumberArray[i].ledPin, HIGH); // turn on the led

            delay(500); // decrease this number to flash faster; increase to flash slower

            digitalWrite(questionNumberArray[i].ledPin, LOW); // turn off the led
        }

        bool correctButton = true; // the user has pressed the correct button
        ButtonLed userSequence [6];      // stores the sequence the user entered
        // lets the user push 6 buttons
        for (int i = 0; i < numLeds; i++){
            userSequence[i] = getButtonPress(questionNumberArray, numLeds);
            delay(500); // delay between button presses
        }

        // check if the user entered the correct sequence
        for (int i = 0; i < numLeds && correctButton; i++){
            if (userSequence[i].buttonPin != questionNumberArray[i].buttonPin)
                correctButton = false;
        }

        if (correctButton){ // user entered the correct sequence
            guessCorrectly = true;
            // This will turn on the leds in the correct sequence
            for (int i = 0; i < numLeds; i++){
                digitalWrite(questionNumberArray[i].ledPin, HIGH); // turn on the led
                delay(500); // delay half a second
                digitalWrite(questionNumberArray[i].ledPin, LOW); // turn off the led
            }
            numLeds++;
            if (numLeds > 6)
                --numLeds;
        }
    }
}

After you are finished typing the code above it ctrl+shift+n and open a new tab called "ButtonLed.h" and add this to it:

#ifndef BUTTONLED_H
#define BUTTONLED_H
#include <Arduino.h>

// We create new data type called ButtonLed which stores the button's pin
    // and the led's pin; this allows us to keep both an led and it's
    // corresponding button together without have to manage 2 arrays
    struct ButtonLed{
        int buttonPin;
        int ledPin;
    };

#endif

Make sure you open a new tab and not a new project. Also as others have said you should really learn how to program. Be aware this code compiles however, I haven't tested it. I will update the code when you tell me what pins the leds are connected to.

Edit 1

I added a while loop that allows the user to keep trying until they guess correctly.

Edit 2

I also updated the code for which pins the leds are connected to. Remember they're connected to "pins" Not "ports.


How do I use the additional serial ports on an Arduino UNO R3 clone?

Those are not additional I2C and UART ports, those are additional connectors connected to the normal peripherals. They are used in exactly the same manner as the normal connector.


You cannot send larger values because byte only covers the range from 0-255.

To send larger values, you can break your int variable into 2 byte variables. Here's an example:

// On Arduino
int myVar = -123;
byte myVar_HighByte = myVar>>8; // get the high byte
byte myVar_LowByte = myVar; // get the low byte
// x86 compatible machines are little-endian so we send the low byte first
Serial.write(myVar_LowByte);
Serial.write(myVar_HighByte);

% On MATLAB
s = serial('COM10')
fopen(s)
myVar = fread(s,1,'int16')

Disclaimer: Syntax might not be entirely correct, since I have no MATLAB or Arduino near me when I typed this. But you should get the idea. ;-)

Edit: On second thought, it might be easier to use a pointer.

// On Arduino
float myFloat = 3.14159265359;
byte* ptr = (byte*) (&myFloat);
Serial.write(*ptr++);
Serial.write(*ptr++);
Serial.write(*ptr++);
Serial.write(*ptr);

% On MATLAB
s = serial('COM10')
fopen(s)
myVar = fread(s,1,'float')

Having said that, you will still have to take care of the endianness, if you use a different microcontroller.


The code below generates 38 kHz and modulates its duty cycle.

// Example of modulating a 38 kHz frequency duty cycle by reading a potentiometer
// Author: Nick Gammon
// Date: 24 September 2012

const byte POTENTIOMETER = A0;
const byte LED = 10;  // Timer 1 "B" output: OC1B

// Clock frequency divided by 38 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 38000L;

void setup()
 {
  pinMode (LED, OUTPUT);

  // set up Timer 1 - gives us 38.005 kHz
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1); // fast PWM, clear OC1B on compare
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  }  // end of setup

void loop()
  {
  // alter Timer 1 duty cycle in accordance with pot reading
  OCR1B = (((long) (analogRead (POTENTIOMETER) + 1) * timer1_OCR1A_Setting) / 1024L) - 1;

  // do other stuff here
  }


Creating a webserver on a Wemos D1 mini pro

you should go for the "Advanced Webserver" example provided by the ESP8266 libraries in your Arduino IDE.
The webserver is using callbacks like

server.on ( "/", handleRoot );
server.on ( "/test.svg", drawGraph );

and so on.
Then you can use these handles to give back a html page to your browser like

server.send(200, "text/plain", message);       //Response to the HTTP request

Note how the function returns an 200 http code to your browser, which is mandatory for showing up your web page!


Can I safely power my UNO and DC motors with the 5v1A and 5v2.1A ports on a USB charger?

You can power the Arduino from either side, since it will only draw what it needs, and most arduinos are powered from a .5 amp USB port. But you'll want to reserve the higher current side for the motors.

Make sure your motors' total draw (including starting current) doesn't exceed the 2 amps available.

Unless you can find out for sure that the two power ports are isolated from one another, you're better off to assume they are not and provide motor spike damping yourself.


When you want to transport 8 people to a festival you can either use two cars and have 4 in each car, or you can get a minibus and have everyone together in one vehicle. It's often simpler to get a minibus, though hiring one may be outside your budget, so two cars is quite often the norm. The tricky part is to set up some form of communication between the drivers so they can both get to the same place at the same time and find each other.

It is exactly the same with microcontrollers (which the Arduino basically is). You can use one big powerful microcontroller to do everything, or you can split your task between a number of smaller microcontrollers. The tricky part is setting up some form of communication between them so that they can all coordinate what they are doing. Bigger microcontrollers can be more expensive though, and if you already have a couple of Arduinos at your disposal then connecting them together and sharing out different parts of your project to them is a good way of going.

Communicating between the Arduinos can be done in a number of ways, depending on how many Arduinos you are connecting, what kind of data there is going between them, etc. One common method which is well documented is to use I2C (Wire.h) to communicate. This is often chosen because it uses just two wires. For higher speed communication SPI is a good choice, but it requires more pins (4 for bi-directional communication). Of course, you can also connect them together using the UARTs, but on the smaller chips (such as the ATMega328P you get on the Arduino Uno) you only get one UART and that is used for programming, so using that for other things gets tricky.


Inaccurate voltage readings on an esp32 as opposed to multimeter

I see multiple problems with your setup:

You only take a measurement every 100ms. That measurement takes the voltage during a very short time span. But the lowest string on a guitar in standard tuning has 82.41Hz (E2). You are measuring at 10Hz. According to the Nyquist–Shannon sampling theorem you need to measure at at least twice the frequency of your lowest frequency to measure. Otherwise your measured data will not have any real meaning and will not represent the input wave. So you need to measure at least with 165Hz.

The amplifier can output voltages up to it's supply voltage, so 5V. You connect the output directly to the ESP32, which is a 3.3V device. That can damage the pin, that you are using.

Currently you are trying to measure the signal directly. But you wrote, that you want to have the amplitude. Currently you would need to calculate that in code (for example by taking the min and max value over a time range greater than one period of the lowest frequency, so at least 12ms (1/82.4Hz)). A multimeter most likely will do that in hardware with analog electronics.

I'm not sure if it is good to connect a speaker and the ESP in parallel. As a speaker is basically an inductor moving in a magnetic field, you might get backwards voltage induced by it. That might be harmful to the ESP. Others here might know more about that.

You connect the Arduino ground to speaker ground. But that is most likely not the same as the amplifiers ground. Most likely the amplifier drives the speaker symmetrically, so also with negative voltages in reference to the speaker ground. That can damage the ADC of the Arduino. Also it's unclear, how good that ground actually is. That pin is not meant for grounding a microcontroller. Driving a speaker is different from measuring the voltage with an Arduino, so you would need different amplifiers to do it.

I'm not an expert in the field of analog electronics, but I guess you could use a diode to get one half-wave and then feeding it into a low pass filter. The resulting voltage is relatively steady (depending on the cut-off frequency of the filter) and can then be measured by the ESP. I'm sure, that this will only give you a rough measurement of the amplitude, but enough for typical applications like amplitude visualization. For really precise measurements you most likely need to use a more complex electronics setup to work against the non-linearities of the parts (especially the diode).


You need CH340G drivers. CH340G is a chip that basically replaces the usual ATMega 8U2/16U2 that is used for USB to serial interface. As CH340 cannot be reprogrammed it means that you can't emulate other USB devices with your arduino for example a keyboard.

You can download the drivers here.


Interruption triggered twice when set to FALLING

but sometimes when releasing the button the interruption also fires

Yes, well when you release the button it may also bounce. In other words OFF/ON/OFF so that will count as a press. A capacitor over the switch might be better.

Example:


Is SPI a good way to connect two rfid modules on separate arduino boards?

Its very easy.

Set one PIN of ARDUINO as ouput pin. You will write that PIN HIGH when your conditions are matched in ARDUINO1 then SET LOW after 1 mS.
Connect that PIN of ARDUINO1 to external Interrupt PIN of ARDUINO2.
Write a CODE for ARDUINO2 such that when EXTERNAL INTERRUPT OCCURS it will set variable high indicating that Conditions is Matched in ARDUINO1.
While providing access to on ARDUNO2 check that variable status if it is HIGH grant access and SET it LOW.

This is the basic Structure you can follow using interrrupt.


How do I upload the sensor data from arduino into a database?

First you have to create the table in your MySQL database, like:

CREATE TABLE IF NOT EXISTS `table_log` (
  `log_id` int(11) NOT NULL AUTO_INCREMENT,
  `log_date` date NOT NULL,
  `log_time` time NOT NULL,
  `log_t1` float NOT NULL,
  `log_t2` float NOT NULL,
  `log_t3` float NOT NULL,
  `log_t4` float NOT NULL,
  `log_vbatt` float NOT NULL,
  PRIMARY KEY (`log_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1;

You can execute it in your phpmyadmin page (or create the table manually there). Above we have columns for auto-increment id ('log_id' - necessary), date & time, 4 temperature values and voltage value (modify these according your requirements).

Than the query to create a new record would be like this:

INSERT INTO `table_log` (`log_id`, `log_date`, `log_time`, `log_t1`, `log_t2`, `log_t3`, `log_t4`, `log_vbatt`) VALUES
    (0, '2016-03-04', '01:53:30', 1.0, 2.0, 3.0, 4.0, 3.0);

You need to create this string dynamically (with real values) and use instead of INSERT_SQL.


Arduino Force sensitive Resistor with an lcd

From the Library Manager, install the LcdBarGraphX library by Balazs Kelemen.

There are several examples there as well.


Why all unset pins of my Arduino Uno are outputting 2 volts?

The electric shocks being felt is due to leakage current from the laptop's switchmode power supply. All unearthed mains powered switchmode plug pack power supplies leak a few micro amps and voltages in excess of 80 volts AC as measured from the plug packs output socket to ground will be observed when measuring with multimeters having 10 meg ohm input impedance.
The solution is to have the GND pin of the arduino board connected to earth. Here in Australia all computer power supplies are grounded via the 3 pin power plug.


Recommend an Arduino Uno shield to monitor the state of 5 DPDT electrical switches

If you're really set on measuring the state of every single connection of every single switch (though I still don't see the need) then yes, you'll need 20 IO connections.
You could create those with IO expanders (MCP23017 for example), or you could use multiplexing.
Instead of 4x5 (20) IO pins you'd instead need 2+10 (12) IO pins.
Treat all the "Common" connections as the rows of a keypad and all the NC and NO connections as the columns of a keypad. Add a smattering of diodes to isolate everything, and you can then scan through the switches one at a time checking each of the two switch states.
You can read more about keypad matrices here.


First, fix the indentation:

New = digitalRead(button);
if ( New!=old) {                        // If the button state has changed
    if ( New == HIGH ) {                // If the button is now in the pressed state
        if (LEDstatus == LOW) {         // If the LED was off
            digitalWrite(LED,HIGH);     // Turn the LED on
            LEDstatus = HIGH;           // Remember the LED state for next time
        } else {                        // The LED was on, so turn it off
            digitalWrite(LED,LOW);
            LEDstatus=LOW;              // Remember the LED state for next time
        }
    }
    old=New;
}

That makes the code a whole lot easier to understand.

It only does something when the button is pressed (switches to HIGH state). It doesn't do anything when you release the button.

Each button press changes the state of the LED.

if it was off, it turns it on. If it was on, it turns it off.


is it possible to write two threads in arduino & switch between data & AT command mode dynamically?

You can switch between command and "online" modes, but you cannot use both at once. While in command mode you can't be receiving data, and while in online mode you can't be sending commands.

You would have to periodically switch between the two in your program at a time when you know you won't be receiving data (or you don't mind losing that bit of data).

And no, the Arduino doesn't have the concept of threads. There are a number of libraries that do emulate threads to a certain extent, but they are (usually) cooperative multi-tasking (one "thread" has to manually "yield" to another) and as such are pretty pointless, since you can get the same effect with a decent finite state machine.


Problem in reading data from encoder with arduino

In my experience (industrial encoders and PLCs) when the output don't change when the motor shaft is rotated its usually one of the following:

The set screw connecting the motor shaft to the encoder that isn't tight,
broken wire (bad connection to the encoder) or
a bad encoder.

Your picture shows what looks like a cover over the encoder coupling to the motor.  Look and make sure that the encoder is actually rotating with the motor.

Then double check your connections.  If a DMM still shows no voltage changes (use AC range if turning the motor to show that the encoder output is pulsing).

If there is still no joy, its likely that the encoder is bad.


Is arduino suitable for high frequency application?

Most Arduinos are based on AVR chips clocked at 16 MHz. On those,
you can generate a 4 MHz clock using hardware timers. Bit-banging
data at this speed would be difficult though. It may be possible,
using unrolled loops and hand-crafted assembly... or not, depending on
the specifics of your application. Even if possible, it would be a nice
challenge for an assembly programmer.

The Arduino Due is based on an ARM chip clocked at 84 MHz. This
gives you more leeway to bit-bang at 4 MHz. But even on the Due you
would certainly need hand-crafted assembly.


Arduino on battery getting unstable if temperature falls

To answer your modified question:

Running the ATmega328p at 16Mhz with 3.7v is out of spec - see this EESE answer for reference or the ATmega datasheet - so the obvious solution would be to lower its speed to 8Mhz.

But since you also mentioned that there is an additional GSM breakout board involved (Adafruit Fona), which expects UART (in auto-baud mode) Rx/Tx connection, it might not be that trivial. Further exploration of the Fona library's source code reveals that it has several hard-coded delays (see Adafruit_FONA.cpp::begin, for example), but its core seems to be implemented inside the Adafruit_FONA::readline method, which uses an underlying Stream, which in turns comes from a Software/Hardware serial object, as shown in the FONAtest.ino example that comes with the library.

From my experience, Software/Hardware serial should work fine on 8Mhz, except maybe when using high baud rates, which is solvable.
The hard-coded delays doesn't look like they should cause actual damage except for delay, but you could cut them in half just to see if you can make the library work.

Additional aspect that you should consider is the comment from Adafruit's Fona product page, regarding pin Vio:

  This is the pin that you MUST drive with an external voltage from
  3V-5V to set the logic level converter

So, despite that from the datasheet, the Fona seems to have a voltage regulator, you might still want to consider adding a decoupling capacitor between Vcc and Gnd of your battery, to  mitigate transient current draws from any component in your circuit.


Merge two Arduino projects (change build process)

Assuming that each separate hardware device (ESP32?) must run self-contained with both the fundamental parts, and the use-specific parts, then you would do well to separate out the fundamentals into a library, and then include that library in each use-specific sketch.

The Adafruit Unified Sensor Driver would be one project that shows this. Each of the sensor libraries based on this driver must #include the unified sensor driver library, and that provides some basic properties and interfaces, while each sensor's individual code handles the specifics for communicating to/from that particular unique hardware device.


All the shields are 5v compatible. So no need to worry about 3.3v.

But there may be a chance of insufficient current if you use a battery to the power-jack of arduino mega (due to the internal voltage regulator). I'd suggest you cut a USB cable and solder the +5(red color) wire to VIN on the mega and ground(black wire) to GND pin. And use a 'power bank', which is used for mobile phones.


Arduino Uno not working as usb HID interface

You have reprogrammed the ATMega16U2 chip to be a HID device. Thus it no longer functions as a serial interface between the Atmega328P and your computer. You need to reflash the firmware on the ATMega16U2 to return to normal operation.
I have instructions for how you might to this on my bootloader uploader page. In brief, you need to put the original hex file back:
sudo dfu-programmer atmega16u2 flash Arduino-atmega16u2-Uno-firmware-Rev3.hex

There are other ways of turning your Uno into a HID device. Search for "Virtual USB Arduino".
More easily, get a Arduino Leonardo or Arduino Micro which are designed for this sort of thing.

Yes but how can I use it as a HID? ...  it cannot detect it so how would I be able to upload code to it  ...

What is "it" here? Look at this photo:

There are two processors on the Uno. It sounds like you have reflashed the ATMega16U2. Do you want to use the ATMega16U2 as a HID or the Atmega328P as a HID? They need totally different techniques.
Once you reflash the ATMega16U2 you can't "get to" the Atmega328P via the USB interface.
On the page you linked there is a workflow for programming the ATMega16U2. Are you following it? If so, which part is not working for you? If not, why not?


How to get the free/used space on a SD card and transmit it

As SD.h includes

  #include "utility/SdFat.h"
  #include "utility/SdFatUtil.h"

or if you use the SDfat library than this function is more efficient than going all over the place:

#include <SdFat.h>

SdFat SD;

void ShowFreeSpace() {
  // Calculate free space (volume free clusters * blocks per clusters / 2)
  long lFreeKB = SD.vol()->freeClusterCount();
  lFreeKB *= SD.vol()->blocksPerCluster()/2;

  // Display free space
  Serial.print("Free space: ");
  Serial.print(lFreeKB);
  Serial.println(" KB");
}


Found this Arduino Forum Thread helpful.

# wget \
https://pypi.python.org/packages/source/p/pip/pip-6.0.8.tar.gz#md5=2332e6f97e75ded3bddde0ced01dbda3\
  --no-check-certificate
# easy_install pip-6.0.8.tar.gz

Apparently the PyPi Package Site is now HTTPS and hence --no-check-certificate option should be used. Also MD5 Checksum of the package needs to attached in the link in order to avoid a HTTP 404 Error


I see people are recommending mosfets (which is the best option). Keep reading this if you still want to use relay. There are two kind of relays, mechanical and solid state. Mechanicals are cheap but they can be noisy (they make sound) also they have low life expectancy compared to solid state relays. On the other hand solid state relays are faster with everything else but they are expensive. Also you need to check voltage and max current rates before buying.


Directly powering a single 32x16 RGB LED matrix (without external PSU)

When powered through USB, the total current consumption is limited to 500mA by the USB interface. If you are using the power connector, the total current is limited by the on board 5V regulator to 1A.

The board will also require some current, so you can draw around 400mA, if powered through USB or 900mA, if powered through the connector; from the 5V pin.

While the matrix on average may not draw than 300 - 400mA, the voltage regulator can overheat and shut off temporarily, and you will never be able to reach 900mA. The regulator is linear, so any extra voltage you supply will result in waste heat.

It is best to get a buck converter or power the matrix externally. You won't be wasting as much power, and avoiding possible thermal shutoff.


Connecting multiple load cells to the same microcontroller

All you need is the following :

Arduino (Mega, if you need alot of inputs.)
Load Cell Amplifier
Load Cells (I recommend only using four wire cells)
Resistors (Only if you are connecting one cell to one amplifier)

If you are using only one load cell per "Scale" , you would connect it as you say correctly. One load cell to each load cell amplifier and then to the Arduino.

Yes, a single Arduino can in theory take as many scales as the number of Digital inputs you have can provide. You can use the Analog inputs as well but from my experience I would recommend you only use the Digital inputs. You can just share the power and ground sources.

Usually each Load Cell Amplifier will need to use two(2) Digital inputs.

If you want to use multiple load cells together (to improve accuracy) to act as a single scale, you would connect them together in what they call a Quarter, Half or Full Bridge wiring configuration depending on how many you would like working together.

You can write to a DB if you want sure.
What I personally like to do is send the readings to the cloud using dweet.io or ThingSpeak. ThingSpeak.com would probably be best for you.

I usually use the NodeMCU arduino boards that have WiFi built in. They are cheap and work great.

I hope this helps.


No, the result is correct, you're just interpreting it incorrectly. If you want the number of elements in a statically-allocated array use:

sizeof(somearray) / sizeof(somearray[0])


Problems improving the inquiry speed of Bluetooth HC-05

You can't change how fast Bluetooth devices report their presence.

Bluetooth works the opposite way that you expect. An inquiry doesn't actively request what devices are there. Instead it sits and listens passively for devices to announce that they are there.

If a device enters the target zone and then leaves again before it has broadcast it's "I am here" signal there is nothing you can do.

That is why inquiries take so long. They wait enough time for devices nearby to announce that they are here.

I am not familiar with that specific module, so I don't know if it is always listening in the background and maintaining a list, or just listening during and enquiry, but either way the onus is on the remote device to announce that it is there.