text:
Calculate absolute time based on cycles and RTC
I'm developing a low power data logging device. It samples sensors at the frequency of 20Hz, and also has a real time clock for absolute time (the logged time need to be exact down to ms).
I think that querying time for every samples would be wasteful of energy. One solution is calculate time based on number of cycles, and after a fixed duration (10 minutes) query RTC to update the time.
Here is my attempt:
#define INTERVAL 12000 //10 minutes: 10*60*20 samples

int count = 0;
int checkPointMillis;
int checkPointRTC;

// timer interrupt at 20Hz
ISR() {
    int a = analogRead(A0);
    int time = millis() - checkPointMillis + checkPointRTC;

    // write data to a buffer

    if (count > INTERVAL) {
        count = 0;
        checkPointMillis = millis();
        checkPointRTC = getRTCTime();
    }
}

Is this a correct approach?

The problem is that getRTCTime only has 1sec resolution. So at the time of the request, it could be up to 999ms off. You could use the RTC to generate an interrupt every second, and connect that to an interrupt pin. Then in the pin-change interrupt check the difference between millis and a whole seconds counter. You can use that difference to get a calibrated millis. Not sure if this is the best solution.

In general, the idea is sound.  But there are problems with some of the details and tuning.
The most important detail:  Use the correct data type for storing and computing with time variables (like time, checkPointMillis and checkPointRTC).  The correct data type is unsigned long (or, equivalently, unsigned long int or uint32_t).
A second detail:  Rather than storing your calibration correction in two variables which you always use as a difference (in effect, checkPointRTC-checkPointMillis) just compute and store the difference.  For example:
...
unsigned long clockCorrection;
...
unsigned long time = millis() - clockCorrection;
...
clockCorrection = getRTCTime() - checkPointMillis;

This will save a few bytes of RAM and a few cycles of computation.
A third detail:  If outside of the ISR you will need to access any of the values computed in the ISR, declared their variables volatile.  Example:
volatile unsigned long time;

Fourth: If getRTCTime() or any of your sensor-reading code use interrupts, you will need to move such code out of the “timer interrupt at 20Hz” section, into (for example) loop(), triggered by a volatile variable going true.  [That's the model under which the balance of this answer was conceived; I overlooked, at first, the “timer interrupt at 20Hz” label.]  Note that millis() itself does not use interrupts.  But if your 20-Hz ISR runs longer than a millisecond, the millis() total will drop one millisecond per millisecond of additional ISR time.
By tuning, I refer to the number of measurement intervals to wait between recomputing the clock correction.  Under reasonable assumptions, the number of compute cycles is so closely the same with a one second interval versus a ten minute interval, that one probably should use only a second (or at the outside, a minute) interval between clock correction computes.
For example, suppose the total number of cycles awake per second is given by the following equation:

a = 20*s + 1000*t + k * r

where s is the number of cycles used per sensor-set reading and recording; t  is the number of cycles used per clock interrupt; k is the number of clock correction computes per second; and r is the number of cycles used per clock correction compute.
For example, if s is 2000, t is 100, and r is 200, the equation becomes

a = 20*2000 + 1000*100 + k * 200 = 140000 + k * 200

Now consider three cases: k equal to 20, or 1, or 1/600, corresponding to a clock correction compute 20 times per second, or once a second, or every 10 minutes:
   k           a
  20        144000
   1        144200
1/600       144000.3

As you can see, under the assumptions s is 2000, t is 100, and r is 200, there is no compelling reason to prefer 1/600 corrections per second to one  correction per second.
If your RTC can be read reliably and quickly, reading it either every time (ie 20 per second) or every second has other advantages:  you compensate more quickly for MCU clock drift (ie, every second, rather than every 10 minutes) and strongly decrease the risk of out-of-order times.
For example, if your MCU clock drifts 2 seconds fast per 10 minutes, readings taken during the first two seconds of each new 10-minute interval would show smaller times than those taken during the last two seconds of the previous interval.  With secondly corrections, no such non-monotonic readings will occur.
Here is a slightly more correct analysis of the 2 seconds fast per 10 minutes case:  2 seconds error in 600 seconds is 3.33 milliseconds per second.  With sensor readings 50 milliseconds apart, and corrected clock readings not more than 3.33 milliseconds out of whack, non-monotonicity won't occur.  However, this does not meet the “logged time needs to be exact down to ms” criterion.  To meet that, drift of more than a half millisecond must be prevented.  That requires drift correction at least 6.67 times per second.  You could accomplish that by making a  clock correction compute at every third sensor cycle.
It should be clear from the example calculations of awake cycles that the major contributor to the count is ISR cycles, here taken as 100*1000, or 100000 cycles per second.  You could set up timer 1 to interrupt 20 times per second and turn timer 0 off (which would disable millis() and require a different time = ... formula).  If each timer 1 interrupt took 1000 cycles, that would contribute 20000 cycles instead of 100000 per second.
Edit 4: As I noted in a comment to Edgar Bonet's answer, one can change the TOP value used for timer interrupts, to control interrupt rate with better resolution than can be obtained by merely subtracting base values.
According to Gerben's comment, “getRTCTime only has 1sec resolution”.  As I haven't seen any code for your getRTCTime() I don't know if that is true or not; but if so, here is another approach for time-rate correction:

• At some beginning point coincident with an RTC seconds-change, record millis() and an RTC reading, in eg millibase and RTCbase.
  • At some interval (eg, 10 seconds or a minute, in each case coincident with an RTC seconds-change) measure millis() and an RTC reading, in eg millinow and RTCnow.  Compute RTCdeltaK as the number of milliseconds from RTCbase to RTCnow.  Compute millidelta as millinow-millibase.
  • Whenever elapsed time in milliseconds is needed, compute elapsedms = ((millis()-millibase)*RTCdeltaK)/millidelta.

The above is an algorithm, and may need some adjustment before use as an implementation.  First, the elapsedms calculation can be arranged to avoid division, using a scaled multiplicative factor based on millidelta, RTCdeltaK, and some powers of 2.  Secondly, relatively constant clock drift is assumed.  If that assumption is incorrect, an average ratio with exponential decay could be used, instead of just a factor equivalent to RTCdeltaK/millidelta.

Yours is a classical problem of clock synchronization. You have a
software clock (your program's idea of the current time) which you want
to keep in sync with a reference hardware clock (the RTC). This is
typically achieved by using a phase-locked
loop, or PLL. It works
as follows:

you measure the difference between your software clock's time and the
reference time
you adjust your software clock based on this measurement.

This is essentially what you are already doing, except that you are
fixing your clock by stepping it abruptly, whereas a PLL would usually
slew the clock to get it in sync progressively.
Stepping the clock has some undesirable effects: it makes the time
discontinuous and, more annoyingly, it can make it non-monotonic. I
would thus recommend you try to slew your clock instead.
Here is the approach I would try if I were in your shoes. I am assuming
you are using an Arduino Uno, or a similar AVR-based board with a 16-bit
Timer 1:

configure Timer 1 in mode 4: CTC mode with TOP = OCR1A
set the prescaler to 64 and OCR1A = 12499 in order to get a period of
50 ms; TIMER1_COMPA_vect will be your data gathering interrupt
configure your RTC to generate a 1 Hz output, and route this
signal to the input capture pin ICP1 (pin 8 on the Uno)
run the PLL logic inside TIMER1_CAPT_vect.

Since the RTC's 1 Hz period is a multiple of the timer period, you
would expect the timer's input capture unit to always capture the same
value. The difference between two consecutive captured values is thus a
direct measure of your clock's drift in units of 4 ppm
(4 µs/s). The ISR would be basically along these lines:
ISR(TIMER1_CAPT_vect)
{
    static uint16_t last_capture;
    uint16_t this_capture = ICR1;
    int16_t drift = this_capture - last_capture;
    last_capture = this_capture;

    // Reduce the drift modulo 12500 into [-6250, +6250).
    if (drift >= 6250) drift -= 12500;
    if (drift < -6250) drift += 12500;

    tune_clock(drift);
}

where tune_clock() is your PLL algorithm responsible for slewing the
software clock.
Pay attention to the signedness of the variables. The subtraction of the
captured values should be done with unsigned numbers, then the result
should be made signed.

Edit: as suggested by James Waldby, I'll give here some suggestions
on the implementation of the PLL. It turns out it is not so simple:
measuring a clock drift is easy, predicting it is harder.
Let me restate the problem. You have a “good” clock: the RTC 1 Hz
signal, assumed to be perfect, but with a limited resolution of one
second. And you have a “bad” clock: Timer 1, which has a 4 µs resolution
but suffers from frequency inaccuracy, instability and sensitivity to
temperature and supply voltage. You want to combine
both clocks into a software clock which tracks the good clock yet has
the superior resolution of the bad clock.
I will use the following notations:

t is the time from the reference clock (the RTC), assumed to be also
the physical time
n = ⌊t⌋ is the integer part of t, which is also the time when we last
got an update from the RTC (a timer capture event)
t′ is the time from the local clock (the Arduino timers)
x = t′ − t is the local clock offset, measured by the ISR above at
integer values of t; the physical time is given by t = t′ − x
y = dx/dt is the local clock drift rate; it's a dimensionless quantity
and typically less than 10−3 (i.e. less than 1 ms/s)
xe(t) is the estimate, made by the software, of the offset x(t)
ye(t) = dxe/dt is the estimate of the drift rate y(t)
te = t′ − xe(te) is our software
clock: a self-consistent estimate of t

The simplest solution, which is equivalent to the one you have in your
question, is to assume x stays constant until it is updated. Thus
xe(t) = x(n)
te = t′ − x(n)
In other words, we are just correcting for the last known offset. The
problem is, as stated before, that this gives a discontinuous time
scale.
A better solution is to try to predict x(n+1), and linearly
interpolate between our previous and our current prediction, thus
building a continuous piecewise linear estimate of x:
xe(t) = xe(n) + (t−n)ye(n+½),
where ye(n+½) = xe(n+1) − xe(n)
From this, the estimated time can be solved for as:
te = n + (t′−xe(n)−n)/(1+ye(n+½))
≈ n + (t′−xe(n)−n)⋅(1−ye(n+½))
The factor 1/(1+ye(n+½)) ≈ (1−ye(n+½)) accounts
for the fact that the clock has drifted since the last update at t = n.
Now we are left with the problem of predicting x(n+1). There are
many possible approaches, and I will try to describe only a few.
Simple PLL
One simple approach is to simulate an analog PLL with a first order
low-pass filter. Here is the first illustration of the Wikipedia article
on phase-locked loop:

Some translation is needed between this analog picture and the digital
domain: The phase comparator takes the difference between the measured
offset x(n) and our previous prediction xe(n). The low pass
filter is implemented as an exponentially weighted moving average. The
output of the filter is our estimate of the drift rate: ye.
The VCO is the formula for estimating te, which has the
built-in drift rate −ye. This could be translated to C++
roughly along these lines:
struct {
    uint32_t n;  // time of last update
    float xe;    // estimate of offset at time n
    float ye;    // estimate of drift rate for t in [n ,n+1]
} clock;

const float tau = 60;  // low-pass filter time constant, in seconds
const float K = 1;     // DC gain of the filter
const float alpha = 1/(1+tau);

// Called by the ISR.
// y is (x[now] - x[1 second ago]) in units of 4 us.
void tune_clock(int16_t y)
{
    static float x;   // last known offset
    x += y * 4e-6;    // update known offset
    float xe = clock.xe + clock.ye;  // estimate of current offset

    // Update time.
    clock.n++;

    // Update our estimate of the drift rate.
    clock.ye += alpha*(K*(x-xe) - clock.ye);

    // Update or estimate of the offset.
    clock.xe = xe;
}

// Estimate the current time.
float time()
{
    float t_local = micros() * 1e-6;
    return clock.n + (t_local - clock.xe - clock.n) * (1 - clock.ye);
}

Note that the code above is only meant as a guide. A good implementation
should use fixed-point instead of floats and should also be
rollover-safe.
The time constant of the filter should be chosen large enough to smooth
out the jitter caused by the 4 µs resolution, yet short enough to
closely track the frequency variations of the local clock. Ideally, it
should be close to the Allan intercept of the x(n) time series.
This kind of PLL normally does a good job at tracking the reference
clock, but it has one drawback: it tends to carry a systematic offset.
Let's assume, for simplicity, that the drift rate is constant. Then it
can be easily seen that the steady state of the PLL carries an offset
error:
te − t = x − xe = y/K
where K is the DC gain of the filter. A large gain minimizes this error,
but it does so at the expense of stability. Too large a DC gain and the
PLL will spontaneously go into large oscillations.
I assume it should be possible to get rid of this systematic bias by
using more sophisticated filters, maybe something like a PID, but I
do not want to dive into the complexities of such filters.
Simple linear extrapolation
Another way of estimating x(n+1), which does not suffer from systematic
bias, is to linearly extrapolate from the two last known values:
xe(n+1) = 2 x(n) − x(n−1)
This means we assume that the drift rate is constant on this
short time scale. The problem with this method is that it tends to
amplify the fluctuations due to the jitter. Assuming for example an
(overoptimistic) drift rate of 2 ppm, the measured offset will
alternate between having zero and 4 µs increments. The
extrapolation will predict every zero increment to be followed by
another zero increment, and every 4 µs increment to be followed by
another 4 µs increment, and thus it will always be wrong. The time
evolution would look as follows:
t[s]    0   1   2   3   4   5   6   7   8   9  10
x[µs]   0   0   4   4   8   8  12  12  16  16  20
xₑ[µs]  0   0   0   8   4  12   8  16  12  20  16

Brown's linear exponential smoothing
Brown's method is one of many linear extrapolation methods
meant to smooth-out noise in the data. It is based on running twice
the same low-pass filter on the input data:
s1 = low_pass(x)   // first smoothing
s2 = low_pass(s1)  // second smoothing

If τ is the time constant of the filter, then s1 is an
average of data which has, on average the age τ, whereas s2
has the age 2τ. When can then, at time t, do a linear extrapolation by
running a straight line through the points (t−τ, s1) and
(t−2τ, s2). This gives the following algorithm for updating
the estimates of the offset and the drift rate:
static float s1, s2;      // x smoothed once and twice
s1 += alpha * (x - s1);   // update s1
s2 += alpha * (s1 - s2);  // update s2

// Update or estimate of the offset.
clock.xe = xe;

// Extrapolate to estimate next offset.
xe = s1 + (s1-s2)*(tau+1)/tau;

// Update our estimate of the drift rate.
clock.ye = xe - clock.xe;

Here again, the optimal time constant should be of the order of the
Allan intercept. Note that the limit τ → 0 gives the simple
extrapolation of the previous section.
The figure below shows the performance of this algorithm on simulated
data. The simulated clock has a drift rate oscillating between 1.7 and
2.3 ppm, and its measured offset is rounded to the closest multiple of
4 µs. The line labeled “predicted (τ = 0)” is the simple
extrapolation of the previous section:

Here, the large jitter of the simple extrapolation method is quite
obvious. On this simulated data, Brown's method works well with a time
constant on the order of 5 s. The frequency of a real clock would
change much more slowly, and a longer time constant would work better.
Now, all this is probably too general for your particular use case. I
didn't know when I started this edit it would lead me so far... If you
can tolerate more than, say, 10 µs of jitter, then the simple
extrapolation should be good enough. And if you only need the time at
t′-periodic intervals, this may enable some optimizations.

The approach of adjusting the drift count due to 6250+ deviation can keep time at perhaps one part per thousand.  However, adjusting the TOP value would allow correction in increments of about one part per 12500.   In other words,  the value loaded into OCR1A should slowly change, over a period of minutes or hours, to produce correct interrupt rate.

@JamesWaldby-jwpat7: I don't understand your comment “[...] can keep time at perhaps one part per thousand”. A properly implemented PLL has exactly zero long term drift (it keeps time at zero parts per million), with only short term variations (phase noise) which depend on the clocks and the PLL time constant. One part in 12500 is 80 ppm, very crude compared with the 4 ppm resolution you get using input capture.

EB, I misunderstood part of your answer and withdraw most of my comment.   It isn't clear to me what control the PLL will vary, what its resolution is, etc.  Perhaps in your answer you could show a typical PLL-corrected time = ... calculation.

@JamesWaldby-jwpat7: Added some options for the PLL algorithm. That was a looong digression...

EB, yes.  Great exposition; I'd upvote your answer again if I could.

If you are using a RTC a far better solution to use alarms.
I use TimeAlarms for this purpose
#include <Time.h>        //http://www.arduino.cc/playground/Code/Time
#include <Timezone.h>    //https://github.com/JChristensen/Timezone
#include <TimeAlarms.h> //  Time alarms for use with Time library
#include <DS1307RTC.h>   //http://www.arduino.cc/playground/Code/Time returns time as a time_t

then include code to do something. The following waits for the Minutes to rollover, then calls function Repeats every 30 seconds etc
const int SampleRate = 30;  // seconds >1

  Alarm.waitMinuteRollover();
  Alarm.timerRepeat(SampleRate, Repeats);           // timer for every SampleRate seconds
  Alarm.alarmRepeat(alarmTime, rolloverLogFile);    // alarm to rollover LogFile (daily)

TimeAlarms can run stuff at one-second-accuracy times, but not 20 times per second.  But perhaps you are referring to using an alarm just for the every-ten-minutes stuff?


text:
WeMOS creating soft access point from old code even when new code doesn't have it
In the past I uploaded the code below:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <DHT.h>

#define DHTTYPE DHT22     // DHT 11
#define DHTPIN D5
DHT dht(DHTPIN, DHTTYPE);

const char *ssid = " Hello_IOT";
const char *pass = "12345678";
String command;
ESP8266WebServer server(8080);

void respond(){
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  server.send(200, "text/html", "
Hello from Wemos R1 Mini
");
}

void outputJson(){
  char temp[400];
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  int tf = dht.readTemperature(true);
  snprintf(temp, 400, "{\"wittyCloud\" : [{\"location\" : \"any\" ,\
    \"temperatureInC\" :%d ,\
    \"temperatureInF\" :%d ,\
    \"humidity\":%d,\
    \"ldr\":%d\
    }]}",
  t, tf, h, analogRead(A0));
  server.send(200, "text/json", temp);
}

void setup(){
  Serial.begin(115200);
  pinMode(BUILTIN_LED, OUTPUT);
  Serial.println("Connect to access Point");
  WiFi.softAP(ssid, pass);
  IPAddress IPserver = WiFi.softAPIP();
  Serial.println(" IP address server : ");
  Serial.println(IPserver);
  server.on("/", respond);
  server.on("/json", outputJson);
  server.begin();
  server.onNotFound([](){
    command = server.uri();
    server.send(200, "text/plain", command);
  });
}

void loop(){
  server.handleClient();
  if(command.equals("/mati")){
    digitalWrite(BUILTIN_LED, HIGH); //turn off BUILTIN LED
  }
  if(command.equals("/hidup")){
    digitalWrite(BUILTIN_LED, LOW); //turn on BUILTIN LED
  }
}

For learning purpose it worked, however when I modified it to the code below for WeMOS, to connect to my home wifi router, it creates instead an access point, and on opening the URL after connecting to the WeMOS access point it displays the web page of the updated code.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include "control.h"
#include "webpage.h"
#include <DHT.h>

ESP8266WebServer server(80);
const char* sid = "router+ssid";
const char* passwd = "ssid_password";

#define DHTTYPE DHT22     // DHT 22
#define DHTPIN D5
DHT dht(DHTPIN, DHTTYPE);
const char* host = "nodemcu";

void outputJson(){
  char temp[400];
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  int tf = dht.readTemperature(true);
  snprintf(temp, 400, "{\"wemos\" : [{\"location\" : \"bangalore\" ,\
    \"temperatureInC\" :%2d ,\
    \"temperatureInF\" :%2d ,\
    \"humidity\":%2d\
    }]}",
  t, tf, h);
  server.send(200, "text/json", temp);
}

void handleRoot(){
  const int nsize = 2300;
  char temp[nsize];
  delay(200);
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  snprintf(temp, nsize,
    "%s\n</\div>\n\
    ",webpage::html);
  server.send(200, "text/html", temp);
}

void handleNotFound(){
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message +=(server.method()== HTTP_GET)? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for(uint8_t i = 0; i < server.args(); i++){
    message += " " + server.argName(i)+ ": " + server.arg(i)+ "\n";
  }
  server.send(404, "text/plain", message);
}

void setup(void) {
  Serial.begin(9600);
  // config static IP
  IPAddress ip(192, 168, 1, 88);
  IPAddress gateway(192, 168, 1, 1);
  IPAddress subnet(255, 255, 255, 0);
  IPAddress dns(192, 168, 1, 1);
  WiFi.config(ip, dns, gateway, subnet);
  WiFi.begin(sid, passwd);
  Serial.println("");
  EEPROM.begin(512);

  // Wait for connection
  while(WiFi.status()!= WL_CONNECTED){
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(sid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  if(MDNS.begin(host)){
    Serial.println("MDNS responder started");
  }
  MDNS.addService("http", "tcp", 80);
  server.on("/", handleRoot);
  server.on("/json", outputJson);
  server.on("/control", control::toggleRelay);
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println(F("HTTP server started"));
}

void loop(void){
  server.handleClient();
}

it creates instead an access point

Did you use setmode() to put it in station mode?
wifi.setmode()
Configures the WiFi mode to use. NodeMCU can run in one of four WiFi modes:

Station mode, where the NodeMCU device joins an existing network.
Access point (AP) mode, where it creates its own network that others can join.
Station + AP mode, where it both creates its own network while at the same time being joined to another existing network.
WiFi off.

When using the combined Station + AP mode, the same channel will be used for both networks as the radio can only listen on a single channel.
NOTE: WiFi Mode configuration will be retained until changed even if device is turned off.
Syntax
wifi.setmode(mode)

Parameters
mode value should be one of

wifi.STATION for when the device is connected to a WiFi router. This is often done to give the device access to the Internet.
wifi.SOFTAP for when the device is acting only as an access point. This will allow you to see the device in the list of WiFi networks (unless you hide the SSID, of course). In this mode your computer can connect to the device, creating a local area network. Unless you change the value, the NodeMCU device will be given a local IP address of 192.168.4.1 and assign your computer the next available IP address, such as 192.168.4.2.
wifi.STATIONAP is the combination of wifi.STATION and wifi.SOFTAP. It allows you to create a local WiFi connection and connect to another WiFi router.
wifi.NULLMODE to switch off WiFi

Returns
current mode after setup

WeMOS access point it displays the web page of the updated code

I think @Ciasto answered that part.

I had this issue with one of my chips. I eventually fixed it by using the SPIFFS uploader tool and uploading a blank "data" folder.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Getting RFID tag data using C#
I am trying to get an RFID tag number using a WinForms application. But whenever I click the Button the application stops responding. Please help regarding this.
Arduino code
void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.init();
}

void loop() {
  if(rfid.isCard()) {
    if(rfid.readCardSerial()) {
      Serial.print(rfid.serNum[0], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[1], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[2], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[3], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[4], HEX);
      Serial.println("");
      delay(1000);
    }
  }
  rfid.halt();
}

C# code
private void button1_Click(object sender, EventArgs e) {
  try {
    serialPort1.Open();
    serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
    textBox2.Text = "connected";
    serialPort1.Close();
  }
  catch(Exception ex) {
    textBox2.Text = "Com port disconnected";
  }
}

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) {
  SerialPort sp = (SerialPort)sender;
  string indata = sp.ReadExisting();
  textBox1.Text = indata;
}

Remove serialPort1.Close(); because that will close the serial port right after you open it.

i tried this now I am getting exception in textbox1.Text=indata; exception is System.InvalidOperationException: 'Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.'

You are closing the port immediately after you open it. You need to keep it open while you are expecting data. Remove the line
serialPort1.Close();

Then, in the callback you try to access the GUI from the callback thread. That's not allowed. Use Invoke().
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
     SerialPort sp = (SerialPort)sender;
     //string indata = sp.ReadExisting();
     string indata = sp.ReadLine();
     //textBox1.Text = indata;
     Invoke(new Action<string>(
         (s) =>
         {
             textBox1.Text = s;
         }
     ), indata);
}

now the error is removed but nothing is shown in textbox

@Ravi First, I noticed I was missing a ) in the code. Second, since you are sending the data with Serial.println(""); you should probably use ReadLine() on the C# side. See updated answer.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Data transmission Serial to TCP
I am trying to send numeric data using ESP8266 to local network python server. Before that I am collecting data from sensors using Arduino UNO and then send it to ESP using hardware serial.
ESP8266 code:
#include <ESP8266WiFi.h>

const char* ssid     = "ssid";
const char* password = "pass";

const char* host = "192.168.1.103";

String serial_data;

WiFiClient client;

void setup() {
  Serial.begin(115200);
  delay(5000);

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

   delay(5000);

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections

  const int port = 8888;
  if (!client.connect(host, port))
  {
    Serial.println("connection failed");
    return;
  }

}

void loop() {

  delay(200);

  while(Serial.available() <= 0)
  {
    //wait for arduino serial data
  }

  if(Serial.available()>0)
  {
    // This will send data to client via TCP
    Serial.println("Sent..");
    serial_data = String(Serial.read());
    client.print(serial_data);
  }
}

Python Server code:
import socket
import sys
from thread import *
from peewee import *

db = SqliteDatabase("data.db")

class post(Model):
    timestamp = DateTimeField()
    current = TextField()

    class Meta:
        database = db

#connecting to database
def initialize_db():
    db.connect()
    db.create_tables([post], safe = True)

initialize_db()

HOST = '192.168.1.103'
PORT = 8888 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

s.listen(10)
print 'Socket now listening'

#keep talking with the client
#Function for handling connections. This will be used to create threads
def clientthread(conn):
    #Sending message to connected client
    conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string

    #infinite loop so that function do not terminate and thread do not end.
    while True:

        #Receiving from client
        data = conn.recv(1024)
        print data

        #send data to database
        post.create(
            current = data
        )

        reply = 'OK ->' + data
        if not data:
            break

        conn.sendall(reply)

    #came out of loop
    conn.close()

#keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])

    start_new_thread(clientthread ,(conn,))

s.close()

After powering up ESP it successfully connects to server and then simulating arduino esp serial communication I am using serial monitor to send some numbers. Before I send anything server outputs number 240:
Connected with 192.168.1.100:26137
240

Then I am sending number 1 but on server terminal I get numbers 49 and 13. Sending numbers some 2 - 3 times and no more data are outputted to server terminal. Should I parse data received from serial to some form I can transmit it via TCP or data should be processed on server side?

The numbers are ASCII Codes (here is a chart from the Arduino website). 49 is the number 1, and 13 is a carriage return ('\n'). There should be a setting in the bottom right corner of Serial Monitor to change line ending, this should be set to "no line ending." If it is, than client.print() must be adding the carriage return, so you will need to remove it in Python. If you are only sending integers, replace
serial_data = String(Serial.read());

with:
serial_data = String(Serial.parseInt());

In the Python code I suggest adding a print statement to check if the connection is closed after
#came out of loop
    conn.close()

Thank you. But can you also explain why after sending number 1 to server it prints 3 times these values 49 and 13 but after I can send anything and server receives nothing?

Is the connection being closed, or is it just not receiving anything?


text:
Problems with installing MIDI library in UECIDE
I installed UECIDE from Majenko but I couldn't register nor email him so I try it here.
When trying in install the MIDI library from 47 effects (https://github.com/FortySevenEffects/arduino_midi_library/releases/tag/4.3.1) I get the following error:
Compiling Failed
Analyzing Arduino_MIDI_Library_v4.3.1.zip ...
Unable to detect any valid libraries in the archive.
You may need to manually install it or re-package it properly.

How to solve this?
I tried install manually by copying files but that didn't result in anything.

The auto-install method only (currently) works with old single-arch style libraries. This one is a new multi-arch style library (though it doesn't use the multi-arch facilities).
You need to install it manually.  Simply that means extracting the zip file into "libraries" within your "UECIDE" folder in your documents (My Documents/UECIDE/libraries on Windows, or ~/Documents/UECIDE/libraries on Linux / OS X).
If UECIDE is open at the time you can use "Help -> Debug -> Rebuild internal structures" to re-scan the available libraries, or just close it and re-open it.

Thanks ... still some errors to be fixed but that's internal in my code. The MIDI library is installed in a breeze.


text:
Where is Arduino on Fedora?
I am trying to install the Teensy loader software but I need to know where Arduino is installed. Does anyone know where in Fedora the Arduino files are?

It depends how you installed it.
If you downloaded the tarball and extracted it then it's wherever you extracted it.
If you used a package manager to install it then they could be anywhere - you should look at the package manager software fedora uses (yum? it's been a while) to see how to find what files a package installs.
If you are running a modern version of Arduino (I know Debian based packages are from the stone age) then the board manager installs will be in ~/.arduino15

Assuming you have installed the tool from the Fedora repositories (that is, using yum/dnf or from the Software tool), the command to run the IDE will be installed at /usr/bin/arduino and you can run it from the command line just by typing arduino — or do the same in the search box in GNOME Shell.
Most of the package itself, including examples and libraries, will be installed under /usr/share/arduino.
And, once you run that program, it will create a new "sketchbook location" at ~/Arduino — that is, a folder named "Arduino" in your home directory. If you've run the IDE already, that folder will already exist.


text:
Set array to array passed as parameter in constructor
I have a constructor which looks like this:
Preset::Preset(char* presetName, MIDICommand* MIDICommands[])
  _presetName = presetName;
  _MIDICommands = MIDICommands;
}

_MIDICommnads is declared like this: MIDICommand* _MIDICommands[];.
When run, this throws the error below on the second line in the constructor:
incompatible types in assignment of 'MIDICommand**' to 'MIDICommand* [0]'
Why do I need to declare _MIDICommands as MIDICommands**, and not MIDICommand* _MIDICommands[]?
The array I pass is declared like this:
MIDICommand* one =  new MIDICommand(1, 2);
MIDICommand* two =  new MIDICommand(2, 2);

MIDICommand* MIDICommandsA[] = { one, two };

EDIT:
When I pass in an array, should I just use MIDICommand* MIDICommands, or do I need the [] at the end?
Now I've taken them off, but then I get trouble with passing the array.
It doesn't find a matching function to call. Basically, this MIDICommand* MIDICommandsA[] = { one, two }; doesn't match this MIDICommand* MIDICommands parameter.
EDIT 2:
So, I've solved the problem of passing the array. I changed the parameter in the constructor to MIDICommand** MIDICommands, and I just pass a pointer to the array.
Now the constructor looks like this:
Preset::Preset(char* presetName, MIDICommand** MIDICommands)
{
  Serial.println(MIDICommands[0]->getProgramChange());

  _presetName = presetName;
  _MIDICommands = *MIDICommands;

  Serial.println(_MIDICommands[0]->getProgramChange());
}

I'm getting an error on the second Serial.println, telling me it is a non-pointer type. I'd like it to be a pointer, so that's what I am looking at now.
_MIDICommands is now declared like this: MIDICommand* _MIDICommands.
EDIT 3: When I try to loop through the array now, it seems I have lost the second element, and have only the first.

Guessing, try leaving off the square brackets in the list of constructor parameters.  If no one answer w/the correct solution, I'll try to dig into this more later.

One is a zero-sized array of pointers, the other is a pointer to an array of pointers. Subtle difference, but important to the compiler.

@st2000 I tried leaving of the square brackets, but then I have some trouble passing the array.

@Majenko Thanks, but I still haven't figured it out.

Using new on a 2KB RAM system is a sure way to avoid the millis rollover problem.

_MIDICommnads is declared like this: MIDICommand* _MIDICommands[];.

This is the major error. That is an incomplete array type. The number of elements (and storage) is unknown.
To solve this you have decide on how the elements should be stored. Should the class allocate storage and copy the values given to the constructor or should a pointer to the vector be used.
One alternative is to use a template class and provide the max element size as a template class parameter.
Cheers!

I've changed that to MIDICommand** _MIDICommands now. Is that not viable as well? I'd rather pass around a pointer to the array of pointers, and it seemed to work, except I can't access my values, so I guess it isn't working in the end.


text:
How to arrange my code block to make it work smooth and correct
I currently working on my system that automatically water the plant based on the water requirement of the plant for one day . I have a java application that let the user input the water requirement of the plant and then the java application send it to arduino the arduino will receive the data and put it inside the variable and it will be use .. I use the following sensor/module ..

SOIL MOISTURE 2 PCS.
WATER FLOW SENSOR 2 PCS.
SOLENOID VALVE 2PS
WATER LEVEL SENSOR 1 PCS.
HUMIDITY SENSOR 1 PCS.
REAL TIME CLOCK DS3231

The data that the java app will send is the water requirements for 1 day for example 400ml , the 400ml will be used by the water flow sensor if the sensor reads that its already 400ml has pass in the tube the solenoid will close the pipe . And my system has a water tank the water sensor is attach to it and will check if the water in the tank is not low if low the arduino will send that data into the java app .. All the sensors reading will be save into database using the java application ..
Here is My Whole code for arduino , its not finish yet because i'm stuck thinking on how to arrange my code blocks . Sorry for my English please bear with me ..
#include <DS3231.h>

//PINS
#define MOISTURE1 A15
#define MOISTURE2 A14
#define WATERFLOW1 A13
#define WATERFLOW2 A12
#define HUMIDITY A11
#define RELAY1 9
#define RELAY2 8
#define ALARM 2

DS3231  rtc(SDA, SCL);
int DELAYNI = 1000;
void setup() {
  // put your setup code here, to run once:
pinMode(MOISTURE1, INPUT);
pinMode(MOISTURE2, INPUT);
pinMode(WATERFLOW1, INPUT);
pinMode(WATERFLOW2, INPUT);
pinMode(HUMIDITY, INPUT);
pinMode(RELAY1, OUTPUT);
pinMode(RELAY2, OUTPUT);

rtc.begin();

Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:

  //Some Code here to get the data send by java app and then assign it to each variable

  readMoistureStatus();
  readWaterLevel();
}
void readWaterLevel(){
  ///Some code here
}

void readMoistureStatus(){

 int  moistureOneSensorValue = analogRead(MOISTURE1);
 int  moistureTwoSensorValue = analogRead(MOISTURE2);

   // checking the moisture range for the first soil moisture
  if(moistureOneSensorValue >= 700){
    // in case of dry soil:
    RelayOne();

     delay(DELAYNI);
  }
  if((moistureOneSensorValue < 700) && (moistureOneSensorValue >= 300)){
    // in case of moist soil:

    delay(DELAYNI);
  }
  if(moistureOneSensorValue < 300){
    // in case of soggy soil:

    delay(DELAYNI);
  }
   //
   //
   // Checking the moisture range for the second soil moisture

  if(moistureTwoSensorValue >= 700){
    // in case of dry soil:
    RelayTwo();

     delay(DELAYNI);
  }
  if((moistureTwoSensorValue < 700) && (moistureTwoSensorValue >= 300)){
    // in case of moist soil:

    delay(DELAYNI);
  }
  if(moistureTwoSensorValue < 300){
    // in case of soggy soil:

    delay(DELAYNI);
  }

}

void RelayOne(){
  //Close or Open the Solenoid

  //Read the water flow if the set point is reach it will close the solenoid using the relay
}

void RelayTwo(){
  //Close or Open the Solenoid

 //Read the water flow if the set point is reach it will close the solenoid using the relay
}

And also how often the arduino read the sensors value ? Or I just let the user decide the interval of reading the sensor and then save to database

I think that overall your code looks good but I don't understand why you need to log data every 1 seconds (DELAYNI = 1000; is approx 1 sec).
Although there's nothing wrong in placing the
if(moistureOneSensorValue >= ...)
...
...

codeblock in your readstatus(), it's best to separate this out into a dosomething function. Alternatively, you can read the moisture status in the void loop() itself and then place a switch case in the doSomething() function.
You can also use the data from the RTC to check moisture and do something:
void setup(){
...
time = DS3231.time(); //Time at the beginning
}

void loop(){

timeElapsed = now() - DS3231.time();//seconds elapsed

if (timeElapsed >= DELAYNI){
    moisture1 = analogRead(MOISTURE1); // Read ADC value
    moisture2 = analogRead(MOISTURE2); // Read ADC value
    updateDatabase(time, moisture1, moisture2, relay1, relay2); //update the moisture values and statuses of the relays to the database
    switchRelays(moisture1,moisture2); // switch relay1 and relay2 depending on vals
time = DS3231.time(); // Update the time

    }

}


text:
Multiplying the voltage output
I'm working on a project where my arduino is receiving a voltage 0-5V, I need the output to be 10V always. Is there a way to do that?

You get a power supply that gives 10V and switch it using the Arduino (just like you would with a relay or a motor). Or if you need analog between 0-10V you amplify it (again with a 10V or higher power supply) with an op-amp.

Hello and welcome. Could you please be more specific about your task? Unfortunately there are multiple interpretations of what you wrote so far. Is your input signal analog (0 to 5 V) or digital (just high and low)? If analog how is your intended relation of the output to the input (multiplication implies an analog relation, i.e. in 0V - out 0V, in 2V - out 4V, in 5V - out 10V) or do you mean that if the input is low (or if analog below a certain threshold) the output should be 0V and if the input is high (analog above threshold) the output should be 10V? [...]

[...] Do you want to drive a certain load with that 10V? If recommending a specific setup (i.e. transistor circuit) that might make a difference.

Assuming the 0-5 Volts is supposed to switch the output, in which case you want a program to control your output, then you will want to use a digital output pin to either switch a relay or a transistor that controls the 10 Volts put out to whatever it is that you are controlling.
Perhaps you want PWM which indicates a transistor circuit.  Hard to tell what you want from the way this is worded.
Taking your words literaly, "I need the output to be 10V always" then that simply means hard-wiring to a 10V power supply.   ;-)


text:
Arduino Mega vs servo shield
I am currently designing a hexapod with a total of 18 servos. I come from a computer science background and know little about electronics, so there is one thing which puzzles me.
Adafruit is selling this servo shield. It can power up to 16 servos while only using two pins. But it's quite expensive as it would cost me ~30€. Add the cost of an Arduino Uno and you are at >50€. At the same time I could just buy an Arduino Mega and power all Servos for a lower price.
I like to think that Adafruit wouldn't sell a uselessly overpriced product, so would there be any advantage to using this shield?
Bonus question: If I'd end up buying the shield, could I just power 16 Servos with the shield and 2 via the Arduino? Would there be any problems with that? Like a delay in the 16 motors or similar issues which could through my kinematics over bord? Would I have to buy two shields (which is not really an option at that price)? Any other suggestions I have not heard of are also very welcome!
If it is of any relevance, I am planning to buy these servos as they are pretty strong and come super cheap in bulk.

The idea of that particular servo shield is that it provides 16 PWM (pulse width modulation) channels. These are all operated simultaneously with no additional processing overhead on the Arduino.
The Arduino Uno itself does not offer 16 (or 18) hardware PWM channels but only 6 (see here). So driving 18 servos without an additional shield would require software PWM which requires some of the Arduino's ressources to be devoted doing the calculations. This may or may not interfere with the rest of your program.
Furthermore the Uno does only provide 14 dedicated digital GPIO pins in total (+6 multiplexed digital/analog pins, as ZS6JMB's answer points out), so additional hardware would* be required either way - or using an Arduino with more pins (such as the suggested Mega). The Mega however offers only 15 hardware PWM channels, leaving you with soft PWM again. (* assuming some pins will be needed for sensors or user interfacing).
An alternative is this board or, uhm, well, cheaper clones if you like. It features the same chip as the shield but with a PCB half the size and thus skipping the "free use area". I expect it to behave the same way like the shield and operate with the same libraries as the both the shield and this board communicate only via I2C. Both can be chained (or stacked for the shield if you will) for up to 992 PWM outputs (62 boards).

you absolutely nailed my question! thanks a lot! just one little thing: what is the difference between the board you linked and the shield? is it just more expansive because it is a shield?

@Neuron from the docs I would say that there is little difference. Both have the same chip and communicate via I2C. I dare say it will work the same way as the shield.

Most of those pen controllers or shields are o.o expanded or own generators. In this case, the resolution maxes out to be just shy of 8 bits.
There are better ways to do it. I can post the link later but I explored quite a few ways to drive multiple servos off of a timer on a pic or avr. The number of servos it can drive is determined by the length of off-duration a servo can tolerate, and number of gpio pins on a mcu.
here is the link: https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/
it provides a few examples for its implementation on PIC and AVR. But the basic concept is the same.
No shield used and it runs in the background so it is full transparent to the user code.

The linked adafruit board claims 12 bit PWM. Do you have details to substantiate the claim it really does not?

I need to correct an earlier poster: the number of PWM pins is irrelevant, since the servo library can control servos on any pins, even analog. That said, the servo library can only control 12 servos, but that has nothing to do with servo pins being PWM or not.
Same poster is also wrong on the number of pins, since the analog pins are fully capable of digital io just like the so-called digital pins. So an Uno has the 14 pins mentioned (0-13, although personally I never include 0 and 1 in that count since life's easier if they are left for serial) and 6 analog pins for a total of 20 (or 18 if you discount the serial Tx and Rx pins).

Thanks for the update on the pins, one should always read the full schematics instead of a simplified table as I did. Sure, all GPIO and multiplexed analog/digital pins can be used for software pwm but hardware pwm does offer a real benefit as in less complex code and reduced computational effort needed on run time. That might or might not be an issue depending on the complexity of the rest of the intended program - a question only the OP can answer.

I would in any case strongly argue that one should not start a project that needs 18 I/O for servos alone on a 18 I/O controller - what about user interface and sensors? So there is imo nothing wrong in designing this using either a "bigger" board or with additional hardware such as the I2C driven PWM extension.

thanks for the correction. but dont post these as new answers, as answers
on stackexchange should answer the question asked. you could post a comment to the answer or edit it if you think there was a mistake! cheers

the hexapod is going to be developed further once the hardware is set up. but eventually at some point i will have to add a raspberry pi for more complex planning and decision making while the arduino will deal with all the low level stuff. but since i found super cheap clones i will just use those either way


text:
Should I use motor driver or Motor driver shield?
I want to run 4 microgear motor for an RC car with Arduino. Should I use L293d motor driver/L298n motor driver/L293d motor driver shield?? I am using N20 microgear motor with following rating: 6 V, 200 RPM and 120 mA with no load, 40 oz-in (2.9 kg-cm) and 1.6 A at stall.

I don't think you should be using L293 based drivers for new projects. You should be using TB6612FNG drivers instead. They're much more efficient.

The right driver module or shield depends on the motor. Do you know the voltage and the stall current of the motors ?
The L293D uses bipolar transistors for the output stage inside the chip and can only drive 600mA. It has a large voltage drop: the motor gets less voltage than the power voltage applied to the driver. Therefor it can be used with small 12V motors, but it does not work very well with 6V.
The L298N also uses bipolar transistors and also has a large voltage drop.
A mosfet driver like the DRV8833 works better with 6V, because it has a low voltage drop.
In small RC toys with four AA batteries, sometimes a H-bridge is made is transistors instead of using a special driver chip.
The very cheap motor shield with two L293D chips (originally designed by Adafruit) can drive four motors, but it uses many pins.
Bottom line: Everything depends on your motors. I suggest to use a mosfet driver.

The T in MOSFET stands for transistor.  It is misleading to say the  L293D and L298N use transistors as if MOSFET drivers don't.  So, instead say  “L293D uses Darlington bipolar transistors” etc

@JamesWaldby-jwpat7, thank you, I have corrected it. Mum, if the motors require that 1.6A and the batteries can supply it, then you need a motor driver that is capable to drive 1.6A, for example the DRV8838, MC33926 or MAX14870. I found those drivers at Pololu: https://www.pololu.com/category/11/brushed-dc-motor-drivers

@Jot Will motor driver shield help?

@Mum, the motor shield with two L293D ? No, it won't work very well with 6V. Look at the bottom of this page what Pololu suggests for the N20 motor: https://www.pololu.com/product/997

@Jot Is there any chance using L293d is harming the motor driver and arduino?Because my arduino seemed to have frozen,

@Mum, when it is connected properly, then the Arduino should still be okay. Disconnect everything from the Arduino board and try to upload the Blink sketch to blink the led at pin 13.

@Jot I  tried but error is showing failed to upload.. and  the receiver led is not blinking while uploading.

@Mum, that's not good. It might be broken. You need another Arduino board.

@Jot cant I somehow revive it?

@Jot and can you tell me why this happened?so that it wont happen again..

@Mum, I'm sorry, I don't know what happened. I don't know how it all is connected. The Arduino gets easily broken with a loose wire with 12V accidently touching the Arduino board. With the motor shield, the Arduino should be okay. Perhaps the L293D got very hot and broke and because of that, a voltage spike from the motor reached the Arduino board. That is just a wild guess, I don't know.

The key differences between the L293D and the L298 are these:

the L298 supports higher currents (up to 4 A with proper heat sink), the L293D is limited to 600 mA
the L298 has a higher operating voltage (up to 46 V), the L293D is limited to 36 V
the L298 is a dual full bridge driver whereas the L293D is a quadruple half bridge driver

Ok, what's the difference of two full bridges vs. four half bridges - it somehow sounds to be equal? In fact, when driving a DC motor that requires to reverse the polarity to reverse rotation a full bridge is required. This full bridge could now be provided by either of the L293D (two half bridges) or the L298 (one full bridge). If you on the other hand want to drive a four winding stepper motor (two phase bipolar) the L293D would be more helpful as it could drive two such steppers (using two separate half bridges) whereas the L298 would need to use both its full bridges and could therefore only operate one such stepper.
But since steppers are not part of this question this difference does not really matter and you could pick either chip with respect to the required current rating. A stall current of 1.6 A would be a serious problem for the L293D:

Peak output current, I_O (nonrepetitive, t ≤ 100 μs): 1.2 A

Whether to use the chip or a driver board or a shield, to be honest, is mainly personal preference. Shields and driver boards come ready-to-use on a pretty printed circuit board which is probably their main benefit.

There are differences, yes, but what they have in common is that both are long obsolete, lossy bipolar devices that should not be chosen today.

Fair enough, @ChrisStratton, but that is not what was asked by the OP ;)

@ChrisStratton If you mention some alternatives, it will be very valuble


text:
incompatible types in assignment of 'int*' to 'int [0]'
I was coding a class for "a kind of gun". I have this code for the classes:
Gun.h:
#ifndef Gun_h
#define Gun_h

#include "Arduino.h"

class Gun
{
  public:
    Gun(String identifier, String name, int teamIRCodes[]);
    String getIdentifier();
    String getName();
    int getIRCode();
  private:
    String _identifier;
    String _name;
    int _teamIRCodes[];
};

#endif

Gun.cpp:
#include "Arduino.h"
#include "Gun.h"

Gun::Gun(String identifier, String name, int teamIRCodes[])
{
  _identifier = identifier;
  _name = name;
  _teamIRCodes = teamIRCodes;
}

String Gun::getIdentifier(){
  return _identifier;
}
String Gun::getName(){
  return _name;
}
int Gun::getIRCode(){
  return _teamIRCodes[1];
}

It returns me this error while compiling:
sketch\Gun.cpp: In constructor 'Gun::Gun(String, String, int*)':

Gun.cpp:8: error: incompatible types in assignment of 'int*' to 'int [0]'

   _teamIRCodes = teamIRCodes;

                ^

exit status 1
incompatible types in assignment of 'int*' to 'int [0]'

The issue is with flexible array int _teamIRCodes[]; This is an old technique which I don't recommend. But if you want to use it, you need you use malloc to create a class object, adding on enough space for the array:
// Allocate space for the class AND the array
Gun *gun = (Gun *)malloc(sizeof(Gun) + sizeof(teamIRCodes));

However, this does not call the ctor, and you still have to manually copy the data:
for(int i = 0; i < (sizeof(teamIRCodes) / sizeof(teamIRCodes[0])); i++) {
    gun->_teamIRCodes[i] = teamIRCodes[i];
}

I think it's much simpler to use a pointer:
int* _teamIRCodes;

Then you can make your ctor:
Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
    _teamIRCodes = new int[numberOfCodes];
    // memcpy does the same thing as the for loop - copies the array
    memcpy(_teamIRCodes, teamIRCodes, sizeof(teamIRCodes[0]) * numberOfCodes);
}

And don' forget to add a dtor:
~Gun() {
    delete [] _teamIRCodes;
}

Or, if teamIRCodes is persistent throughout the lifetime of the object, you can just use a pointer to it:
 class Gun {
     public:
     int *_teamIRCodes;
     int _numberOfCodes;
     Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
         _teamIRCodes = teamIRCodes;
         _numberOfCodes = numberOfCodes;
   };

(Maybe this is an Arduino thing as this is the 2nd flexible array question I've seen today).

Ok, using this worked:
Replace
_teamIRCodes = teamIRCodes;

For
for(int i = 0; i < (sizeof(teamIRCodes)/sizeof(int)) ;i++)
    _teamIRCodes[i] = teamIRCodes[i];

Needed to iterate through array, cannot copy full array.

Close, but where do you allocate space for _teamIRCodes?

Doesn't it initialize with a value of 0? In Gun::Gun(String identifier, String name, int teamIRCodes[]) I add all the values

By now, it worked

Ok, it complied, but it seems that not working


text:
Powering the attiny85 with a separate power source
I have an LED project for which i'm using a 9v power supply. For part of the project I'm using an off the shelf LED driver that is compatible with 9v however I have one LED component that I want to drive with the attiny85 (random blinking pattern), which is not compatible with 9v.
Does it make any sense to power the attiny85 separately with say a 3v coin cell, while allowing my LEDs to draw from 9v? The attiny85 would only be tripping transistors. I assume the attiny85 itself doesn't consume much power so hopefully I wouldn't be changing out the coin cell too often.
I have a couple 5v buck converters on hand but they take up more space than a coin cell would.
P.S. It's a Guy Manuel Daft Punk Helmet.

They make voltage regulators that are even smaller than coin cells.

@IgnacioVazquez-Abrams I assume you aren't talking about the lm317 which I've already ruled out. I'll shop around and see what's out there. Thanks

Nah, I'd look at the LM78L05/33 or LP2985.

Does it make any sense...

Well, actually it does make sense and you already rationalize it in your question: less space consumed, expected life time of the coin cell is ok for your intended use case (though you could/should confirm the assumption about power consumption with the AVR's data sheet).
There is nothing wrong in powering the microcontroller with a different voltage than the "power" circuitry, assuming the ground lines are connected and the transistors mentioned are operated in a suitable mode, e.g. open collector/open drain type.


text:
Utilizing Array with RGB
I am trying to create a sketch that utilizes two arrays, one array to hold five buttons as input, assigned to pins, and another array to hold five musical notes.  I have attached a RGB LEDs with pull-down resistors and attached a 8 ohms resistor speaker.
The code is as followed:
 //Pentatonic Piano
 // C D E G A

 #define NOTE_C   262 //HZ
 #define NOTE_D   294 //HZ
 #define NOTE_E   330 //HZ
 #define NOTE_G   392 //HZ
 #define NOTE_A   440 //HZ

 const int SPEAKER = 9;   //speaker on pin 10
 const int BLED = 10;      //Blue LED on pin 9
 const int GLED = 6;      //Green LED on pin 6
 const int RLED = 5;      //Red LED on pin 3

 int buttonState = 0;

 //Button Array
 int Buttons[]= {11, 8, 7, 4, 3};

 //Tone Note Array
 int Notes[] = {NOTE_C, NOTE_D, NOTE_E, NOTE_G, NOTE_A};

 void setup()
 {
 pinMode(BLED, OUTPUT);
 pinMode(GLED, OUTPUT);
 pinMode(RLED, OUTPUT);
 pinMode(Buttons, INPUT);
 }

 void loop()
 {

   buttonState = digitalRead(Buttons);

   if (buttonState = Buttons[0])
   { tone(SPEAKER, Notes[0]);
    digitalWrite(BLED, LOW);
    digitalWrite(GLED, LOW);
    digitalWrite(RLED, HIGH);

   }
   else if (buttonState = Buttons[1])
   {tone(SPEAKER, Notes[1]);
    digitalWrite(BLED, LOW);
    digitalWrite(GLED, HIGH);
    digitalWrite(RLED, LOW);
   }
   else if (buttonState = Buttons[2])
   {tone(SPEAKER, Notes[2]);
    digitalWrite(BLED, HIGH);
    digitalWrite(GLED, LOW);
    digitalWrite(RLED, LOW);

   }
   else if (buttonState = Buttons[3])
   {tone(SPEAKER, Notes[3]);
    analogWrite(BLED, 127);
    analogWrite(GLED, 0);
    analogWrite(RLED, 127);

   }
   else if (buttonState = Buttons[4])
   {tone(SPEAKER, Notes[4]);
    analogWrite(BLED, 0);
    analogWrite(GLED, 127);
    analogWrite(RLED, 127);

   }

   else
   {
    digitalWrite(BLED, LOW);
    digitalWrite(GLED, LOW);
    digitalWrite(RLED, LOW);
    noTone(SPEAKER);
   }
 }

The problem is no matter what button I press, the RGB only emits a green light and there is absolutely no sound coming from the speaker.  I am truly stumped.

First, these statements:
if (buttonState = Buttons[0])

are doing an assignment, not a test for equality. You want:
if (buttonState == Buttons[0])
//               ^Notice

Next, pinMode takes two integers, but you are passing an array. You can use a loop to call pinMode multiple times:
for (int i = 0; i < sizeof(Buttons) / sizeof(Buttons[0]); i++) {
     pinMode(Buttons[i], INPUT);
}

Same goes for digitalRead(). You need to read the state for each button:
buttonState = digitalRead(Buttons[0]);
if (buttonState == HIGH) {
   ....
}
buttonState = digitalRead(Buttons[1]);
if (buttonState == HIGH) {
   ....
}
//etc


text:
How do you balance an Arduino quadcopter using calculated gyro values?
I was working on an Arduino quadcopter project. I setup all my hardware and was having balancing problems with my software end. I am using an MPU-6050 gyro and accelerometer. I have calculated the angle of the quad in relation to the ground and was trying to implement these values by adjusting the output values to each of the four motors.
Here is some of my code:
    x=(-computedGyroAngleX-3.5)*10;
    y=(-computedGyroAngleY-2)*10;
    esc1.writeMicroseconds(rc_values[RC_CH1]+x-y);
    esc2.writeMicroseconds(rc_values[RC_CH1]+x+y);
    esc3.writeMicroseconds(rc_values[RC_CH1]-x-y);
    esc4.writeMicroseconds(rc_values[RC_CH1]-x+y);

If the quad is leaning forward I increase the power at the front of the quad and reduce it at the back. I do the same for the y axis. But I run into problems when I test out the quad. It flips over to the side or forward. How would I fix this?

Hello and welcome. Could you please edit in another line break near your code section... to make code formatting work (I cannot do the edit due to the six-character rule).

Such task is usually done by PID regulator (library) and to save you a lots of time by trying to tune it correctly also by PID Autotune library

That was happening with me too. Check if the weight distribution of the drone is perfect. Lets say if the battery is placed a little more to one side of the frame than the other side, your drone will try to hover from the other side.
The center of gravity should be taken care of when the drone is not balancing properly.


text:
Voltage transfer
I'm trying to read the battery voltage using Arduino, using a 9V battery. I keep getting the same voltage (4.99). I connected my Arduino to Matlab so I'm only using the command voltage=readVoltage(a,'pin'). I'm very new to this, so any help would be appreciated.

Analog inputs on the arduino will measure 5v maximum. If you want to mesure higher voltage you will have to use a voltage divisor circuit (resistors).

Also your analog input might now be dead from providing almost twice the voltage it's designed for.

Aren't you getting any Magic smoke ?

Thank you all, somehow I didnt damage the analog input, thank God. But i tried with resistors (10k) and its still measuring the same voltage...

And if you measure with a multi-meter the voltage at the Arduino input ?

@SoundoussSassi could you show/describe how you have connected the resistors (just to make sure it is a proper voltage divider)? I also wonder if it is necessary to select a proper reference (there should be an internal and external reference possible).


text:
MFRC522 ReadNUID example reboots unless I include a null if statement
I'm fairly new to Arduino (and C), but not to embedded electronics and programming.
I'm using an MFRC522 module (the common one) with a Nano, and getting some strange results. They are on a very simple custom PCB I've made (the only parts on it, except for a couple of LEDs on D4 & D5)
I'm using SS_PIN on 8, and RST_PIN on 7, which is changed from 10 & 9, because the board will also be using an NRF24L01 module on the SPI bus (not fitted yet).
And I'm using the MFRC522 library.
The DumpInfo example in the library works fine, but not the ReadNUID example.
When I bring a tag/card near the reader, the sketch (sometimes) gets some of its output to the serial monitor, but then (always) the board reboots and the startup messages appear again. This happens continuously while the card is near.
I have the RFID IRQ connected to pin D3, and while thinking that may be causing the problem, and trying all sorts of stuff, I found that it wasn't. In the process I did get the sketch to work, and have distilled the fix down to two seemingly superfluous lines of code:-
Added a null if statement at the start of loop:-

if (GotIRQ) {}

and defined a volatile variable for it to test:-
volatile boolean GotIRQ=false;

Doesn't work if it's not volatile. (A clue?)
What Gives? Some dumb newbie mistake?
(I could post the entire code if required, but I've started again from the original source, and only made the 2 changes and 2 additions described above)
Here is the code:-
/*
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read new NUID from a PICC to serial.
 * --------------------------------------------------------------------------------------------------------------------
 * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
 *
 * Example sketch/program showing how to the read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
 * Reader on the Arduino SPI interface.
 *
 * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
 * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
 * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
 * will show the type, and the NUID if a new card has been detected. Note: you may see "Timeout in communication" messages
 * when removing the PICC from reading distance too early.
 *
 * @license Released into the public domain.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 */

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 8   //QQ This changed from 10
#define RST_PIN 7   //QQ This changed from 9

MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class

MFRC522::MIFARE_Key key;

volatile boolean GotIRQ=false; //QQ needed for null if statement

// Init array that will store new NUID
byte nuidPICC[3];

void setup() {
  Serial.begin(9600);
  SPI.begin(); // Init SPI bus
  rfid.PCD_Init(); // Init MFRC522

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }

  Serial.println(F("This code scan the MIFARE Classsic NUID."));
  Serial.print(F("Using the following key:"));
  printHex(key.keyByte, MFRC522::MF_KEY_SIZE);
}

void loop() {
  if (GotIRQ) {}   //QQ If this is not included, board resets when a RFID tag is detected

  // Look for new cards
  if ( ! rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if ( ! rfid.PICC_ReadCardSerial())
    return;

  Serial.print(F("PICC type: "));
  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
  Serial.println(rfid.PICC_GetTypeName(piccType));

  // Check is the PICC of Classic MIFARE type
  if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
    piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
    piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
    Serial.println(F("Your tag is not of type MIFARE Classic."));
    return;
  }

  if (rfid.uid.uidByte[0] != nuidPICC[0] ||
    rfid.uid.uidByte[1] != nuidPICC[1] ||
    rfid.uid.uidByte[2] != nuidPICC[2] ||
    rfid.uid.uidByte[3] != nuidPICC[3] ) {
    Serial.println(F("A new card has been detected."));

    // Store NUID into nuidPICC array
    for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = rfid.uid.uidByte[i];
    }

    Serial.println(F("The NUID tag is:"));
    Serial.print(F("In hex: "));
    printHex(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
    Serial.print(F("In dec: "));
    printDec(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
  }
  else Serial.println(F("Card read previously."));

  // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
}

/**
 * Helper routine to dump a byte array as hex values to Serial.
 */
void printHex(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
}

/**
 * Helper routine to dump a byte array as dec values to Serial.
 */
void printDec(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], DEC);
  }
}

OK, trying to cut down to a minimal example has proved useful. It seems the problem is caused by the loop that stores the NUID, but not if the superfluous if statement is present. The code is :-
// Cut down version of MFRC522 library ReadNUID example that exhibits strangle
// problem of rebooting the board when a card is near the reader.
// But only if:-
// * the Store NUID loop is included
// and
// * the superfluous "if" statement at start of loop() is NOT present.
// Changes from original example are indicated by comments starting with "//QQ"
// (plus a lot of removed code)

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 8   //QQ This changed from 10
#define RST_PIN 7   //QQ This changed from 9

MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class

MFRC522::MIFARE_Key key;

volatile boolean GotIRQ=false; //QQ needed for null if statement

// Init array that will store new NUID
byte nuidPICC[3];

void setup() {
  Serial.begin(9600);
  SPI.begin(); // Init SPI bus
  rfid.PCD_Init(); // Init MFRC522

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }

  Serial.println(F("This code scan the MIFARE Classsic NUID."));
}

void loop() {
//  if (GotIRQ) {}   //QQ If this is not included, board resets when a RFID tag is detected

  // Look for new cards
  if ( ! rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if ( ! rfid.PICC_ReadCardSerial())
    return;

  Serial.print(F("PICC type: "));
  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
  Serial.println(rfid.PICC_GetTypeName(piccType));

  // Store NUID into nuidPICC array //QQ does not fail if this loop is excluded
  for (byte i = 0; i < 4; i++) {
    nuidPICC[i] = rfid.uid.uidByte[i];
  }

  // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
}

Please can you post a minimal verifiable example of code.  Sorry but just adding two lines means nothing.

Welcome to Arduino SE.  Be sure to take the tour to see how things work here:  https://arduino.stackexchange.com/Tour

"minimal verifiable example of code". I wanted to use code that many would be familiar with, and just show the simple change I made that brings on the problem. I'll try to reduce it, but then we don't have a familiar starting point. just adding two lines means nothing.

This comment system is confusing. I just wanted to start a new line, but it kept posting each time, so my comment could be gibberish, and then it timed out on me.

Added my modified example code, and a minimal version of it. It seems the loop that stores the NUID causes the problem (new problem), and including the null if statement fixes it (original problem)

I've included this code into another sketch, also using SPI to talk to an NRF24L01, and again a (different) problem appears when the code to store the NUID is present. "i=0; i<4;" means the loop with execute 4 times with i=0,1,2,3. Correct? But If I change the array declaration to "byte NUID[4]", the problem goes away. But that's 5 bytes, no?, so there should be no overrun with NUID[3]?

In C, byte NUID[4] means a 4 elements array (index 0 to 3). Remember, you declare how many elements you want.

You've defined this array to have three elements:
byte nuidPICC[3];

those three elements are numbered 0, 1, and 2.
In this for loop:
for (byte i = 0; i < 4; i++) {
    nuidPICC[i] = rfid.uid.uidByte[i];
  }

you are writing to position 3, which is out of bounds for that array.
Once you write out of bounds on an array the behavior is undefined.  Resetting is one common result.  But anything could happen.

I'm assuming that the extra byte in the array is needed, possibly for a null terminator or whatever, and that the example code has a bug. I've had no further problems since changing the NUID[3] to NUID[4], so I'll leave this at that.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
What is the theory behind the Arduino UNO being able to create AM waves at 800 kHz
I am doing a school project and saw someone use an Arduino and a piece of wire as an antenna here: https://forum.arduino.cc/index.php?topic=88422.0
I've tested this experiment and it works, but I have searched the internet for some time now for some background knowledge or theory on why this works, and how does it?
If anyone knows anything about the arduino creating simple AM waves, could you please let me know about it or redirect me to another source.
For some context, in this school project I've got to explain the theory behind creating basic AM waves and amplitude modulation in general, then prove the theory by conducting this experiment which I prove it correct.

That code just generates a 800kHz PWM signal, that is then turned on and of to greater the clicking sound you get.

Strictly speaking it's not AM, it's OOK (On-Off Keying) which just turns a carrier frequency (800kHz PWM, 50% duty cycle) on and off.
Many cheap 443MHz (eBay) modules do the same thing - turn the carrier frequency on and off.
The presence of the carrier frequency is seen as a logic 1 and the absence as a logic 0.
The fact that it's using PWM to generate a square wave means that the "cleanliness" of the signal will be incredibly horrible. You really want to get the carrier frequency as close to a pure sine wave as possible. A square wave has lots of harmonics at 3x, 5x, 7x, 9x etc the frequency. So your 800kHz signal will also have a 2.4MHz signal, a 4MHz signal, a 5.6MHz signal and so on, each at a lower level. That causes interference in other signals.
To understand more about why it works you first have to understand radio transmission theory, and that's not something we can cover on an Arduino site (it's an entire college course all by itself).

How do you get 2.4, 4.8, and 7.2 MHz from  6x, 6x, and 9x?

@JamesWaldby-jwpat7 Through the careful use of a typo. Should have been 3x 6x 9x. Actually there should be 5x and 7x in there too. And 6 is wrong.

I thought that might be the technique used!  So useful sometimes :)

It works because everything is wrong. A perfect sine wave of 800 kHz would not transmit very well with such a small wire as antenna.
The output signal is a digital pulse (PWM signal) with very sharp edges. Those edges create many harmonics as Majenko wrote. It is those high harmonic frequencies that can use that small wire as antenna. The receiver might get help of those harmonic frequencies to combine them with the base signal to be able to receive the base signal of 800kHz. The receiver might also receive the electrical field coupling (capacitive coupling) instead of really receiving radio signals. The electrical (capacitive) coupling might even be main part of what is received.
You could add a large antenna or a large open coil or a tuned circuit of a coil with a capacitor. That should increase the range, because that will transmit real radio signals.
The Arduino board with the wire can not be used to explain AM radio signals, because it is not a AM radio signal. You can also not use it to explain AM modulation, because there is no modulation (only on/off).
Do you know someone who has equipment to make modulated AM signals ?
Last but not least: it is illegal to transmit at 800kHz.


text:
Not able to add JSON data to Arduino data
In my recent project, I'm working with Arduino with JSON.
I made software on JSON. Now, I want to send data from this software to my Arduino. Serial communication is done between Arduino and JSON. But somehow, I can't able to get proper data from JSON to my Arduino. So, I google out and find library named ArduinoJson. And here, I found out example code. So, I tried out that code and modified based on my requirement.
Here, below is my code.
Now, Software sends me value. And I split it out into three variable MAP_Json, TPS_Json, and LOAD_Json.
In Arduino side, I have already the value of MAP, TPS, and LOAD.
So, now my main intention is to compare MAP_Json with MAP & TPS_Json with TPS. If they are matched then LOAD_Json is added to LOAD. But, when I try it out, then LOAD_Json not added to LOAD. I don't understand why this happened?
 #include <ArduinoJson.h>

//----------------------------For MAP calculation----------------------------//
float MAP_MIN = 0.85;
float MAP_MAX = 1.90;

int LOAD_MIN_MAP[] = {1, 2};
int LOAD_MAX_MAP[] = {3, 4};

float mMAP[2] = {};
float yMAP[2] = {};

int i, j, a;
float MAP, mFinalMAP, yFinalMAP;

//----------------------------For TPS calculation----------------------------//
float TPS_MIN = 0.00;
float TPS_MAX = 5.00;

int LOAD_MIN_TPS[] = {1, 3};
int LOAD_MAX_TPS[] = {2, 4};

float mTPS[2] = {};
float yTPS[2] = {};

int k, l, b;
float TPS, mFinalTPS, yFinalTPS;

//----------------------------For LOAD calculation---------------------------//
int LOAD_MIN = 2;
int LOAD_MAX = 100;

float injTime_MIN_LOAD[] = {8.00, 9.06};
float injTime_MAX_LOAD[] = {10.60, 11.86};

float mLOAD[2] = {};
float yLOAD[2] = {};

int m, n, c;
float LOAD, mFinalLOAD, yFinalLOAD;

//------------------------------ Variable ---------------------------------//

float load;

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

void loop()
{
  //----------------------ARDUINO DATA-------------------------//

  //----------------------------MAP----------------------------//

  MAP = analogRead(A0) * (5.0 / 1023.0);

  for(a = 0; a < 2; a++)
  {
    mMAP[i] = (LOAD_MIN_MAP[a] - LOAD_MIN_MAP[a]) / (MAP_MAX - MAP_MIN);
    yMAP[j] = mMAP[i] * (MAP - MAP_MIN) + LOAD_MIN_MAP[a];
  }

  //----------------------------TPS----------------------------//

  TPS = analogRead(A1) * (5.0 / 1023.0);

  for(b = 0; b < 2; b++)
  {
    mTPS[k] = (LOAD_MAX_TPS[b] - LOAD_MIN_TPS[b]) / (TPS_MAX - TPS_MIN);
    yTPS[l] = mTPS[k] * (TPS - TPS_MIN) + LOAD_MIN_TPS[b];
  }

  //----------------TPS/MAP CALLIBRATION / LOAD----------------//

  mFinalTPS = (yMAP[1] - yMAP[0]) / (TPS_MAX - TPS_MIN);
  yFinalTPS = mFinalTPS * (TPS - TPS_MIN) + yMAP[0];

  mFinalMAP = (yTPS[1] - yTPS[0]) / (MAP_MAX - MAP_MIN);
  yFinalMAP = mFinalMAP * (MAP - MAP_MIN) + yTPS[0];

  LOAD = (yFinalTPS + yFinalMAP) / 2;

  Serial.print("T : ");
  Serial.print(TPS);
  Serial.print("\t");
  Serial.print("M : ");
  Serial.print(MAP);
  Serial.print("\t");
  Serial.print("L : ");
  Serial.print(LOAD);
  Serial.print("\t");

  while(!Serial)
  {
    // wait serial port initialization
  }

  StaticJsonBuffer<200> jsonBuffer;

  char json[] = "{\"TPS\":1.67, \"MAP\":1.83,\"LOAD\":30}"; // JSON DATA

  JsonObject& root = jsonBuffer.parseObject(json);

  // Test if parsing succeeds.
  if(!root.success())
  {
    Serial.println("parseObject() failed");
    return;
  }

  // Splitted JSON DATA

  float TPS_Json = root["TPS"];
  float MAP_Json = root["MAP"];
  float LOAD_Json = root["LOAD"];

  Serial.print("T_J : ");
  Serial.print(TPS_Json);
  Serial.print("\t");
  Serial.print("M_J : ");
  Serial.print(MAP_Json);
  Serial.print("\t");
  Serial.print("L_J : ");
  Serial.print(LOAD_Json);
  Serial.print("\t");

  //Compare JSON DATA and ARDUINO DATA

  if(TPS_Json == TPS && MAP_Json == MAP) //If matched
  {
    load = LOAD_Json + LOAD;            // Add LOAD_Json and LOAD
  }

  Serial.print("Final Load :");
  Serial.print(load);
  Serial.print("\n");
}

EDIT 1: Improve question formatting
EDIT 2: Upload Complete code

Downvoter, please tell me what is wrong?

What output do you expect to get, and what output do you actually get? Just saying "I can't do X" doesn't help us work out what you expect to happen and what is happening.

JSON isn't javascript its a way of representing data that uses a syntax derived from JS.  If you can't write your own parsing code then look at some of the libraries available.  I agree with the down vote, its not a well phrased question.

@Majenko ok...let me update question in more detail.

@CodeGorilla Ok...I think I have to clear all things.

What are MAP and TPS?

@Majenko TPS and MAP are just variables and they have just stored the value of sensors which are attached to analog pins.

There's no such thing as "just" a variable. I am assuming they are float but it all depends on how you defined them, which you omitted from your incomplete code.

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.   Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem.  Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant. Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem.

@Majenko Ok let me upload my complete code.

@JamesWaldby-jwpat7 Ok let me upload my complete code.

Comparison of floating point values is nigh on impossible. They aren't as accurate as you may think anyway, and two values have to be precisely the same to be considered equal - not something that is easy to achieve (23.4893782 != 23.4892480).
Instead you should either round them to a specific precision, or take the difference between the two values and decide if they are "close enough".
E.g.:
float diff = abs(TPS - TPS_Json);
if (diff < 0.5) {
    // do something
}

Ok...Got it. Let me try out this. Thank you for this.


text:
Measuring voltage from -12 to +12 VDC
I'm making a -12 to +12V DC regulated power supply, on which I want to measure voltage and current with Arduino (through a voltage divider, of course).
I'm not sure, how to either detect nor measure negative voltage. I could "detect" it via a Schottky diode, but I'd get about 0.3V voltage drop, but that's not what I want, because any voltage between 0.0V and -0.3V wouldn't be measured. I want also to be able to measure positive and negative voltage on the same Arduino analog input pin.
And furthermore, how to measure current, flowing into both ways? (not an AC current, but will change during operation).
I will make additional PCB for this application, so size and number of components isn't important at all.

What magnitude of current do you need to measure?  Microamps?  Amps?

We're discussing range from 0 to 5A, I'd really like to measure it on at least 2 digits, while measuring amperes, and if the current would be <1A, I'd like to show it in miliAmps.

Measuring voltage
Use the following interfacing circuit for measuring voltage:

Resistors R1, R2, R3 (1% tolerance or better recommended) will map the voltage input range (-12 to +12V DC) to an output range that can be read will the Arduino ADC  (+0.5 to +4.5V DC, in order to have some slack from the top and bottom end of the ADC range). The actual theoretical input range would be -15 to 15V DC.
The optional (but recommended) Schottky diodes D1 and D2 will protect the Arduino analog IN pin that you connect to Vout from any input under/overvoltage outside the -15 to +15V DC range.
This is the resulting input to output voltage translation curve:

Measuring current
For measuring current, use a current shunt (i.e., a very low resistance resistor, in the milliohm range) and measure the voltage drop on it via a high input impedance differential amplifier, then sample the output of the amp with the Arduino ADC.

simulate this circuit – Schematic created using CircuitLab
Follow this link to an article in EE Times to learn more about the main options available for current measurements using a shunt.

The Schottky diodes have too much leakage current, the measured voltage will be less accurate. It is better to use 1N4148 diodes with a extra resistor to the Arduino pin (100 ohm to 1k). The diodes are probably not needed at all, since it is allowed to push 1mA into a pin or pull 1mA from a pin. It is therefor safe to apply larger voltages than -15 or 15v.

With only those three resistors with those values (20k, 6.65k, 10k) the input may be +/- 40V.

I have already selected the values of R1, R2 and R3 so that the leakage of the 1N5819 doesn't distort the measurement. The simulated curve reflects that. The diodes are optional and are there just for protection purposes, it's up to the OP to get rid of them, as I said myself.

@Jot I don't get your point.

The leakage of the 1N5919 is very unpredictable, what if one is close to a voltage regulator that is very hot ? The leakage could be 0.1 to 10mA.

My leakage numbers are wrong, I found graph in the ST datasheet. The typical leakage according to that graph are can be 1µA to 0.3mA (at 100°C).

@Jot I'm happy you finally got your numbers right.

@EnricBlanco: That's just perfect, thank you for the reply!
I just can't figure out, what actually means Vin, Vout and VS. I mean, I know that Vin stands for Input voltage, Vout for output voltage, but what am I supposed to connect to those pins? Which voltage to be accurate?

Connectivity: Vin -> the -12/12V voltage you want to measure; Vs -> 5V from Arduino of from a stable, accurate voltage reference; Vout -> any analog input from Arduino.

@EnricBlanco: Thank you thank you THANK YOU!!!


text:
Smooth out digital signal from SW-420 vibration sensor in order to record duration?
I'm attempting to make a sensor that will record the duration and frequency of a pump going off. It always fires for at least 4 seconds, but the duration can be up to 7 days.  The vibration sensor I have is a SW-420, which I think will work. I'm fairly new at this, and I don't mind figuring out the actual code myself, but I'm running into newb problems.

Should I approach this as an interrupt that uses a callback while loop, or would it be better to look at it as a typical debounce sub? Is there a better solution?
Since the duration can (very rarely) exceed running for more than a few minutes, I'm wondering if I need an RTC module. The time is not very important, it just needs to be "close".
The duration info will be fed to node-red via MQTT. I can count frequency in that system... I'm trying to decide if I should do remote frequency calculations, or try and wrap it into the firmware on the Arduino. Any suggestions for this?

Bonus points if I can accomplish this without any additional libraries. I'd love to put this on an ESP8266.
Thanks for your help, I appreciate it.

Should I approach this as an interrupt that uses a callback while loop, or would it be better to look at it as a typical debounce sub?

No. If you want to use interrupts then just record the start time on one edge of the signal and subtract it from the current time on the other edge (not sure which edge is which on that sensor).

Since the duration can (very rarely) exceed running for more than a few minutes, I'm wondering if I need an RTC module. The time is not very important, it just needs to be "close".

It depends how you define "close".  An RTC can give you better accuracy over long periods, yes, and the Arduino struggles with > 49 days by itself.

The duration info will be fed to node-red via MQTT. I can count frequency in that system... I'm trying to decide if I should do remote frequency calculations, or try and wrap it into the firmware on the Arduino. Any suggestions for this?

What kind of frequency are you wanting? The frequency of the vibration itself, or the frequency at which some vibration occurs?  If the former the sensor you have won't do the job - that just tells you when there is vibration above a certain threshold.
To sense the actual frequency of vibration you need a more hands-on approach by the MCU. Either use the raw HDX-2 vibration sensor as used on the SW-420 (that's the blue tube at one end), or do it properly and use an accelerometer which you sample over time and perform an FFT on the sampled signal to isolate the different frequencies.

Thanks for responding. This sensor is normally closed, I'm pretty sure I can figure out which edge to use. It's just nice to have a direction to move towards.

The sensor (HDX-2) is normally closed, but it integrates that with a capacitor and uses a comparator to set a threshold. It's the output of the comparator that gives you your two edges, and I haven't spent the time working out which edge would be which.

The frequency I'm looking for is how often the pump goes off, not the actual vibrations of the pump. I basically want to know that the pump went off for 6 seconds at 10:59:40 and then again at 11:04:20 for another 6 seconds. This is the frequency I'm looking for. The timestamps can be handled by the remote end based on when the MQTT message was received, so I only have to pass on a duration of X seconds.

Then this sensor sounds fine to me.

I think that I may not have been clear on one point. When this sensor gets activated, it's not a simple ON and then OFF. it's a series of ON OFF readings that are between a few microseconds and several seconds. The hard part for me is determining the FIRST on and the LAST off. Any pointers on that one? I think that is what I was getting at when I mentioned the while loop... in my head, I see jumping into a while loop when the first ON is triggered, and then staying in that loop until last OFF was received > X MS ago. Does that make any sense, or am I just complicating things?

In that case you probably want to treat it like a normal button and debounce it well.


text:
Error compiling: expected unqualified id before token {
#include <LiquidCrystal.h>
#define trigPin 12              // the trig pin to digital pin 12
#define echoPin 13              // the Echo pin to digital pin 13
#define led 8
#include <Servo.h>
Servo servoMain; // Define our Servo

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600); // Starts the serial communication
  lcd.begin(16, 2);
  servoMain.attach(11); // servo on digital pin 11
}

void loop() {
  servoMain.write(5);  // Turn Servo Left to 5 degrees
  delay(1000); // Wait 1 second
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance < 3) {
    digitalWrite(led, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("PLEASE REFILL!");
    lcd.setCursor(0, 1);
  } else {
    digitalWrite(led, LOW);
  }
  if (distance < 6) {
    digitalWrite(led, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("U May Refill Now");
    lcd.setCursor(0, 1);
  } else {
    digitalWrite(led, LOW);
  }
  if (distance < 8) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Take it easy");
    lcd.setCursor(0, 1);
  }
  if (distance <= 16) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("FULL!!");
    lcd.setCursor(0, 1);
  }
  if (distance > 16 || distance <= 0) {
    Serial.println("Out of range");
  } else {
    Serial.print(distance);
    Serial.println(" cm");
  }
}
delay(1000);

}
    }

A big chunk of your code isn't contained in a function.

how do i fix that..i am new with arduino

By placing it in a function. I suspect you really wanted to have it inside the loop() function, not after it.

i dont understand...which part should be in the loop() function

i dont understand...which part should be in the loop() function

Everything that comes after the end of the loop function.

i just edited the question (the code) ...is that how we do it

I think you should learn a programming language first. I konw the Arduino IDE is nothing compared to VisualStudio, Xcode or all the other fancy IDEs but knowing your language and reading errors carefully will help.

You should also learn basic formatting rules, or at the very least use the autoformat button in the IDE. It saves many headaches getting your indenting right from the start.

can someone help me to fix the error... i need to have this code run by today

What does it do now you have edited it?

Pressing ctrl-T in Arduino IDE helps. As you can see after reformatting, your code is flawed. Fix that first.

i hv fix the error..but now how do i make the servo to only rotate for 2seconds

At line 82 you have the closing bracket of the loop function. Then after that you have:
  delay(1000);

}
}

Which is invalid.
If you format your code properly it's easy to see. Fix that and it will compile. Will it do what you want is an other question...
#include <LiquidCrystal.h>
#define trigPin 12        // the trig pin to digital pin 12
#define echoPin 13        // the Echo pin to digital pin 13
#define led 8
#include <Servo.h>
Servo servoMain; // Define our Servo

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup()
{
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600); // Starts the serial communication
  lcd.begin(16, 2);
  servoMain.attach(11); // servo on digital pin 11

}
void loop()
{
  servoMain.write(5); // Turn Servo Left to 5 degrees
  delay(1000);     // Wait 1 second

  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;

  if (distance < 3) {
    digitalWrite(led, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("PLEASE REFILL!");
    lcd.setCursor(0, 1);
  }
  else {
    digitalWrite(led, LOW);
  }

  if (distance < 6) {
    digitalWrite(led, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("U May Refill Now");
    lcd.setCursor(0, 1);
  }
  else {
    digitalWrite(led, LOW);
  }

  if (distance < 8) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Take it easy");
    lcd.setCursor(0, 1);
  }

  if (distance <= 16) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("FULL!!");
    lcd.setCursor(0, 1);
  }

  if (distance > 16 || distance <= 0) {
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
}
delay(1000);

}
}

I suspect that will always say FULL!! no matter the level.  Think about if distance is 2, that's less than 16 isn't it?  Maybe you need some else if action.


text:
Button to not run script
I'm looking to have a button that, when pressed down, will mean that the script loaded on the Arduino doesn't run. So far I have:
void setup() {
  pinMode(3, INPUT_PULLUP);
  if (digitalRead(3) == LOW) {
    while(1);
  }
  // Beginning the Keyboard stream
  Keyboard.begin();
  // then the rest of the code.

I have a push button soldered to the ground and 3 pin. Could you see what is wrong with the code?

Well the while(1); will mean that the code will stop cold. Even if you release the button, the code will not resume.

@AndreCourchesne Since that code is in setup() it will only get called if the button is closed when the Arduino starts up.

@JohnnyMopp true indeed.

aside: compiled code is not a "script"...

Welcome to Arduino SE.  Be sure to take the tour to see how things work here:  https://arduino.stackexchange.com/Tour

I would do it this way:
void setup () {
    pinMode(3, INPUT_PULLUP);
}
void loop () {
    while (digitalRead(3)==LOW) {}; //do nothing, wait for release button
    // do all my stuff
}

or even better I would use some LED to indicate, that the button is pressed (or released) to have some visual state indicator (or another stuff to do while the button is pressed
void setup () {
    pinMode(3, INPUT_PULLUP);
    pinMode(13, OUTPUT);
    digitalWrite(13,LOW);
}
void loop () {
    while (digitalRead(3)==LOW) {
       digitalWrite(13,HIGH); // let it shine
       };
    digitalWrite(13,LOW);
    // do all my stuff
}

eventually
void setup () {
    pinMode(3, INPUT_PULLUP);
    pinMode(13, OUTPUT);
    digitalWrite(13,LOW);
}
void loop () {
    if (digitalRead(3)==LOW) {
       digitalWrite(13,HIGH); // let it shine
       while (digitalRead(3)==LOW) {
          // do some other stuff
       };
    digitalWrite(13,LOW); // switch indicator off
    // do my regular stuff
}

You need to move the code that checks the button into loop(). Put the code that you want to pause in the if block.
void loop() {
    // Only execute if not pressed
    if (digitalRead(3) != LOW) {
        // Do stuff
    }
}