How to compile an official VS1003 / VS1053 example for Arduino / ESP8266?

Ok, after long battle with C++ compiler I have a working example (at least for VS1003 and ESP8266) with a checklist how to recreate it (with minimal changes to the example files). I'm sure someone else will have this problem so I'm attaching it:

The things that you need to do in player1003.c:

rename to player1003.h (change file extension only)
remove all 5 includes from the top (stdio, string, stdlib, ctype, "player.h")
turn off REPORT_ON_SCREEN (change #if 1 to #if 0) if you don't want to have a lot of serial output
mass replace "FILE *" to "File " - mind the space (change type of file variables in all methods, mark "Case sensitive" to avoid errors in player1053!)
mass replace fopen( to fopen2(
mass replace printf( to Serial.printf(
mass replace fflush(stdout); to //fflush(stdout); (or Serial.flush();)
remove method: VSTestInitHardware(void)
remove SM_SDISHARE flag from WriteSci(SCI_MODE, SM_SDINEW|SM_SDISHARE|SM_TESTS|SM_RESET); line  (in VSTestInitSoftware(void) method)
in VSTestHandleFile() at the bottom add fp.close(); after VS1003PlayFile(fp); and VS1003RecordFile(fp); lines (especially after the record!). We don't want unclosed files on SD card.

The main sketch (.ino):

#include <SPI.h>
#include <SD.h>
#include "player.h"

using namespace std;

// I use these values below for ESP-12 (ESP8266):
#define MP3_xCS 2
#define MP3_xDCS 4
#define MP3_DREQ 5
#define MP3_xRESET 16
#define SD_CS 15
#define SPI_MOSI 11 //SPI
#define SPI_MISO 12 //SPI
#define SPI_CLK  13 //SPI

#define  WAIT_DREQ()  while(!digitalRead(MP3_DREQ))

File song;

int VSTestInitHardware()
{
  pinMode(MP3_DREQ, INPUT);
  pinMode(MP3_xCS, OUTPUT);
  pinMode(MP3_xDCS, OUTPUT);
  pinMode(MP3_xRESET, OUTPUT);
  pinMode(SD_CS, OUTPUT);

  digitalWrite(MP3_xCS, HIGH);
  digitalWrite(MP3_xDCS, HIGH);

  digitalWrite(MP3_xRESET, LOW); // chip off!
  delay(100);
  digitalWrite(MP3_xRESET, HIGH); // chip on!

  Serial.begin(115200);

  if (!SD.begin(SD_CS))
  {
    Serial.println("Can't initialize SD!");
    return -1;
  }
  Serial.println("SD OK!");

  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV32);  // Bus SPI at 1MHz (for Arduino: 16MHz / 16 = 1MHz)
  SPI.transfer(0xFF);  // Write something to the bus
  delay(10);
  return 0;
}

void setup()
{
  if (VSTestInitHardware() || VSTestInitSoftware())
  {
    Serial.printf("Failed initializing VS10xx, exiting\n");
    exit(EXIT_FAILURE);
  }
  /* ... */
  /* Playback example. You can call these functions many times in a row
  because they leave VS1003 in a stable state. */
  VSTestHandleFile("TEST.mp3", 0);  // remember to use 8.3 file names format on SD!
  /* Recording example */
  VSTestHandleFile("RECORDED.WAV", 1);  // original example for VS1003 has a bug here (OGG extension)

  Serial.println("Playing recorded file...");
  VSTestHandleFile("RECORDED.WAV", 0);

  Serial.println("THE END");
}

void loop()
{
}

void WriteSci(unsigned char reg, unsigned char hsb, unsigned char lsb)
{
  // for debugging:
  Serial.printf("Setting %s to: %d (%X, %X)\n", RegName(reg), (hsb<<8) + lsb, hsb, lsb);

  WAIT_DREQ();
  digitalWrite(MP3_xCS, LOW);

  SPI.transfer(0x02);
  SPI.transfer(reg);
  SPI.transfer(hsb);
  SPI.transfer(lsb);
  WAIT_DREQ();
  digitalWrite(MP3_xCS, HIGH);
}

void WriteSci(u_int8 addr, u_int16 data)
{
  WriteSci(addr, data >> 8, data & 255);
}

uint16_t ReadSci (unsigned char reg)
{
  WAIT_DREQ();
  digitalWrite(MP3_xCS, LOW);

  SPI.transfer(0x03);
  SPI.transfer(reg);
  delayMicroseconds(10);

  char response1 = SPI.transfer(0xFF);
  WAIT_DREQ();
  char response2 = SPI.transfer(0xFF);
  WAIT_DREQ();

  digitalWrite(MP3_xCS, HIGH);

  unsigned int resultvalue = response1 << 8;
  resultvalue |= response2;

  // for debugging:
  if (reg != SCI_HDAT0 && reg != SCI_HDAT1)  // these registers are filtered out because they are intensively used during recording
    Serial.printf("%s is: %d (%X, %X)\n", RegName(reg), resultvalue, resultvalue >> 8, resultvalue & 255);

  return resultvalue;
}

int WriteSdi(const u_int8 *data, u_int8 bytes)
{
  WAIT_DREQ();
  digitalWrite(MP3_xDCS, LOW);

  for(int y = 0 ; y < bytes ; y++)
    SPI.transfer(data[y]);

  digitalWrite(MP3_xDCS, HIGH);
}

const char* RegName(uint8_t reg)
{
  switch (reg)
  {
    case 0x00: return "SCI_MODE";
    case 0x01: return "SCI_STATUS";
    case 0x02: return "SCI_BASS";
    case 0x03: return "SCI_CLOCKF";
    case 0x04: return "SCI_DECODE_TIME";
    case 0x05: return "SCI_AUDATA";
    case 0x06: return "SCI_WRAM";
    case 0x07: return "SCI_WRAMADDR";
    case 0x08: return "SCI_HDAT0";
    case 0x09: return "SCI_HDAT1";
    case 0x0A: return "SCI_AIADDR";
    case 0x0B: return "SCI_MIXERVOL";
    case 0x0C: return "SCI_AICTRL0";
    case 0x0D: return "SCI_AICTRL1";
    case 0x0E: return "SCI_AICTRL2";
    case 0x0F: return "SCI_AICTRL3";
  }
}

void SaveUIState(void)
{
}

void RestoreUIState(void)
{
}

int GetUICommand(void)
{
  while (Serial.available() > 0)
  {
    char c = Serial.read();
    if (c != 10 && c != 13)
      return c;
  }
  return -1;
}

void exit(int code)
{
  if (code == EXIT_SUCCESS)
    Serial.println("Exited with no error.");
  else
    Serial.printf("Terminated with error: %d\n", code);
  while (true) { yield(); }  // yield() is needed for ESP8266 only
}

File fopen2(const char* fileName, const char* mode)
{
  if (mode[0] == 'w')  // fast workaround!
  {
    Serial.printf("Opening for writing: %s\n", fileName);
    song = SD.open(fileName, O_WRONLY | O_TRUNC | O_CREAT);
  }
  else
  {
    Serial.printf("Opening for reading: %s\n", fileName);
    song = SD.open(fileName, O_RDONLY);
  }

  if (!(song))
  {
     Serial.printf("File not found: %s\n", fileName);
     return song;
  }
  Serial.printf("File opened: %s\n", fileName);
  return song;
}

size_t fread ( void * ptr, size_t size, size_t count, File stream )
{
  yield();  // this is needed for ESP8266 only (otherwise reboots)
  return stream.read(ptr, size * count);
}

int fseek ( File stream, long int offset, int origin )
{
  stream.seek(offset);
}

size_t fwrite ( const void * ptr, size_t size, size_t count, File stream )
{
  return stream.write((uint8_t*)ptr, size * count);
}

int fflush ( File stream )
{
  stream.flush();
  return 0;
}

#include "player1003.h"

(i had to manually clean this file out of my additional code, but I hope it will compile just fine).

I have a request:

If you run this example, please write me in comment whether the recording worked. I can't make my VS1003 module record sound. I have a suspicion that mic in my module is broken. That's why I was trying the official example (with the minimum changes as possible). It records only noise in my case, but plays mp3 perfectly. If you have a working example of recording, please share too.

And one more to the people with more rep (moderators): Please add a VS1003 (and VS1053 and VS1063) keywords and assign it to my questions about VS1003, because I'm unable to do it and it should be done. The chip deserves a keyword. (It's really good and not expensive.)


How do I convert 0-5v PWM to a 0-12v PWM

I advice you to learn about basics of how to connect external components to MCU.
Anwser to your question is simple transistor amplifier... So you can use bipolar transistor (NPN/PNP) or MOSFET... MOSFETs is better for switching like your case, switching via PWM.
If you switching inductive load with MOSFET like motors or coils, don't forget add antiparallel flyback diode. Otherwise your MOSFET will burn out.

If you need switching with higher frequency or load with more voltage or power I advice to use push-pull logic to drive mosfet gate.
Something like this:


Passing serial data to Processing using something other than ln to trigger Processing

If I understand your question (which is not certain):

Pick a different "trigger" byte that you won't be sending in your messages.  Maybe TAB?
In your "Processing" program, use: port.bufferUntil(TRIGGER);
In your Arduino sketch, rather than println, use print to send both your data and the trigger byte:  Serial.print(your_message); Serial.print(TRIGGER);

Note that sending binary data will cause this to fail when the data uses the trigger byte.

From: https://www.arduino.cc/en/Serial/Println The println()
   method sends your output then a CR and NL.  And it seems bufferUntil() takes a character on which to trigger:
https://processing.org/reference/libraries/serial/Serial_bufferUntil_.html


Is it possible to have an Adafruit music maker shield and a sensor connected to the same Arduino?

If you look at the PCB of the Adafruit Music Maker here:

https://learn.adafruit.com/assets/16643

You can see that there are no connections on the analog I/O of the Arduino.


It's to do with programming the chip. When you are programming the chip using an external programmer you need the flash and EEPROM to be running. However you don't want the CPU to be running since you are doing things with the flash that it would normally access. By having the CPU (and RAM) on a separate clock you can clock the flash without clocking the CPU and all is well.


problem data I2C to sensor GY955/BNO055 (China)

I had the same problem with the Adafruit library. When a Chinese module is used the id needs to be specified in the constructor like this:

Adafruit_BNO055 bno = Adafruit_BNO055(55,0x29);


NodeJS (Galileo-IO) + Arduino sensor library

Including the header files for the libraries in the standard Firmata
sketch is only the first step. You will have to also modify the sketch in
order to actually use the libraries. You will have to figure out a way
of interacting with the libraries through the Firmata protocol and
implement this in your modified version of the sketch. You will then
have to modify the JavaScript side to enable these new interactions.
That's where you will write the missing methods


Using an Arduino Nano to program (as ISP) a standalone 328p

You can temporarily put it in an UNO. Don't connect this UNO via USB, but use jumper wires to connect the ISP pins plus the power pins to the other Arduino that you are using as an ISP programmer. (You could also use the (2x3) ISP header on the UNO if that's more convenient.)

Or, you could use a high voltage programmer.

Or get/desolder a crystal from some junk electronics. Exact frequency doesn't matter that much. I think somewhere between 1 Mhz and 16 Mhz would work.

You can then reset the fuses, so it doesn't need a crystal.


Using Arduino fix_fft or arduinoFFT library to filter some specific sound?

FFT is a tool for analyzing sound. It is not very appropriate for
filtering, unless you have loads of computing power to spare. And it is
even less appropriate for real-time filtering, if that is what you are
after.

Attempting to filter-out a noise based on its frequency is a reasonable
strategy for narrow-band noise, i.e. noise that lies in a narrow band of
frequencies. You can hope that, with some luck, removing this narrow
band doesn't affect too much the interesting part of the signal.

Alas, wind noise is very broad band, although it has more weight at low
frequencies:

(image source).

If the frequencies that interest you are above ≈ 2 – 4 kHz, you could
try a simple high-pass filter. Something like this should work even on
an Arduino if the sample rate is not too high:

static uint16_t filter(uint16_t input)
{
    static uint16_t sum;
    uint16_t delta = input - (sum >> SCALE);
    sum += delta;
    return delta
}

where SCALE is a small constant that determines the cut-off frequency.

Edit: The Z-domain transfer function of this filter is

H = (z − 1) / (z − u)

where u = 1 − 2−SCALE. Its cut-off frequency is then
approximately fsamp ÷ (2 π 2SCALE).


ISR executes even though an interrupt is not triggered

After checking the queue functions that you use in your sketch, I see there is no protection against concurrent accesses in the enq and deq functions, which is a must-have if you use any of these functions from within an ISR.

I would suggest the simplest changes to these functions as follows:

void enq(TPrioQueue *queue, void *item, int priority)
{
    TPrioQEntry *newEntry=(TPrioQEntry *) malloc(sizeof(TPrioQEntry));

    if(newEntry != NULL)
    {
        newEntry->item=item;
        newEntry->prio=priority;
        newEntry->prev=NULL;
        newEntry->next=NULL;

        // Protect against concurrent accesses starting here
        uint8_t sreg = SREG;
        cli();
        if(queue->head==NULL)
            queue->head=newEntry;
        else
        {
            // Find insertion point.

            // First special case: Item at head has lower priority
            if(queue->head->prio > newEntry->prio)
            {
                // Insert item at the start of the queue.
                newEntry->next=queue->head;
                queue->head->prev=newEntry;
                queue->head=newEntry;
            }
            else
            {
                // Find your insertion point
                TPrioQEntry *trav= queue->head;

                while(trav->next!=NULL && trav->prio < newEntry->prio)
                    trav=trav->next;

                newEntry->prev=trav;
                newEntry->next=trav->next;
                if(trav->next != NULL)
                    trav->next->prev=newEntry;

                trav->next=newEntry;
            }
        }

        queue->itemCount++;
        // Protect against concurrent accesses stops here
        SREG = sreg;
    }
}

void *deq(TPrioQueue *queue)
{
    // Protect against concurrent accesses starting here
    uint8_t sreg = SREG;
    cli();
    // Return NULL if queue is empty
    if(queue->head == NULL)
    {
        // Protect against concurrent accesses stops here
        SREG = sreg;
        return NULL;
    }

    void *ret=queue->head->item;
    TPrioQEntry *tmp=queue->head;

    if(queue->head->next!=NULL)
        queue->head->next->prev=NULL;

    queue->head=queue->head->next;
    free(tmp);

    queue->itemCount--;

    // Protect against concurrent accesses stops here
    SREG = sreg;

    return ret;
}


No, you cannot do HTTP in an interrupt, and you certainly can't use SoftwareSerial in an interrupt.

To trigger a heavy task in an interrupt you just set a flag (variable) which means "this task is due to be performed". Your main loop then checks that variable, runs the task, and resets the variable ready for the next time the interrupt triggers.

In multithreading environments these flags are called semaphores (yes, from the old signalling system using flags on ships). One thread (the interrupt) signals to the other thread (loop()) that it can do something.


It turns out that the libraries for compiling were incomplete. Having copied the libraries for the official IDE, it worked fine.


How do I turn off a 12V 3A RGB LED strip?

That's pretty simple: when you turn off all the colours you are actually turning off the entire strip with very minimum leakage current in each of the three FETs.


Arduino constant vs Microchip PIC constant

const means different things in different contexts as far as storage goes.

For a simple numeric value the compiler will generally replace the constant with the literal value. Any mathematics using purely constants or literals will be replaced at compile time with the result.

For instance, the code:

const int a = 3;
const int b = 4;

void setup() {
    int c = a + b;
    Serial.println(c);
}

void loop() {

}

results in the AVR assembly:

be: 4a e0           ldi r20, 0x0A   ; 10
c0: 50 e0           ldi r21, 0x00   ; 0

c2: 67 e0           ldi r22, 0x07   ; 7
c4: 70 e0           ldi r23, 0x00   ; 0

c6: 80 e2           ldi r24, 0x20   ; 32
c8: 91 e0           ldi r25, 0x01   ; 1
ca: 0c 94 4a 01     jmp 0x294   ; 0x294 <_ZN5Print7printlnEii>

Registers r22 and r23 store the second integer parameter to the Serial.println() - the actual function call generated is _ZN5Print7printlnEii(&Serial, 7, 10).

So you see that the literal value 7 has replaced both the sum of the constants and the variable it is placed in.

However it is very different when more complex values are called for - such as arrays (either numeric or character arrays, AKA "C Strings"). In this case yes the values are stored in Flash, however the startup code crt0.o copies that data into SRAM so that the software can access it easily.

Generally flash is hard for software to read from. In some architectures it requires special instructions to be executed. In others it requires setting values in SFRs (Special Function Registers) and reading from other SFRs to get the data. In other words it's far harder than just reading from a memory location (a limitation of Harvard Architecture). So it's copied at boot time into SRAM so that it then becomes easy to access, as it's just now accessing a memory location.

However that then defeats one of the objectives of using a constant value - reduction of SRAM usage by placing the data in Flash. So the Arduino has a specific macro PROGRMEM, which sets attributes on the variable to say "Never copy this data to SRAM".

More specifically it's actually provided by the file avr/pgmspace.h in the avr-gcc compiler:

#define __ATTR_PROGMEM__ __attribute__((__progmem__))
#define PROGMEM __ATTR_PROGMEM__

But now of course you can't access the data using simple memory accesses, so there are special functions to allow it to be done. Some are alternate versions of standard C library routines, for instance strcmp_P() shadows strcmp() with the second parameter being a PROGMEM variable. Others are special functions for reading bytes or words from locations in flash, such as pgm_read_byte_near().

The Arduino API also provides an extra little trick, called the __FlashStringHelper which is an empty class used to identify strings held in flash for the purpose of function overloading so that the F() macro can be used to call the right variant of a function to use the flash reading functions instead of assuming the string is in SRAM.

So as you can see it's not as straight forward as "consts are in Flash, non-consts are in RAM".

Highlighting the differences between how the AVR accesses Flash and how the various PIC sub-families access Flash:

The AVR has one single instruction that can read Flash - LPM:

  There is only one instruction for the read access to the program storage space. It is defined for the pointer pair Z and it is named LPM (Load from Program Memory). The instruction copies the byte at program flash address Z to the register R0. As the program memory is organized word-wise (one instruction on one address consists of 16 bits or two bytes or one word) the least significant bit selects the lower or upper byte (0=lower byte, 1= upper byte). Because of this the original address
  must be multiplied by 2 and access is limited to 15-bit or 32 kB program memory. Like this:

LDI ZH,HIGH(2*address)
LDI ZL,LOW(2*address)
LPM

PIC10, PIC12 and PIC16 chips have no way of reading the flash.

Instead a "lookup table" of "RETLW" calls is used. For instance the string "Hello" would be stored in flash as:

RETLW 72    ; H
RETLW 101   ; e
RETLW 108   ; l
RETLW 108   ; l
RETLW 111   ; o
RETLW 0     ; NULL

RETLW returns from a CALL with the W register set to the literal value in the instruction. The entire command, that is both the RETLW and the 8 bit literal value, fits into a single 14-bit opcode.

PIC18 uses SFRs to access the Flash memory. Set the three registers TBLPTRU, TBLPTRH and TBLPTRL to the three bytes of the address in flash you want to read, a TBLRD instruction is issued through the EECON1 register, then you can read the byte from TABLAT.
PIC24 / dsPIC33 uses PSV - Program Space Visibility. This gives you the ability to map a 32kB chunk of the flash memory into the upper 32kB portion of the data space. This allows direct reading of data from within that 32kB chunk as if it were in RAM.
PIC32 uses a Von Neumann architecture which means that Flash and SRAM both share the same 32-bit address space. There is no difference reading from Flash or SRAM, so no special instructions are needed.

The only chip from those above where const really means const is the PIC32 where there is no need to copy from Flash to SRAM during startup since all the Flash memory can be directly accessed with normal MIPS LW and LB etc instructions.


A key point of the Arduino 'language' is every statement is completed before the next one can begin.

A simple statement has a ';' at the end of it.
Or followed by ')' instead of ';' in for (...; ...; statement) loop.

So digitalWrite() will set the pin, HIGH or LOW, before it completes and allows the next statement, delay(...) to begin.

Side note:
Actually digitalWrite() takes a small amount of time to do its work, so it is not exactly 'the moment' it is called. digitalWrite() is pretty quick, a few millionths of a second, which is usually near enough to be practically 'the moment' for most applications.


Trouble using a TSSP77038 with an Arduino

Gerben is correct it looks like you need a pull up resistor so that the pin is high unless the receiver drives it low.

I found this, which was the closest to useful information I found. Have a look at the proximity sensor section, it is similar to what you are using.

You'll want to know a value, I haven't got a clue.  I use 4.7K for I2C pull ups. It's probably easier to start high (weaker) and work your way down, because if you put a 100K resistor in and the signal is low, then the resistor is too strong and you need a smaller one.


how to increase the delay factor of DHT11?

The DHT11 and DHT22 used to be cheap and easy to use humidity and temperature sensors when they were used together with an Arduino Uno.

But things have changed.

They are not accurate and can become totally inaccurate with certain
gasses or fumes.
It turned out, that the most used DHT libraries have
a serious bug that creates a shortcut in the datasignal.
This was no problem with the Arduino Uno, which can output
40 mA with a pin. The newer processors have problems with
that shortcut.
In 2018 the DHT11 seems to behave differently,
the internal controller has probably changed.
Because the communication with the sensors requires accurate timing,
the interrupts are turned off temporarily. That was no problem
with the slow Arduino Uno, but it is not normal with
a faster processor.
Some libraries use a timeout with a loop or with clock cycles.
That worked well with the Arduino Uno,
but it is not always reliable with newer processors.

In 2018, all the DHT libraries for the ESP8266 and ESP32 have issues with the DHT11 and DHT22.

Since the sensors are not very accurate anyway, it is best to stay away from all the troubles and avoid them. There are a number of good humidity sensors with I2C interface.


Can't drive long NeoPixel strips with Due or Duemilanove?

Your Duemilanove only has 1k of RAM. That's not much. Each pixel takes 3 bytes of RAM (R/G/B). So (say) 60 pixels would be 180 bytes. That's less than 1k, but there would be other uses of RAM in your sketch.

750 LEDs sounds like pushing it for the low-RAM Arduinos.

You might want to look at NeoPixels Revealed: How to (not need to) generate precisely timed signals The author managed to drive over 1000 NeoPixels with a Duemilanove.

I'm not sure if that applies to your exact type of NeoPixels, but it is worth considering.


How frequently do you need to poll UI buttons before they are perceived as laggy?

The short answer is that you have 100 miliseconds to respond to the user if you want them to feel the action occurred instantaneously.
According to Jacob Nielsen in his book Usability Engineering, from 1993, which is considered an important reference in Systems Usability and User Experience:

0.1 second is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.

He also mentions that this basic advice regarding response times has been about the same for many decades [Miller 1968; Card et al. 1991].
I've taken this citation from this article: Response Times: The 3 Important Limits, also writen by Jacob Nielsen.
Note that in this time you must include all time taken to read the button press and give feedback to the user.
Other response time thresholds that are important for user experience, from the same source, but that were not mentioned directly by the OP are:

1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.

10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.


You're missing out option 4, which is the option I would personally go for:

Use a different temperature sensor.

A quick parametric search on Microchip (my favourite, I'm a Microchip fanboy after all...) I find quite a nice one - the MCP9844.

  Microchip Technology Inc.’s MCP9844 digital temperature sensor converts temperature from -40°C and +125°C to a digital word. This sensor meets JEDEC Specification JC42.4-TSE2004B1 mobile Platform Memory Module Thermal Sensor Component. It provides an accuracy of ±0.2°C/±1°C (typical/maximum) from +75°C to +95°C.

  Operating Voltage Range (V): +1.7 to +3.6

However it is only available as a TDFN which makes prototyping difficult, although it is one of my two preferred footprints for real building - the other being variants of QFN.

I am sure you can search other makers for similarly specified chips that will do the job without the need for fancy boosters or doublers or the expense of multiple batteries etc.

One of the first steps of any design is the component identification. Often the chip or component that many people automatically reach for because it's the first one they used, or it's the one people most often talk about, may not be the right tool for the job. It pays to shop around a bit and look to see if there is something better that will fit the bill and save cost and time in the long run by ending up with a simpler system.


The SimpleWriteln() function just sends an instruction. It doesn't return anything.  Once you have sent the instruction to retrieve the IMEI you then have to actually read the IMEI.

However, fortunately, there is a function that does it for you:

char imei[20];
gsm.getIMEI(imei);

The IMEI should now be in the C string imei. What you do with it then is up to you.


Control Arduino through ethernet. How to contact from outside network and securely

The easiest way to do this is to use Blynk, an Internet Of Things (IoT) web service that includes an Arduino library, apps for iOS and Android, and a central server that the smartphone app and the Arduino both connect to. Since both connections are outgoing (and matched up by the Blynk server), each one works just fine from behind NAT routers without any ports needing forwarding. See Blynk's demo video for how to create a basic working app in 5 minutes (including your described LED controller and much more). Ok, I'll admit that starting from cold, it takes most of us a little longer than 5 minutes to get it going, especially if you like to read about and understand what you're doing as you do it. But it will still be minutes, not hours. This is the quickest, most painless way to get an IoT device up and running.

That basic app (which can read & write to ports, PWM, and A/D) is then extensible to work with your own code & hardware. The functions available lend themselves to just what you are looking to do, with the possible exception of uploading the images it takes. And the Arduino itself isn't really well suited to that task, given its memory constraints.

Update:
I use the ESP8266 like the one you linked to. They're cheap and easy to use but with a gotcha: they are 3.3v only on both power & signal lines, which can be a challenge when working with a 5v MCU board. Here's how to wire one up for a 5v Arduino. Note the dedicated 3.3v regulator; the Arduino's on-board 3.3v supply isn't sufficient for an ESP8266:

For quick & dirty, you can wire this up on a breadboard. Ultimately you'll want something more stable (mechanically) than breadboard wiring. I made up a few 5v ESPs on strip-board (aka Vector board or Vero board), but that's another project:

--

** (Disclaimer: I have no connection to the organization other than as a happy user/experimenter.)


move the modbus refresh out of the if (client) condition
mb.begin() calls Ethernet.begin(). Do not repeat it in setup()
move client.println("</html>"); break; inside the if block before it
copy the rest of the detection of empty line from the WebServer example
stop() the client after response
change type of ts to unsigned long


Enabling pins of Arduino Due with direct port manipulation

I suggest the following test:  Use REG_PIOB_SODR = 1<<27; to set the bit, and  REG_PIOB_CODR = 1<<27; to clear it.  If that works ok, see about enabling synchronous data output via the port's PIO_OWSR register.  (If it doesn't work ok, perhaps review section 31.6, “I/O Lines Programming Example”, on page 629 of Atmel document 11057, the Cortex datasheet.)

Section 31.5.5, “Synchronous Data Output”, on page 623 says in part:

  After reset, the synchronous data output is disabled on all the I/O lines as PIO_OWSR resets at 0x0.

I imagine that writes to REG_PIOB_SODR and  REG_PIOB_CODR should have effect after you enabled output by setting bits in PIOB->PIO_PER and PIOB->PIO_OER, which you did.  However, with the bit in PIO_OWSR being clear, synchronous data output isn't available, so writes to REG_PIOB_ODSR have no effect.


How can I speed up reading of an SD card?

Well I have two ideas on the SD card side, though neither really seem great to me they could still help you. I read on the Arduino forum that the SD card R/W speeds generally come out to 600kB/s, I'm not really sure why, the Arduino SPI can go up to 8 MB/s and I didn't think there would be that much protocol/data-handling in SD.

Sector R/W - As Chris Stratton said, this is an obvious method, it's probably much faster to do sector reads. You may have to greatly change your code to implement it, but I imagine you'd see performance increase in the end. Apparently there's an unofficial library for it, though it seems to impart some potentially serious limitations.
RAM - This is the second thing that came to mind when thinking about the problem is that you could use external RAM, when not handling network transfers (Idling, should be most of the time) the Arduino transfers data to external SRAM which you add. SPI RAM is most likely the easiest to implement, but not likely to be any faster than an SD card. Parallel RAM is going to be difficult to implement, you'll likely need to write your own class/library, but it could be much faster than SPI RAM or an SD card.

I'm not actually sure if either of these would be any faster, it's all just theory and I hope others will share their thoughts. If you have trouble finding the download link for the SD Card library, it's right here. In that ZIP folder there's a file called SDCARD, just move that folder into your Arduino libraries folder on your computer.


5V 1A vs 5V 5A power supply for 6 LED + Arduino

Depending on your led, it will draw 10 to 20mA for a standard led. Thats 0.010 to 0.020A. Multiply this by 6 and you see that a 1A power supply will be enough.

Your arduino, when driving those leds, will also use a few mA. So you can power everything with a 1A power supply.


Why is there no smooth value from ADXL335?

It is called moving average, the calculations you can use to prevent such problems can be found at wikipedia

In principle, what you do is take the average over the last x measurements to take away the peaks.


Arduino HTTPClient passing string to variable

The getString() method calls writeToStream which is documented write all  message body / payload to Stream. It writes all the data of the http response to he output and doesn't store them internally. The next call has nothing to read because the first call to getString() put everything out.


Steppers only vibrate, not rotate with I2C

In both master and slave, you have x and y declared in the broadest scope possible. Different devices, shouldn't matter. But x and y usual mean coordinates, which is not what you are trying to say - properly named variables help with understanding and maintenance.

I think your biggest issue, and one that confuses your attempts to debug, is the underlying logic.

You have 4 independent buttons, but prioritise one button over the
other. What happens if both buttons are pressed together?
You have 2 independent motors but prioritise one after the other.
Your slave uses repeating code.
You use your slave as both a writer and  decider. In this case, your
writer is making the decisions over which motor to move and which
direction.
Your master only makes one move at a time - but you have two motors and 4 buttons, so you should be able to move both motors in one loop.
Your handler expects the number of bytes to be read but you don't use that to control your reading.
Your consecutive reading does not differentiate on where the data comes from. x could be filled with any of the button presses, and so could y.
If the event handler is doing the work, why have a blocking delay in the code?

Effectively, you are taking a random read and expecting the device to do something deterministic. Hence your jittering.

To help you debug your device, you can first clean up your code.

reconfigure your slave to send a single response each loop. You only need 4 bits, where each bit represents whether buttons 1-4 are pressed. Only 1 variable to be written.
Use your master to decipher the input. This is where you can put the safety in (e.g. if both 1&2 are pressed/HIGH then ignore). This also reduces the possibility that your code is sending a forward then backwards signal.
Use your master to determine how many bytes have to be read and use this properly.

You will find your code cleaner, easier to read and easier to debug. Perhaps you will also see a way to directly slave the NANO to the UNO without i2C in the middle, simplifying your set up even more.

EDIT (additional information):

You can use the built in functions (see Arduino function reference under "Bits and Bytes") such as BitWrite/BitSet/BitClear and BitRead to set/clear the relevant bits on the variable you create (e.g. Byte ButtonStates). Note the use of Byte instead of Int
You can then use the slave to write the information and the master to read the information (Wire.write and Wire.read), you then know that each byte is complete and reflects what you intend.


connect USB keyboard to Arduino using clk and data wires

USB doesn't have data and clock lines. It has a pair of data lines with inverted polarity (D+ and D-). The USB protocol is considerably more complex than you seem to imagine.
However there is a caveat: some keyboards have the ability to work in IBM PS/2 mode. For this you will need a USB to PS/2 adaptor (pictured below) and then use the PS2Keyboard.h library. Your mileage may vary, though, as not all keyboards will work.


Dimming this ~30V led with PWM, what do I need?

It will not be possible for you to PWM dim your LED with that LED driver (power supply).
That is a constant current driver with under/over-voltage protection. It delivers a specific amount of current (1.5A) and varies the voltage to allow that to happen.
If the voltage rises too high or falls too low then there must be a fault, so it shuts the power off. This is usually because there is either a short (LEDs tend to "fail short") or an open circuit. The former causes the voltage to drop too low and the latter for it to be too high.
When you insert PWM control you alternate between driving the LEDs and an open circuit. If that open circuit persists too long (low duty cycles) the driver will shut off.
You will need to replace the LED driver (the power supply) with one which includes PWM control internally to it.


How much current and voltage has my resistor + LED

The problem is that if you're trying to measure the current directly, you're going to get the wrong answer. Whether it's due to burden voltage or the (in)accuracy of the meter, it's a hopeless situation. The 0.005A your meter is showing is actually closer to 3mA in reality, but your meter can't distinguish between the two well enough.

If you need to measure current this small then the only way to do so accurately is to use a very low-value shunt resistor and an amplifier. This is the method the µCurrent uses, and it's essentially the defacto gold standard for measuring current in small circuits.


How do I control arduino uno multiplexed digital pin (using HC74595)

It is good that you are thinking of abstraction in order to simplify programming.  Simplifying programming by using familiar names makes it easier to understand the code.

In your example:

int triggerPin=2
pinMode(triggerPin, OUTPUT)

..you are abstracting the actual pin used to trigger the ultrasound by calling it by a familiar name "triggerPin".  You could have just as easily wrote the same code as:

pinMode(2, OUTPUT)

Now you are asking how to abstract the pins when connecting the Arduino to the 74HC595.  The truth is, you don't have to.  But to make it easier to write & read the code you can use what ever names make sense to you.  In this example of connecting an Arduino to a 74HC595 there are 3 Arduino pins connected to the 74HC595.  They called them "dataPin", "latchPin" and "clockPin".  If these make sense to you use these names.

  Add: can i address the output like this?

 #define LED_PIN     Q1

No, nothing knows what "Q1" is.  Remember, you are adding this hardware to the Arduino.  So nothing, not the compiler nor a library, knows about the hardware you added let alone a pin called Q1 on the added hardware.

First you need to understand how to set Q1 through Q8.  Refer to the 74HC595 Arduino tutorial linked to above.  Inspect the example programs.  Once you understand how to set / un-set Q1 through Q8, you can decide if you what to simply shift out a number or if you want to use abstraction giving names to the shift register output pins.

If I were only writing patterns, for example lighting up 8 LEDs, I would stick to numbers. However, if I were controlling different things, for example a light, a motor & a buzzer, I would assign each a unique name and build my program around the names.


The solution turned out to be a couple of things, some of which mentioned by others in the comments.

Problems that needed to be fixed:

My level-shifter was a huge part of the problem. I switched to a MAX232-based chip and then I was a least able to get responses shorted lines 2 and 3 (Tx and Rx).
I needed a cross-over cable. I had tried this while troubleshooting, but because that alone didn't fix the problem, I had not idea whether or not that was the problem, or just one of the problems.
I needed to use the onboard UART (Serial1) rather than SoftwareSerial. The problem was that I needed to be able to set the protocol to 8 bits with no parity. This configuration parameter cannot be changed on SoftwareSerial, but is as simple as Serial1.begin(9600, SERIAL_8N2).

Thank you for the help, and hopefully my mistakes make the process easier for others.


You need additional hardware like a RTC for example an DS1307 or on the other hand an arduino/shield with ethernet or wifi so you could get the time by NTP another option might be DCF77 time via the air - sorry forgot GPS could also be used to get the time .... the rest then should be simple creating a string.


It becomes much easier if you start thinking in binary.

If you have an 8 bit multiplexer connected to four 8 bit multiplexers that gives you 32 inputs. Four of the inputs on the "master" multiplexer are unused and can be ignored.

You have 32 inputs. That's inputs numbered 0 to 31. In binary that equates to, in full,

0 = 000000   8 = 001000  16 = 010000  24 = 011000
1 = 000001   9 = 001001  17 = 010001  25 = 011001
2 = 000010  10 = 001010  18 = 010010  26 = 011010
3 = 000011  11 = 001011  19 = 010011  27 = 011011
4 = 000100  12 = 001100  20 = 010100  28 = 011100
5 = 000101  13 = 001101  21 = 010101  29 = 011101
6 = 000110  14 = 001110  22 = 010110  30 = 011110
7 = 000111  15 = 001111  23 = 010111  31 = 011111

I have laid it out like that especially so that you see a pattern occurring. Four columns with 8 rows. Four slave multiplexers with 8 inputs. A perfect match. Each column has bits that are distinct to that column. Each row has bits that are unique to that row.  So you could split those bits up and know that the left-hand three bits indicate the column, and the right-hand three bits indicate the row. Between the two it's a unique location in the table.

The same applies to the multiplexers.  The left-hand three bits indicate which slave multiplexer to use, the right-hand three bits which input to use on the selected multiplexer.

So you can loop through each of the 32 inputs with a single loop and examine the individual bits of the input number and apply those bits directly to the select outputs to control the multiplexers - the left-hand bits to the master to select which slave to use, and the right-hand bits to the slaves to select which input to use.

So you have:

for (int i = 0; i < 32; i++) {
    digitalWrite(M_S2, i & 0b100000);
    digitalWrite(M_S1, i & 0b010000);
    digitalWrite(M_S0, i & 0b001000);
    digitalWrite(S_S2, i & 0b000100);
    digitalWrite(S_S1, i & 0b000010);
    digitalWrite(S_S0, i & 0b000001);

    delay(1);

    int reading = analogRead(Z);
    Serial.print("Input ");
    Serial.print(i);
    Serial.print(": ");
    Serial.println(reading);
}

The i & 0b000001 etc performs the same function as bitRead() but is more explicit using a mask that is far more visual as to what it achieves.

I also include a tiny delay after setting the multiplexers up so as to ensure they have settled into their new settings properly before reading. It shouldn't be needed, but it doesn't hurt.


Removing Robot IR Arduino Library on Macbook

The folder name is RobotIRremote.

It's actually not necessary to remove that folder, though that will solve your problem. A better solution is to change the folder name of the IRremote remote library so that the file named IRremote.h found in that library will be given include priority over the one found in the RobotIRremote library. This is better because you would need to remove the RobotIRremote library every time you update to a new version of the Arduino IDE. The Arduino IDE gives include priority to files that match the name of the library folder but unfortunately if you install the IRremote library manually it will tend to have the folder name Arduino-IRremote-master which causes the wrong file to have priority. So you just need to find that folder and rename it IRremote.

If you don't know where it is the library folder can be found by:

File > Examples > IRremote > AiwaRCT501SendDemo
Sketch > Show Sketch
Folder


Rough block diagrams below show two ways this can be achieved - "Easiest" costs least but is inefficient. "Better" uses PV panel output more efficiently. Details of either can be discussed if of interest.

'Schottky diodes' should be used to minimise losses.

(1) "Easiest"

Connect PV panel to battery with diode.
Panel is clamped to battery voltage (+ diode drop).
This will not hurt the PV panel but wastes some of the available power.
[What is the formal PV panel specification. Is it 21V O/C or loaded or .... Do you have a datasheet link for it?].

Use 12V (nominal) to 5V converter to power load.
This could be

A linear regulator - only about 40% efficient - very wasteful.
A buck converter (build or buy from eg ebay)

(2) "Better"

Use a buck regulator to charge the battery - ideally an MPPT (maximum power point transfer) controller. Details can be discussed if you are interested.

Use a second buck regulator to power the load. This must be capable of (at least) 11V to 22V input. Power this from a Schottky diode from the PV panel AND a Schottky diode from the battery. When the panel voltage is > battery voltage the panel will power the load.


Posting the clear photo is helpful because it shows the USB host board has the following problem.


Keep a boolean that begins as false. Set it to true when the start button is pressed, and set it to false again when the finish button is pressed. Then you can read and respond to the add and reject buttons only if that boolean is true, and otherwise ignore them.


Determining power consumption with Arduino and JeeLib

What board are you using? For example, the Uno has a lot of other components that will consume power, even if you sleep the main processor. Instead use something like a Pro Mini.

You can bypass the voltage regulator, and just supply 4.5v by using 3 AA batteries. You can even use just 2 AAs if you have the 3.3v version. The lower the voltage the less current the ATMega uses.

Most importantly, measuring the power consumption using a multimeter. Measure the current the led uses. Disconnect the led, and measure how much the arduino uses. Use this handy Battery Life Calculator, and just fill in those numbers.

Run the led with the lowest current, where the led is still visible enough. Running a power-led at just 1mA will still give a decent amount of light.

In your situation, if coded correctly, power usage of the ATMega is negligible. The only real power user is the led. If you run the led at 1mA, and use a set of AA batteries, you get around 3.5 years of running time, no problem.


I am tying to split a float variable into bytes and then re combine to the original float

I have been told to be careful about a simple casting of non-byte variables to an array of bytes because there's no guarantee that the memory allocated for certain data types will be contiguous. I.e., the bytes might be spread out to non-adjacent spots in memory. For example, I was encouraged to use a union to convert a unit64_t, which is 8 bytes, to a byte array on an ESP8266. This involves declaring a union type:
union u64_bytes {
  uint64_t u64;
  uint8_t u8[sizeof(uint64_t)];
};

And then you can use this to convert either way, for example:
  uint64_t myNum = 1;
  u64_bytes splitNum;
  splitNum.u64 = myNum;
  // now i can loop thru the bytes
  for(int i=0; i<sizeof(uint64_t); i++) {
      uint8_t myByte = splitNum.u8[i];
      Serial.print("byte ");
      Serial.print(i);
      Serial.print(" is ");
      Serial.println(myByte);
  }
  // or just refer to individual bytes
  uint8_t oneByte = splitNum.u8[0];

  // you can also take bytes and convert the other way
  u64_bytes rebuilt;
  for(int i=0; i<sizeof(splitNum); i++) {
      rebuilt.u8[i] = splitNum.u8[i];
  }

  Serial.print("The rebuilt value is ");
  Serial.println(rebuilt.u64);

EDIT: I added some code to show conversion the other way.
That said, it's probably pretty safe in your case to use the bitwise operators you are using. A float is in all likelihood 4 bytes on your hardware, and most hardware allocates memory these days in four-byte blocks.
HOWEVER you still have to take into account the Endianness of the system when it stores values. The basic idea is that if you have four bytes that represent one number, are the most significant bytes first or are the least significant bytes first?
For example, if you are talking about a four byte unsigned integer the number 1, aka 0x00000001, it would be stored like this in Big-Endian hexadecimal:
0x00 0x00 0x00 0x01

But on little endian hardware (like mine) the order is different. They put the least significant bytes first in memory like so:
0x01 0x00 0x00 0x00

This might be very confusing, but the bottom line is you might have to think twice about what the byte order is for your data. I'd add that floats and signed integers might have some aspects that surprise you, and when you try and communicate any information over a serial line (SPI, I2C, etc.) or over a network then you might have to worry about what sort of conversions are happening. You must have to make sure that you know what order your bytes are and you unpack them in a way that's appropriate to the way you packed them.
Lastly, I would encourage you maybe think about (and possibly elaborate) what you are hoping to accomplish by taking apart a float into bytes? If you don't know about the structure of bits inside a float, you would need to get better acquainted with that before you start monkeying with the bytes inside it.
EDIT 2: here's an example where I use a struct to convert a float:
  union float_bytes {
    float flt;
    uint8_t u8[sizeof(float)];
  };

  float myNum = -127.0;
  float_bytes splitNum;
  splitNum.flt = myNum;
  // now i can loop thru the bytes
  for(int i=0; i<sizeof(splitNum); i++) {
      uint8_t myByte = splitNum.u8[i];
      Serial.print("byte ");
      Serial.print(i);
      Serial.print(" is ");
      Serial.println(myByte);
  }
  // or just refer to individual bytes
  uint8_t oneByte = splitNum.u8[0];

  // you can also take bytes and convert the other way
  float_bytes rebuilt;
  for(int i=0; i<sizeof(splitNum); i++) {
      rebuilt.u8[i] = splitNum.u8[i];
  }

  Serial.print("The rebuilt value is ");
  Serial.println(rebuilt.flt);


Arduino-compatible micro-controller with both I2C and CAN

Many options come to mind:

Bluepill board
Literally any board with I2C and CAN buses from the STM32 series, as searchable on their website (https://my.st.com/content/my_st_com/en/products/microcontrollers.html)
ESP32

A Bluebill board is programmable with mbed, STM32HAL (CubeMX) and Arduino, all of which have either CAN libraries for the CAN peripheral or have it even built-in in the OS (mbedos).

The Bluepill board is extremely low cost ($1.81 with free shipping from aliexpress) and features an STM32F103C8 microcontroller with 128kB Flash and 20kB RAM. Its peripherals include two I2C and one CAN bus.

Infos & Datasheet: http://www.st.com/en/microcontrollers/stm32f103c8.html, http://wiki.stm32duino.com/index.php?title=Blue_Pill

For flashing and debugging the chip you should have one cheap ST-Linkv2 clone (~3$ from china).

For programming environments you can use:

Arduino IDE (STM32Duino Arduino Core for STM32F1/F3/F4 chips: http://wiki.stm32duino.com/index.php?title=Boards_Manager_package)
PlatformIO, more general purpose and more powerful (https://platformio.org:443/boards?count=15&filter%5Bmcu%5D=STM32F103C&page=1&sorting%5Bname%5D=asc)

As frameworks you can use:

Arduino (see above)
ARM mbedos (builds upon STM32HAL, natively supported by PlatformIO)
STM32HAL (e.g. with project files for an IDE generated by STM32CubeMX)

Documentation references:

https://os.mbed.com/docs/v5.8/reference/can.html
https://www.st.com/resource/en/user_manual/dm00154093.pdf (Chapter 8)
https://github.com/Locoduino/Commanders

8 Bit microcontrollers from STM8AF series have a few micros with 1 I2C and 1 CAN bus: See http://www.st.com/en/microcontrollers/stm8af-series.html?querycriteria=productId=SS1583

Ready buyable evaluation board: http://www.st.com/en/evaluation-tools/stm8a-discovery.html (you want the STM8AF5288 one)

The toolchain changes then, of course. See https://my.st.com/content/my_st_com/en/extended-query.html?querycriteria=productId=LN1759$$associatedTo=SS1584


Comparing orientation data obtained using gyroscope and accelerometer

Normally the values from gyroscope will drift overtime. It is natural and depends on the parameters of your code. It could drift a few degrees per seconds and the data will be far way from the accelerometer in a few seconds.

I have seen that you have applied the complementary filter, so you don't need to worry about the single value from the gyros since you combine them with the acceleromter and everything seems fine.

The gyros are good for short time response, in long time response the values get pretty bad as they drift a lot.

On the other hand, accelerometers are good for long time response, since short time response is noisy because of gravitational influence.

That's why you need a filter to combine them.

Wrapping up, it is normal to have this behavior in gyros. If you want to know more about the effect behind this sensor, try this reading.


Can anyone suggest me a software timer library that does not use polling but timer ISR instead?

Yeah, I have the same problem.
The only solution I found is to rewrite  a lot of the code. Still ongoing, though.

For you, Timer1 is probably the best candidate, unless you have already some use for it, like in my case.

A quick hack is to free Timer0: it is currently (ab)used by the wire library, which provides the typical arduino timing.
But you can remove/rename the file wiring.cpp to something that will not be identified as source (ex: wiring._cpp) and comment out the init() function call from the main() function in the main.c file.

Normal Arduino stile time functions will not work, of course.

Unfortunatelly Arduino SW really lacks the structured design that would allow it to be useful in more complex cases and most of the libraries make exclusive use of resources that could be shared, timer being the most prominent example.

Port ISRs is another.

Btw, if you happen to use a SW serial library, it's already game over, as it busy loops inbetween bits, in interrupt context (!), rather than using a timer.


I see this problem more profound than just some if and else. As you may observe, there may be two peaks in flex and always there is one in relax.

What makes difference is the width of the pulse: flex is wide and relax is narrow.

You should detect the width. It can be measured by amount of times, when you detect a value in input that is over the treshold.

When the amount is less than some value when signal is very low again, you detected a LOW for output and if it is more than some value it means HIGH.

in setup

unsigned int times = 0;
unsigned int threshold = xxx;
unsigned int low = xx;
unsigned int high = yyy;

...

in loop

...
if (level > high) {
      times = times + 1;
} else if (level < low) {
     if (times > threshold) {
          digitalWrite(ledPin, HIGH);
     } else {
          digitalWrite(ledPin, LOW);
     }
     times = 0;
}


You've assumed that a char * is some kind of string object, since you've got the following line of code: output += espData[x][i];, and then later espData[x] = output;

It quite simply doesn't work like that. At best you can point output inside espData[x] and then do some other logic: but your attempt to "accumulate" the correct characters is incorrect.

Please consider the following code instead:

char* espData[15];

for(int x = 0; x < index-1; x++){
    size_t nullTerm = strlen(espData[x]); // Get current length
    char* output = espData[x];            // Start of string
    for (size_t i = 0; i < nullTerm; ++i){
        if(espData[x][i] != ':') {        // If it's NOT a colon
            *output++ = espData[x][i];    // Copy character 'up'
        } // if
                                          // If it WAS a colon, then
                                          // output does NOT get incremented
    } // for
    *output = '\0'; // End string off with NUL
    Serial.println(espData[x]);
} // for


The ADC is a "Successive Approximation" type ADC.  It works by:

Taking a snapshot of the incoming voltage in a small capacitor
Generating a reference voltage
Comparing the voltage in the capacitor to that reference voltage
Refining the reference voltage
Go back to 3 until you have the accuracy you desire.

There's lots of "time" involved there:

The capacitor can only store the voltage accurately for so long before the self-discharge (leakage current) causes the voltage to drop (this defines the maximum amount of time you can take to do a reading)
Each refining of the reference voltage and comparison thereof takes one ADC clock tick. There are a few "setup" clock ticks as well. This defines the minimum number of ADC clocks that you need to take a reading (13)
The DAC and comparator take a certain amount of time to operate each clock tick - this limits the maximum clock frequency the ADC can run at.

So you have a "sweet spot" of speed (like the "goldilocks zone" of the solar system). Set the ADC too slow or try and get too high a resolution out of it and you lose accuracy due to voltage droop on the capacitor. Set it too fast and the DAC can't keep up and you lose accuracy due to the comparison voltage not being right.

Well, that's the internals. Then on top of that you have the Arduino API. That adds an entire other layer of complication. analogRead() is a blocking operation.  It:

Congfigures the IO pin (if needed)
Turns on the ADC (if needed)
Configures the ADC MUX to the right channel
Starts a conversion
Sits there twiddling its thumbs for a while
Reads the conversion result
Returns it to you

And it does that (except maybe 1 and 2) every time you take a reading.  That's fine for reading a potentiometer, or an LDR, etc. But rubbish when you want to do fast, time-based, readings.

Instead you need to push the envelope a little and step away from the Arduino API.  Much of what the ADC does is done without intervention of the CPU. Manually configuring the ADC to read continuously and trigger an interrupt when the conversion is done, and then using that interrupt to grab the result of the comparison and start a new one (or use a timer interrupt to read the previous result and trigger a new reading) will give you much more control over the ADC and exactly when things happen.

So, now to answer your main question of "when during that 8us interval the actual reading takes place.", in the context of how the ADC works:

At the moment the SAH capacitor is detached from the MUX to start the comparison sequence.

When exactly is, though, is subjective.  If you use the Arduino API (analogRead()) then it's at some point near the start of the function call, but not at the start of it.

If you configure it manually and trigger it from within a timer interrupt, it's on the second (out of 13) falling edge of the ADC clock after ADSC has been set HIGH.

There are also "Free Running" and "Auto Trigger" modes whose timing is the same as for a single conversion.  Note that the first conversion performed in any mode imposes a "run-in" clock sequence where the ADC MUX and reference voltage DAC are initialised.

All this timing can be found in figures 23-4 and 23-5 on page 209 of the ATMega328P datasheet.  On page 210 there is a handy table that gives you how many ADC cycles from the start of a conversion the Sample And Hold occurs and how long the conversion takes in clock cycles.

For best throughput you want to use "Free Running" mode and read and store the ADC result in the interrupt the ADC triggers.  For most accurate and controllable timing you want to use Auto Triggered mode with a timer for the trigger source, and again read the result in the ADC interrupt.


error: ‘sleep’ was not declared in this scope

"sleep()" is not a function on arduino. The sleep.h file contains functions for the hardware sleep functionality used to reduce power consumption when processing isn't necessary. "delay()" is the right thing to use.

AVR only has one thread, and so there is no meaning to pausing execution by deferring to another thread. Hardware interrupts will always interrupt the current code no matter what it is doing, they are not equivalent to threads (although they can introduce similar bugs).

If you want to wait and still do other calculations you will need to write code that can wait for a time without blocking. This can be done many ways, one way being to use the arduino library function "millis()" to repeatedly check if it is time to do a certain action, and doing something else for a while if not.

Also, vanilla arduino should be using its own packaged avr lib, for example:

arduino/hardware/tools/avr/avr/include/avr/sleep.h

instead of the one located in your usr/lib directory.


I want to pour 500ml of Water in jar with Arduino water flow controller?

The flow meter you specified, YF-S201 Hall Effect Water Flow Meter (datasheet) measures the water flow rate, producing signal output frequency in range 16Hz (at 120L/H) to 90.2Hz (at 720L/H). Datasheet claims "error range +/- 10)". Note that this only measures the rate of flow, it is not a valve and so does not control the flow.

Problem with using a flow rate sensor to measure total quantity of water, is that you must constantly integrate the flow rate over time to get the total volume. Any errors in rate measurement or integration time, will accumulate; so this is generally not an accurate approach. Cumulative errors are highly undesirable, because they are difficult to detect and compensate. You have to not only measure the output frequency, but also carefully control the time between measurements, because you are integrating over time. This will be even more of a problem if you are printing out messages to the serial port.

If the water supply is well regulated and always provides a steady flow, then you will open the valve for a specific time interval. But if the supply pressure is not well regulated, then you may accumulate integration errors and dispensing will not always be accurate.

If you care about dispensing precisely 500mL of water, a more practical solution is to use a weigh scale (load cell). First, measure the tare weight of the empty container, then dispense (using a control loop) until net increase in weight is 500g. With this setup, the dispenser accuracy is determined by the load cell repeatability error (0.1% for a good quality load cell, a couple % for a fair quality load cell) and the measurement accuracy of the ADC (depends on resolution and reference voltage stability). You could try using the Arduino's on-chip ADC which is only 10 bits, or for best accuracy use a real 24-bit weigh scale ADC. The load sensor's offset error is set to zero by measuring the tare weight of the empty jug, so you only need to be concerned about gain error at 500mL and repeatability of the load sensor. This approach does not have cumulative errors.

You have not specified what kind of valve you will use to control the flow. If you use a solenoid value, the valve is only on-or-off, there may be some overshoot due to valve reaction time (10ms), so you will need to experiment and determine an "off threshold" before reaching 500g.

Since you have no way to compensate if the system overfills the jar, you will need to dampen the system response so that it slows down as it approaches the target level, without overfill. I'd therefore suggest using a proportional valve instead of a solenoid valve. Start with a fast flow rate when net weight <400g and then switch to a slower rate as the jar reaches its target weight.


Error array value after passed to a function

sizeof counts bytes. the type of your array is int. sizeof of the int array of length 5 is 10 bytes. your for loop goes to i < 10 and reads after the 5th item of the array.


How to install a dependency library to an Arduino compilation environment?

If the library is installed the Arduino IDE (or CLI I assume too) just finds it and compiles/links it for you.


I found that the 3V isn't enough to power the relay.
https://www.instructables.com/Getting-Started-With-ESP8266LiLon-NodeMCU-V3Flashi/ shows the board supplies USB power (pin VU).
You can remove the jumper that connects signal voltage to relay power and connect the relay board to the USB power.
After that change I could turn the relays on and off, but I could not reliably power 4 relays, 2 relays as shown below seems fine.


Combining code for multiple sensors (Current and Voltage Sensors) in one program

How to combine two sketches.

First, make sure every global variable and function name is unique (except setup and loop). Choose the smallest sketch and rename its. variables, function names and any other named items (like DEFINE).

Is convenient to refactor things. I extract the code for reading Voltage and Current to separate functions, to reduce the count of global variable and length of each function, making things easier by reducing the side of setup() and loop().

Now, combine the code inside the setup and loop:

const int analogInput = A1;

void setup() {
  Serial.begin(9600);
  pinMode(analogInput, INPUT);
}

void loop(){
  Serial.print(getCurrent());
  Serial.print(" ");
  Serial.println(getVoltage(),2);
  delay(500);
}

float getCurrent() {
  float average = 0;
  for(int i = 0; i < 1000; i++) {
    average = average + (.0264 * analogRead(A0) -13.385) / 1000;//this is
    //for the 5A mode, if 20A or 30A mode, need to modify this formula to
    //(.19 * analogRead(A0) -25) for 20A mode and
    //(.044 * analogRead(A0) -3.78) for 30A mode
    delay(3);
  }
return average;
}

float getVoltage() {
   const float R1 = 30000.0; //
   const float R2 = 7500.0; //
   float value = analogRead(analogInput);
   float vout = (value * 5.0) / 1024.0; // see text
   float vin = vout / (R2/(R1+R2));
  return vin;
}


Arduino UNO stuck in Setup function when interfacing UNO with ESP8266 module

It's always a good idea to put a serial output in the setup of your code.

It seems that your Arduino resets itself.

But why?

I believe the problem would be with too little power for your ESP8266 and Arduino. When the ESP8266 wants to create a network connection, it takes a little more current, possibly leaving your Arduino without enough current to run on itself.

So your Arduino would shut down since the ESP8266 takes up all the current. Creating some kind of bootloop on your Arduino.

Please tell us how you powered the devices and how you connected them.
You might try using a separate power supply or a big capacitor on the Arduino's 5V+GND.


Wow, I remember the ol' 84a... That was my first ever microcontroller.

Making any long-term timing on a microcontroller is not an easy task.  If you have interrupts firing they can cause calibrated delay loops to be themselves delayed, and over long periods like 250 seconds small errors soon mount up into big errors.

So there's basically 2 ways to tackle delays without adding extra hardware - calibrated delay loops and timer interrupts.

A calibrated delay loop is a function that you can call and will delay for a known pre-defined period. Typically it involves counting the number of clock cycles required to both call an execute the delay function, and a loop with a number of NOP instructions used to make the delay the right length.  Getting the balance between the number of NOP instructions inside the loop and the number of iterations of the loop is important for accuracy - the number of NOP instructions basically sets the granularity of the delay.  Also as mentioned before, if an interrupt occurs the delay will itself be delayed and things will start to slip.  So it's a reasonable solution for rough delays for things like blinking an LED, but for long term timing it's not going to be accurate.

The second option is to use a timer interrupt.  Now, a timer runs much too fast to be able to time 250s.  So you need to time a much shorter period and "add them up".  For instance, I often set a timer to trigger once every millisecond, then in the interrupt routine I add 1 to a millisecond counter.  Then in a delay routine you just look at the start of it to see what the current millisecond count is, and then wait in a tight loop checking the new current millisecond count and comparing it to the old. When a certain time has elapsed then it's time to finish the delay.  For your situation it may be better to have the interrupt trigger once a second so you're just counting seconds rather than milliseconds (which means you're working with much smaller numbers - 250 instead of 250000).  However, this method does have down sides of its own: chiefly that you have a pre-defined granularity and your delay will be ± that granularity - that is you will start the delay "at some point during a second" and finish it "on a second", so there's some leeway around where you start the timing from.  The smaller your measured period the finer your granularity, and the more accurate your delay.

A third option, not grouped with those two above, is to use an external Real Time Clock (RTC) chip to do the timing for you.  That is by far the most accurate method over long periods of time, and most RTC chips have an alarm function that can trigger an external interrupt at a pre-specified time.


74HC595N shift register with separate power supply

All ground connections except those which are explicitly isolated must be connected together in order to provide a common voltage reference for the circuit. Any breaks in the ground connection can result in gross misbehavior such as what you are experiencing.


Wired serial connection between two Arduinos - do they need a common Ground (GND)?

Short answer: Yes.

Rx/Tx is referenced with a logic ground. Without ground being common, there is no way to determine what is high or low.

(Sorry I don't have a more technical explanation)

Edit: I thought I would add, if you are using the same power source, then they probably have a common ground. In this case, a common power source doesn't mean the wall side of a wall adapter, but the SAME wall adapter.


There are many circuits using the TIP120 NPN transistor because it is a darlington transistor. This is used because its max voltage is 60V and the max current is 5A, this means you can control a variety of external high current devices with low voltage circuitry because of the darlington arrangement.

You can use the BC548B with your motor(low current) and a 9V battery as it does handle 30V, but it is limited to 100mA, which is fine for tiny low current motors. But these are actually Amplifier transistors, so there main design area is not for inductive loads.

I recommend the TIP120 as this will ensure that you don't trash a transistor with current spikes as you could easily go over the 100mA spec of the BC548.


Your arrays are both too short for the strings they're meant to hold. In particular, ang has three digits and only three bytes. The string-terminator, NUL, ends up in the 1st byte of lat. Since you generated the ang string first, lat over-wrote ang's NUL character, effectively getting appended to ang.

The lat string will need at least (10+1) bytes; ang will need (3+1) bytes, counting only the actual data in your question.

I make it a habit to declare string arrays just as I wrote the sums above, to make it clear that I've counted both the contents and the NUL byte, so:

  char ang[3+1], lat[10+1];

I doubt that you need to specifically add the NUL terminator; it would quite unusual (counter-conventional) for a C/C++ function that generates a string to leave off the terminator (except in a few special cases).

Try increasing just your array sizes first; it'll probably work.


100 hz Square Wave of 50% duty cycle in digital pin 3 and verifying with pin 4

You wrote:
uint16_t val2 = pulseIn(4, HIGH);

It makes no sense to call this here, as the timer has not been
initialized. You probably cannot expect anything but a timeout in this
context.
noInterrupts();
cli();

These two are synonyms. No need to repeat yourself. Actually, no need to
block interrupts at all.
sei();
interrupts();

Ditto.
OCR1A = 19999; // = 16000000 / (8 * 100) - 1

This is supposed to fire interrupts at 100 Hz. But if you want a
100 Hz output signal, you should fire the interrupts at 200 Hz
(two interrupts per cycle). Thus:
OCR1A = 9999; // = (16 MHz / 8) / (2 * 100 Hz) - 1

Then,
// Set CS12, CS11 and CS10 bits for 8 prescaler
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);

This is configuring Timer 1 for an external clock source. If you
want ÷8 prescaler, you should only set bit CS11. Check the datasheet.
uint16_t val = OCR1A/8;
ICR1 = val -1;
OCR1A = val/2 - 1 ; // 50% duty cycle for pin 3

This doesn't make any sense to me. Why are you setting ICR1? Why are
you changing OCR1A although it was already configured in setup()?
You can remove all this. Here is the loop() I used for testing:
void loop() {
    Serial.println(pulseIn(3, HIGH));
    delay(1000);
}

And it repeatedly printed 4955, which is quite close to the expected
value (namely 5000).


Serialize JSON as response to HTTP request

serializeJson() accepts a Print&, i.e, a reference to a class that implements the Print interface.

WiFiClient does implement the Print interface, but serializeJson() cannot make a reference to it because ESP8266WebServer::client() returns a temporary. Indeed, C++ forbids references to temporary variables, only const reference to temporaries are allowed.

To fix this compilation error, you must extract a variable:

WiFiClient client = server.client();
serializeJson(doc, client);

The way I see it, ESP8266WebServer::client() should return a WiFiClient& instead of a WiFiClient, just as HTTPClient::getStream() does. I opened issue #7075 about that.

Anyway, even it this fixes the compilation, I'm not sure it will work as you intend because ESP8266WebServer may not allow writing directly to the WiFiClient.


Interrupts inside a class attaching to the function of the class

I have a post about this problem.

Basically you cannot attach a class function with attachInterrupt because of the hidden "this" pointer which needs to be supplied to a (non-static) class function, where "this" is the particular instance of the class. You can work around it like this:

class myClass
  {
  static volatile bool switchChanged;  // declare

  public:

  void begin ()
    {
    pinMode (2, INPUT_PULLUP);
    attachInterrupt (0, switchPressed, CHANGE);
    }  // end of myClass::begin

  static void switchPressed ()
    {
    switchChanged = true;
    }  // end of myClass::switchPressed

  };  // end of class myClass

volatile bool myClass::switchChanged;  // define

myClass foo;  // make an instance of myClass

void setup ()
  {
  foo.begin ();
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

But that isn't great because, as you observed, you are really downgrading the class to use a static boolean.

Another way of doing it is to write "glue" routines, like this:

class myClass
  {
  volatile bool switchChanged;

  static myClass * instances [2];

  static void switchPressedExt0 ()
    {
    if (myClass::instances [0] != NULL)
      myClass::instances [0]->switchPressed ();
    }  // end of myClass::switchPressedExt0

  static void switchPressedExt1 ()
    {
    if (myClass::instances [1] != NULL)
      myClass::instances [1]->switchPressed ();
    }  // end of myClass::switchPressedExt1

  public:

  void begin (const byte whichPin)
    {
    pinMode (whichPin, INPUT_PULLUP);
    switch (whichPin)
      {
      case 2:
        attachInterrupt (0, switchPressedExt0, CHANGE);
        instances [0] = this;
        break;

      case 3:
        attachInterrupt (1, switchPressedExt1, CHANGE);
        instances [1] = this;
        break;

      } // end of switch
    }  // end of myClass::begin

  void switchPressed ()
    {
    switchChanged = true;
    }

  };  // end of class myClass

myClass * myClass::instances [2] = { NULL, NULL };

// instances of our class
myClass foo;
myClass bar;

void setup ()
  {
  foo.begin (2);   // pin D2
  bar.begin (3);   // pin D3
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

That's still not a great solution, but it might give you some ideas.

Your fundamental problem is that classes, by their nature, can be instantiated many times, however you only have a small, fixed, number of interrupts on the microprocessor.


Can I measure the current (mA) of my project with just a multi meter?

No, you won't get the right result measuring resistance. Integrated circuits contain lots of semiconductors which are inherently non-linear.

You need to somehow put your multimeter in series with the power supply, set to the mA range. The easiest way I can think of is to use an external battery (7v or higher) and make up a custom cable with standard barrel jacks. As your board appears to have a linear voltage regulator, the current measured will be very close to the current consumed when powered from the USB port.


The product you linked looks like a fairly standard LCD module, so it's probably very difficult to swap the backlight LED. Like most electronics, they're not designed to be modified by hand. It would likely need some precision re-soldering.

When you see LCDs with other types/colours of backlight, it's usually because they were originally manufactured that way.


Fatal Exception Error on ESP8266 + Arduino

Looking at your serial monitor window it shows "Geuino Uno". I think you forgot to change the target of the compiler to "Generic ESP8266" like shown in the how-to and you probably uploaded bad code to your module.


How to replace the delay() function in my code?

The first set of delaymicroseconds for measuring is fine.

you'll want to replace the delay(5000) when switching the leds.

  if(distance1>20 || distance2>20){
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
  }
  else if(distance1<20){
    digitalWrite(led1,HIGH);
    delay(5000);
  }

  else if(distance2<20){
    digitalWrite(led2,HIGH);
    delay(5000);
  }

you can do that by using a timestamp of when the distance was last high:

  if(distance1<20){
    digitalWrite(led1,HIGH);
    timestamp1 = millis();
  }

  if(distance2<20){
    digitalWrite(led2,HIGH);
    timestamp2 = millis();
  }

if(millis() - timestamp1 > 5000){
  digitalWrite(led1,LOW);
}

if(millis() - timestamp2 > 5000){
  digitalWrite(led2,LOW);
}

timestamp1 and timestamp2 should be globals (or static locals). This code will delay turning off the led to 5 seconds after the sensor last detected something close.


SIM808 module GSM working fine, GPS not working (No GPS ready message on power on)

You have a version2 module. Use AT+CGNSxxx instead of AT+CGPSxxx


This is an electronics question, and it should be forwarded to the electronics stackexchange.

The fan needs to have a proper amount of current to spin, and because the microcontroller that controls the fan draw very little current on its output pins (check the datasheet for the exact value, but it should be a few milliamps), unless you have a miniature fan, wiring it directly on the microcontroller will not be able to move the fan.

And this is by design that microcontrollers cannot provide much current. Because to provide larger amount of current than what they do, they'd need to have bigger copper tracks between the transistor to avoid having they internal circuits building too much heat, and they would be much much bigger.

So as a work around, we use an transistor, which receives on the "Base" pin a voltage, drawing almost no current, which will "connect" the collector and emitter pins where you can have a much bigger current flowing (though be careful to respect the datasheet's nominal values for current! Or use either a MOSFET, a Triac or a Relay for bigger currents).


This part also goes by the name BH1750.  And that is available in the Fritzing  parts library.


Cannot find COM port for Arduino after replacing Atmega328p

Generally the IDE will detect one it can use, so you shouldn't need to use the Device Manager.

When you select the board type, so far, so good.

Then when you ask it to pick the port, it will present a list of ports that it has discovered that are registered in the Device Manager.

One thing you will notice is that if you have a Genuine Uno, for instance, it will list that next to the port name.

But if you are using a board (of any type) that have the CH340-type port it will show just the COM9 or whatever it finds.

If it doesn't find any ports (My laptop always detects the COM1 port on the back that I never use so in my case if that is all it finds then it is not finding any USB ports)  then jump ahead to the arrow below.

So by trying each one you will find a port that works with your board.  Or not.

I am sure you have already seen the errors it throws when you use a port that won't work for you.

----->  If you have tried all the ports listed and none works, then you are left with only a couple of possibilities:  Either the cable is bad, or the board is not responding.

Ultimately, it doesn't matter what it says in Device Manager if the IDE won't use it.

So if you can find another board and see if the cable works that would eliminate the cable as being a problem.

But if it simply will not respond then look above in the comments at what @Majenko said.

Good luck.


DT-06 WIFI. How to program with Arduino Uno

Are you wiring it to Arduino pins 0 & 1? These are hard-wired to the other processor on the Arduino board that handles USB to/from your PC. There may be interference with the DT-06 unless you disconnect from your PC after upload. But then you'll need an alternate source of power to the Arduino.

You can pick another pair of pins and use the SoftwareSerial library (up to 9600 baud) to talk to the DT-06. Make sure Arduino and the DT-06 use the same baud-rate. You may have to experiment to find what baud-rate the device has now, in order to set it to 9600.

Update:

  Do i have to use any resistence?

Two sites I looked at described the DT-06 voltage requirement as:
"Working voltage: 4.5V~6.0V, TTL working voltage: 3.3V (compatible with 5.0V);", so you should be OK without voltage divider resistors.

  And what settings to make in arduino IDE before uploading code?

You won't need to change your IDE to upload code to the Uno.


Is it possible to connect a camera to an arduino?

Yes. Check out ArduCam. Do a google search. http://www.arducam.com


As mentioned in the comments, a Raspberry Pi would be superior here.

The standard AVR (not Due/Galileo/Yun) Arduino is superior to the Pi in only one area: IO. It has a 5V logic that's more compatible than the Pi's 3.3V (although you can use a logic level shifter). The Arduino also features more PWM pins and an ADC, along with interrupts. An Arduino also is a lot simpler to use for basic projects, but it becomes impractical when you need more computing power.

A Pi excels at the data-crunching side of things. It can handle a lot more data than the Arduino could ever dream of, and then some! Just to put things in perspective, the Pi has a clock speed of 700 MHz by default and the Arduino Uno has one of 16 MHz (with a less powerful architecture).

For your purpose, the Pi's audio jack and ethernet port are unmatched on the Arduino. Sure, you can get shields that replicate these behaviors, but the Pi's built in functionality doesn't cost extra and it's more powerful.


Multiple definition error when linking firmware.elf

Rule #1:
Header file extension is ".h". Files with ".cpp" are ususally compiled as separate compilation units into the object file. If you have any function definition (= declaration + implementation) or any global variable in more object files, it'll fail to link.
Rule #2:
No definitions in headers - variables and functions will cause this error if you include .h file into more .cpp files. If you need super global variable, you have to use declaration with extern modifier and you have to define it in one of the .cpp files. But only one! Also there can be only function prototypes (declarations) in header file. Implementation have to be only once in one of the ".cpp" files.

It's usually in the first chapter of books about learning C/C++.

Really short example:

// myLib.h
#ifndef _myLib_h_guard_
#define _myLib_h_guard_

void myFunction(); // function prototype (declaration)

extern int mySuperGlobalVariable;  // variable declared as extern, there must be definition somewhere

class MyClass {
public:
  int someMethod(); // method declaration

  int anotherMethod() { return 1; }  // definition inside of class works, but sometimes is less readable
};

#endif

// myLib.cpp
#include "myLib.h"

void myFunction() { // function implementation (definition)
  // do something...
}

int mySuperGlobalVariable; // definition

int MyClass::someMethod() { return 2; } // method definition

// main.cpp
#include <myLib.h>

int main() {

  mySuperGlobalVariable = 10;

  myFunction();

  MyClass instance;
  int first = instance.someMethod();
  int second = instance.anotherMethod();
}


Is analogWrite() not affected by blocking codes and/or Interrupts?

is the analogWrite() function
  continue generating near-consistent PWM when it encounters blocking
  codes or signal interrupts?

Yes for 'hardware' PWM used by analogWrite on AVR and SAMD Arduinos. The hardware PWM is handled by wave output of Timers, which are MCU peripherals running independently from CPU and other MCU peripherals.

  Is it the same case for both the classic arduinos(atmega chips) and
  the new arduinos(SAMD21 chips).

yes

  If analogWrite() does get affected by blocking codes, is there a way
  to create a uninterruptible PWM signal?

N/A


So, the first consideration goes to the radio propagation aspect. Every country does things a little different with their radio clocks. And you might only have good signal a few times a day. For a nice overview, check out a solution for the German DCF77. If you're totally set on using a radio clock, time-nuts has discussed in the past ripping open a $10ish clock to get at the fun parts of a WWVB receiver, so that's one overview of the pool you're diving into.

For myself I've skipped past the terrestrial time keeping and went straight to GPS. Find a receiver that provides a pulse-per-second and attach that to an interrupt and process it alongside the timestamp; you can see how I've gone about that in both code and final product.

I think GPS is both easier and more precise than the alternatives, assuming you're above ground and can pick up satellites. I think of RTCs as something to tell me the day and the year, while GPS can tell me the second. But you could consider ripping the antenna out of a cheap bedside radio-controlled clock and using that to set an RTC, careful to consider whether you want a cheap RTC (DS1307) that drifts a minute per day or a slightly more expensive RTC (DS3231 or ISL1220) that drifts a minute per month. (Rough numbers of course.)


What you need to do is learn what a finite state machine (FSM) is.

An FSM is a way of having the Arduino in one of a finite number of states, such as "light flashing", or "letting water in", etc.

I have written a reasonable (IMHO) tutorial here: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/


(ultrasonic sensor code : No such file or directory)

It means what it says:

  Ultrasonic.h: No such file or directory

The file Ultrasonic.h can't be found.

Anything in your code that starts #include... is usually a library. These are third party pieces of software that you have to obtain and install into the relevant location (See Installing Additional Arduino Libraries).

Some libraries are bundled with the IDE, and some are available through the "library manager" in the IDE. However most aren't, and you will have to get used to finding those libraries and installing them.

The location you got your example code from will most likely link you to where to find the relevant libraries to get the code working.


Voltage divider producing unexpected voltage

Since you are connecting your pixel strip in parallel with R2, the
correct formula is

Vout = Vin × (R2∥Rp) / (R1 + (R2∥Rp))

Where Rp is the resistance of the pixel strip and

R2∥Rp = R2 × Rp / (R2 + Rp)

is the combination of R2 and Rp in parallel. From this you can see that
an output voltage of 1.6 V is consistent with a strip resistance of
300 Ω.

This is, however, somewhat oversimplified, as the I(V) characteristic of
the LED strip is probably non-linear, thus not really equivalent to a
resistor.


Try using the example code from the MD_DS1307 library to find the settings on your RTC, when I first wired mine up the clock was not running and I couldn't set the time on it. After I enabled it, it worked just fine.


You said you are using a Xbee shield.  What shield is it, and what pins does it use for Serial communications?

If you were using software to emulate the second serial port on other arduinos, you were probably using different pins, and so if the shield is designed to communicate over (as an example) pins 2 and 3 then it will most likely not work with pin 0 and 1 without moving jumpers or switches.  For example, this
Xbee Shield: http://core-electronics.com.au/xbee-shield.html/?acc=9f61408e3afb633e50cdf1b20de6f466 has a switch to switch between pins 0 and 1 and pins 2 and 3.

You could also try some code that reads from Serial and prints the data to Serial1 and visa versa.  This means you can experiment to get a greater understanding of the problem.


Need Help in circuit diagram of 8*8 reed switch matrix

This answer is based on a previous version of the question

Not necessarily. You can use the internal pullups of the arduino if you're willing to accept that reading a "1" means that no piece is there and reading a "0" means a piece is there.
Connect each wire up to a pin on the arduino. If you do it wisely, step 3 becomes fairly easy.
You need to configure the pins connected to the letter wires as inputs with their pullups enabled. Set the number pins to inputs as well, but without the pullup enabled so that they are floating. The number pins will be each set as an output in sequence with the value being low (non-active number pins are set back to inputs). As you do so, you can read the pins on the letter wires and build a picture of the board.

Example

This is how I would do it just taking a naive stab at it. I'm sure there are more effective ways to do this.

Wiring:

Configure the outputs and inputs in setup:

pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
pinMode(4, INPUT_PULLUP);
pinMode(5, INPUT_PULLUP);
pinMode(6, INPUT_PULLUP);
pinMode(7, INPUT_PULLUP);
pinMode(8, INPUT_PULLUP);
pinMode(9, INPUT_PULLUP);
pinMode(10, INPUT);
pinMode(11, INPUT);
pinMode(12, INPUT);
pinMode(13, INPUT);
pinMode(14, INPUT); //A0
pinMode(15, INPUT); //A1
pinMode(16, INPUT); //A2
pinMode(17, INPUT); //A3
pinMode(18, INPUT); //A4

Make a function to scan the rows into an array of bytes:

void scan_rows(uint8_t *rows)
{
    uint8_t i, j;

    for (i = 0; i < 8; i++)
    {
        if (i)
        {
            pinMode(i+9, INPUT);
        }
        pinMode(i+10, OUTPUT);
        digitalWrite(i+10, LOW);
        for (j = 2; j <= 9; j++)
        {
            rows[i] <<= 1;
            if (digitalRead(j))
                rows[i] |= 1;
        }
    }
    pinMode(18, INPUT);
}

Now, just call that function with a pointer to an array with 8 bytes in it whenever you need to scan the board. Each byte in the array represents one of the rows and each bit represents a column.

[moderator note: This answer appears in this thread as a result of a merge]


Debugging library - Error- expected unqualified id before '.' token

class _Sluz;
class _SDHT;

You're forward declared two classes but I see nothing about what those classes are. You then to and use those class declarations as if they were class instances.

I think you are lacking a bit of basic syntax knowledge there. You may have meant:

Sluz _Sluz;
SDHT _SDHT;

Though not knowing what those classes are meant to be or how they are even defined I cannot know really what you think you're meaning.


How to make auto keyboard using arduino nano V3.0 ATmega 328P ?

I found this link : http://www.practicalarduino.com/projects/virtual-usb-keyboard  Is that what you've been looking for?


Problems recycling c++ lib with templated class for Arduino

SOLVED:

Putting the .cpp contents in the .h and removing the .cpp from the lib folder entirely worked.


What’s the most common (and low cost) microprocessor with at least two threads?

ESP32.  Dual core 240MHz, plus an extra XLP state machine.  Cheap and easily available on eBay/Amazon/Ali Express etc.  And with full Arduino support.


How to fix this code so instead of having to hold button to change led, you can press?

instead of changing every time the buttonState == HIGH, change it when the button state was LOW the previous time but HIGH now:

buttonState = digitalRead(buttonPin);
if (oldButtonState != buttonState && buttonState == HIGH) {
    //...
}
oldButtonState = buttonState;

However keep in mind contact bounce. Which can result in multiple transitions being detected. Most solutions for that set a minimal delay between handling transitions, dropping all others detected.


There are some SIMCOM modules with GPRS + GPS, for example: SIM968

In addition to GPS, it also supports GLONASS/Galileo/QZSS.

As for the MCU, you will need something more powerful than ATMega328, because 2KB RAM is not enough for multi-threading + GPS code + GSM/GPRS code + CAN + etc. Also it hasn't CAN peripheral. You will need MCU with ARM core. From Arduino line, Arduino Due looks suitable: has 96KB RAM, multiple HW serials, CAN. There is also compatible CAN library here. Also worth looking on STM32F103 (or STM32F407 with Cortex M4) which also can used be with Arduino IDE with some extra effort (STM32 MCUs usually more cost effective than Atmel counterparts, and have higher performance).


Run Arduino on USB and at the same time BreadBoard on higher voltage?

I think as far as i understood the problem, the system or whatever you call is will run on what ever power as long that power is not fed to the arduino that will not be a problem, just connect the two grounds together and power the arduino through the computer and connect the pins to the system accordingly. i think this will solve thus the trivial problem.


How do I add Gyroscope, Accelerometer, Euler, and Temperature data to one Arduino board?

Does the code below work? I have no compiler at hand, so I can not test it.
If you have to explain what you have done, you'll get into trouble. I don't know your teacher, but ... ;-). Seriously, that was very basic stuff. Try to find some documentation, how to program with the Arduino IDE and learn the basics. A good startpoint is https://www.arduino.cc/en/Tutorial/HomePage .
Then go on with SENSORs and Vector Maths.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>

Adafruit_BNO055 bno = Adafruit_BNO055(55);

void setup(void)
{
  Serial.begin(9600);
  Serial.println("Orientation Sensor Test"); Serial.println("");

  /* Initialise the sensor */
  if (!bno.begin())
  {
    /* There was a problem detecting the BNO055 ... check your connections */
    Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
    while (1);
  }

  delay(1000);

  bno.setExtCrystalUse(true);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  /* Display the current temperature */
  int8_t temp = bno.getTemp();

  Serial.print("Current Temperature: ");
  Serial.print(temp);
  Serial.println(" Celsius");
  Serial.print("");

  imu::Vector<3> gyroscope = bno.getVector(Adafruit_BNO055::VECTOR_GYROSCOPE);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(gyroscope.x());
  Serial.print(" Y: ");
  Serial.print(gyroscope.y());
  Serial.print(" Z: ");
  Serial.print(gyroscope.z());
  Serial.println("");
  delay(100);

  imu::Vector<3> accelerometer = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(accelerometer.x());
  Serial.print(" Y: ");
  Serial.print(accelerometer.y());
  Serial.print(" Z: ");
  Serial.print(accelerometer.z());
  Serial.println("");
  delay(100);

  imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(euler.x());
  Serial.print(" Y: ");
  Serial.print(euler.y());
  Serial.print(" Z: ");
  Serial.print(euler.z());
  Serial.println("");
  delay(100);
}


Can I use Visual Studio instead of Arduino IDE?

I only use Visual Studio for Arduino programming.
Arduino Plugin for Visual Studio


What are the components of a Xively HTTP PUT request to send to my SIM800 GPRS module?

I've got a working solution to this issue. Here's the values you can edit and the function:

String FEED = "YOUR_FEED";
String KEY = "YOUR_API_KEY";
String DATASTREAM1 = "YOUR_DATASTREAM1_NAME";
Int VALUE1 = YOUR_VALUE1;
String DATASTREAM2 = "YOUR_DATASTREAM2_NAME";
Int VALUE2 = YOUR_VALUE2;

void send2Cosm()
{
mySerial.println("AT+CGATT?");
delay(100);
ShowSerialData();
mySerial.println("AT+CSTT=\"CMNET\"");//start task and setting the APN,
delay(1000);
ShowSerialData();
mySerial.println("AT+CIICR");//bring up wireless connection
delay(300);
ShowSerialData();
mySerial.println("AT+CIFSR");//get local IP adress
delay(2000);
ShowSerialData();
mySerial.println("AT+CIPSPRT=0");
delay(3000);
ShowSerialData();
mySerial.println("AT+CIPSTART=\"tcp\",\"api.cosm.com\",\"8081\"");//start up the connection
delay(2000);
ShowSerialData();
mySerial.println("AT+CIPSEND");//begin send data to remote server
delay(4000);
ShowSerialData();

mySerial.print("{\"method\": \"put\",\"resource\": \"/feeds/" + FEED + "/\",\"params\"");
delay(500);
ShowSerialData();
mySerial.print(": {},\"headers\": {\"X-ApiKey\":");
delay(500);
ShowSerialData();
mySerial.print("\"" + KEY + "\"},\"body\":");
delay(500);
ShowSerialData();
mySerial.print(" {\"version\": \"1.0.0\",\"datastreams\":");
delay(500);
ShowSerialData();
mySerial.print("[{\"id\": \"" + DATASTREAM1 + "\",\"current_value\": \"");
mySerial.print(VALUE1);
delay(500);
ShowSerialData();
mySerial.print("\"},{\"id\": \"" + DATASTREAM2 + "\",\"current_value\": \"");
mySerial.print(VALUE2);
delay(500);
ShowSerialData();
mySerial.println("\"}]}}");
delay(500);
ShowSerialData();

mySerial.println((char)26); //sending = ctrl+z
delay(5000);//waitting for reply, important! the time is base on the condition of internet
mySerial.println();

ShowSerialData();

mySerial.println("AT+CIPCLOSE");//close the connection
delay(100);
ShowSerialData();

}

void ShowSerialData()
{
while(mySerial.available()!=0)
Serial.write(mySerial.read());
}

To answer part of my question: no, the colons aren't a String operator, they're part of the HTML. Here's an example of the formed URL that gets sent:

{"method": "put","resource": "/feeds/YOUR_FEED/","params": {},"headers": {"X-ApiKey":"YOUR_API"},"body": {"version": "1.0.0","datastreams":[{"id": "DATASTREAM1","current_value": "VALUE1"},{"id": "DATASTREAM2","current_value": "VALUE2"}]}}

This code updates my feed but after several hours the updates stop. I'm still troubleshooting this new problem so I'm not 100% sure that this code is good. I will post back if the problem's in here.