To be clear, you want to read the values of buttons (meaning unspecified) and use those values to set a float and an int variable. Further, you want to write a function that takes a couple of parameters that specify where you want to store those button values?

That is an unusual way to use function parameters. Usually function parameters specify an input value, and then you use that value to do something. Instead, you want to have the inputs be globally available readings (button values) and have the function parameters specify where to store those values.

C and C++ function parameters are usually passed "by value". That means that what gets sent to the function is a value, not a pointer to the variable that contains that variable. Thus the called function can't change the original variable.

If you want to pass a pointer to the variable, you have to use the & "address of" operator to pass the variable "by reference".

Your function might look like this using C++ pass by reference syntax:

void SetTFgr(float &T, int &FGr) {
    float input_T = //figure out button value for T
    T = input_T;
    int input_FGr = //figure out button value for Far
    FGr = input_FGr;
}

Then you'd invoke it like this:

SeTFgr(T, FGr);

You could also accomplish the same thing using C pointer syntax.


What's the function of this transistor on Arduino Mega?

It's a P-channel MOSFET.  It's job is to act as a "dropless" diode.

The principle is this:

MOSFETs have a built-in diode across them in reverse bias (an effect of the chemistry)
The P-channel MOSFET is connected backwards in series with the incoming USB power.
The internal diode conducts power when there is +5V in to the USB to give power to the board.
The diode imposes a voltage drop, but there is enough voltage still to run the circuitry.
An op-amp compares the incoming voltage from the barrel jack (divided by 2) against 3.3V.  If it's less than 3.3V (6.6V incoming) or not there at all, it turns on the P-channel MOSFET
The MOSFET then short circuits the internal diode removing the voltage drop, giving the full 5V from the USB to the rest of the board.

simulate this circuit – Schematic created using CircuitLab

Note: diode shown is internal to the MOSFET.

The MOSFET is designated T2 in the schematic, and is a FDN340P on the reference design, although the actual model is not that critical, as long as the threshold voltage is above about -3V and it can happily handle 500mA or more.


Some important facts:

The 32U4 cannot act as a USB master, only a USB device (it doesn't have a USB OTG interface).
The USB shield is an SPI based device. It can communicate with any host MCU that can use SPI, as long as you can wire it in properly.
The Arduino doesn't have the processing power or memory to deal with the sheer onslaught of data a USB camera sends.

So yes, you could use the USB shield with a 32U4 based board if you can work out the right wiring. However you will not be able to use things like cameras with it since you lack the processing power to do it.

For camera work you need something more like a Raspberry Pi.


Arduino on breadboard, and then soldered using a board made on Eagle but won't work

I haven't worked out why it's "not working", but some comments on your PCB:

Your crystal is too far from the clock pins
Your crystal capacitors are most definitely too far from the crystal
There are no decoupling capacitors on your Vcc / AVcc pins

Your crystal should be right next to the pins on the chip that it is connected to, and the capacitors for it should be immediately next to that. The layout you have at the moment, if it actually works, will be radiating huge amounts of EMI and would immediately fail any emissions test you'd care to perform.

Without decoupling capacitors on the power pins the chip may not function properly.

Edit: I have just found your main mistake

You haven't linked the output of your regulator sub-circuit to Vcc. Power gets regulated but goes nowhere.


You can indeed use pointers, but passing multi-dimensional arrays is a bit of a pain in C(++).

There's a pretty good explanation here.


Arduino UNO/Nano communication with SP1ML-868 module

For some weird reason, this only works when the Arduino RX is connected to the module RX, and TX with TX.

This works because in that configuration you are actually using your Arduino as a USB-serial adapter. When you make the RX-RX, TX-TX connection you cannot communicate between the ATmega328P on your Uno but you are also making a RX-TX, TX-RX connection with the ATmega16U2 chip on your Uno that is used as the USB-serial adapter on the board.

I feel that it's problematic to try to use Serial (pins 0 and 1) for communication both with the computer and the module. Instead I would recommend using the SoftwareSerial library for communication between the Uno and the module.

SoftwareSerial doesn't work reliably at 115200 so you should first use the current working wiring to configure the module to communicate at a lower baud rate. 9600 is quite safe but if communications speed is a bottleneck for your application you can probably use a higher baud rate.

Next, wire the module to any unused pins on your Uno other than 0 and 1.

Finally, upload the following code to the Uno:

#include <SoftwareSerial.h>

SoftwareSerial SP1MLserial(10, 11); // RX, TX

void setup() {
  Serial.begin(115200);  // set this to the baud rate of the Serial Monitor
  SP1MLserial.begin(9600);  // set this to the baud rate of the module
}

void loop() {
  if (SP1MLserial.available()) {
    Serial.write(SP1MLserial.read());
  }
  if (Serial.available()) {
    SP1MLserial.write(Serial.read());
  }
}

This is the equivalent of the simple echo code you posted above and can be used to verify that everything is working before moving on to more complex code. I have arbitrarily chosen pin 10 for the Uno software serial RX pin 11 for the TX pin but you can modify the code to any pins that are convenient for you. You should make the connections with the module as RX-TX, TX-RX.


How do I replace a burnt atmega328 with a new atmega328(bootloaded) in arduino?

Once the bootloader has been burned to it, the chip can replace the one that is currently on the Arduino board. Simply follow normal DIP removal and insertion procedures to replace it.


Using same GPIO pins to control multiple stepper drives

Those devices use opto-isolated inputs. To all intents and purposes they look just like an LED with a resistor in series.
The built-in resistor looks like it sets the current to "between 8mA and 15mA" and typically 10mA, though it's impossible to say what it actually is.  So we'll take the worst-case scenario of 15mA.
The Arduino has an absolute maximum of 40mA, and a recommended maximum of 25mA from each IO pin, with a maximum of 200mA in total through all pins.
That means you ideally can't really have more than one TB6600 per IO pin, but you could get away with 2 per pin, certainly no more.
To run lots in parallel you would need a separate set of drivers that can "fan out" the low-current signal to either a single high current signal or a parallel set of low-current signals.
It looks like you provide 5V to one pin of each input (the anode of the opto-isolator) and sink the current through the other pin (the cathode of the opto-isolator) to ground through your IO pins. That means you could use a single large N-channel MOSFET to sink all of the cathodes in parallel and invert your IO logic in software.


How to generate musical notes using an uno without using tone() function? Can anyone share the embedded c language code for it?

Yes, that's easy enough to do. I wrote a library to do that, as described here.

Basically you could make a class like this:

class TonePlayer
  {
  // addresses of output ports - NULL if not applicable
  volatile byte * const timerRegA_;
  volatile byte * const timerRegB_;
  volatile byte * const timerOCRH_;
  volatile byte * const timerOCRL_;
  volatile byte * const timerTCNTH_;
  volatile byte * const timerTCNTL_;

  public:
    // constructor
    TonePlayer (
          // ports
          volatile byte & timerRegA,
          volatile byte & timerRegB,
          volatile byte & timerOCRH,
          volatile byte & timerOCRL,
          volatile byte & timerTCNTH,
          volatile byte & timerTCNTL)
       :
         timerRegA_  (&timerRegA),
         timerRegB_  (&timerRegB),
         timerOCRH_  (&timerOCRH),
         timerOCRL_  (&timerOCRL),
         timerTCNTH_ (&timerTCNTH),
         timerTCNTL_ (&timerTCNTH)
  { }

    void tone (const unsigned int Hz);
    void noTone ();

  };  // end of TonePlayer

Then implement the two functions like this:

void TonePlayer::tone (const unsigned int Hz)
{
  // it takes two toggles for one "cycle"
  unsigned long ocr = F_CPU / Hz / 2;
  byte prescaler = _BV (CS10);  // start with prescaler of 1  (bits are the same for all timers)

  // too large? prescale it
  if (ocr > 0xFFFF)
    {
    prescaler |= _BV (CS11);    // now prescaler of 64
    ocr /= 64;
    }

  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;

  // reset counter
  *timerTCNTH_ = 0;
  *timerTCNTL_ = 0;

  // what to count up to
  *timerOCRH_ = highByte (ocr);
  *timerOCRL_ = lowByte (ocr);

  *timerRegA_ = _BV (COM1A0);             // toggle output pin
  *timerRegB_ = _BV (WGM12) | prescaler;  // CTC
  }  // end of TonePlayer::tone

void TonePlayer::noTone ()
  {
  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;
  } // end of TonePlayer::noTone

And now call it:

TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

void setup()
  {
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  tone1.tone (220);  // 220 Hz
  delay (500);
  tone1.noTone ();

  tone1.tone (440);
  delay (500);
  tone1.noTone ();

  tone1.tone (880);
  delay (500);
  tone1.noTone ();
  }

void loop() { }

In this example you plug your speaker into D9 (digital pin 9) on your Uno, with the other pin going to ground. Since this plays tones using the hardware timers you can do other things in your loop without affecting the tones.


Arduino sketch not uploading to Arduino Nano

In IDE in the Tools menu, select in submenu Processor the "Atmega 328P (Old Bootloader)" option.

The upload speed 115200 in your console output indicates the you try to upload for new bootloader. The fail to upload could indicate that your Nano has the old bootloader.


External access to Yun - request not recognised as HTML

It works!

The changes to the uhttpd must have done the trick to listen for http traffic on a given IP/port (other than 0.0.0.0:80).

Instead of supplying a port number for the server in the code, I would surmise that the change to the config takes care of it so this, so the port number in code is no longer needed:

YunServer server(XXXXX);

should be changed back to

YunServer server;


Using ATiny102 as HID device(emulating mouse)

I have build a HID midi keyboard with the hiduino lib which is base on LUFA.
http://code.google.com/p/hiduino/w/list

I know LUFA is also capable to build a HID mouse device. But you need to switch to a bigger controller (i think). I used a 8u2 from atmel.

I used AVR Studio 6 to compile hiduino.
Currently i have no link to the LUFA because the git page is gone. Maybe you find a mirror or a other webpage.


Reading serial.print data with unknown characters python

This is not an answer, but you have a insidious little problem in your code that can be easily solved disabling interrupts before using flow_frequency:

  if(currentTime >= (cloopTime + 1000))
   {
     cloopTime = currentTime;              // Updates cloopTime
       // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min. (Results in +/- 3% range)
      noInterrupts();
      int flow_copy = flow_frequency;
      flow_frequency = 0;                   // Reset Counter
      interrupts();
      l_hour = (flow_copy * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flow rate in L/hour

The reason is that you need to freeze flow_frequency so it doesn't change while you are using it. If an interrupt comes while your are using flow_frequency, you will end up with a value that's a mixed of old and new.

Solution: Copy the values updates inside the ISR before using them. Disable interrupts before doing it and reenable after that.

Reason: High level operations like flow_frequency++ and flow_frequency=0 are not atomic. At machine level they are composed of multiple machine instructions, which can be interrupted at any time, leaving things in an undeterminated state.


Multiple node communication using NRF24L01

// check if there is data ready
    uint8_t pipeNr;
    if ( radio.available(&pipeNr) )
    {
        Serial.print("Pipe: ");
        Serial.println(pipeNr);
    }


Mega SPI communication changing between setup and loop

No, there is no problem with SPI on the Mega. If there were it would have been noticed by now.
Instead it's either the way you are measuring it or your method of generating the SPI signals that are at fault (and since you won't show us your real code we can't help you with that).
This is a trace of your provided "code" with the delays reduced to allow easier fitting on a single trace:

Clock goes low when SPI.begin() is called. Then there are the successive transfers - the first being in setup() and the rest in loop(). As you can see they are all identical.


case doesn't work like that; it can only switch on a single integer. Are you trying to pattern-match those sequences of bytes? You'll have to use some sort of state machine instead, keeping track of what bytes you've received and where in the expected pattern you are.


What is the best way I can detect if a ping pong ball has hit the ping pong table?

Having played ping-pong (badly) I think a microphone would be able to count ball/table impacts quite well. The 'click' sound is much higher than that of hitting the paddle, so you might be able to differentiate on that basis. You might consider a two microphone/transducer arrangement- one coupled to the table and one not touching the table. If you get a simultaneous signal on both, the ball has hit the table. If you get only one signal (from the not-touching microphone) then the ball has hit a paddle. This also gives you the option of getting some timing information.


Connecting a 5v dc fan to ultrasonic sensor

It's wrong.

A fan is a motor. A motor is a power hungry inductive device.

Just like any other motor or similar device (such as a relay or solenoid) you cannot drive it directly from the Arduino. Instead you need (at the very least) a transistor to switch a higher current and a diode to absorb back EMF.


Problems splitting a string to get authentication and command

The command array created inside get_command() is local data. That means it's only available while that function is being executed.

However, you're returning a pointer to it. That means when you're trying to use command afterwards from inside loop(), you're trying to refer to data which has been deallocated. By that point, it's getting used for something else.

There are various solutions to this. A fairly simple approach would be to have the caller allocate the command array, passing a pointer to it into get_command(). For example:

void get_command(char *data, char *command) {
    strncpy(command, data + 24, 3);
}

From loop(), you would call it like this:

char command[3];
get_command(received_data, command);

The command array is still local data in this case. However, it's local to the loop() function (or wherever else you put that code). That means it will still be available when get_command() is called.


Until you have the correct baud rate and good satellite reception, many fields will be zero or empty.  I wrote a diagnostic program for NeoGPS that will try different baud rates and confirm that the GPS device is functioning.  The example program is in this directory:

examples/NMEAdiagnostic

Installation instructions are here.

If you're inside, you may not be able to receive anything.  Move next to a window or go outside.


Strange discrete errors when reading HC-SR04 sonar sensor

I think it's from the HC-SR04... it uses echos and it seems your bad readings are some kind of echo reflections.

What you should do is either remove the bad readings, or take the average/most common value of the last x readings.

Or throw away values too far off some default (like the last average) and average the rest.


firstly, move your pinMode() settings to setup section.

in your code, when the temperature is 21 active pin will be 6 and 8.
you should rewrite your code in next ways:

1:

if (t < 22) {
  ... its cold temp ...
} else if (t > 26) {
  ... its hot temp ...
} else {
  ... it's nor temp ...
}

2:

if (t < 22) {
   ... its cold temp ...
}
if (t > 26) {
   ... it's hot temp ...
}
if (t >= 22 && t <= 26) {
   ... it's nor temp ...
}

and my small advice for u, rewrite in this way, it is more readable

digitalWrite(6, HIGH);
digitalWrite(7, LOW);
digitalWrite(8, LOW);

digitalWrite(6, LOW);
digitalWrite(7, HIGH);
digitalWrite(8, LOW);

digitalWrite(6, LOW);
digitalWrite(7, LOW);
digitalWrite(8, HIGH);

visually changing ENUMS (like LOW or HIGH) more noticeable than changing numbers (6/7/8)


Interpreting pull-up values Rp and Rpu in AM3202 (DHT22) datasheet

The datasheet is as inaccurate as the sensor itself and it is even worse than you think!

In that datasheet is also written: "usually require an external about 5.1kΩ pull-up resistor".

In the datasheet is also mentioned that the output signal can go up to 8 mA for a high output and minimal 10 µA low output. The 10 µA means that the pullup resistor should be 500k or more. That is not correct.

In this datasheet is a picture with 1k.
In this Chinese datasheet is a picture with 5k.
I ran that Chinese datasheet through Google Translate, but that did not help.

Conclusion: The datasheet is not reliable.

You can do as everyone else: use a 10k resistor for short wires, and try 4k7 for longer wires.

That is not the only problem. Some DHT libraries create a shortcut on the data signal.

The AM3202 is not accurate for measuring the humidity. If you want to avoid trouble, then use a better sensor.
A sensor from Bosch is a good choice (for example the BME280 or BME680). Bosch makes datasheets that are reliable. Those sensors from Bosch operate at 3.3V, if you are going to connect that to a 5V Arduino board, then you need level shifters for the signals.


How to share/Reassign analog pin for two Adafruit libraries for two adafruit hardware

If they are using I2C (which i think they are), then it doesn't matter, because I2C is just a transfer protocol. In theory, you could have hundreds of devices using those pins, and have everything working fine. Just try using both, and tell me if anything doesn't work.


How to get the encoder position while the rotary motor is moving

While your delay() function is running, you won't be able to read any data. Suggestion is to use interrupts, which basically guarantee that whenever your pin state changes (low edge, high edge, or any change, feel free to select it), some action will be performed. This action can be reading your encoder position.

Read about it here https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

I am sure it will answer all your questions, it is quite well documented


How can a DC motor (toy) be run with only an Arduino and transistor without an external power source?

Your confusion lies in what can "supply" power.
Your assumptions are all correct for an IO pin. However the Arduino has more than just IO pins. It has power pins.
These power pins are not controlled in any way by the microcontroller - they are merely connections into the power supply circuit that also powers the microcontroller.
So in that circuit the Arduino's power supply is shared between the Arduino (the MCU) and the motor.
The 5V pin of the Arduino can supply up to 450mA (when powered from USB - 500mA less about 50mA for the MCU) or up to 800mA when supplied with about 6.5V into the barrel jack (any more than that will cause excess heat to be dissipated which will reduce the maximum current the 5V regulator can handle before shutting down).


Speed control of BLDC with an integrated controller (Hall out, PWM in)

This is only a partial answer, about measuring pulse period or duration.
For best accuracy, I would recommend using the “input capture” feature
of a 16-bit timer. This is not as easy as using pulseIn() or timing
the signal with micros(): you will have to carefully study the MCU's
datasheet and manually configure the bits of some I/O registers. You
will be rewarded with high accuracy (single-cycle if the timer runs at
the MCU clock speed) and without the jitter inherent to any
software-based approach.
Beware that the Nano and Nano Every use different MCUs, with very
different timers. Both have input capture capability, but if you switch
from one to the other you will have to redo most of the work. Note that
the Nano is capable of 10-bit PWM if you program it low-level.
A software-based approach (pulseIn() or attachInterrupt() +
micros()) has the advantage of portability.


Depending on how fast you need to go, the apa102-arduino library by Pololu doesn't seem to have a hard limit on their LED capacity.  They say the refresh rate goes down after 60 LEDs, but don't say anything about the maximum amount of LEDs you can have.

https://github.com/pololu/apa102-arduino

The max I'm doing at a time is only a string of 48, so I haven't checked how many it can update at once.  I am, however, running a total of 180 LEDs with this library, over 5 separate "channels".

To make it even a tiny bit harder, I'm doing it with a Nano.

This library has a "slow" and "fast" way to update the LEDs.  So far, the "slow" way is faster than the BlueTooth connection I'm sending data over to update the LEDs.

They state that the "fast" method is something like 20x faster than the "slow" way, but takes a little more in-depth programming.  Since the "slow" way works for me, so far, I haven't bothered trying the "fast" way.

Other option:

Talking with a friend at my local maker space, he said that it could be due to the speed of your board vs the timing of your LEDs. If your board isn't running fast enough, it can prevent the LEDs from being updated correctly after a certain amount of LEDs.

He was also saying that if you don't have enough available memory, it can affect how many LEDs you can update.

Seeing as you have an Arduino Uno, you shouldn't have a problem with speed or memory. Without knowing what else you are running on your Arduino (code, sensors, GPS, other shields, etc.), it's hard to say what could be holding you back.

My friend's son uses the FastLED library, so I'm going off other-than-first hand knowledge here.


Syntax for stopping loop until the condition has made false

Your code doesn't make sense. You have a while (1) statement, which will run forever. Inside the body of that statement, you never change the value of temp.

An Arduino sketch's loop() function runs continuously. You should not have a while (1) loop inside your loop function. You should have a loop function something like this:

void loop() {
  temp = //read a temp value somehow
  if(temp>=0&&temp<=20)
  {
    digitalWrite(2,HIGH);
  }
  else if (temp>=20&&temp<=30)
  {
    digitalWrite(1,HIGH);
    digitalWrite(3,HIGH);
    digitalWrite(1,LOW);
  }
}

With that loop function you would fetch a new value of temp on each pass through the loop, then decide what LEDs to light.


SIM900/Arduino UNO R3 serial communication not working

To make everything work fine with this exact code and wiring from the lastminuteengineers, you need to change the jumper (black plastic piece) position in J11. it has to connect the pins D8(RX) and D7(TX), which are the pins at the top of the yellow plate, to the two pins in the middle of the yellow plate.


Reading Arduino serial stream in Java using jSerialComm

Since you are reading received data into array newData, you should replace System.out.println("Read " + numRead + " bytes."); with System.out.print(newData); (not sure about the syntax, since I dont know Java) if you want to print the actual data received and not just the number of bytes received.


Can I connect this LED Matrix to a ESP8266 Huzzah directly?

The Huzzah is a great board but I don't think it is capable of driving a large led matrix by itself.  Adafruit also makes a led matrix feather wing which could enable the huzzah : https://www.adafruit.com/product/3090


Depending on the shield you can connect an external powersource through mosfets or transistors (Depending on the size of the steppermotor).

But if it is smaller motors with a 12v powersource, i really don't se why you would do that, since stepper motor controllers cost about $2-$4 each. Being cost effective i think that writing this question would cost more than actually just go and buy 6-8 controllers. (Don't buy the shield ones, they are overly expensive)


How to perform two tasks in one loop in Arduino?

Consider using a finite state machine to track multiple tasks.  Specifically, the state in which you send your message once every 5 hours.  And, the state you update your LCD, perhaps once every second.

As your tasks are associated with time, consider using the built in Arduino call to millis() to find how many milliseconds the Arduino program has been running.  This will not block your program.  Instead it will immediately return with a number you then need to manage.

To create a delay, use the above number from millis() and add the number of milliseconds for the desired delay.  Call millis() repeatedly until it returns the calculated number or a number greater than the calculated number.  Use this to drive your state machine.  Perhaps you only use millis() to count seconds and use software to count up to 5 hours (5 x 60 x 60 seconds).

Note, millis() will eventually roll over as it is of type "unsigned long".  That is, it will roll over once about every 50 days.  If you want to keep accurate timing when this happens, you will have to account for the roll over in your program.


How do you write to a free location on an external EEPROM?

You can divide EEPROM space into entries and provide each entry with a single "dirty" bit. You could use a separate byte to store it, or reuse a bit from a byte which is not completely used by your data.

Suppose you start with EEPROM willed with zeroes, and you decide that the first byte of each entry holds the "dirty" bit in the LSb. When you log coordinates the first time, you'll have:

 /---"dirty"
01 51 00 00 04 00 00
00 00 00 00 00 00 00
 \---"clean"
...
00 00 00 00 00 00 00

(of course, you don't have to store GPS coordinates as BCD, it's just an illustration).

Note that as you add entries, it's trivial to keep track of the last one: just check the entries in sequence until you find a "clean" one and go back one step. Also note that the first entry is always "dirty".

This will go on until all your entries are "dirty":

01 51 00 00 04 00 00
01 52 00 00 05 00 00
...
01 53 00 00 06 00 00

At this point (when you have to write new data but there are no "clean" entries), you start writing from the first entry again, inverting the value of the "dirty" bit:

 /---"dirty"
00 54 00 00 07 00 00
01 02 00 00 05 00 00
 \---"clean"
...
01 53 00 00 06 00 00

(remember that the first entry is always "dirty"? Thanks to this, it's possible to simply swap the values representing "dirty" and "clean" entries without actually erasing anything).

To sum up, the algorithm is:

read the "dirty" bit from the first entry
scan entries until the value of the "dirty" bit changes, or until you reach the end.
to read the last logged data, use the last "dirty" entry
to write new data, use the first "clean" entry. If there are no "clean" entries, start from the beginning, inverting the "dirty" bit.


Can Arduino libraries be compiled for ARM MCU's?

Depending on the rest of your application, you might find the easiest path is to use the Gecko with the mbed.org tools. There already seem to be mbed Gecko development boards so the task is, to port the Rockblock-IridiumSBD Arduino library.

The benefit of using mbed with the Gecko is it looks like mbed have all of the libraries, including low-power control implemented.

The Rockblock-IridiumSBD Arduino library won't compile 'out of the packet' on mbed.

However, the Rockblock-IridiumSBD Arduino library appears to be a serial interface over a few wires. They recommend 'soft serial' which uses digitalWrite, under program control, and no deep access to Arduino peripherals. That should be relatively straightforward to port to mbed. Mbed has equivalent library calls for digitalWrite, so a first attempt might be a few global search and replace edits.

The alternative would be to use Gecko with an Open Source or commercial development system. However, mbed would provide a faster start, if you have good internet access and are not too paranoid about security, because the tools are 'cloud based', saving you time to set up the tools, and their is an mbed community who might help you over the initial hurdles.


To drive a relay you'll need a transistor (a MOSFET is a good choice) and you'll need a diode across the relay coils to protect the transistor from the reverse current pulse when you remove power from the relay coils.

As Majenko says, if you Google "Arduino relay" you'll find lots of articles covering the topic. (And if you use a digital output line from your PI the exact same circuit will work.)

This MOSFET is a good option for switching high current loads with a 5V logic signal:

https://www.adafruit.com/product/355

The diode will need to be a power diode that can handle your voltage/current needs. You'll need to figure out how much current your light bar uses, and then I'd suggest a diode that can handle twice that much current (at 12V) for a margin of safety.


How to connect Arduino with ESP8266-11 WiFi module to 000webhost (free webhosting)

The web server is using virtual hosts. Unless you tell it to which virtual host are you making a request, the server won't know where to send the request and generate an error.

You need to add the required header Host, which tell it just that.

Make the proper request like this:

String getStr = "GET /getCpno.php?user_type=admin HTTP/1.1\r\n";
getStr += "Host: jvystocksystem.000webhostapp.com\r\n"; // add the required header
getStr += "\r\n";


How many interrupt pins can an Uno handle?

There are two types of "pin change" type interrupts. The external interrupts, of which there are two on the Uno. They are called 0 and 1, however they refer to digital pins 2 and 3 on the board. These can be configured to detect rising, falling, change (rising or falling) or LOW.

In addition to that are "pin change" interrupts, which detect a change to the pin state in any of the 20 pins (A0 to A5, and D0 to D13). These pin change interrupts are also hardware based so, in themselves, will be as fast as the external interrupts.

Both types are slightly fiddly to use at the register level, but the standard IDE includes attachInterrupt(n) and detachInterrupt(n) which simplifies the interface to external interrupts. You can also use the Pin Change Library to simplify the pin change interrupts.

However, steering clear of the library for a minute, we can establish that pin change interrupts can be as fast, or faster, than external interrupts. For one thing, although pin change interrupts work on batches of pins, you don't have to enable the whole batch. For example, if you want to detect changes on pin D4, this will suffice:

Example sketch:

ISR (PCINT2_vect)
 {
 // handle pin change interrupt for D0 to D7 here
 if (PIND & bit (4))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of PCINT2_vect

void setup ()
  {
  // pin change interrupt (example for D4)
  PCMSK2 |= bit (PCINT20);  // want pin 4
  PCIFR  |= bit (PCIF2);    // clear any outstanding interrupts
  PCICR  |= bit (PCIE2);    // enable pin change interrupts for D0 to D7
  pinMode (4, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

My testing indicates that it took 1.6 µs for the "test" pin (pin 5) to react to a change on the interrupt pin (pin 4).

Now if you take the simple (lazy?) approach and use attachInterrupt() you will find the results are slower, not faster.

Example code:

void myInterrupt ()
 {
 if (PIND & bit (2))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of myInterrupt

void setup ()
  {
  attachInterrupt (0, myInterrupt, CHANGE);
  pinMode (2, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

This takes 3.7 µs to change the test pin, a lot more than the 1.6 µs above. Why? Because the code the compiler has to generate for the "generic" interrupt handler has to save every conceivable register (push them) on entry to the ISR, and then restore them (pop them) before returning. Plus there is the overhead of another function call.

Now we can work around that by avoiding attachInterrupt() and doing it ourselves:

ISR (INT0_vect)
 {
 if (PIND & bit (2))  // if it was high
   PORTD |= bit (5);  // turn on D5
 else
   PORTD &= ~bit (5); // turn off D5
 }  // end of INT0_vect

void setup ()
  {
  // activate external interrupt 0

  EICRA &= ~(bit(ISC00) | bit (ISC01));  // clear existing flags
  EICRA |=  bit (ISC00);    // set wanted flags (any change interrupt)
  EIFR   =  bit (INTF0);    // clear flag for interrupt 0
  EIMSK |=  bit (INT0);     // enable it

  pinMode (2, INPUT_PULLUP);
  pinMode (5, OUTPUT);
  }  // end of setup

void loop ()
  {
  }

That is the fastest of them all at 1.52 µs - it looks like one clock cycle got saved somewhere.

There is one caveat though, for pin-change interrupts. They are batched, so if you want to have interrupts on lots of pins, you need to test inside the interrupt which one changed. You could do that by saving the previous pin status, and comparing it to the new pin status. This is not necessarily particularly slow, but the more pins you need to check, the slower it would be.

The batches are:

A0 to A5
D0 to D7
D8 to D13

If you just want a couple more interrupt pins, you could avoid any testing by just choosing to use pins from different batches (eg. D4 and D8).

More details at http://www.gammon.com.au/interrupts


I would use some sort of epoxy and cover up the exposed circuitry. The major concern would be where the wires connect to the board as flex over time can weaken it.

Some options include:

3M™ Scotchcast™ Wet-Niche Potting Kit
Hysol

  US1150™—For electronics, telecommunications, and automotive
  components. Provides environmental hazard protection.

  US1152™—For electronic assemblies. Provides environmental hazard protection.

  Heat might play a factor if you cover up the boards in epoxy but you shouldn't be producing that much heat in a wearable device anyway, right?


ESP8266 EEPROM seems not working, saved data are different when I try to read them

You can read the emulated EEPROM only between begin and end. It works with memory image.

begin allocates the in-memory image.
commit writes it to flash.
end commits and deletes the memory image.


For measuring oxygen saturation (SpO2) with a pulse sensor, you need to use the fact, that hemoglobin, that carries oxygen, will reflect in different light wave lengths, as hemoglobin, which doesn't carry oxygen. But that also means, that you need to use light in at least 2 different wavelengths. Common are one red (about 660nm)(though green may also work) and infrared (about 940nm). When lighted sequentially with both LEDs, you can measure the refection of both parts and calculate the ratio between them (SpO2).

But your sensor only has 1 LED, which is green. So you cannot measure SpO2 with this sensor. You need one fitting the above description.


Probably the end device is set into sleep mode. Check the Sleep Mode(SM) and the sleep period(SP) because what I can see is the XBee gives readings for every 10 seconds.


Losing top brightness when using tip120 and PWM with 70w LED panel

Replace the TIP120 with a Low Rds N-channel MOSFET. Look at AOD508 or AOD514 for example, very low Rds, so it will develop very little voltage drop as the current increases.


Is there any way for one Arduino board to communicate with multiple sensors?

Yes you can ... however, how you transmit the sensor data? If wireless, you need some RF communication, and possibly a microcontroller like Arduino (or ESP) within each sensor module.

With nRF24L01 (2.4GHz) you can use 6 'slaves' (sensor modules in your case) to send data to the master (monitoring module).

Do things one by one:

First make one sensor module
Than make the master to receive data
Than make the GUI screen
Than make the other five sensor modules


Serial.parseInt() has a timeout. If something arrives on the serial, or is left over from a previous transmission and hasn't been read yet, Serial.parseInt() will start looking for a number to parse. When that fails it times out (and so does the second one immediately after it). When that timeout occurs parseInt() just returns 0.

IMHO the Arduino serial parsing routines are very poorly written and should be avoided. I have some tips on how to properly read serial here.


Where to connect BLK and GRN pins of Openlog board on my Uno?

If you read the page about the OpenLog board you can see (on the schematic link) what the pins mean:

I've added the labelling on the board in blue.  The GRN pin (DTR in the schematic) is actually an input, which resets the chip:

Thus:

GRN should be connected to RESET on your Uno, so that when you reset the Uno, you rest the OpenLog.
TXO (transmit out) on the OpenLog would be connected to serial input on the Uno (ie. digital pin D0 - labelled RX).
RXI (receive input) on the OpenLog would be connected to serial output on the Uno (ie. digital pin D1 - labelled TX).
You can see that GND and BLK are both ground pins, and thus should be connected to ground.
VCC (RAW on their schematic) is the voltage input to the 3.3V very-low-dropout voltage regulator MIC5205 on the OpenLog. This will accept input voltages in the range 3.3V to 12V. (The datasheet seems to suggest a maximum of 16V, but it might get rather hot if you did that). Connecting VCC to +5V on the Uno would be satisfactory.


How do I set a 25 kHz PWM signal on an ESP-WROOM-32?

It is very simple to set up a PWM signal at any frequency you desire, with any resolution you desire, provided you don't exceed the maximum 'bandwidth': the frequency multplied by the resolution must be less than half the clock speed of the device.

The full explanation with relation to the ESP-IDF is available here. The article explains the intricacies of all the channels and their configurations. I must confess I have not read it all, because my application was very basic.

In setup(), the code required to instantiate a PWM signal on channel chan at frequency freq, with a resolution of bit_num bits is:

double ledcSetup(uint8_t chan, double freq, uint8_t bit_num)

The code to attach the channel chan to an output pin pin is:

void ledcAttachPin(uint8_t pin, uint8_t chan)

Within loop(), or otherwise, inflict a duty cycle duty to a given channel chan using:

void ledcWrite(uint8_t chan, uint32_t duty)

I recommend perusing esp32-hal-ledc.c in the core files you installed that enabled you to program the ESP32 in Arduino Studio. You don't need to include any files to get the above functionality, but it's always good to know a bit about what goes on behind the scenes.

A few things to note, if reading through the core code is too much:

chan can only be between 0 and 15, and the function will return 0 if you try an number outside these bounds;
you can't attach the PWM output to all of the GPIO pins, as some are input only and others might have secondary functions that you need;
duty is a 32-bit type but the maximum value is determined by the resolution you used for bit_num. For example, if bit_num is 8 then the range of duty is from 0 to 255. I don't know what happens if you put higher number: the duty may stay at 100%,  or the duty may be bitmasked such that writing 256 is the same as  0, 257 is 1, etc.

Once you have mastered this, the ESP32 includes 'fading' functionality, whereby the duty cycle changes from x% to y% in z milliseconds. There are a number of tutorials on the internet for such a thing.

FINAL NOTE:

If you haven't already, take a look at Intel's PWM fan specs. It states that you need an open-collector or open-drain source provided, in your case, by the ESP32. There's a chance that the PWM pin is pulled up to 5.25V within the fan; this will hurt the ESP32 if you just wire the two together. Likewise, the Tachometer output is pulled all the way up to 12V. This will kill the ESP32 if you wire it directly to the fan.


How to program pressure sensor and motor with motor shield

Depending on the jumper settings, the MegaMoto shield will drive current sense voltages onto one or two of the Arduino analog inputs.

Your picture shows the shunt installed to drive A0, which is of course going to conflict with your attempt to use the same pin for the force sensor.

If you are not using current feedback, it seems like you may be able to just remove that jumper, otherwise you will need to pick distinct pins for the current sense and your force sensor.  Consult the manual to be certain.

(The other placement of the other jumper in that block looks a bit suspicious too, almost seems it may be shorting the two current sense channels together, but not certain about that)


Odd symbols in ESP8266 responses to AT commands

I nutted over this for quite a while. If you look up the reference for SoftwareSerial - https://www.arduino.cc/en/Reference/SoftwareSerial - and look at the limitations, you'll find that it won't work above 57k baud rate and pins 2 and 3 wont support change interrupts, whatever they are.  Sometimes I think some of these projects are untested.  I think I'll use the hardware ports on two arduinos and use SoftwareSerial on the right pins and baud rate to get the two arduinos to communicate, or use Software serial to talk to the pc through a MAX232.  I don't think you'll get a 115200 baud esp to talk SoftwareSerial


Use of two external power sources for a power cell - charger

A switch would be the best way of preventing damage, but you could also use diodes to prevent power flowing back to the PSU or Inductive circuit.

I tried something similar once using transistors to prevent both circuits operating at the same time, but never managed to get it to work.  You could practice any solutions on a breadboard with some LEDs.


As you probably already know, the standard setup for measuring a
resistance with an Arduino is to put the unknown resistor in series with
a known one between 5V and GND, and measure the voltage at the point
in-between them:

     5V
     │
     R₁
 A0 ─┤
     R
     │
    GND

where R is the unknown resistor and R1 is the known
reference. The resistance is then computed as:

const float R1 = ...;  // reference resistance

int reading = analogRead(A0);
float R = (float) reading / (1024 - reading) * R1;

First, it is worth noting that the reference voltage does not appear in
this calculation. You could, of course, do the calculation in terms of
voltage, but you should then notice that the reference voltage can be
simplified away. This is not surprising if you realize than the ADC of
the Arduino does not actually measure a voltage: it rather measures a
voltage ratio: the ratio of the input voltage to the reference
voltage. This ratio can then be easily related to the resistance ratio
R/R1. What all this implies is that you should not expect to
get better accuracy by using a 3.3 V reference rather than
5 V. Any inaccuracy in the voltage reference is irrelevant to the
measurement of the resistance.

Next, when measuring a physical quantity, you are almost always
interested in the relative rather than the absolute accuracy. From
the equation above, it can be easily shown that you get the best
relative resolution when the reading is near the middle of the ADC
range:

raw reading    │   64 │  128 │  256 │  512 │  768 │  896 │  960
───────────────┼──────┼──────┼──────┼──────┼──────┼──────┼──────
resolution (%) │ 1.67 │ 0.89 │ 0.52 │ 0.39 │ 0.52 │ 0.89 │ 1.67

This is consistent with your observations, and it means that the
reference resistor should ideally have a value that is of the same order
as the unknown resistor.

Now, for the autoranging, I would advise you against putting all your
reference resistors in series. With this setup, you always have the same
voltage across the unknown resistor, irrespective of what range you
choose. Reading a different input does not help. You may find out that
the voltage between R1 and R2 gives a better
reading (closer to mid-range), and you get a better accuracy on the
measurement of R+R1. However, when you subtract R1
you are immediately degrade the relative accuracy of the result. In
the end you cannot really improve the accuracy this way.

What I suggest is to put the reference resistors in parallel instead of
in series, and power each one from an analog pin:

     A1  A2  A3
     │   │   │
     R₁  R₂  R₃
 A0 ─┼───┴───┴── ...
     R
     │
    GND

You then use these analog pins in digital mode: all of then in INPUT
mode, except one which is set to OUTPUT HIGH. You can try all of
them in turn and select whichever gives a result closer to mid-range. Or
you can implement a smarter algorithm that finds the optimal one without
trying them all.

There is something to be aware of with this setup: the pins have an
output resistance that is about 25 Ω, which ends up being in series
with the corresponding reference resistors. You can account for that by
adjusting, in your code, the values of those references. But then that
output resistance is not very well known, and can vary with temperature.
This should only be an issue when you are in the low ranges though. You
can mitigate this problem by measuring the voltage at the pin that is
currently pulling up, and replacing 1024 in the equation for R by that
reading. That's why I suggest to use analog instead of digital pins.

Finally, there are a couple of limitations that you should be aware of
when measuring resistances with the Arduino ADC. At the low end of the
resistance range, you cannot use a reference resistor with a very low
value, because you have to make sure you do not pull more than about
20 mA from the pin that pulls up. Your smallest reference may then
end up being somewhere around 220 Ω, and you will loose significant
accuracy when you try to measure anything below 50 Ω. At the upper
end of the range, you should be aware that the ADC is meant to measure
voltage sources with an output resistance no larger than 10 kΩ,
otherwise you risk cross-talk between the ADC channels. Then your higher
reference should probably be 10 kΩ, and any measurement above
50 kΩ will give poor accuracy. Going past these limitations would
require extra electronics, like a good-quality op-amp to “condition” the
signal into something that the ADC can reliably measure.


Why does my Esplora only send serial data when the serial monitor is on?

Esplora is based on a MCU with native USB. The native USB reports connected only when it really connects. You have in setup() a while loop until the USB Serial is valid. The skech waits there for connection. Comment out the while (Serial) loop.

The TX and RX LEDs of Esplora are connected to the native USB port Serial interface. They will not light for the Serial1 interface.

You should disconnect the Uno from computer to not disturb the Serial interface with USB connection. Or use SoftwareSerial to communicate with Esplora and have debug prints to Serial Monitor.


The OneWire stuff can be quite slow. I think I timed doing a temperature read at 12.5 mS which is a long time to be in an ISR. I think you will find that the master assumes it is going to get no response and times out, in that time.

1-Wire Peripheral Interface - for Arduino

What I suggest you do, is get the temperature in the slave, as often as you want, and then just return the temperature when requested. eg.

volatile float lastTemp;

void loop(){
  sensors.requestTemperatures();
  float t = sensors.getTempCByIndex(0);
  // protect move of 4 bytes
  noInterrupts ();
  lastTemp = t;
  interrupts ();
}

void requestEvent(){
  Wire.write ((char *) lastTemp, sizeof lastTemp);
}

Untested, but that is the general idea.

Documentation about interrrupts, and why I am turning off interrupts when moving the temperature to a global variable: http://www.gammon.com.au/interrupts


is there any real arduino emulators (so I can upload and run machine code on it)

There are many different processors used in making many different types of Arduino boards.  So there is no one way to write Arduino machine code.

There are emulator for simpler processors available for the asking.  But, while they work, it is not believe they claim to be totally accurate.

At one point in processor development history, ICE machines were widely used.  This is where a real processor is modified to allow access to internal controls and registers.  (This actually sounds like the answer to your question.)  However, as processors grew in speed and complexity, this approach grew out of favor.

Currently, most processors are built with extra internal circuitry and interface to break program execution for debugging purposes.  JTAG is one such industry standard / example.

So, while the question has merit, the common practice is likely not to run code on an emulator, but to run it on the processor using the JTAG interface and an IDE running on a host-computer / work-station.


For the very same reason that you don't normally write 00000069 instead of just 69. The leading 0's are completely meaningless and can be omitted or included without any change to the value.


Does 'digitalPinToInterrupt' work with analog pins

Interrupts only work on interrupt pins. Trying to translate a pin number into an interrupt number for a pin that isn't an interrupt pin will never work.

  External Interrupts: 2 (interrupt 0), 3 (interrupt 1), 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2). These pins can be configured to trigger an interrupt on a low level, a rising or falling edge, or a change in level.

Many pins (including the analog pins) can use the pin change interrupt. This requires an external library which has its own way of interfacing with them (see the examples).


Multiple serial monitors with the same arduino mega

Use an USB to TTL Serial adapter. Wire it to one of the RX/TX pin pairs and in code use the corresponding Serial object Serial1, Serial2 or Serial3. Don't forget to wire Ground.

You can use some terminal program or Serial Monitor in Arduino IDE to communicate over the adapter. You can open a second instance of the Arduino IDE by starting it with the Desktop or menu shortcut. In this instance you can select a different port then the sketch upload port.


Input state is stuck HIGH when function called using input also uses same input to call another function

There needs to be a delay() after the button state is read to allow time for it to return LOW, dumba**.
You already have enough delay() in your textN() functions, just check the button state after calling that function, not before. Code should be as follows:
void loop()
{
  question1();
}

void question1()
{
  if (q1 == false)
  {
    text1();
  }

  button1State = digitalRead(9);
  button2State = digitalRead(8);

  if (button1State == HIGH)
  {
    question2();
  }

  if (button2State == HIGH)
  {
    question3();
  }
}

void question2()
{
  if (q2 == false)
  {
    text2();
  }

  button1State = digitalRead(9);
  button2State = digitalRead(8);

  if (button1State == HIGH)
  {
    question4();
  }

  if (button2State == HIGH)
  {
    question5();
  }
}

This solves the issue completely.


Error: Function not declared in the scope

Because in the call:

 dofun();

you should put from which class you are calling that function.
In your case:

AllTimer::dofun();

in that case your function must be declared as static method.

EDIT:
Thanks to the comment:

I'm not pretty sure if your code reflects what you want to do. Because you can create your timer after defining the class:

Alltimer mytimer;

and call the method as a normal function (it must be declared as public):

ISR (TIMER1_OVF_vect)
{
    mytimer.dofun();
}

But it is hard to say since I m not sure what you want to do.


Why do all analog pins measure the same value?

If you want to measure a pin (i.e. defined as input pin, either digital or analog), you have to use a pull up or pull down resistor (either internal or external depending on what the MCU GPIOs have).

This resistor makes sure in case there is nothing attached, that the (mostly high ohm) resistor will make sure the nonconnected pin will either give a LOW or HIGH as input (or in case of analog, the minimum or maximum value).

When the pin is connected, the pull down/up resistor will change the result so marginally that it can be ignored.


Getting the average of sound in last minute

I assume what you actually want is to measure sound intensity. This is
significantly more involved than just averaging the samples you read. I
have written a few weeks ago a program that does exactly that: it
measures the sound intensity and sends those measurements through the
serial port. It is a pretty short program (43 lines of code) you may be
able to adapt to your needs, so I am now sharing it as a GitHub gist:
sound-meter.ino.

In order for this not to be a link-only answer, I'll try to explain the
program's inner working, and go through the theory of measuring sound
intensity on an Arduino. But first let me put here a disclaimer: a
“real” sound level meter should have a frequency response that complies
with some standards, and it should be calibrated to absolute levels.
This program only provides uncalibrated readings with whatever frequency
response its analog hardware has.

Signal conditioning

Four measuring sound on an Arduino, you obviously need a microphone,
but you also need some kind of interface circuit between the microphone
and the Arduino. The purpose of the interface is to “condition the
signal”, i.e. to make sure the Arduino gets a voltage in the proper
range for it's analog-to-digital converter (ADC). It's typically an
op-amp based circuit that provides some amplification and also adds a DC
bias to avoid clipping the negative side of each oscillation. Ideally,
the DC bias should be around Vcc/2, i.e. 2.5 V on an Arduino Uno.

See this SparkFun microphone
breakout for an example on how
such a circuit may be built (click on “Schematic”).

ADC sampling

Once you have a properly conditioned analog signal, you have to sample
it fast enough to catch all its spectral content. The Nyquist–Shannon
sampling
theorem
tells us the sampling rate should be at least twice the highest
frequency in the signal. For audio signals, sampling rates of the order
of 8 kS/s (kilosamples per second) are typical of low quality,
telephone-like applications, whereas high quality audio would run at
44.1 to 48 kS/s.

The ADC of the Arduino Uno, in its default configuration, takes
104 µs to convert one sample. If you just call analogRead() in a
tight loop, this gives a sampling rate of about 9.6 kS/s, which is
fine for this kind of application, unless we have to measure noise above
4.8 kHz. The problem with this approach is that analogRead() is a
blocking function. Calling it in a tight loop means the program will
spend most of its time just waiting for the ADC. If you do anything else
in the loop, not only will the sampling rate be lowered, it will also
become unsteady, which is generally not desirable.

In order to avoid blocking the CPU, we have to forgo analogRead(), and
instead get our hands dirty with low-level configuration of the ADC. The
ADC of the Arduino Uno offers a so-called “free running mode”, which is
well suited for this kind of application. In this mode, the ADC starts a
new conversion as soon as the previous one is done, ensuring a very
consistent sampling rate of 9.6 kS/s. It can also trigger an
interrupt after each conversion, in order for the interrupt service
routine to retrieve and process the sample. See the datasheet of the
ATmega328P
for details on configuring the ADC.

Removal of the DC bias

Once we have the digitized samples, the first thing to do is to remove
the DC bias that was added by the interface circuit. If the bias is
stable and known (maybe determined by experiment), this only involves
subtracting a constant. If it is not known, it can be estimated by
running the samples through a digital low-pass filter with a cutoff
frequency below the range of interest. Subtracting the output of a
low-pass filter is essentially building a high-pass filter. As an
alternative, a numerical derivative (difference between consecutive
samples) can be used as a crude high-pass filter. This, however, will
bias the sensitivity of the detection towards the high end of the
spectrum. Depending on the noise you want to detect, and on the
background noise, this could be acceptable for your application.

In the program I am sharing, I assume the DC bias is known: it's the
dc_offset constant at the beginning of the program.

Instantaneous intensity

With the DC bias removed, the signal we have is a digital image of the
sound picked by the microphone. It could be tempting to just average it
as is. This, however, would just give zero, as the positive fluctuations
of the signal would cancel the negative ones.

The are several options to solve this problem. We could do a peak
detection instead of an average, or we could take the absolute value
before averaging. The most popular option is probably to compute the
squares of the samples. Since the square of a real number is always
positive, this avoids the averaging-out problem. But the square has also
a deeper physical meaning: it is proportional to the sound
intensity, i.e. the
energy carried by the sound wave.

Low-pass filter

The intensity computed above is a very fast varying quantity. If the
signal is a simple tone of constant frequency and volume, the
instantaneous intensity fluctuates between zero and some maximum at
twice the tone frequency. In order to recover the “constant volume”
property of the sound, we need to perform some sort of averaging or, in
other words, we need a low-pass filter.

There are many ways to implement a digital low-pass filter. The most
intuitive may be to group the samples into batches, and then compute the
average of each batch. However, this is neither the best nor the most
efficient to implement. When I need a quick and simple low pass filter,
I generally use an exponential moving
average.
This is the discrete-time equivalent of an analog RC filter, and it can
be implemented very efficiently by remembering the previous output and
updating it as

output += input - output / N;

where, for efficiency reasons, N should be a power of two. The filter's
time constant is N/fs, where fs is the sampling
frequency. In the program I use N = 256, which makes the
division virtually free. This gives a time constant of 26.6 ms. You
can tune the time constant to your needs simply by changing N, but make
sure it is still a power of two.

Decimation

If you only want to trigger an event when the sound intensity exceeds a
defined level, you may not need this. But if you have other processing
to do with those measurements, it is probably not useful to process more
than one intensity reading per time constant of the previous filter.
That's why the program has a decimation step. This is simply the ISR
periodically signaling the main program that an intensity reading is
available. Notice that, since the sample count is an 8-bit variable, it
automatically counts modulo 256. If you want to increase the decimation
factor, you should make sample_count wider and mask out the bits you
do not need.


What is the Proper Voltage to supply an enough Current to the Arduino

The Technical Specs say that 2.7-5.5V DC is ok so you should be good at 3.7V DC.

Remember though:  Power consumption = Current  x  Voltage

So check that your power supply has enough current available. The current amount used will depend on how many pins you are using. The maximum each digital pin may use is 40mA. 1A (1000mA) will be plenty but mAh (milliampere hours) sounds like a battery specification.

Also, a word from the wise is that some cheap power supplies can be bad (little spikes and dips). If you are having trouble with strange issues it can be a good idea to check the power is ok.


Keeping track of the number of rotations of a stepper motor

you can keep track of number of rotations by calculating the time


Replacing the IC (atmega328) if lifespan has been arrive

You only need to change the IC, not the entire board. The microcontroller IS the IC.
Also, you will not see any degradation, it will just 'suddenly' fail, or starting to fail sometimes, without any warning or counter that counts up/down to 10,000.
Also keep in mind that this number is the MINIMUM guaranteed value, most ICs will go much further.
The best way to prevent getting into problems related with this issue is:

When you have a finished project and it works, just keep that IC for that project.
In case you fear getting into this problem during development, only change it if you are sure you have problems (i.e. you cannot upload your sketch anymore).
Think before uploading 100 times per day a sketch for debugging purposes (add Serial.print lines, or even better, use a PC to debug all non Arduino related code.


Powering Arduino from 7805 voltage regulator

I read that this is not advised, and solutions ranged from making sure the 5V is regulated, to connecting a diode between +5V and Vin to using one of the ICSP pins and so on. So which is actually a good way to do this?

Nothing wrong with that as long as it is regulated 5V (which yours is). You can use either the 5V pin on the header, or the 5V pin on the ICSP connector. They are both the same.  It is good practice to connect a diode between 5V and VIN to prevent current flowing backwards through the onboard regulator should something connected to VIN want to draw current.

  I later realized that the DC motors are rated for max 6V dc, and so switched the 9V battery to 4x AA batteries giving a total voltage of 6V. When I connected this to the regulator, the regulator and the Arduino still turned on, even though the data sheet says the minimum input voltage is 7V. So what is going on here? Can anyone help me understand what is happening?

A regulator has a "drop-out" voltage. That is often in the order of 1.2V for these kind of regulators (it's certainly right for the Arduino's on-board one.

You are providing less than the regulation voltage plus the drop-out voltage, so the output of the regulator will be the input voltage minus the drop-out voltage.

As long as that is above the lowest voltage the Arduino can run from at 16MHz then it will still work fine. You should be fine down to about 4V output from the regulator, and even lower if you're lucky (you may start getting stability problems though since the ATMega328P isn't rated to run at 16MHz at lower voltages).

It also means that the GPIOs on the Arduino will be running at a lower voltage as well.


Using Arduino to detect when a sensor is on and off and display time elapsed

You can easily do this in Arduino.

However I've noticed that you've written the code in C with the Windows functions. Why not write the Arduino code and use what the Arduino already has available, which is the millis() and micros() functions? The only problem with the micros() function is that it will overflow after 70 minutes.

The other thing to mention is how will you know when your sensor is on? One way would be to constantly read the value and set a threshold so that you can see whether the pressure sensor is under pressure or not.

Most of the code for this can be extracted from the various Arduino examples that are on the website.

For the pressure sensor threshold you can use the Arduino AnalogInput example and add an if statement after the analog read and combine that with the millis() function from the Arduino BlinkWithoutDelay example:

int sensorPin = A0; // Choose whichever analog pin you like
int sensorValue = 0;
int flagA = 0;
// flag is used just to indicate if timer has started or stopped

unsigned long startTime;
unsigned long stopTime;
unsigned long elapsedTime;

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

void loop() {
  sensorValue = analogRead(sensorPin);
  // read the value from the sensor
  if(flagA == 0  && sensorValue > xxx) then {
    // if above threshold run timer
    startTime = millis();
    flagA = 1;
  }
  if(flagA == 1 && sensorValue < xxx) then {
    // if falls below threshold stop timer
    stopTime = millis();
    elapsedTime = stopTime - startTime;
    Serial.print("Elapsed time = ");
    // Put your print function in here
    Serial.print(elapsedTime);
    Serial.println(" ms");
    flagA = 0;
  }


for loop reads pots, passes value to PWM pins, can this be in the same for loop?

Having both the analogRead() and analogWrite() in the same loop is
perfectly fine. That would be be my preferred choice if only for one
reason: less RAM consumption. If you split them in two loops, you have
to store somewhere the readings of the four channels, either before or
after mapping. If you keep them in the same loop, you don't need the
pot_vals[] nor val[] arrays. You would use a local variable instead,
which consumes no RAM:

void loop() {
  for (int i = 0; i < 4; i++) {
    int val = analogRead(analog_pins[i]);
    analogWrite(digital_pins[i], map(val, 0, 1023, 0, 255));
  }
  delay(2);
}

  My concern is accidentally mixing up the pot values due to
  difficult-to-perceive timing issues.

“Difficult to perceive”? I would call these issues “imaginary” instead.
You have no risk of “mixing” any values here. Maybe, if you can
elaborate on the kind of issues you imagine you could have, we could
help you clear some misunderstanding about how the microcontroller
executes your code.

Edit: To expand on Andrew's comment, the for loop can be optimized
as

for (int i = 0; i < 4; i++) {
  unsigned int val = analogRead(analog_pins[i]);
  analogWrite(digital_pins[i], val / 4);
}

Dividing the value by 4 is the best way to map the input range to the
output range. It gives a more uniform mapping than the map() call
above, as every output value is mapped to exactly 4 input values. It
could be noted, though, that map(val, 0, 1024, 0, 256) gives the same
uniform mapping.

The division by 4, however, is optimized by the compiler into a bit
shift, which is orders of magnitude faster than map(), and likely to
consume less stack space. There is one caveat to be aware of: this
optimization is only possible if val is unsigned. If it is signed,
then it is compiled into a call to a division routine, which is quite
expensive.

One could be tempted to go even further and get rid of the temporary
val variable, like:

for (int i = 0; i < 4; i++) {
  analogWrite(digital_pins[i], (unsigned int) analogRead(analog_pins[i]) / 4);
}

However, there is zero benefit from doing so: from the point of view of
an optimizing compiler, this form is exactly equivalent to the previous
one. I prefer the former which I deem more readable.


There are four things wrong with your code.

You are not sending the "start measurement" command properly. The Wire.write() function can only send 8 bits, but you are passing it a 16-bit value. Instead you should break it apart into 2 separate 8-bit values:

Wire.beginTransmission(0x63);
Wire.write(0x78);
Wire.write(0x66);
Wire.endTransmission();
The data returned is spread over 9 bytes, not 16.  According to the datasheet:

  Temperature data is transmitted in two 8-bit words and pressure data is
  transmitted in four 8-bit words.

and:

  Two bytes of data are always followed by one byte CRC checksum

That's 2 + 4 = 6 + (6/2) = 9

You aren't waiting for the conversion to complete. According to the datasheet, in "ultra low noise" mode (0x7866) it takes up to 94.5ms to perform the measurement.  So you should add a delay of slightly more than that to allow it to do what it needs to do.
The command you are sending responds with temperature first, not pressure, but you are reading pressure first (and reading the wrong bytes anyway).

In all, your code should look more like:

Wire.beginTransmission(0x63);
Wire.write(0x78);
Wire.write(0x66);
Wire.endTransmission();

delay(100);

Wire.requestFrom(0x63, 9);
uint8_t tmsb = Wire.read(); // Temperature highest byte
uint8_t tlsb = Wire.read(); // Temperature lowest byte
Wire.read();

uint8_t pmmsb = Wire.read(); // Highest pressure byte
uint8_t pmlsb = Wire.read(); // Next highest pressure byte
Wire.read(); // Discard checksum
uint8_t plmsb = Wire.read(); // Next lowest pressure byte
uint8_t pllsb = Wire.read(); // Lowest pressure byte
Wire.read(); // Discard checksum

pressure = (pmmsb << 24) | (pmlsb << 16) | (plmsb << 8) | pllsb;
temp_2   = (tmsb << 8) | (plsb << 8);


Use Female USB Type A as Power Supply for external device

Yes. Just connect VCC to +5V and GND to GND and you can plug a 5V device into it.

If you need to use it as a charge port (for charging a phone) you will need to connect the D+ and D- pins together.


MCU Type ATmega16U2 not avaliable in Eclipse AVR Plugin

The ATmega16U2 on those boards isn't intended to be programmable by the end-user. It's only there to help convert from USB to TTL serial, which lets your computer communicate with the board's main microcontroller. It replaces the FTDI chip which was used on some older boards.

In the case of the Uno, the main microcontroller is the ATmega328. For the Due, it's the AT91SAM3X8E. If you want to program them from the Arduino IDE, you can usually just select the board by name from the drop-down menu.


Try different pins than 5 and 6, because those PWM generators share the timer with delay(), which I'd interpret as: You use analogWrite() to set the timer to fire every n microseconds to toggle your PWM signal  -- and then you call delay(1000), which sets that same timer to fire in one second to continue the program.

Pins 10 and 11 do use a different timer, so try these.

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

  "The PWM outputs generated on pins 5 and 6 will have
  higher-than-expected duty cycles. This is because of interactions with
  the millis() and delay() functions, which share the same internal
  timer used to generate those PWM outputs."


Arduino Uno not able to handle 2-dimensional array

2D arrays work fine on arduino, but you run out of space very quickly.

An uno has 2 kilobytes of ram; your array has 56*96 = 5376 2-byte elements.

I would guess that you are writing over some critical memory value with a 5 at some point causing the program to fail.


How I can divide information stream from bluetooth hc-06?

Your code have various issues.

This:

   if(color==1)
      {
       chosed_color = rPin;
      digitalWrite( rPin, HIGH );
      digitalWrite(rPin, LOW);
       return chosed_color;
      }

means that when you find a color, you exit loop() instead of reading the val variable.

Serial.read

Serial.read read only one byte. If you need to read an arbitrary integer, need Serial.parseInt or some elaborate solution. As it, you are only able to read one-digit integer values.

Worse, when you type "1" in the Serial Monitor, what the program received is the value 49 (the ascii code for char 1).

Also, you have to filter non interesting chars, like LF, CR, commas or whatever char you use as delimitir.

Please, read the excelent post by Majenko about Reading Serial on the Arduino.

Here a better version of your code. It is very basic and lacks all error checking, etc.

const int rPin = 3;
const int gPin = 5;
const int bPin = 6;
int pins[3] = {rPin, gPin, bPin};

void setup()
{
    Serial.begin(9600);
    pinMode(rPin, OUTPUT);
    pinMode(gPin, OUTPUT);
    pinMode(bPin, OUTPUT);
}

void loop()
{
    if(Serial.available()>0) {
        int color = Serial.read();
        int chosed_color = pins[color-1];
        digitalWrite(chosed_color, HIGH);
        digitalWrite(chosed_color, LOW);

        if(Serial.available()>0) {
            int val = Serial.read();
            digitalWrite(chosed_color, HIGH); // I suppose you want this
            delay(val);
            digitalWrite(chosed_color, LOW);
            delay(val);
        }
    }
}


There is no such thing as a PCM file. PCM is completely erroneously used to describe an uncompressed digital audio file. What it actually means is "A file which contains data that can be fed directly to a PCM device without any form of intermediate conversion".

What you have in a "PCM" WAV file is just raw sample data. After your header (usually 44 bytes) you just have 16-bit values representing your sample points, with the two channels interleaved one after the other.

Since PCM is a linear audio representation, the sample data it expects is a simple linear representation of the audio (unlike µLaw or A-law) and with no compression (such as MP3 or FLAC). And that is the exact same data that PWM expects since it too is a simple linear output.

However, none of that matters, because the Arduino simply isn't powerful enough to play your file. Maybe a smaller one (8kHz, mono, 8-bit) would be playable, but not yours. The numbers just don't add up.

There is a PCMAudio example available, but it only works from audio embedded within your program.

There is also a TMRpcm library available which plays from SD card, but is limited to 8-bit mono, though it can supposedly do up to 32kHz sample rate (though I wouldn't want to try doing anything else at all at that rate).

You would be better off using a system more geared towards audio - something with an I2S CODEC chip attached would be the best solution.


It's not possible. To sample a 1GHz signal you need to sample at least 2 billion times per second (a sample rate of 2Gsps). You can maybe get a couple of hundred KILO samples (thousand) per second on an Arduino.

Also the 1GHz signal itself is of no interest to you. What is of interest is what is modulated on the 1GHz signal.

What is normally done is:

Down-mix (filter) the carrier signal to an IF (Intermediate Frequency) usually in the order of a few kilohertz
Demodulate the signal using whatever modulation scheme was used to encode it.
Extract the encoded information from the demodulated signal.

To do that you'd need

the precise carrier frequency (1GHz is not the same as 1.029GHz)
the modulation scheme used (there's loads to choose from)
knowledge about any data formats and encodings used in the signal

As well as the hardware to do all that.

So no, you're never going to come even anywhere close with an Uno. You need specialised RF hardware just to prepare the signal for working with.


Is it possible to package a sketch with dependent libraries for cross-platform compatibility?

I would suggest switching to UECIDE instead of the Arduino IDE. (Yes, shameless plug, it's my IDE).

UECIDE has a facility that I dubbed "localizing" a library whereby it copies it into a libraries folder within the sketch folder itself, and that copy of the library is used in preference to any other library named the same in the system.

That means that a sketch and its libraries then become completely self contained in one folder, and it's perfectly possible to have different versions of the same library in different sketches.


Running a servo and tone() won't compile? "multiple definition of `__vector_32'"?

The problem you're seeing arises when two codes (e.g. libraries) try to use the same interrupt.

If you look at the source code of the two libraries, you'll find that they both make use of a number of ISRs (interrupt service routines): Tone.cpp uses

ISR(TIMERn_COMPA_vect) {...}

for n = 0..5, while Servo.cpp uses

ISR(TIMERn_COMPA_vect) {...}

for n = 1, 3, 4, 5.

Now what happens when you compile this code is that they both libraries generate identical symbols (the __vector_32 part) which then clash when the compiled code is linked to give the final binary you'd upload to your Arduino.

There is no simple way around this because the interrupt handlers need to be  registered at certain fixed positions in flash memory and there can only be exactly one interrupt handler for each of these slots (these slots are simply entries in a look-up table with the addresses of the interrupt handlers in flash, cf. Table 9-1 in the datasheet).

Now to solve this problem you would need to find a way to either merge the interrupt handlers of the two libraries (not so easy I guess), or make them use different interrupts (without looking further into what options the pro micro offers, the code suggests that there are several TIMER interrupts which could be assigned one to the Servo, one to the Tone, if that is supported by the hardware).

In any case you'll not get around modifying the libraries (or writing your own code for one functionality or the other).


connecting RTC DS1307 to ethernet shield

I assume that snippet of code is supposed to provide the +5Vand GND for powering the RTC module.  Well, there's two fundamental flaws with it:

Pins 2 and 3 are the DIGITAL pins, not the analog pins. Instead you want to be using pins A2 and A3.
analogWrite controls the PWM output on pins that support PWM. HIGH is 1, so analogWrite will be providing a 1/255 duty cycle PWM signal on that pin.

So to fix it:

Use pins A2 and A3 instead of 2 and 3
Use digitalWrite() instead of analogWrite().


Exit from for function after detecting obstacles

First, try to avoid duplication of code, so make a sub function (I slightly changed the print statement, but I assume it's only for debugging):
void fadeBlu()
{
    fadeBlueCycle(0, 255, 5);
    fadeBlueCycle(255, 0, -5);
}

void fadeBlueCycle(uint8_t start, uint8_t end, int8_t step)
{
    for (int i = start; i != end; i += step)
    {
        rgb(0, 0, i);
        delay(40);

        Serial.print("halt in step ");
        Serial.print(step);
        Serial.println(halt);
    }
}

Now to break from the for, you can use break, or simply return. It's not a good practice to have multiple return statements in one function, thus put it at the end, and use a break. Also, some people don't like a break and prefer using a `while. This would look like:
void fadeBlueCycle(uint8_t start, uint8_t end, int8_t step)
{
    uint8_t i = start;
    bool condition = true;

    while ((i != end) && condition) // or !condition, depending on what you prefer
    {
        rgb(0, 0, i);
        delay(40);

        Serial.print("halt in step ");
        Serial.print(step);
        Serial.println(halt);

        condition = `some condition`;
        i += step;
    }
}


How to store 1 bit Boolean data into EEPROM and retrieve this 1 bit data?

Since this is Arduino SE I'm going to do this with the Arduino functions, there are other ways of course.

Write a bit to EEPROM:

byte EEPROMbyte = EEPROM.read(EEPROMaddress);
bitWrite(EEPROMbyte, pinBit, pinState);
EEPROM.update(EEPROMaddress, EEPROMbyte);

Read a bit from EEPROM:

boolean pinState = bitRead(EEPROM.read(EEPROMaddress), pinBit);

This is for updating/reading a single bit at a time as asked. If you need to read/write multiple bits at the same time(as I'd assume you are doing after power on) then it's more efficient(and less wear on the EEPROM in the case of the write) to do all the bits at once instead of one EEPROM read/write per bit.

I assume by "I/O ports" you mean Arduino pins. If you're working directly with the PORT registers(e.g. PORTB) then you can just write or read the whole register to the EEPROM, no need to deal with the individual bits.


There are many different types of photo-shields, sometimes they have interconnected rows or they just have individual solder holes or even breadboards.  What you get all depends on what you are doing.  My personal favorite are the interlocked rows so I buy that and use a breadboard while I am developing my project then take off the breadboard and solder everything into place.

Example of non interlocked rows  and an My favorite proto-shield, it has a little of both kinds


How do I set a variable so that after a condition is met the loop ignores input?

You've already described what you need to do.  Just set a boolean variable.  It really couldn't be easier.

boolean runThisPart = true;

void loop() {

  if(runThisPart) {
     // this part only runs if runThisPart is true
     //  if something happens and you don't want
     //  to run this part anymore then
     if(some-condition){
        runThisPart = false;
     }
  }
  //  The rest of your code can also set runThisPart
  //  to true or false to turn that section on or off.
}


The array CRGB leds[NUM_LEDS] only holds the current state of the LEDs. It is used to push the data out to the LEDs. If you want the code to save one color to use later, you need an extra variable, that can hold the color.

Add a variable at global scope:

CRGB saved_color;

In the if statements for R, G and B you can set this variable to the corresponding value, for example:

if(incomingByte == 'R'){
    saved_color = CRGB(255,0,0);
}

And in the if statements of 1 to 8 you can use this value, for example:

if (incomingByte == '1'){
    for (int i = 0; i <= 44; i++) {
        leds[i] = saved_color;
    }
}

Note: The above code does not change any LEDs on R, G or B. They just set the color for future operation 1 to 8.


Any way to use DMA to transfer data to SD Card in ESP8266

So, sorry for late response, i figured it out. Because it took lots of time for me and it might be a prevalent issue, i think it worth to contribute my experience for further similar issues.
As mentioned buffering can do the job, here are some constraints that should be satisfied to have right buffering mechanism;

Writing to SD card SHOULD NOT be handled in the Timer ISR, but store ADC data into a buffer, aka int[] which is normally kept in SRAM (Your Timer ISR should be as short and fast as needed)

Handle reading from buffer to SD outside of Timer ISR in, for example in loop().

priority of ISR should be more than loop(), and it is so by default.

It's a good practice to divide your buffer into chunk of 512 or 1024. for example 2 chunks of 1024 Bytes making your buffer. you check for "filled" flag to be set in the loop() and when this happens call SDFile.write(..) for corresponding filled chunk and then reset the flag.

By conforming to these constraints you enjoy these benefits:

you can be sure that no ADC on time sampling missed because of sluggish SD write process.

by buffering and pilling data and then storing, you have chance to avoid byte wise write to SD, which is  really inefficient. and instead handle write in chunks of 512 or 1024 bytes. which is equal to sector size of SDs. so you have faster SD write process too.

This way you can easily handle voice recording up to 16 ksps even without using DMA.
I have added the code to my github, in this repository; https://github.com/A-R-S-D/WAVRecorder


BASCOM-AVR stk500_2_ReceiveMessage(): timeout: -1

I know next to nothing about Bascom, but Arduino Uno R3 does not use an STK500v2 bootloader.  It uses one that avrdude refers to as "arduino", basically a modified STK500(v1) protocol.  The arduinoisp.ino sketch also implements stk500v1.  So if you're using UNO "as a programmer", that is with arduinoisp.ino, it would also not be STK500v2.  STK500v2 has been used in some of the larger arduino "Mega" boards.
So if you have a choice of programmer, it would be "arduino" or perhaps "stk500(v1)" at 115200 baud.  If you are choosing an arduino board, it sounds like you have an Arduino Mega type board selected rather than the UNO.  If you are using arduinoisp.ino sketch, it would be stk500v1 at 19200 baud.


Arduino receive response from SIM800H to AT+CCLK? command

You declare your variables for month and minute differently (rtcm1[3] vs rtcmm1[3]), but you load rtcm1 with month, and then a few lines later, with minutes.


I'm not sure why your IDE is doing that, but the official Arduino IDE from Arduino.cc works on Ubuntu and does not have that issue. Download from Arduino Software download page.


Arduino Uno R3 to Wemos D1 R2 project migration - Pinout problems

The tricky thing with the WeMos boards is the pin notation is different from other Arduino boards.

Sometimes you will see the digital pins on Arduino boards referenced with the Dn notation. For example: "Connect the HC-SR04's Trig pin to D4 on the Uno". In fact some boards such as the Nano even use the Dn pin notation on their silkscreen. This is just a way of further differentiating the pins from the An pins. You will only refer to that pin by the number 4 in your code.

The WeMos boards are different. You actually need to use D3 and D4 in your code to control the pins marked D3 and D4 on the silkscreen:

#define TRIGGER_PIN D4
#define ECHO_PIN D3

We can take a peek at the source code of the ESP8266 core for Arduino to see why:
https://github.com/esp8266/Arduino/blob/2.4.0/variants/d1_mini/pins_arduino.h#L40-L50

static const uint8_t D0   = 16;
static const uint8_t D1   = 5;
static const uint8_t D2   = 4;
static const uint8_t D3   = 0;
static const uint8_t D4   = 2;
static const uint8_t D5   = 14;
static const uint8_t D6   = 12;
static const uint8_t D7   = 13;
static const uint8_t D8   = 15;
static const uint8_t RX   = 3;
static const uint8_t TX = 1;

Now you can see that if you use your original code:

#define TRIGGER_PIN 4
#define ECHO_PIN 3

That would actually be referring to the pins marked D2 and RX on the WeMos D1 R2!


Hardware to measure velocity via string/wire attatchment? beginner

This is an example of the optical encoder.
You want to use interrupt detection, rather than polling.
Or maybe even an HW counter.
That's all you really need.

I am using 4 of them for a car.

I am in the process of refactoring the code, but you could already have a look at the driver & example I wrote for ChibiOS, here.


My Serial plotter isn't working (arduino)

You must have each set of data point (or points) on a separate line and if you are plotting more that one value you need a space or a tab between each value.

So to have 3 lines on your plot, I think you want this:

 Serial.print(AnalogIn_Val0);
 Serial.print(' ');
 Serial.print(AnalogIn_Val1);
 Serial.print(' ');
 Serial.println(Pwmout_Val);

The output in the serial monitor should be something like this:

123 456 789
234 567 901
...


Have you tried the following?

if(!actualString.startsWith(expectedString)) {
  // do whatever you have to
}

BTW, that is what actually suggested in @EdgarBonet's comment.


Why perform bitwise operations here? (SPI FRAM read method)

Let's assume addr is 0xbeef. Then, if we break down each operation:

expression             │ value
───────────────────────┼───────
addr                   │ 0xbeef
addr >> 8              │ 0x00be
(uint8_t)(addr >> 8)   │   0xbe
addr & 0xFF            │ 0x00ef
(uint8_t)(addr & 0xFF) │   0xef

So this is essentially breaking down the address into two 8-bit chunks,
and transmitting those chunks individually. It's done like this because
SPI only transmits bytes.

  the casting is to keep sign extension from occurring.

Non, sign extension cannot occur, since addr is an unsigned number.
The casting really serves no useful purpose, other than documenting the
code. It would be done implicitly simply because SPItransfer() takes
an uint8_t argument. The casting could be useful if SPItransfer()
was overloaded with a 16-bit version.

  Finally, it always returns the same value x = 0, why?

No, it returns whatever the call to SPItransfer(0); returns, i.e. the
data sent by the FRAM module.


Accessing configuration registers of OV7670 cam on i2c

To communicate with the OV7670:

SIOC => SCL
(pulled up to 3.3V)
SIOD => SDA
(pulled up to 3.3V)
RESET => 3.3V
PWDN => GND
XCLK => Clock signal is necessary (at least 10 Mhz)
Vcc => 3.3V
GND => GND

The XCLK needs at least 10 MHz according to the datasheet, but from other accounts, it seems that's not a hard limit. You can get a 4 MHz clock from the Uno using its timer0; check out this post on how to do it. After this, you can write a small sketch along the lines of:

Wire.begin();
Wire.beginTransmission(0x21);
Wire.write(0x12);  // software reset
Wire.write(0x80);
Wire.endTransmission();
delay(500); // wait for reset to complete

Wire.beginTransmission(0x21);
Wire.write(0x01);  // u now read from reg 0x01
Wire.endTransmission();
Wire.requestFrom(0x21, 1);
while (Wire.available() == 0);  //block till u get something
while (Wire.available())
  Serial.println(Wire.read(), HEX);

You can place everything in setup() after including the Wire library and setting up the XCLK clock signal. If all goes well, 80 should be printed in the serial monitor and this will confirm that you're now communicating over the SCCB with the camera.

I should warn you that while others have used the Uno to grab images from the OV7670, the process is moderately complex, especially for a beginner, and it's not what the Uno is intended for; all you'll be able to do is grab frames and pass them on to some TFT screen or your PC and even then you'll get at most 5 fps, I think, with QVGA or QCIF output. You'd be better off with some ARM dev board, one running Linux perhaps. Good luck.


Serial Communication Not Receiving Entire String

I can see several issues:

If the Serial buffer contains more than one command already, you'll read it too. For example serial buffer contains "s43;t25;" and  the input_string would be something like "s43t25". This is highly to happen if you send those characters in less than 3seconds (as you have delay(500) for each appended character). You have to stop reading from buffer if you detect ';'.
Parsing of commands is also pretty weird. You are blocking for some time, so you can detect 's'/'t' and then use Serial.parseInt(); with Serial.setTimeout(1000); to do similar but much faster get command.
Variables set inside of ISR (function trigger is called from ISR) must be volatile. Otherwise it might be optimized out or into register by compiler.

Anyway, if you want to read whole commands try the serialEvent() example. Just change checking for '\n' to ';' and then you can parse that command in your way when it's complete.


ESP8266 and the AT firmware are products of Espressif. They have everything documented on the web site.

The AT command for version is AT+GMR.


GSM library_ all examples ar working except GPRS?

I had the same problem I solved it by moving the jumper wires on the shield(if you are using one) to SW serial. if that doesn't work try testing it with AT commands


Get data from website with ESP8266 using AT commands

As pointed out in the first comment, my printResponse() function was not working correctly when waiting for a response from a website. I changed my code to the following, and now it seems to work every time.

#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.19\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /test.html HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}


It is looping faster than the serial is delivered, so each time there is a byte delivered, it tests it against 0x30 until nothing is left, and then drops out, leaving nothing .available() for the next if(), so it fails out as well and starts up the loop() again.

I'd read a byte at a time and work with that:

int incomingByte = 0;   // for incoming serial data

void loop(void) {

if(Serial.available())
{
    incomingByte=Serial.read();

    if (incomingByte == 0x30)
    {
         func1();
    }

    if (incomingBute == 0x31)
    {
         func2();
    }

}


Using the SD library with the ESP8266 DevKit

After some trial and error got both the screen and sd card reader working sharing the MISO and SCK lines.
I was using a display wit the Adafruit ST7735 driver (and their library), worked fine with both hardware and software, but the SD card reader (generic, not even a part number on it) was able to work only with hardware SPI as the standard SD library does not support software SPI for some reason.
The most important takeaway is this: The SD library internally uses the predefined MOSI,MISO and SCK pins, but fot the ESP8266 dev kit they were mapped to pins labeled HMOSI, HMISO and HSCLK - D7, D6 and D5. Now that I think about it, the H must stand for "Hardware", if only I had this epiphany sooner.