Here is a library that might be able to help you out: https://github.com/cyborg5/IRLib/. Also a specific example of controlling a server from a sony remote control. https://github.com/cyborg5/IRLib/blob/master/examples/IRservo/IRservo.ino

I am slightly confused on what you mean 'get input'. So I am assuming an input from a button. Here is some pseudo code compiled from the IRservo example that might point you in the right direction.

#include <IRLib.h>

#define MY_PROTOCOL SONY
#define BUTTON_0 0x90bca  //LED ON
#define BUTTON_1 0x00bca  //LED OFF

#define LED_PIN 13 //Pin to LED

IRrecv My_Receiver(11);//Receive on pin 11
IRdecode My_Decoder;

void setup() { //Code to run once
  My_Receiver.No_Output();//Turn off any unused IR LED output circuit
  My_Receiver.enableIRIn(); // Start the receiver

  pinMode(LED_PIN, OUTPUT); //Set LED 13 to out
  digitalWrite(LED_PIN, LOW); //Start off in the off position
}

void loop() { //Code that runs forever
    if (My_Receiver.GetResults(&My_Decoder)) {
       My_Decoder.decode(); //Convert the values into types
       if(My_Decoder.decode_type==MY_PROTOCOL) { // Match the controller
          switch(My_Decoder.value) {
            case BUTTON_0:      digitalWrite(LED_PIN, HIGH); break; //Turn the LED on
            case BUTTON_1:      digitalWrite(LED_PIN, LOW); break; //Turn the LED off
          }
       }
     My_Receiver.resume(); //Wait for next input
    }
}

This should theoretically work, but has never been tested. Now if you are just wanting any result to turn on the LED you might be able to do this

void loop() { //Code that runs forever
    if (My_Receiver.GetResults(&My_Decoder)) {
        My_Decoder.decode();
        digitalWrite(LED_PIN, HIGH); //Turn the LED on
    }
    My_Receiver.resume(); //Wait for next input
}

Edit:

A sample from getting text (Different library) from the receiver and printing it to the Serial Monitor. Link to library: https://github.com/z3t0/Arduino-IRremote

    #include <IRremote.h> //Link: https://github.com/z3t0/Arduino-IRremote

#define IR_PIN = 11; //The data pin to the IR recv
#define LED_DATA = 13; //Either the builtin LED or plug one in

IRrecv irrecv(IR_PIN); //Start recv obj
decode_results results;

void setup()
{
  Serial.begin(9600); //Start Serial at 9600 baud
  pinMode(LED_DATA, OUTPUT); //Set LED pin to out
  digitalWrite(LED_DATA, LOW); //Start recv data view pin in low
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    //We have recieved something... lets print it and turn on the LED
    digitalWrite(LED_DATA, HIGH);
    Serial.println(results.value, HEX); //Send line in ascii hex format
    delay(200); //Make the LED visible
    digitalWrite(LED_DATA, LOW); //Turn off data led
    irrecv.resume(); // Receive the next value
  }
}

Edit #2

Since an image has been provided I believe this is what you want. To turn the ir data into a visible light... To do that is a little more tricky in just doing code. Here's an example that doesn't require any external libraries and will do what you want.

    #include <avr/interrupt.h>
#include <avr/io.h>

#define TIMER_RESET  TCNT1 = 0
#define SAMPLE_SIZE  64
#defome LED_PIN 13

int IRpin = 2;
unsigned int TimerValue[SAMPLE_SIZE];
char direction[SAMPLE_SIZE];
byte change_count;
long time;

void setup() {
  Serial.begin(115200);
  Serial.println("Analyze IR Remote");
  TCCR1A = 0x00;          // COM1A1=0, COM1A0=0 => Disconnect Pin OC1 from Timer/Counter 1 -- PWM11=0,PWM10=0 => PWM Operation disabled
  // ICNC1=0 => Capture Noise Canceler disabled -- ICES1=0 => Input Capture Edge Select (not used) -- CTC1=0 => Clear Timer/Counter 1 on Compare/Match
  // CS12=0 CS11=1 CS10=1 => Set prescaler to clock/64
  TCCR1B = 0x03;          // 16MHz clock with prescaler means TCNT1 increments every 4uS
  // ICIE1=0 => Timer/Counter 1, Input Capture Interrupt Enable -- OCIE1A=0 => Output Compare A Match Interrupt Enable -- OCIE1B=0 => Output Compare B Match Interrupt Enable
  // TOIE1=0 => Timer 1 Overflow Interrupt Enable
  TIMSK1 = 0x00;
  pinMode(IRpin, INPUT);
  pinMode(LED_PIN, OUTPUT);
}

void loop()
{
  Serial.println("Waiting...");
  change_count = 0;
  while(digitalRead(IRpin) == HIGH) {}
  TIMER_RESET;
  TimerValue[change_count] = TCNT1;
  direction[change_count++] = '0';
  while (change_count < SAMPLE_SIZE) {
    if (direction[change_count-1] == '0') {
      while(digitalRead(IRpin) == LOW) {}
      TimerValue[change_count] = TCNT1;
      direction[change_count++] = '1';
      digitalWrite(LED_PIN, LOW);
    } else {
      while(digitalRead(IRpin) == HIGH) {}
      TimerValue[change_count] = TCNT1;
      direction[change_count++] = '0';
      digitalWrite(LED_PIN, HIGH);
    }
  }
  Serial.println("Bit stream detected!");
  change_count = 0;
  time = (long) TimerValue[change_count] * 4;
  digitalWrite(LED_PIN, LOW)
  Serial.print(time);
  Serial.print("\t");
  Serial.println(direction[change_count++]);
  while (change_count < SAMPLE_SIZE) {
    time = (long) TimerValue[change_count] * 4;
    Serial.print(time);
    Serial.print("\t");
    Serial.println(direction[change_count-1]);
    Serial.print(time);
    Serial.print("\t");
    Serial.println(direction[change_count++]);
  }
  Serial.println("Bit stream end!");
  delay(2000);
}

If you want a non code example check out the answer below. It is a great solution. Without needing any arduino.

best regards, David


Are INTx pins the only ones eligible for Software Serial?

SoftwareSerial uses PCINT.  AltSoftSerial uses INT0 or INT1, which has FALLING, RISING, CHANGE or LOW LEVEL options.  See Section 12.2, p. 71 of the Atmel ATmega328 spec, for example.


In your for() loop, use Serial.println() to display both strings before the compare. You'll be able to see why the compare is failing.

Update:

  it seemed identical.

Something has to be different for the test to fail. If the strings look identical then there must be some non-printing characters that differ: \r, \n, , , missing \0 ), etc.

Try printing your buffers byte-by-byte in hex for a few more bytes than the string length, to be sure there is an  where it should be.

Or print the buffers with this hexdump function which lists a specified memory range in both ASCII and hex:

/***

Name:       hexdump

Function:   Dump memory contents to terminal

Description:Dump a specified range of memory in hex and ASCII

Parameters: byte *mem       - starting address
            uint16_t len    - # of bytes

Returns:    void

Notes:      Based on: http://grapsus.net/blog/post/Hexadecimal-dump-in-C
            Formats with sprintf(); outputs with Serial.print().
            Modified to print ...0 - ...F of each hex-block containing
            any of the requested memory range. Data not in the range are
            not shown.

***/

void hexdump(byte *mem, uint16_t len)
{
   byte *p, *pfirst, *plast;    // -> curr byte, first & last hex-blocks to print from
   char buf[10+1];              // sprintf o/p buffer

   // Print entire hex-blocks that contain the requested mem range,
   // except only show data within the range.
   pfirst = (byte *)((uint16_t)mem & 0xFFF0);           // beg of 1st  hex-block
   plast = (byte *)((uint16_t)(mem + len) | 0xF);       // end of last hex-block

   for( p = pfirst;  p <= plast;  ++p ){

      /* Print block addr */
      if( ((byte *)((uint16_t)p & 0xF)) == 0 ){
         sprintf_P(buf, PSTR("%06X: "), (unsigned int)p);
         Serial.print(buf);
      }

      // Print hex data, or if outside mem range, print spaces
      if( mem <= p && p < (mem + len) ){
         sprintf_P(buf, PSTR("%02hhX "), *p);
         Serial.print(buf);
      }
      else
         Serial.print("   ");                   // outside requested range - just spaces

      // Maybe print gutters and/or ASCII data
      if( ((uint16_t)p & 0xF) == 0x7 )
         Serial.print(" ");                     // narrow gutter after 8 bytes
      // If at end of hex block, print a gutter & re-print the block as ASCII
      if( ((uint16_t)p & 0xF) == 0xF ){
         Serial.print("  ");                    // wide gutter after 16 bytes

         // Print as ASCII.
         // Note: In this loop, we re-use the outer loop's index, 'p', to rescan
         // the hex block. We must leave 'p' as we found it!
         for( p = (byte *)((uint16_t)p & 0xFFF0);  ; ++p ){
            if( !(mem <= p && p < mem+len) )
               Serial.print(' ');               // not in requested mem range
            else if( !isprint(*p) )
               Serial.print('.');               // not printable
            else
               Serial.print(*(char *)p);        // print as ASCII

            if( ((uint16_t)p & 0xF) == 0xF ){
               break;                           // end of hex-block
            }
         }
         Serial.print('\n');
      }
   }
}


The lab power supply you linked is serious overkill for your needs. It shouldn't need a separate voltage regulator or buck converter, since I assume that it provdes a voltage and current regulated supply.
A regulated, fixed voltage 4V power supply that can provide 2A is what you want. That will probably cost < 1/10 of the amount of the lab supply you linked. The challenge is to find a 4V supply. (Most regulated power supplies are either 3.3V or 5V, since those are common voltages for solid state electronics.)
That said, the linear voltage regulators are usually adjustable with a decent voltage range using a resistor.
You could always build your own voltage regulator using a linear voltage regulator rated for 2A, plus a resistor and a couple of capacitors. You could either feed it from an unregulated 6V power supply or use a transformer, bridge rectifier, and capacitor to provide an unregulated DC input to a voltage regulator.
Edit:
With a little googling I found a few 4V 2A power supplies online. This one, for example:
https://www.alibaba.com/product-detail/US-AC110-220V-To-DC-4V_62155516966.html?spm=a2700.7724857.normalList.14.a5e64009aUU1ln&s=p
(That link is to a wholesale manufacturer that sells them in volume, but you may be able to find the same supply for single unit sale. A 2A switching 4V supply would meet your needs as well)


Arduino Nano ATmega328P bootloader difference

The bootloader currently shipped on the official Arduino Nano boards and selected via the Arduino IDE's Tools > Processor > ATmega328P after choosing Tools > Board > Arduino Nano is the same version of optiboot used by the Arduino/Genuino Uno:
https://github.com/arduino/ArduinoCore-avr/blob/master/boards.txt#L152

nano.menu.cpu.atmega328.bootloader.file=optiboot/optiboot_atmega328.hex

https://github.com/arduino/ArduinoCore-avr/blob/master/boards.txt#L72

uno.bootloader.file=optiboot/optiboot_atmega328.hex

The bootloader selected via Tools > Processor > ATmega328P (Old Bootloader) is the "ATmegaBOOT" bootloader.

As used by the Nano hardware definition, there are two significant differences between the two bootloaders:

Optiboot will not go into an endless reset loop after a watchdog reset. ATmegaBOOT will.
Optiboot expects the upload communication at 115200 baud. ATmegaBOOT, 57600. This is the reason why the old boards don't work with the Tools > Processor > ATmega328P selection and vice versa.

There is another very significant difference between the two bootloaders that, sadly, you will not benefit from with the new Arduino Nano board/hardware definition: Optiboot will fit in a 0.5 kB boot section, while ATmegaBOOT requires a 2 kB boot section. Unfortunately Arduino forgot to change the BOOTSZ fuse accordingly and so the opportunity to free up 1.5 kB of precious flash memory for the users of the Nano was lost. The willingness of Arduino to knowingly release flawed hardware has historic precedent.

  I haven't been able to find any release notes about the bootloader.

Arduino's release notes have not yet adapted to the fact that hardware packages may be released independently of IDE releases ever since Arduino IDE 1.6.2. There is a note about the bootloader change in the IDE release notes for the next IDE release:

https://github.com/arduino/Arduino/commit/ec179e5af67b7f1eeb5e46d22034798f8b24b7cb

Other than that, you can consult the commit history:

https://github.com/arduino/ArduinoCore-avr/commit/1b14cc07331268e95eddcce2cc67e29ed667e62f


This is done by carefully placing a layer of wood veneer over the 7-segment displays. The veneer is thin enough to let the light pass through. I wouldn't be surprised if some manufacturers use brighter than normal LEDs to make the display easier to see. Here is a video detailing an example.

It is also possible to simply drill out the wood to make it very thin where the 7-segment displays go. Here is an example of drilling the solid wood to be very thin.


If you want to declare multiple variables with the same name inside different case statements, you can enclose the code inside each of them inside curly braces:

case 1:{
    Code...
break;}
case 2:
...

The curly braces will set the limits for the variables scope to just this case.


Data Logging without Interfacing SD Card module

The simplest answer is to install a program that handles serial connection and can write everything into a logfile. On Linux, CuteCom is a program like that. On Windows, putty can handle serial (as well as SSH and telnet), and has logging.

The more advanced soulution is to write a program (or a simple script) that can do that. You could make it to do some other stuff as well (like configuring the Arduino side), and you can run it in the background without user interaction.


Serial Monitor appears unreadable characters

It can have many reasons, but the most likely are:

You set the baudrate wrong
You set the stop/start bits wrong
You send wrong data
The cable is bad

It helps if you show your sketch(es), for sender/receiver and possibly your circuit.


How to produce 6 PWM signals with 60 degrees phase shift?

Using hardware it's not possible. Simply because you effectively only have three PWM timer units, each with two compare outputs.

That means you have three timebases, which are each compared with two values for two PWM signals each.

You would need a single master timebase with six independent offsettable counters with comparison for your needs.

It would be possible to (roughly) do it in software, though, depending on your needs. You get jitter from software generated PWM, due to interrupts getting in the way of your smooth execution. However you have complete control over how the waveform is generated. Instead of a 0-X duty cycle you could program it to have an X-Y duty cycle. And with all of them taken from the same counter value it's then all synchronised 100%.


Using a photo resistor to detect objects of a certain color

Use a TCS230 photo sensor and a 6500K light source to color correct your objects.

This hookup will get you started

This sketch, courtesy of Best-Microcontroller-Projects  will get you going.  Read the tutorial and dont forget to calibrate.

//
// Detect colors using TCS230.
//

// Arduino uno pins for control of TCS230
#define TCS320_OE 7
#define TCS320_S0 10
#define TCS320_S1 11
#define TCS320_S2 2
#define TCS320_S3 3
#define TCS320_OUT 4

#define variance 50  // Acceptable detection error 2%.

#define SEL_RED  \
   digitalWrite(TCS320_S2,LOW);digitalWrite(TCS320_S3,LOW)
#define SEL_GREEN \
   digitalWrite(TCS320_S2,HIGH);digitalWrite(TCS320_S3,HIGH)
#define SEL_BLUE \
   digitalWrite(TCS320_S2,LOW);digitalWrite(TCS320_S3,HIGH)
#define SEL_CLEAR \
   digitalWrite(TCS320_S2,HIGH);digitalWrite(TCS320_S3,LOW)

#define TWO_PER \
   digitalWrite(TCS320_S0,LOW);digitalWrite(TCS320_S1,HIGH);

#define debug(a) Serial.println((a));

#define NUMCOL 5

// int RGB[NUMCOL][3]; // Five colors with 3 elements.
// Array of NUMCOL strings len 10. 11 for null.
// char colname[NUMCOL][11];

// Typical values for 2% dividers (set variance to 50).
int RGB[NUMCOL][3]={
   {248,647,393},
   {188,261,265},
   {404,710,546},
   {506,493,304},
   {930,1199,837},
};

char colname[NUMCOL][11]={
"red",
"yellow",
"brown",
"blue",
"black",
};

////////////////////////////////////////////////////////////////
void setup() {

   pinMode(TCS320_OE,OUTPUT);
   pinMode(TCS320_S0,OUTPUT);
   pinMode(TCS320_S1,OUTPUT);
   pinMode(TCS320_S2,OUTPUT);
   pinMode(TCS320_S3,OUTPUT);
   pinMode(TCS320_OUT,INPUT);

   TWO_PER;

   digitalWrite(TCS320_OE,LOW); // On always.

   Serial.begin(115200);
   Serial.println("TCS230 color detector");
}

////////////////////////////////////////////////////////////////
unsigned long get_TCS230_reading(void) {
  unsigned long val;
  noInterrupts();
  val = pulseIn(TCS320_OUT,HIGH,20000); // 2000us=2ms  2Hz min.
  interrupts();
  return val;
}

static int clr,red,green,blue;

////////////////////////////////////////////////////////////////
uint16_t detect(void) {
   unsigned long val;

    SEL_RED;
    red = val = get_TCS230_reading();
    Serial.print("RED: "); Serial.print(val);

    SEL_GREEN;
    green = val = get_TCS230_reading();
    Serial.print(" GREEN: "); Serial.print(val);

    SEL_BLUE;
    blue = val = get_TCS230_reading();
    Serial.print(" BLUE: "); Serial.print(val);

    Serial.print(" \n");
}

////////////////////////////////////////////////////////////////
int withinEQ(int c, int xl, int xh) {
   if (c>=xl && c<=xh) return 1;
   return 0;
}

////////////////////////////////////////////////////////////////
// Compare a value to a value and variance.
int compare(int c, int v, int err) {
int xh=v+err, xl=v-err;
   if (withinEQ(c,xl,xh)) return 1;
   return 0;
}

////////////////////////////////////////////////////////////////
void loop() {
uint8_t chr,i,fnd;

   if (Serial.available()>0) {

      chr = Serial.read(); // Consume.

      // Find color match.
      detect();
      fnd=0;
      for (i=0;i<NUMCOL;i++) {
     if ( compare(red,RGB[i][0],variance) &&
          compare(green,RGB[i][1],variance) &&
          compare(blue,RGB[i][2],variance)
        ) { // Found
          Serial.print("Col is :");
          Serial.println(colname[i]);
          fnd=1;
          break;
        }
      }
      if (!fnd) Serial.println("NOT Found");
   }
}


Can I use the TLC5940 LED Driver if I'm already using other SPI devices on my Arduino mega?

Can I just include this in the standard daisy chaining and assign a new slave select?

SPI is normally used as a parallel bus and requires MISO to be tri-state (disconnected when not selected).

  In some forums online some people seem to indicate you can't use the TLC5940 on the same SPI bus as other devices.

The device does not have a chip select which gives a challenge. No direct wiring is possible but can be solved.

  Are there different forms of SPI? I'm quite confused, can I use the TLC5940 with other SPI devices?

It is possible to connect the TLC5940 but it requires some extra logic. You can for instance block the clock signal when it is not selected. This can be done with a MOSFET or 74HC125 and a pull-low resistor.

Cheers!


constant current or constant voltage power supply to use with RGB shield with high power LEDs

Your thinking and reasoning is pretty much spot on.

The board you have is basically a trio of high current low side switches. So yes, you need something to limit the current, and as you have noted resistors are not going to be very efficient.

The best way to drive high power LEDs is, as you know, with constant current. However, you need a constant current source per LED channel, not one single one for the whole board. That means three individual constant current sources, each providing the right current for the LEDs you are driving on that channel.

It's possible to roll your own cheap constant current sources using LM317T linear voltage regulators (http://diyaudioprojects.com/Technical/Current-Regulator/). It's a cheap option, though pretty much as in-efficient as using resistors, just easier to deal with the heat sinking.  Note that on the LM317T the tab is live, so you must use three separate heat sinks for each channel.

My personal preference though is to use PWM capable constant current sinks. My favourite is the CAT4101 which can deal with up to 1A per channel (more if you parallel them) and uses a single resistor to set the current. It has a PWM input that you can drive direct from an Arduino's PWM pin. Of course, as you note, that then makes your nice shield redundant.


How can I power an ESP8266 using a 9V 1A barrel connector power supply?

You cannot. If you look at the datasheet:

https://cdn-learn.adafruit.com/downloads/pdf/adafruit-feather-huzzah-esp8266.pdf

you can read all details on page 25/26:

  Alternative Power Options

  The two primary ways for powering a feather are a 3.7/4.2V LiPo
  battery plugged into the JST portor a USB power cable.

  If you need other ways to power the Feather, here's what we recommend:

  For permanent installations, a 5V 1A USB wall adapter (https://adafru.it/duP) will let you plug in a USB cable for reliable
  power
  For mobile use, where you don't want a LiPoly, use a USB battery pack! (https://adafru.it/e2q)
  If you have a higher voltage power supply, use a 5V buck converter (https://adafru.it/DHs) and wire it to a USB cable's 5V and GND input
  (https://adafru.it/DHu)

  Here's what you cannot do:

  Do not use alkaline or NiMH batteries and connect to the battery port - this will destroy the LiPoly charger and there's no way to
  disable the charger
  Do not use 7.4V RC batteries on the battery port - this will destroy the board

  The Feather is not designed for external power supplies - this is a
  design decision to make the board compact and low cost. It is not
  recommended, but technically possible:

  Connect an external 3.3V power supply to the 3V and GND pins. Not recommended, this may cause unexpected behavior and the EN pin will no
  longer. Also this doesn't provide power on BAT or USB and some
  Feathers/Wings use those pins for high current usages. You may end up
  damaging your Feather.
  Connect an external 5V power supply to the USB and GND pins. Not recommended, this may cause unexpected behavior when plugging in the
  USB port because you will be back-powering the USB port, which could
  confuse or damage your computer.


Playing Audio from SD - Get VU, or audio waveform

You are sampling your audio signal with only 20Hz. That is very low frequency for an audio signal, that humans can hear. Generally you need to sample your signal with double of the highest containing frequency at minimum, or you will only get nonsense (you can google Nyquist Rate for more information). Also a Nano does not have a real DAC, so the audio is generated via a PWM signal, which turn the line on and off very fast, so you only see the waveform only, if you apply a low pass filter (like a speaker will do, because it cannot move that fast).

But directly sampling the audio signal is overly complex, only for making a VU meter visualization. These visualizations are way slower, than the actual audio signal. So you need to take the mean value over a specific time interval. Best you can reach this by building a low pass filter using a resistor and a capacitor. You can sample the output of that filter, which will only have lower frequencies. The sampling frequency then should be double of the cut of frequency of the filter at minimum.

Of course it is also possible to do all this in software, but for this you would have to change the library and I guess you don't want to do this.


My rather fancy solution would be to make a 3 axis device with x and y controlled by stepper motors and z a simple solenoid to press the buttons.
For extra marks you could add a camera and try to recognise the buttons in software so any remote would work.
How do you plan to control the arduino?  Perhaps with a remote controller?


Do not use String. And especially do not use String in the way you are using it.

You can read more about why not here.

Instead stick to just using char* buffers.

The correct way of doing what you want is to define the buffer outside your function and then pass that buffer to the function to be populated:

int getAPIData(char *buf, int maxlen) {
  return inet.httpGET("myserver.com", 80, "/call.php?id=1&q=1&code=1001", buf, maxlen);
}

Then you call it with:

char *my_buffer[450];
getAPIData(my_buffer, 450);
Serial.println(my_buffer);


Dshot implementation on Arduino (ESC protocol)

In short, I ended up creating a library capable to drive multiple DShot600 ESCs:
DShot-Arduino
It still need a lot more polish, but the bit-banging works really well.

SPI method

I tried the method @dannyf mentioned, which involved combining 3 SPI bytes to form 1 dShot bit and it actually works.

But there's a few problem with SPI:

It takes up the valuable SPI port, in theory you can still connect other SPI devices, but;
maximum 1 dShot ESC can be connected
During transmission of the packet, the CPU need to wait for the whole task, assume we are sending DShot300, each packet is about 54us long so CPU is halt for that amount of time. If you are doing this in 1000Hz, that is 5% CPU time.
The timing is not very accurate to the DShot protocol standard

e.g. for DShot300, each bit is

  1.25us High - 1.25us H/L - 0.83 Low

  for a 16MHz Arduino, 1.25us will be 20 CPU cycles which is not accurate to transmit with a SPI byte

I end up with the following codes to send a bit:

inline void dshot_0(){
  SPDR = 0xFF;
  NOP;
  while (!(SPSR & _BV(SPIF))) ;
  SPDR = 0x60;
  NOP;
  while (!(SPSR & _BV(SPIF))) ;
  SPDR = 0x00;
  NOP8;
  while (!(SPSR & _BV(SPIF))) ;
}

inline void dshot_1(){
  SPDR = 0xFF;
  NOP;
  while (!(SPSR & _BV(SPIF))) ;
  SPDR = 0xFF;
  NOP;
  while (!(SPSR & _BV(SPIF))) ;
  SPDR = 0xF0;
  NOP8;
  while (!(SPSR & _BV(SPIF))) ;
}

Above code is for DShot150, the SPI was set to 4Mbps, to adhere to the correct timing, I cannot transmit a full DShot byte as all on or all off, here's how the calculation done:

  4Mbit SPI, each bit 0.25us. Thus for 16M clock arduino:

  DShot 0 sequence: 10 bits of 1, 14 bits of 0
  DShot 1 sequence: 20 bits of 1, 4 bits of 0

Those NOPn are just macro for the number of NOPs. I avoided using SPI library code here since the overhead of making library call is quite a lot.

Pure software bit-banging

This is the method resulted in my library, since using hardware SPI won't give me any advantages of releasing CPU time, and doing some Math gives me that a DShot600 require total 27 CPU cycle on 16MHz UNO. Which the pattern is the following:

  10 Cycle High -> 10 Cycle H/L (depending on bit 1/0) -> 7 cycles low

Which gives total of 1.6875us per bit or 27us per packet. To allow the very tight timing those are coded in assembly.

Also by applying bit-masking the library is capable of driving at most 8 ESCs on the same hardware port (on UNO, Digital pin 0-7, PORTD).

Update cycle

One last note about DShot is during my test, I found it is quite strict on the update frequency. It must be updated at exact time interval and I found the slowest update frequency will be around 500Hz. To provide the correct timing for that, the library used Timer 1 and by default update in 1000Hz frequency.


Is it better to use Vraw or Vcc on Mini Pro?

Use the 5V connected to the Vcc pin.

If you use the Vraw pin, the voltage goes through a voltage regulator. This voltage regulator will convert the higher voltage down to 5V by converting the extra volts to heat. So in case of using 12V you'd be throwing away around 60% of the power. Which is both wasteful, and will heat up the regulator quite a bit (depending on the load).


I'm using too much RAM. How can this be measured?

You can use the functions provided AVRGCC: Monitoring Stack Usage

The function was intended to check the stack usage but what it reports is the actual RAM that has never been used (during execution). It does so by "painting" (filling) the RAM with a known value (0xC5), and then checking the RAM area counting how many bytes have still the same initial value.
The report will show the RAM that has not been used (minimum free RAM) and therefor you can calculate the max RAM that has been used (Total RAM - reported RAM).

There are two functions:

StackPaint is executed automatically during initialization and "paints" the RAM with the value 0xC5 (can be changed if needed).
StackCount can be called at any point to count the RAM that hasn't been used.

Here is an example of usage. Doesn't do much but is intended to show how to use the functions.

// -----------------------------------------------------------------------------
extern uint8_t _end;
extern uint8_t __stack;

void StackPaint(void) __attribute__ ((naked)) __attribute__ ((section (".init1")));

void StackPaint(void)
{
#if 0
    uint8_t *p = &_end;

    while(p <= &__stack)
    {
        *p = 0xc5;
        p++;
    }
#else
    __asm volatile ("    ldi r30,lo8(_end)\n"
                    "    ldi r31,hi8(_end)\n"
                    "    ldi r24,lo8(0xc5)\n" /* STACK_CANARY = 0xc5 */
                    "    ldi r25,hi8(__stack)\n"
                    "    rjmp .cmp\n"
                    ".loop:\n"
                    "    st Z+,r24\n"
                    ".cmp:\n"
                    "    cpi r30,lo8(__stack)\n"
                    "    cpc r31,r25\n"
                    "    brlo .loop\n"
                    "    breq .loop"::);
#endif
}

uint16_t StackCount(void)
{
    const uint8_t *p = &_end;
    uint16_t       c = 0;

    while(*p == 0xc5 && p <= &__stack)
    {
        p++;
        c++;
    }

    return c;
}

// -----------------------------------------------------------------------------

void setup() {

Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
Serial.println(StackCount(), DEC);  // calls StackCount() to report the unused RAM
delay(1000);
}


Search for a certain combination of strings in serial and read the following characters until another set character stops the search

Firstly you should really be working with a C string (char *) instead of a String object, otherwise you will be massively fragmenting your heap with the string manipulations to come.
Once you have your data in a C string (char array) you can use strtok_r to split the string on the | character, then for each substring further split it on the :.  You need the _r variant of strtok to make it "re-entrant" so you can have two tokenizations at once nested.
For example (untested):
char *data = "<Idle|MPos:158.500,0.000,0.000|FS:0,0|Pn:H|Ov:100,100,100|SD:0.21,/instruction.nc>";
char *pair; // Pointer to a K/V pair
char *pairptr = data; // Pointer for outer strtok

// Split the string on the first |
pair = strtok_r(data, "|", &pairptr);

// While we have a K/V pair
while (pair) {
    char *kvptr = pair;
    // Split the substring into two parts on the colon
    char *key = strtok_r(pair, ":", &kvptr);
    char *val = strtok_r(NULL, ":", &kvptr);
    if (val) { // If we split the data correctly:
        if (strcmp(key, "SD") == 0) { // If the key is "SD" then
            Serial.print("SD data: ");
            Serial.println(val);
        }
    }
    // Get the next string portion
    pair = strtok_r(NULL, "|", &pairptr);
}

Once you have your val you can further split that down on commas in the same way as it's been split on the colon.


How do I send a string to master using i2c

data is a String. "test" is a char*. Wire.write() has no prototype that takes a String.

Wire.write(data.c_str());


The R3's ATmega16U2 supports USB, so all you need to create a USB MIDI device is software.

On AVRs, you typically use the Lightweight USB Framework for AVRs (LUFA), which has support code for both the basic USB protocol and for USB MIDI.


Weird result printing an array using a loop

Constants like String(number_small[0][0]) are optimized by compiler during the build (=compile time).

However that's not the case of loop. So you have to use specific functions for reading values from PROGMEM in the runtime:

for (int i = 0; i<14; i++){
  Serial.print("I: ");
  Serial.print(i);
  Serial.print(" - ");
  Serial.println((int)pgm_read_word(number_small[0]+i));
}

Btw: Don't use string concatenations. These are extremely hungry for the memory. See Majenko's article: The Evils of Arduino Strings


Can't you easily use "quadrature" incremental rotary encoders at 2X or 4X their number of "stops"?

Maybe the encoder you got is being incorrectly described?  I have a handful of the little thru-hole rotary encoders popular in Arduino module kits and they have 12 detents for one rotation, but they are actually 48-position-per-rotation encoders. When I use them, I have to divide the tick count by 4 to have one physical "click" count as one tick in my code.

For some of these, it's fairly straightforward to open them up and remove the detent, and thus get a higher-resolution, smooth spinning encoder. Unfortunately, others, such as the ones I have, are difficult to open without destroying them, and since they physically snap to the detents, aren't usable at the proper resolution.

The method you note, where you track the high/low change in either direction of both outputs is the normal way to read quadrature encoders.


Can't upload arduino code on the board due to some programmer issues

I faced the same problem while uploading.

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding

To solve that I changed my port to another USB port and I selected the particular port, Its uploaded successfully. But it's in MacBook not in Windows.

Try this once, by changing the port.


28 BYJ stepper motor runs faster using delay() and little slower using millis(), why?

Maybe for the second function you want something like this:

 void stepper_run_cw(void){
  stepper_step_cw(1,0,0,0,1);
  stepper_step_cw(1,1,0,0,1);
  stepper_step_cw(0,1,0,0,1);
  stepper_step_cw(0,1,1,0,1);
  stepper_step_cw(0,0,1,0,1);
  stepper_step_cw(0,0,1,1,1);
  stepper_step_cw(0,0,0,1,1);
  stepper_step_cw(1,0,0,1,1);
}

void stepper_step_cw(uint8_t m_in1, uint8_t m_in2, uint8_t m_in3, uint8_t m_in4, uint8_t delay_time){
  unsigned long temp, i;
  for (i=0;i<delay_time;i++){
    temp = millis();
    while (temp == millis){};//wait for millis to change
  }
    digitalWrite(in1, m_in1);
    digitalWrite(in2, m_in2);
    digitalWrite(in3, m_in3);
    digitalWrite(in4, m_in4);
}

This code is also avoiding the millis overflow issue if you run your board for a long time.

Still, apart for a improved timing, there is no gain in using millis(), you still have to wait for millis to change, you might want to use a timer interrupt to do the job in background.


I fished out some code I wrote a while back while evaluating the 1232.  SPI is a headache because of the need toggle the clock signal to prevent the last data bit from 'sticking', which will botch repeated reads when the last data bit is high.

If you are absolutely required to use SPI stop reading this answer.

Everything you need to know is on pages 18 and 19 of the ADS1232 datasheet.  Note this is strictly demo material, for example it doesn't take into account settle time when switching channels.

int32_t read_adc(const uint16_t wait_millis) {
   int32_t data = 0;
   // reset ADC
   digitalWrite(ADS1232_PDWN, LOW);
   delayMicroseconds(10);
   digitalWrite(ADS1232_PDWN, HIGH);
   delayMicroseconds(10);

   for (; data < wait_millis && digitalRead(ADS1232_DRDY_DOUT) != LOW;
        delay(1),
        data++);

    if (data == wait_millis) {
        // timeout
        return -1;
    }

   // read in 24 bits, see Page 19 of the datasheet

   data = 0;
   for (uint8_t i = 0; i < 24; i++) {
        digitalWrite(ADS1232_CLK, HIGH); // clock out next data bit
        data <<= 1;
        data |= digitalRead(ADS1232_DRDY_DOUT);
        digitalWrite(ADS1232_CLK, LOW);
    }
    // adjust for sign. See page 18 of datasheet
    if (data & 0x00800000)
        data |= 0xFF000000;
    // avoid having DRDY/DOUT remain in the state of the last bit
    // see page 19 of datasheet
    digitalWrite(ADS1232_CLK, HIGH);
    delayMicroseconds(10);
    digitalWrite(ADS1232_CLK, LOW);

    return data;
}


How does the build process in Arduino IDE work for ESP8266

Does it uses same for compiling programs for esp8266 ?.

No. It uses xtensa-lx106-elf-gcc. The compiler has to match the architecture.

Most of the build "process" (as in the actions that are taken) is the same, but executables specific to the EXP8266's XTensa core are used. There's also a few extra things in there, like building the (optional) SPIFFS image, etc.


For me, your code is working like charm. but change the

gprsSerial.begin(9600)

to

gprsSerial.begin(4800)


Why Firmata Test doesn't allow me to choose a port?

I had the same problem until I ran it as:
sudo ./file


Problem “Didn't find PN53x board” Arduino NFC Card Reader

EDIT:
Try using Elechouse library, it worked better for me.

This might be irrelevant, but I wanted to share.

I had a similar issue, not related to the sketch code.

So make sure:

Connect wires to the NFC module at 90 degrees - there should be angular headers included. Also the wires should be above the antenna - the white strip.
There shouldn't be any wires underneath the NFC module or they should on significant distance.
Soldered wires work better on the NFC module.


The resonator on the Arduino Uno is better than the internal oscillator of the Atmega328p, but still not very precise. Therefore, for accurate measurements, you need to use a better quality crystal. For instance @ 16 MHz. Once you set the correct prescaler in the Arduino, this should give you accurate millis() - as long as the crystal that you're using is accurate.


You can use a single analog pin to read an entire keypad.

First, read up on voltage dividers - they let you convert a resistance into a voltage. You will need to know this later on.

A keypad typically has 4 inputs, and 3 outputs (or vice-versa). Label the 4 pins A,B,C,D and the 3 pins E, F, G. You will be wiring A up to a voltage supply, and G up to an analog pin, and via a suitable resistor to ground. This becomes your voltage divider.

Then, put a resistor between A+B, B+C, C+D, and between E+F, F+G. So, if you press the button that connects A to G, there will be no resistance (=+5V). If you press the button that connects A to F, then the resistance will be that of the resistance F->G. If you press the button that connect D and E, the circuit goes: VCC-A-resistor-B-resistor-C-resistor-D-pushbutton-E-resistor-F-resistor-G - Arduino analog pin. With no button pressed, the voltage will be 0.

You will need to work out different resistors in advance, to give you as even a range as possible between 0 and 5 volts (the critical thing being the smallest difference). You can calculate the resistance of any combination here: http://www.calculator.net/resistor-calculator.html and you can use Ohm's law to calculate the final voltage. This depends on what you have in your kit. I ended up making a spreadsheet, and then trying random resistor values until I got a good spread.

DO NOT use any resistors under 1kOhm.

Once you have the right spread, make it up on a solderless breadboard. Measure the voltage with your arduino (use the "readanalogvoltage" sketch, take out * (5.0 / 1023.0) , and make up a table - press button 1, you get a reading if A, press button 2, get a reading of B. Include the reading when no button is pressed, which should be 0.

Then find the numbers exactly in between.

For example, if the lowest three readings are 0,20,37 for no button, A, and B pressed, respectively, then in your code, you will say: if the pin measures less than (half way between 0 and 20=) 10, then no button is pressed; else if the pin measures less than (half way between 20 and 37=) 29, then button A is pressed... and so forth.


The ATmega328 used in a lot of Arduinos is a 8-bit microcontroller. This means that registers are 8-bits, the data bus is 8-bits, the ports are 8-bits. There are some minimal 16-bit aspects to the system (e.g. one of the timers), but nearly everything is 8-bits.

Therefore, most operations handle 8-bits at a time. Working on anything except 8-bits (i.e. 16-bit or 32-bit integers and floating point numbers) requires what could essentially be described as software emulation, where the compiler uses multiple instructions to work on these larger variables.

8-bits is obviously adequate to address a 8-bit port. It's also enough to deal with many loop counters, return values, and ASCII characters. It isn't really enough though when dealing with numbers. A signed 8-bit int (int8_t) can only represent -128 -> +127. Unsigned (uint8_t) can only represent 0 -> 255.

8-bit integers are quite limiting. C/C++ int must represent at least -32,678 -> +32,767 so maps to int16_t - the smallest size that will do so. This gives a good balance of range and efficiency. This is especially important when beginners are learning - overflow is not really something that non-programmers understand.

There is a performance impact of doing this however, because most 16-bit operations take at least twice as long as an 8-bit operation, and use twice as many registers. This may or may not make a difference to you.

Many of us switch to the native types such as int8_t and uint8_t as it gives you far more control.


Short answer is probably.  There is a voltage drop from base to emitter that is about .7 volts.  But something still has to contend with the rest of the energy.  You might try a different Arduino digital output on the chance that the balance of the processor is working as expected.
I say probably because several things might have happened if the transistor actually turned on.  For instance the forward biased (backwards) diode may have allowed so much current to flow through the relay and transistor that the transistor failed first.  Or, if the power supply had a low current rating, it may not have had the capacity to burn anything out.  As you can see, it is difficult to say what exactly happened with out testing each part individually.


Your code does not configured SignalPin as an output, but only trigPin.

As already explained in comments, your observed voltage is due not really to the voltage divider you constructed, but rather one formed by the "weak" internal pull-up resistance and your external resistors.  From your measurement, it appears the value of the weak internal pull-up is about 35K, which is within the range of expectations.  That and your 4K external form the top of the divider (39K) while your 10K forms the lower half, yielding about a fifth of the supply voltage.

In some versions of the Arduino library, writing to an input pin enables and disables the internal pull-up resistor, so you could have observed your program seeming to control the pin - but at minimal drive strength.

To get the desired behavior, you merely need to add

pinMode(SignalPin, OUTPUT);


The filter is only needed if low noise is important to your application.
For monitoring batteries, you probably don't need the accuracy level at
which you would want the filter. For what it's worth, the Arduino Uno
doesn't have such filter: it's AVCC is connected straight to VCC.

If you really want the filter, the exact characteristics are not
critical. The datasheet suggests 10 µH + 100 nF, so this
should be a safe choice.

Edit: To answer the question in the comment, yes, it is generally
advised to use decoupling capacitors, usually something like
100 nF, even when powered from a voltage regulator.

Notice that both the VCC and the AVCC pins are very close to a ground
pin. Best practice is to use one decoupling cap for each (A)VCC/GND
pair, and to place that cap as close as possible to the pins.


How do I avoid this error trying to connect arduino to pc with linux fedora 20

The warning, as I'm sure you can tell, is about a mismatch in version of RXTX arduino is expecting, and what is installed on your system. If everything is functioning, I would not worry about it at all. The versions seem to only be slightly different, maybe just a few bug fixes are missing from the older one.

RXTX is a library for java to communicate with serial devices, but it is not under development anymore and only available from mirrors, not the original developer site. Arduino has moved on to a library called jSSC, which is currently being maintained, and a much better library IMHO. The change to jSSC is still only in the arduino beta version, 1.5.6r2 at time of writing, but it works very well. Anyway, if RXTX ever actually gives you trouble, you can download the beta version of arduino and not have to deal with it.


Debugging my Stepper Motor Driver circuit

I had this same issue when setting up this circuit with this code and driver on an Arduino Uno. All else was fine, but the current for the motor was set WAY too high on the driver from the factory. The VREF was 1.7 volts, and it needed to be around .5 for the motor I was using. As I set the VREF to the appropriate voltage, the motor started to spin as it should and stopped hissing.

I know this post is old, but I hope that this helps someone else. Pololu has a great video (and documentation in general) for setting the appropriate voltage on most of their drivers on the product page here: DRV8825 Stepper Motor Driver Carrier, High Current.


The extension you use for a header file doesn't technically matter because the compiler never sees it. You could name it with the extension .this-is-a-header-file and it would probably still work.

The compiler only handles the C/C++ source files, typically named .c and .cpp. However, before that happens, the preprocessor goes through and looks for any #include lines. When it sees one, it basically copies the entire contents of the included file into the source file before it gets compiled.

This is normally used to include header files. However, the preprocessor doesn't know or care about different programming languages. All it does is process the raw text so there's nothing stopping you from including any text file you like, with any name or extension.

Choosing to use .h or .hpp is mostly just personal preference. You could certainly argue that it lets you (as a programmer) distinguish between C/C++ code more easily.

However, the reason why .h is more common is probably that C and C++ code is mixed so freely. You can generally compile C code as C++ without any problems, in which case it's the context (rather than the file itself) that tells you if it's C or C++. It's also possible to write a library in C++ which only exposes a C interface, meaning it could be used by C programs.

You could definitely include a C++-specific header file in a C program by mistake. All that would happen is that the compiler wouldn't understand the contents of that header file. Sensible development environments don't link to a project/library when it sees a #include directive (the Arduino IDE is the only one which does this, as far as I'm aware).


The string you are sending ("E\n") is not the same one you are checking for: 'E'.

You could, for example, strip newlines from the string:

if arduino.readline().strip() == 'E':


First of all: The Arduino IDE brings its own GCC compiler. It is a version, that can compile for the AVR platform (don't know, if the standard version is capable of that).
When you activate verbose output for compilation in the preferences of your Arduino IDE, you can actually see, what calls to GCC the IDE is doing. You could use that to replicate it.
If you only want to use the sublime text editor for programming and not rebuilding the compilation environment of Arduino for fun (which I wouldn't able to help with), you might wanna have a look at the Arduino-cli. It gives you a tool to invoke important function, that normally the IDE does, via commandline (like installing cores and libraries, compiling and uploading). Thats what I'm currently using with sublime for programming in Arduino. It allows me to invoke building an uploading from sublime without having the Arduino IDE open.
If you want to go that way, here are the sublime-build files, that I use for my Arduino Nanos and ATtiny84s. Maybe you can adapt them for your needs. (Note: I omitted multiple variants, that I use to upload on different com ports, because the com port is the only thing, that changes there. Also I'm on Ubuntu, so on Windows or Mac it might look a bit different)
For the Nano:
{
    "cmd" : ["arduino-cli compile --fqbn arduino:avr:nano"],
    "working_dir": "$file_path",
    "shell":true,
    "file_patterns":["*.ino"],
    "variants": [
        {
            "cmd" : ["arduino-cli compile --fqbn arduino:avr:nano && arduino-cli upload -v --fqbn arduino:avr:nano:cpu=atmega328old --port /dev/ttyUSB0"],
            "working_dir": "$file_path",
            "shell":true,
            "name": "Compile & Upload ttyUSB0"
        }
    ]
}

For the ATtiny84:
{
    "cmd" : ["arduino-cli compile --fqbn ATTinyCore:avr:attinyx4:chip=84"],
    "working_dir": "$file_path",
    "shell":true,
    "file_patterns":["*.ino"],
    "variants": [
        {
            "cmd" : ["arduino-cli compile --fqbn ATTinyCore:avr:attinyx4:chip=84 && arduino-cli upload -v --fqbn ATTinyCore:avr:attinyx4:chip=84 --programmer arduinoasisp --port /dev/ttyUSB0"],
            "working_dir": "$file_path",
            "shell":true,
            "name": "ATtiny84: Compile & Upload ttyUSB0"
        }
    ]
}


Controlling multiple solenoids with arduino

Arduino I/O pins, and the output pins of 74HC595 shift registers are logic-level outputs, and are not intended to drive power-hungry items like solenoids. In either case (direct I/O or shift registers) you need to use the logic signal from the output pin to drive something else that switches the 12V source.

That something else can be a MOSFET or a relay, though often even relay coils are themselves driven by a MOSFET or other transistor that is switched by a microcontroller output pin.

One of the many search results that describe this is at http://hades.mech.northwestern.edu/index.php/Driving_using_a_single_MOSFET


How does an 8bit MCU make use of data-types over 8bits?

The basic answer is that the processor does math in 8-bit chunks, so it takes more instructions than it would on a 32-bit processor.

A good answer is found in EE.SE


If you just want to remove the letters:

#include <ctype.h>

char inByte = SerialPortOne.read();  // read byte
if (!isalpha(inByte)) {              // not letter
    strRecordIn.concat(inByte);      // add byte to receive buffer
}

Or you may test it for isdigit() and explicitly compare to ',' and
'.':

if (isdigit(inByte) || inByte == '.' || inByte == ',') {
    strRecordIn.concat(inByte);      // add byte to receive buffer
}

C.f. the documentation of
<ctype.h>.


That is an incredibly hard question to give a definitive answer to.

In general using OO consumes more memory, but that is the price you pay for greater flexibility and ease of use. The difference is usually minor though. Variables within an object take the same amount of space as variables outside an object. It's just the overhead of instantiating the object itself that adds to the memory usage, and that can be quite small, depending of course on what the object does.

Calling functions increases memory use on the stack. Every time you call a function the return address and a number of the internal CPU registers, along with some of the parameters, get placed on the stack. The deeper your function calls go the bigger the stack gets. But that is all temporary - as you leave the functions the stack shrinks again.

However, this is where it gets more complex:

The compiler performs optimizations. One of them is to consider functions for inlining. This replaces the function call with the content of the function that is being called. It makes for a slightly larger program, but it's a program that runs faster and uses less stack.

In your first two examples, because there is only one call to the blinkLed() function, the compiler will see that as a good candidate for using inline. So your first and second programs may well both end up exactly the same.

There are times, as well, where variables that you declare don't actually ever exist. For instance, if you use a couple of temporary variables to do a few calculations in a function and then return the result the compiler may instead just use CPU registers to store the temporary values instead of allocating variable space in memory.

So it is very hard to say "this is better" or "that is better". Instead you should pay more attention to how and where you declare and use your variables.

In general there are two rules:

Keep your variables the smallest size possible for the contents (use 8 bit variables instead of int for storing smaller numbers).
Keep the scope of variables as small as possible.

The latter is often overlooked. The scope of a variable is the block (delimited by { and } for example) where the variable is declared. Anything inside that block, including sub-blocks, can see the variable. By keeping the variable in as small a scope as possible you increase the chances that the compiler will choose to use CPU registers instead of allocating memory.  For example:

int i;

for (i = 0; i < 1000; i++) {
    .... do something ....
}

.... other things ....

for (i = 30; i < 2000; i++) {
    .... do something else ....
}

That is pretty much guaranteed to allocate memory for i.  However:

for (int i = 0; i < 1000; i++) {
    .... do something ....
}

.... other things ....

for (int i = 30; i < 2000; i++) {
    .... do something else ....
}

With that method the variable i will only exist within the first loop, after which it disappears. It is then recreated as an entirely new variable for the second loop. It doesn't need to stay in memory in between. The compiler may just place it in internal registers, or it may reuse the same block of memory, etc.

Also by keeping scope as small as possible you increase the ability of the compiler to re-use the same bits of memory for different purposes. 10 integers in different scopes doesn't mean 20 bytes of memory - it may mean just 2 bytes for all 10 integers.

So as you can see managing memory effectively can be a bit of a black art at times.


How to drive SPI MAX7219 7-segment led module using MCP23S17 extender

I'm not 100% on what you want to do but I have used both the chips you seem to want to do it with.

The MAX7219 can control 8 7Segment displays.
I don't remember it being an SPI device, you just set the pattern you want in the registers and off it goes.  (It could be that is used such a high level abstraction that I didn't realise it was SPI)

The IOX chip you are referring to is quite similar in behaviour, you setup the registers and away it goes.

On the surface it appears you can do what you want, but I suspect you will hit timing issues unless you want very static displays (maybe < 1FPS).  The time it takes you to establish the correct settings on the IOX chips will be the limiting factor.

You might want to look at the I2C version of the IOX which will require just 2 pins to connect to up to 7 ICs.

Alternatively use a network of microprocessors to each drive the maximum number of MAX7219s that they can, such as Nanos, ESP8266-12/NodeMCU, etc.


Is there a semi-permanent way to attach wires to the Nano?

There are jumper wires that have a female header on one end and a male header on the other. Example: https://www.sparkfun.com/products/9140

You could also attatch several wired to a strip of breakaway female headers, such as https://www.sparkfun.com/products/115


A relay is nothing more than a switch - but instead of your finger controlling it, it's controlled by an electromagnet.

The relay can perform the exact same function as the switch on that cable.  In the image you have posted you would use the right-hand two screw terminals (middle is "common", right is "normally open") to replace the switch.


You have a misconception, which signals get's outputted where. If you want to simply read the analog signal of the sensor, you need to use the "control" connector. There you can find the analog signal on pin 2. But this analog signal goes up to 10V, so you need a voltage divider between the sensor and the Arduino, to divide the voltage down to 5V max.

Currently you are using the RS232 connector. RS232 is a communication standard, which transmits digital data, not analog data. Thus you read only digital values (min voltage and max voltage, nothing inbetween). You can use it do talk with the sensor, change configuration settings and reading data digitally. But to actually do this, you need to consider 2 important things:

RS232 is an interface, which involves it's own voltage levels (namely +-12V), which do not fit the TTL level (0 - 5V) that the Arduino Uno uses. You can very well destroy your Arduino by connecting it directly to RS232. For making this work, you need a level converter chip (I think the MAX232 is commonly used for this), to convert the voltage levels to TTL logic. From there on this communication is normally called UART.
You need to understand and then implement the sensors communication protocol (when to send what data), so that the sensor and Arduino are understanding each other

For me it seems, that the analog signal from the "control" connector is all, that you currently need, so for simplicity you can use this. RS232 is used for more control over the functionality of the sensor.


How to get Transmission package Timestamp from ESP8266

You can use timestamp from NTP client and attach it

Install NTPclient library from Arduino library manager
This library uses WiFiUdp library to connect to the NTP server, so download that too

Then you can just update the time every time your sending/receiving something and log it as and how you see fit!


How can I move an arduino library into my project repo and use it from there?

What's the deal? Aren't I supposed to be able to import libraries with
  an absolute path to the library? This is literally the same file.

Yes you can use both absolute and relative paths, but "libraries/LiquidCrystal/LiquidCrystal.h" is a relative path because it doesn't start from C:\\ or / basically. Also make sure you get the LiquidCrystal.cpp file which actually contains all the functions LiquidCrystal.h specifies.

  What is the difference between #import  and #import
  "my_libraries/myfoo.h" ?

#include "my_libraries/myfoo.h" specifies that myfoo.h is in a folder my_libraries first searched for in current_folder/my_libraries/myfoo.h then quote directories and rest of the search paths later, #include <foo.h> specifies that foo.h is a system header, it's only searched for in search paths.

Solution here would be saying inside your sketch that it is in a subfolder, that the folder is one folder below and then two folders deeper for ex. #include "../libraries/LiquidCrystal/LiquidCrystal.h" this here assumes your sketch is in root_folder/Sketch/Sketch.ino and library in root_folder/libraries/LiquidCrystal/LiquidCrystal.h.


Prevent reiteration of loop instruction in Arduino/Execute instruction via off switch

An Arduino doesn't understand the concept of "powering off".  It is either on (running) or off (not able to do anything).

Your first task must be to design a system whereby the Arduino can control its own power so the Arduino can then go "I have been asked by this external stimulus to switch off. Therefore I will play this sound and then perform whatever actions are required to remove power from myself."

Only when you have worked out how you can get the Arduino to control its own power and still have the ability to manually turn the power on can you begin to think about adding things that happen "when it powers off".


How to expand an Arduino when using a TFT display shield?

As I can read your link, the shield is using D2-D8 and A0-A3, leaving some pins unused. So some Arduino pins are still free to use, just the shield is in the way to get connected there.

So there are some possible ways:

brutally solder some wires to the shield unused pins from front side and use that wires to connect where you want (sensors, breadboard, universal PCB, ...)
brutally solder some wires to arduino bottom on unused pins, then continue as mentioned
create intermediate shield (there are many, which allow you connect to arduinou on bottom and stack antother shield on top, draw your wires from there (and maybe even put some circuities on the middle shield, if you want
(something like this https://www.aliexpress.com/item/UNO-Prototype-DIY-shield-kit-for-Arduino-UNO-Universal-Extend-Board-UM-UNO/32555004112.html or any "arduino universal shield"

https://www.indiegogo.com/projects/ardushield-most-universal-shield-for-arduino-ever#/ works excelently across arduinos and other shields/breadboards ...

or anything along this lines ... http://shieldlist.org/sunhayato/universal

use pins D10-D13 as they are connected also to ISP header https://www.arduino.cc/en/Tutorial/ArduinoISP and could be connected from there. As they are part of SPI interface
https://www.arduino.cc/en/Reference/SPI that could be good coise too (if you manage ChipSelect somehow.

As for other part of question -
It is possible to connect more arduinos, there are so much different ways, that it is hard to write here all - choose one, that would suit you best. (anyway you would need some access to some pins anyway )


How to free up Flash space by removing the bootloader on UNO?

You'll need to use an ISP programmer with avrdude. Perform a chip erase and then unprogram the BOOTRST fuse in the high fuse byte.


How to send AT command to sim800l with SoftwareSerial

NeoSWSerial would be better for this.  It can read and write at the same time, unlike SoftwareSerial, and it doesn't disable interrupts for the entire character receive time (~1ms!).  AltSoftSerial would be even better, but you can only use it on pins 8 & 9 (on an UNO, different pins on other Arduinos).


You can cast it to an integer after adding an offset.

Casting to an int will lower the value to the lowest integer value (e.g. 0.9975 will become 0). However, if you want an accuracy of 0.5 (e.g. all values from 0.5 <= x < 1.5 should be 1.0), than add 0.5, thus:

int roundedValue = (int)(0.9975 + 0.5);

If you use constants and want to calculate with it, either add .0 to it, or use a f(loat) or d(ouble) postfix, e.g.:

float f = 12.0 / 3.0;

or

float f = 12f / 3f;

Than calculate the rounded value:

int roundedValue = (int)(f + 0.5);


how can I change the setting for number of upload retries in the IDE?

The code is not in the arduino ide but in the tool chain (.exe) that it runs.

Normally it is a program called avrdude.exe that is running so you would need to rebuild the avrdude.exe tool which is not practical.

The easiest way, but rather crude, is to pull the usb cable. If the port disappears avrdude should stop immediately.


Streaming integer data from Arduino to Java, integer greater than 0xFF

I'm assuming you will be using the Arduino millis() function for keeping time. The output of the millis() function in the Arduino environment is a 32-bit unsigned integer*.
A 32-bit integer can be split into 4 x 8-bit bytes. To keep things simple you could program the Java receiving side to always expect 4 bytes (or whatever amount you need, see *). Assuming 32 bits is enough, you could use the following:
void sendData (uint32_t uptime) {
    int i;
    for (i = 0; i < 4; i++) {
        Serial.write (uptime & 255);
        uptime = uptime >> 8;
    }
}

On the Java side, you would receive the lowest order byte first, and you could reconstruct the 32-bit value by taking the first received 8-bit value, adding the second value shifted left by 8 bits (=multiplied by 256), adding the third value shifted left by 16 bits (=multiplied by 65536) and adding the fourth value shifted left by 24 bits (=multiplied by 16777216). Java is not my strong point so I will leave that to you.
BTW, is there a particular reason you have to use Serial.write()? It would be much easier to just write the value as a string with Serial.println().
*After 2^32 milliseconds (a little under 50 days of uptime) the 32-bit counter that feeds the millis() function will wrap around to 0. You could keep the amount of times that the timer has overflowed in a separate (integer) variable and make that (i.e. bytes 5 and onward) part of your output.


attachInterrupt(digitalPinToInterrupt(0), interrupt, LOW);

should be either

attachInterrupt(0, interrupt, LOW);

or

attachInterrupt(digitalPinToInterrupt(2), interrupt, LOW);

As pin 0 is not an interrupt pin. Also the button is connected to pin 2, not pin 0. digitalPinToInterrupt(0) would actually return -1.


I'll assume that you are trying to charge from a 5V "USB" source.

If you only want to use a UNO + passive components then the hardware intensive method of application note AVR146: Lithium-Ion Battery Charging via USB with ATmega16/32U4 which Ignacio suggests does not meet your need. This is a capable charger but the UNO would not be the major part of it.

"Normal" charger

The use of any of the available LiIon charger ICs is an easy and low cost way of adding a charger. These ICs and all related components can cost as little as a few dollars. But ...

UNO + one resistor very low current charger:

If using a UNO with no external active parts the current drive rating of the UNO pins limits the maximum current able to be provided. If you really want to meet your specification you can achieve a few ten's of mA charge using with a UNO and a few resistors (possibly just one.)

Super simple good capability charger

But, a good compromise can be achieved using a UNO (or similar) + one transistor plus a few resistors and capacitors. This can achieve all the usual basic capabilities

Low current "trickle up" for very low voltage cells
Constant current charge until Vmax is reached
Constant voltage charge until I_cutoff is reached.
Terminate and stay active until recharge needed.

I will only outline the basic system here. More can be said as and if required.
The main point of note s that in its simplest form the charger uses a linear charging mode so a modest amount of heat needs to be dissipated in the control transistor. Max power dissipation for a A max charge rate would be 2 Watts when the battery was at 3V and full charge was wanted from 5V in.
Power dissipation = (Vin - Vbattery) x Icharge
Worst case here = (5V - 3V) x 1A = 2 watts.
A buck converter could be used (UNO controlled) if desired.

A transistor Q1 connects Vin to battery

Q1 can be PWM controlled by the Uno.

Battery current is monitored by a small resistor Rcur from B- to ground (or in B+ lead)

Vbattery is monitored with an ADC channel (ADC1 or ADC_V)

Current is measured by measuring voltage across Rcur with an ADC (ADC2 or ADC_I).

If Rcur is from B- to ground then V Rcur = V ADC2. If Rcur is in B+ lead V across Icur = V_ADC2 - V_ADC1.

Q1 on state can be varied by PWM from Uno to control battery current. PWM voltage is smoothed by an RC low pass filter to allow smooth DC control.

Charging:

The following steps constitute the standard LiIon charging algorithm implemented by most charger ICs. Variations can be made.

If Vbat < 3V set Ichg to Itrickle by PWMing Q1 and reading battery current.

While 3V <= Vbat <= 4.2V chg at Imax for battery.

When Vbattery = V-max = 4.2V adjust Ichg with PWM to hold Vbat at 4.2V until   Ichg falls to desired fraction of Imax.

Turn off chg voltage fully and monitor Vbat to restart charge at Vbat = Vrestart - maybe 4.0V or as desired.


If you don't know how many data points will be recorded, look into vectors or an external storage device. Alternatively you could use a circular array if you don't mind losing recorded data after a while.

If you know how many data points will be recorded, a basic array will suffice.

As for excluding invalid values:

// Keep trying to get a valid data point
While (RangeInCentimeters > 512 && RangeInCentimeters < 400)
{
 delay(200);  // The minimum value of this delay depends on the sample rate of your sensor
 RangeInCentimeters = ultrasonic.MeasureInCentimeters();
}

//... Store data to array/linked list/etc

I changed your max range to 512 because this is likely the max real value (2^9 = 512).


How to Control 2-wire Rotary-Gear Linear Actuator

I suspect that's little more than a geared brushed DC motor with a fancy "nut" on it. So yes, you will need any standard motor driver rated for the correct voltage / current (an H-bridge).


Including keypad library removes sound from my piezo element

I was able to solve it , piezo dissent work in pin 9 but works when connected to pin 13.


Arduino Mega 2560 R3 with Shield Model Wireless SD R3 not working

You see that double row of 10 pin headers?  That's an XBee connector.

https://www.sparkfun.com/pages/xbee_guide

You use it to connect your XBee module of choice (there's a few to choose from) to communicate wirelessly between Arduinos using the special XBee system.

Note that XBee is not WiFi, it's Wireless.  The two are very different things (Wireless refers to any wire-free communication system, WiFi is one specific protocol on one specific set of frequencies using a specific set of encodings, etc).  XBee cannot talk WiFi in the same way that I can't talk Chinese.

For WiFi you need a WiFi shield.

https://www.arduino.cc/en/Main/ArduinoWiFiShield


How do I update the serial monitor without printing a new line each time?

The ultra-basic "serial monitor" in the Arduino IDE cannot do what you want.

Instead you need to either write a special client program, or use a more standard serial terminal program, such as Tera Term (Windows), Minicom (Linux), etc.

These standard serial terminal programs use a special sequence of characters called ANSI escape codes which manipulate the display, doing such things as setting colours, moving the cursor around, etc.

More information on ANSI escape codes can be found here: http://en.wikipedia.org/wiki/ANSI_escape_code


Weird text when pressing a certain touch button

It seems by changing 16 to 12 on

for (int x = 0; x < 12; x++) {
      if (Key == keys[x].kCode) {
        lcd.print(keys[x].kValue);
      }
}

fixed it.


How to concatenate a part of a string and convert then to a int?

There's multiple ways.

The String class (which TBH you should avoid) has some useful methods:

substring - extract part of a string as a new string
toInt - convert a string to an integer

So you can join them together:

int val = myString.substring(3).toInt();

That's the easy way.  Grab the string content from the 4th character (it's zero-based, so 3 is the 4th character) onwards, and convert it to an integer.

If you are avoiding String, as you should, then you are working with pointers.  For instance:

char myString[10]; // This is where your data gets stored
strcpy(myString, "AR0236"); // Let's put in some dummy data

int val = atoi(myString + 3);

myString + 3 gives you a new string pointer to a location that is 3 bytes further up in memory from myString - which equates to where the start of your number is.  Then convert that portion of the string to an integer.

The "easy" way consumes and makes a mess of your heap, since it's having to make a new String object and copy data into it. The "better" (second) way uses no more memory. It just converts a subset of the existing string directly.


Why does my analogRead work on Teensy but not Arduino Uno?

If you're still using D0 as your output on the Uno then yes you are doomed to failure.

D0 and D1 are the serial port. You are using that to communicate with the PC. You cannot use them for any other purpose at the same time.

Pick a different IO pin to be your voltage source.


What is outPin?
Don't start a SoftwareSerial object on the Serial port.  Just use Serial
The Serial Monitor window will have to use the GPS baud rate if the GPS is connected to pins 0 & 1.  This is a good choice, but you'll have to disconnect pin 0 to upload a new sketch over USB.
Don't use delay.  This prevents the sketch from reading GPS characters.  Eventually, the input buffer will overflow and characters will be lost.  Instead, save a timestamp and compare the current time with the timestamp.  When the difference is 50ms, simply toggle the pin and save another timestamp.
Try NeoGPS.  It's smaller, faster, more reliable and more accurate than all other GPS libraries.  There are many tips on the Installation and Troubleshooting pages, and the examples are structured properly.  If you want to use pins other than 0 & 1, be sure the read the section about choosing a serial port.  SoftwareSerial is the worst choice.

Here is your sketch, modified to use Serial and NeoGPS:

#include <AD9850.h>
#include <NMEAGPS.h>
NMEAGPS gps;

#define gpsPort Serial  // GPS on pins 0 & 1
static const uint32_t GPSBaud = 9600;

const int OUT_PIN   = 4; ???
const int W_CLK_PIN = 8;
const int FQ_UD_PIN = 9;
const int DATA_PIN  = 10;
const int RESET_PIN = 11;

const double trimFreq = 124999500.0;

int phase = 0;

unsigned long lastToggle;

void setup()
{
  //Serial.begin(115200);  // NOT needed if gpsPort *is* Serial (pins 0 & 1)
  gpsPort.begin( GPSBaud );

  DDS.begin(W_CLK_PIN, FQ_UD_PIN, DATA_PIN, RESET_PIN);
  DDS.calibrate(trimFreq);

  pinMode( OUT_PIN, OUTPUT ); // must be set to output mode
  lastToggle = millis();
}

void loop()
{
  // Toggle the OUT_PIN every 50ms
  if (millis() - lastToggle > 50) {
    digitalWrite( OUT_PIN, !digitalRead(OUT_PIN) );   // toggle the pin
    lastToggle += 50; // step to the next toggle time
  }

  // Dispatch incoming characters
  if (gps.available( gpsPort )) {
    gps_fix fix = gps.read(); // get a fix structure with all GPS fields

    Serial.print(F("SPEED km/h="));

    // for testing, use some random values (comment this out later)
    fix.valid.speed = true;
    fix.spd.whole   = random( 0, 35 );

    if (fix.valid.speed) {
      float speed=fix.speed_kph();
      Serial.print( speed );

      double freq = map(speed, 0, 100, 0, 160);
      DDS.setfreq(freq, phase);

      Serial.print( ' ' ); // for debugging, show the DDS frequency
      Serial.print( freq );
    }
    Serial.println();
  }

}

Notice that it checks to see if there is a valid speed.  The GPS device may not know the speed, depending on satellite reception.

If you want to try it, NeoGPS is available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.

UPDATE

For the code you posted (which is not a complete program) in an Answer (instead of editing your question :-/), you could do something like this:

#include <NMEAGPS.h>
NMEAGPS gps;
gps_fix fix;

#define gpsPort Serial  // GPS on pins 0 & 1 or whatever
static const uint32_t GPSBaud = 9600;

void setup()
{
  Serial1.begin(115200);
  Serial2.begin(115200);

  gpsPort.begin( 9600 );

    ...other things?
}

void loop()
{
  // Constantly read GPS characters
  if (gps.available( gpsPort )) {

    // Update the global fix structure with the latest GPS info.
    //   The speed will be used later by SendData.
    fix = gps.read();
  }

  // Constantly read Serial2 characters (a sensor?)
  if (Serial2.available())
  {
    int b     = Serial2.read();
    int chunk = b >> 6;
    if (chunk == syncc)
    {
      bytes[syncc] = b & 63;
      syncc++;

      if (syncc == 4)
      {
        syncc = 0;
        tach = bytes[0] + (bytes[1]<<6);
        velocityfreq = bytes[2] + (bytes[3]< delayTime)  ??? "<" ???

        SendData();
        prevTxTime = millis();
      }
    }
  }
}

void SendData()
{
  // No need to use sprintf, just print the pieces.

  Serial1.print( data1 );
  Serial1.print( '|' );
  Serial1.print( data2 );
  Serial1.print( '|' );
  Serial1.print( data3 );
  Serial1.print( '|' );
  Serial1.print( data4 );
  Serial1.print( '|' );

  // use the current GPS speed, as set in loop
  Serial1.print( fix.speed_kph() );
  Serial1.print( F("\r\n") ); // F macro saves RAM for doubled-quoted string constants
}

I had to guess at the nesting of curly braces because IT IS NOT INDENTED, nor do the CURLY BRACES MATCH.  sad.


You are getting exactly what you said you want. 4 bytes representing the number in float format.

What you are expecting to get, is 4 bytes representing the number in big-endian integer format.

Using Majenkos solution for casting, you need to change the types and reverse the for loop for big-endinaness.
I also used int32_t because the size of the int is 16-bit (2-byte) on the Arduino Uno (and other ATMega based boards) and on the Arduino Due it's 32-bit (4-byte). Its better to define the exact int in this case.

union {
    int32_t ival;
    byte bval[4];
} int32AsBytes;

void writeInt32(unsigned int addr, int32_t x)
{
    int32AsBytes.ival = x;
    for(int i = 3; i >= 0; i--) // reverse for big-endian
    {
        i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM
        Serial.println(int32AsBytes.bval[i], BIN);  // Debug line
    }
}


Connecting 12V WS2811 RGB LEDs to Arduino Uno & 5V Power Source (Breadboard needed?)

This image, from here, shows which pins are what:

Note the flat key next to the 12 V and GND pins. In addition:

the GND wire has a black broken line printed along it;
the data line is in the middle.

If you trust the image then you should be able to wire them up correctly.


There's an easy way to achieve reading multiple pushbuttons using single analog input.
All you need to do is create some voltage dividers at different voltages which can be read using analogRead. The last resistor,R6, in the diagram below ensures that the pin reads 0 when no push-button is pressed (i.e pull-down resistor).
In the diagram below, connect Vcc to 5V on the Arduino.

Try it out, you should be able to get well spaced out values for different push buttons!


Are there any electro-chemical sensors available to measure nutrient contents of soil?

You have pH and humidity sensors for Arduino, but "soil fertility" is an unprecise term.

If you do a web search, you will find results for a number of devices that claim to measure soil fertility. I am highly suspect of these devices. Even laboratory testing cannot tell you accurately how fertile your soils are because of the methods used. Most labs test for the presence of inorganic chemals, including nitrogen, potassium, phosphorous and an array of other nutrients plants need. What most of them do not or cannot measure is the amount of plant-available nutrients in the soil. It takes a host of soil organisms to make nutrients in the soil available to plants. If those organisms are not present or are low in numbers, it is difficult for plants to take up nutrients. Fertilizers only exacerbate the problem because they kill off soil organisms, especially mycorrhizal fungi, throwing the entire ecology of the soil out of kilter. There are a couple of laboritories out there that test for soil biology and some nutrients.

Soil is hard. There is a lot of things in soil (compactness, unwanted chemicals/elements, microbes) that can affect the fertility, even if you have the right nutrients in it.

For hydroponic (not your case), you have cheap handheld EC/TDS meters. The pH and EC of your reservoir is all you need to measure the fertility of your water solution.

Go hydro and stop worrying about your tomatoes.


115200 baud at 200Hz means you should be able to transfer in excess of 50 characters between each "trigger". That is more than enough time to send the data even as ASCII encoded text.

serialEvent() is no better than manually looking at things like serialAvailable() in your loop since that is all it does anyway. It just runs after each iteration of your loop.

One problem that you have is that you're appending each character to a String object. This is very inefficient and should be avoided. Instead you should really use a character array:

// Input text in the form "123 456\n"
char instring[20]; // Room for 19 characters plus terminating null
int spos = 0; // Location in the array
int val1 = 0;
int val2 = 0;

void loop() {
    if (Serial.available()) {
        char *bita, *bitb;
        int c = Serial.read();
        switch (c) {
            case '\r': break; // ignore
            case '\n':
                 spos = 0;
                 bita = strtok(instring, " ");
                 bitb = strtok(NULL, " ");
                 if (bita && bitb) {
                     val1 = atoi(bita);
                     val2 = atoi(bitb);
                 }
                 // You now have two new values in val1 and val2
                 break;
            default:
                if (spos < 18) {
                    instring[spos++] = c;
                    instring[spos] = 0;
                }
        }
    }
}


How do I implement a userspace bootloader on Arduino Due?

The guys at Phoenard did just that with an AVR2560. They wrote a bootloader that loads and saves FLASH memory from/to the Micro-SD card. You can save HEX files on an SD card and then load one of them in the FLASH memory and run it.


Simple ESP to ESP reading blink program not reading input voltage

Arduino GPIO automatically set as inputs, so I assumed the same for ESP32. Once the pinMode of the input pin was set, it worked:
#define LED 2 // ON Board LED GPIO 2
#define inPin 26

void setup()
{
  Serial.begin(9600);
  // Pins 34, 35, 36, 39 are input only
  pinMode(LED, OUTPUT);
  pinMode(inPin, INPUT); // <----------
}

void loop()
{
  Serial.println(digitalRead(inPin));
  digitalWrite(LED, digitalRead(inPin));
}


Can I use TCS34725 Color Sensor with Lilypad?

Yes but please note that the I2C pins are D2 (SDA) and D3 (SCL). No extra components are required when connecting to the Adafruit TCS34725 breakout board. It contains pull-up resistors, and voltage/signal level converters (if needed).

Cheers!

Ref. https://cdn.sparkfun.com/datasheets/E-Textiles/Lilypad/Lilypad_Arduino_USB_v12.pdf


I think response time would be a big problem. I used the ESP8266 with a temperature and humidity sensor, complete with a small web server on the ESP8266, and it works fine. But I wouldn't want to control an RC car with it. But if you buy it on ebay from China, it is only a few dollars, so buy one anyway.

Use Bluetooth, either a couple of HC-05 modules, or the Bluetooth Low Energy HM-10 modules. Both can communicate at 115200 baud. The HM-10 modules may be a bit tricky, because some Chinese sellers put a stripped down version of firmware on the module, and forces you to search online how to flash a usable firmware version.


There's some logic slightly askew with your length calculations:

int clen = input.length()/2;

Ok, so for a (say) 20 character string you have clen=10.

for (int i=0; i < clen; i+=2)

Ok, so for the first 10 characters of your 20 character string you take alternate ones (0, 2, 4, 6, 8)

What about the last 10 characters?  clen is 10, not 20, since you divided it by 2 at the start.

Decide if you want clen to be half the string length, then count double, or is the whole string length, and you divide it by 2 where you want the final string length. Or have two variables - one before and one after dividing by 2.

Oh, and you should pass your String parameter by reference so you don't duplicate the object and end up fragmenting your heap.

void SendCTRL (String &input)

I haven't gone into depth about the working of your dehex function, but this is the function I always use and works well:

unsigned char h2d(char hex)
{
    if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
    return(hex & 0xf);
}

Also you should or your values together, not add them:

cmd[i/2] = (dehex(hin[i])<<4) | dehex(hin[i+1]);

This would go some way to fixing your current issue, since | has a different precedence to +. At the moment you have effectively:

cmd[i/2] = dehex(hin[i]) << (4 + dehex(hin[i+1]));

since the + happens before the <<, whereas what you want is:

cmd[i/2] = (dehex(hin[i]) << 4) + dehex(hin[i+1]);

However with | instead you get

cmd[i/2] = (dehex(hin[i]) << 4) | dehex(hin[i+1]);

because the << happens before the |

Here is your code written in pure C to run on a PC (faster to debug and test than an Arduino when you're on Linux):

#include <stdio.h>
#include <string.h>

unsigned char dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

void SendCTRL (const char *hin)
{
  int ilen = strlen(hin);
  int clen = ilen / 2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < ilen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
    printf("%02x\n", cmd[i/2]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  for (int i = 0; i < clen; i++) {
    printf("%c", cmd[i]);
  }
}

void main() {
    SendCTRL("010307E40001C549");
}


DCMotorTest from the Adafruit site – got fatal error exit status 1

Based on the error report it seems that you have just opened the example program from the downloaded folder. In order to add library files (which includes the header files, c++ source code, etc.) you have to move the Adafruit_Motor_Shield_V2_Library-master folder to the libraries folder.

  Documents > arduino > libraries

If no such folder exist, then create a new folder and name it libraries.

To check weather the libraries have been installed, open arduino IDE goto

  file > example and check weather the example programs are added (you will see "adafruit" in the list)

Now, restart the arduino IDE and things should get going.

Note:
Do not use "-" and do not include space while naming a folder, as the compiler may throw up error. Instead you are free to use "_","$". Name of a folder should always start with a letter.

For more detail visit https://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use/how-to-install-a-library


Bad Data : Arduino Mega & NodeMCU Serial Communication

Sir mane ardunio mega 2560 my programing k hy jo k different sensor k value lake display karty hy aur sir ab my us value ko server jo k thingspeak hy aus p bajna chahta ho sir aus k leye mane esp8266 node-mcu use kar raha ho to sir ab my chahta ho k arduino value lake node-mcu ko send kary aur node mcu phr server p sir in k leye serial communication chahyae between two arduino sir is k leye koi refrence or any help


The relay I linked to couldn't be operated with 3v3 from the NodeMCU board. I was powering the NodeMCU via a breadboard power supply that had both 3v3 and 5v output (https://www.electronicscomp.com/mb102-breadboard-power-supply-module). I connected the Vcc and GND of relay to 5V supply on that module. the IO pin relay was connected to NoddeMCU. It worked fine and NodeMCU could switch it on and off.


Writing and Reading data from RTC module EEPROM_Arduino

These two lines write a 16 bit (2 8-bit) value, which is signed -32768..32767 or unsigned 0..65535.

Assume a value in bits: 10101010 11001100

Statement 1:

Wire.write((int)(eeaddress >> 8)); // MSB

The first statement shifts the value 8 bits (positions) to the right; this is called the MSB (Most Significant Byte, the left 8 bits). Bits on the right are clipped / fall off. Thus

10101010 11001100

will become

00000000 10101010

When casted to an 8 bit value you get:

10101010

Statement 2:

Wire.write((int)(eeaddress & 0xFF)); // LSB

The second statement will get the LSB (Least Significant Byte). This used the AND operator, meaning a bit is only 1 if both values are 1. 0xFF is the 'mask'

Original value: 10101010 11001100
Mask:           00000000 11111111
                ----------------- AND (&) operator
Result:         00000000 11001100

As you can see only the right 8 bits are kept. When casting this to an 8 bit value:

11001100


Look at these lines:

distance = temp;
duration = pulseIn(echo,HIGH);
distance = duration * 0.0343 /2;

Here is what they do:

The first line sets the variable distance to zero (that's the value
of temp).
The second line waits for the ultrasonic pulse to reach the target,
bounce against it and come back, while at the same time timing the
whole trip. This can take a long time (several milliseconds). Chances
are your program spends most of its time executing this line.
The third line sets the variable distance to something sensible.

This means distance is zero most of the time (while the second line
executes). When the interrupt fires, there is a very high probability
for the interrupt handler to find a zero distance, and thus to set pwm
to zero.

Simple fix: never set distance to an unreasonable value. Leave it's
value alone until you have a new distance measurement ready, and only
then update that variable. In other words, just remove the first of
those three lines.

But there is a catch now. The variable is four bytes long, and updating
it takes four instructions. There is a small probability that the
interrupt fire in between these instructions. When that happens, the
interrupt handler finds the distance variable half-updated, with a mix
of bytes from the previous and the current distance measurements. This
is called a “race condition”, and is one of the worst kind of bugs you
can meet, because it is very hard to systematically reproduce.

The fix to the race condition is to update the variable with interrupts
disabled. The wrong way to do it is:

duration = pulseIn(echo, HIGH);
noInterrupts();
distance = duration * 0.0343 / 2;
interrupts();

This is bad because interrupts are blocked during the distance
calculation, which is too much. The right way is this:

duration = pulseIn(echo, HIGH);
temp = duration * 0.0343 / 2;
noInterrupts();
distance = temp;
interrupts();

Now interrupts are blocked only while writing the distance variable.

Personally I don't think it is such a great idea to read the buttons
with interrupts. Buttons are extremely slow peripherals. If you make
your code non-blocking, your loop() will always be fast enough to deal
with them. Handling the buttons in loop() means you don't have to
worry about all the bugs that can easily sneak into interrupt-driven
code, like the above mentioned race condition.

Edit: In the original version of your code, interrupts were used to
read the switches. In the edited version, you added a debouncer, and you
don't need interrupts anymore. In fact, the way this version uses
interrupts makes no sense at all. The most problematic bit is the fact
that this code can disable interrupts for arbitrarily long times. This
is not good, and you should be aware that the Arduino's timekeeping
functions rely on interrupts to perform their job.

I suggest you just remove from this code every single line where you see
the word “interrupt” (singular or plural), and you replace

if(distance>8)interrupts();

by

if (distance > 8) {
    red();
    green();
}

or, to streamline things a little bit, by

if (distance > 8) {
    if (ys == HIGH) pwm = 250;
    else if (rs == HIGH) pwm = 150;
    else pwm = 0;
}


Possible configure ESP8266 as wifi shield for Arduino?

The ESP has 40 kb of ram and the average SPI flash rom used by ESP modules have 1 ~ 8 MB of code space. The average Arduino has much less of both. Uno R3 has the ATMega328, with 2kb of SRAM and 32kb of code space. Your trying to drive a truck with a mini cooper engine.


if (strcmp (unit,"cm") == 0) {

    // matches cm

}

For syntax like this the intellisense in products such as Atmel Studio or Visual Studio can really help. Whilst you still need to understand what you might be looking for the intellisense makes all the available Arduino functions visible from the code. If you install the Arduino plugin then there will be an Arduino reference explorer in both ide's which explains everything.


Ublox GPS with Arduino Mega 2560 not working

The Arduino Mega 2560 has three additional hardware serial ports. Why not use one of them instead? Serial1 on pins 19 (RX) and 18 (TX).

void setup()
{
  Serial.begin(9600);
  Serial.println("uBlox Neo 6M Test");
  Serial1.begin(9600);
}

void loop() // run over and over
{
  if (Serial1.available())
     Serial.write(Serial1.read());
}

Cheers!


Problem with DHT11 and DS18B20 temperature sensors

There appears to be several DHT sensor Arduino libraries available:

niesteszeck/idDHT11
adafruit/TinyDHT
adafruit/DHT-sensor-library

You might try an alternate library to see if that solves your current problem.  Note, some if not all of these libraries need to know which DHT model you are using.

Before going through the DHT and OneWire source code line by line looking for conflicts, try to narrow down what is causing the problem:

Try only instantiating the OneWire class and skip calling the read method within the class.

If this works, then the conflict likely resides in the OneWire read method and not in the OneWire initialization code (that is, the OneWire's Constructor).

Calling the DHT read method multiple times consecutively to see if the problem resolves it self.

Actually, you have done this and exposed a curious patter of good-bad-bad-good-bad-bad... which is worth looking into.  The point here is that if only the 1st call to the DHT read method after a call the the OneWire read method was bad, then there might be a setup problem in the DHT read method.

Call the DHT Destructor, the DHT Constuctor then make the call to the DHT read method every time you read the DHT sensor.

This is a test case only and an extreme measure.  What you are doing here is re-initializing the DHT library (driver) every time you use it.  If this works it points to an initialization problem where the DHT library is initialization something which should probably be re-initialized again inside the DHT read method.  As the OneWire library is using the same "something" (resource).

One last thing, the OneWire example I looked at here:
PaulStoffregen/OneWire
...did not use the DallasTemperature library.  I doubt this will make a difference, but it is usually best to keep your code simple and avoid unnecessary complexities.

Added later...

As pointed out in the comments, it turns out the DHT11 only takes new readings every few seconds.  Guessing, the DHT11 library you are using either knowingly returns an unreasonable value of -999.0 until this time passes.  Or is returning exactly what the DHT11 reports which, again, is an unreasonable value of -999.0.

In this DHT11 library, there is code:

boolean DHT::read(bool force) {
  // Check if sensor was read less than two seconds ago and return early
  // to use last reading.
  uint32_t currenttime = millis();
  if (!force && ((currenttime - _lastreadtime) < 2000)) {
    return _lastresult; // return last correct measurement
}

...which returns the last good value for 2 seconds after a DHT11 "real reading" should the library user call upon it faster then the DHT11 can respond.


Arduino: Reading PPM values from MQ-131 Ozone sensor

First you need t make it burn for 24hrs mini (48 advised). Just plug it and wait. Then for calibration you need a reference atmosphere free of NOx, CL2 and O3. In this reference atmosphere you should get an output value of 0.

I don't know this model you bought exactly, but most of these gas sensors mounted on a PCB have a mini eeprom so the output is the actual PPM concentration. Note that these sensors are not able to tell you how much of which gas is detected, but only a ppm concentration (you then have to guess which one is in the air). If you have several of these gas in the air, you will not be able to tell their concentration with such a sensor.


Connect Arduino with fischertechnik TX Controller

As described in the Wire library that brings supports I²C support to Arduino, except for the DUE that has 2 pairs of pins for 2 I²C buses, other Arduino boards support one I²C connection.

However, this is when you want to use hardware facilities of ATMEL chips that these limitations apply; there is a software I²C library exists that allows using other pins for I²C. One major drawback, though, is that it is very slow; not sure if this is a problem in your situation.

One important thing though: the principle of I²C is to be able to plug several slave devices (more than 100) to one master device. In general, Arduino is the master device, but the Wire library can be used as master or slave. Wouldn't that fit your requirements?

In this situation, you could just use the same I²C bus for everything, including connection to Fischertechnik TX controller.


Python script not reading from serial unless teensy is rebooted

Serial communication is always terminated with a specific character (usually \n). The receiving device will accumulate the incoming bytes in a buffer until it receives this terminating character.

To fix the problem simply change the last line of your arduino loop to Serial.println(sensor);

Also note that the arduino might be faster than your python script, meaning that you will get several sensor values per readout. If that's the case you have to add a short delay in the arduino loop.


Most power efficient way to constantly save 2 kilobytes of data per second

There are two constraints here, and I think it might back you into a corner. Size and then power.

2Kbyte/s is 2*60*60*24/1024 = 168.75Mbyte/day. This is a lot. The only readily available technology that can be used with a small microprocessor that can store this volume of data is an SD card. There are no serial EEPROM or flash chips this large, and the Arduino, as far as I know, can't deal with the NAND flash used in USB sticks and SD cards.

However, SD cards can be relatively power hungry. They draw between 5mA and 100mA when writing, typically around 30-50mA. The SD spec says the maximum is 200mA. Writing is also quite lengthy as they operate on blocks of data rather than individual cells. I've never done a full analysis of how much power they use, but it is not insignificant and much, much more than serial EEPROM or flash.

So your only choice, if you have to store that much, is to go with SD cards.

I would investigate compressing the data. Even very basic schemes can make a huge difference.


What you are looking now is NOT the IR frequency, but the de-modulated signal.

Here is what I'm talking about:

(image taken from http://www.electronicwings.com/sensors-modules/ir-communication)

As you can see, the various pulses are made of smaller pulses.

In your case you are seeing what is here called "Serial data", which is different from the carrier frequency. What the saleae board is telling you is that the width of the high part is 1.625ms, while the width of the low part is 0.631 ms; as you can see, the waveform is NOT periodic, so the "frequency" is meaningless (it's the reverse of the time marked on the view, which is the sum of one large high value and one low value).

Your plot resembles the NEC protocol (see for instance here). A logic '0' is a 562.5µs pulse followed by a 562.5µs space, while the logic '1' is a 562.5µs pulse burst followed by a 1.6875ms space (this is similar to by 0.631 ms and 1.625 ms measurement)


CAN-Bus shield, SD-card module & LED_BUILTIN use D13; possible collision?

Yes you are in danger of a collision, how much danger I can't say, but the potential is there.

You could stop using the LED on D13?
Could you move the pins of your SD card reader, or get a different one that allows I2C or SPI interfacing?

I guess there is nothing that can be done to the CAN bus device, but if there is it might be a good idea to move its pins.