At 16 MHz, your instruction cycle is 62.5 ns, and your PWM period is 40 \$\mu\$s. This is only 640 instruction cycles per PWM period.

To have any hope of doing this, the first thing you need to do is forget using anything Arduino other than the hardware. Download the datasheet for the AVR in question and start getting familiar with it. Your best bet is to use 8 bit timers to reduce the overhead of loading them.

My approach would be to use every 8 bit timer available, and divide the outputs up among the timers. Load the shorest pulse width output in the 8 bit tiemrs. Keep a 16 bit timer available to use for the PWM period. Start all the timers at once. On the first 8-bit timer interrupts, toggle the output, and reload the timers with the time between the next shorest pulse width. Rinse and repeat.

Alternatively you could run one timer, and write a little scheduler that puts the outputs in order from shortest to longest pulse width, constantly poll the timer, and toggle the bits as needed.

Both of these options have a ton of software overhead, and the pulse widths will all be semi-deterministic. Neither would be good for any application where the micro has to do anything else in a timely fashion, such as communication or drive a LCD.


Arduino Leonardo as keyboard for an iPad

If indeed the descriptor is the problem then yes you can change it.

In the core file USBCore.h is the line:

#define D_CONFIG(_totalLength,_interfaces) \
    { 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED | USB_CONFIG_REMOTE_WAKEUP, USB_CONFIG_POWER_MA(500) }

Just change the 500 to something smaller (it has to be an even number).

However it may be that the Leonardo isn't programmed to support the Boot Protocol for HID. In which case that would require bigger changes to the USB and HID stacks in the core.


Flip the RX and TX wires of the HC06. This is because this statement : SoftwareSerial BT(10, 11); actually means SoftwareSerial BT(RXpin, TXpin);. Considering this, 10 is your Rx and 11 is your Tx. In this case, you have to connect pin 10 (software Rx) of your Arduino to the Tx pin of your HC06 and pin 11 (software Tx) to the Rx pin.


Judging by the fact that you agree it looks like this, a search reveals it is a knock-off of the Adafruit V1 motor shield.

Their page shows how to connect to it, and has example code and a library.

I don't really want to post a link-only answer, but the alternative would be to parrot the Adafruit page, which isn't really fair to them because this board wasn't even purchased from them.


Sending arduino sensor data via WiFi to a MySQL server

So I don't quite know why, but I started from scratch and it works now. I've put the new code below in case it helps someone in my situation.
// Arduino Low Power - Version: Latest
//#include <ArduinoLowPower.h>
//#include <ArduinoIoTCloud.h>
#include "thingProperties.h"
#include <Arduino_MKRENV.h>
/*
  Repeating Wifi Web Client

  This sketch connects to a a web server and makes a request
  using a WiFi equipped Arduino board.

  created 23 April 2012
  modified 31 May 2012
  by Tom Igoe
  modified 13 Jan 2014
  by Federico Vanzati

  http://www.arduino.cc/en/Tutorial/WifiWebClientRepeating
  This code is in the public domain.
*/

#include <SPI.h>
#include <WiFiNINA.h>

int status = WL_IDLE_STATUS;

// Initialize the Wifi client library
WiFiClient client;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    //Serial.print("Attempting to connect to SSID: ");
    //Serial.println(SSID);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(SSID, PASS);

    // wait 10 seconds for connection:
    delay(10000);
  }
  // you're connected now, so print out the status:
  //printWifiStatus();
  //Start arduino cloud.
  //ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  //Begin ENV shield.
  if (!ENV.begin()) {
    Serial.println("Failed to initialize MKR ENV shield!");
    while (1);
  }
}

void loop() {
  //ArduinoCloud.update();
  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }
    //Serial.println("Start reading sensors.");
    relativeHumidity = int(ENV.readHumidity());
    //Serial.println(relativeHumidity);
    lightIntensity = int(ENV.readIlluminance());
    //Serial.println(lightIntensity);
    airPressure = int(ENV.readPressure(MILLIBAR));
    //Serial.println(airPressure);
    temperature = int(ENV.readTemperature());
    //Serial.println(temperature);
    UV_Index = int(ENV.readUVIndex());
    //Serial.println(UV_Index);
    if (digitalRead(2) == LOW) {
      rain = 1;
    } else if (digitalRead(2) == HIGH) {
      rain = 0;
    }
    //Serial.println(rain);
    //Serial.println("Sensor data read.");
    //Serial.println("Start http request.");
    httpRequest();
    //Serial.println("Stop http request");
    delay(60000);
}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the Nina module
  client.stop();

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    //Serial.println("connecting...");
    // send the HTTP PUT request:
    client.print("GET /weather_data.php?temp=");
    client.print(temperature);
    client.print("&pressure=");
    client.print(airPressure);
    client.print("&humidity=");
    client.print(relativeHumidity);
    client.print("&illumination=");
    client.print(lightIntensity);
    client.print("&UV_Index=");
    client.print(UV_Index);
    client.print("&rain=");
    client.print(rain);
    client.print(" ");
    client.println("HTTP/1.1");
    client.println("Host: 192.168.0.29");
    client.println("User-Agent: ArduinoWiFi/1.1");
    client.println("Connection: close");
    client.println();
  } else {
    // if you couldn't make a connection:
    //Serial.println("connection failed");
  }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}


On a direct USB CDC/ACM connection (as you get on the Micro) there is no such thing as baud rate.

Any baud rate setting performed by the host (the PC) is merely an instruction to the device (the Arduino) to say "I would like you to operate at this speed", not "I would like you to communicate with me at this speed".

It is used in situations where the PC may want to set the baud rate of a real UART interface within the device, such as when the ATMega16U2 is used as a USB interface on the Uno - in that case the PC tells the 16U2 that it wants to communicate at, say, 115200 baud, and the 16U2 sets its UART (the one that communicates with the ATMega328P) to 115200 baud. The actual PC to ATMega16U2 (or ATMega32U4 in the case of the Micro) is at the native USB 2 bulk packet rate.

It is also used as a "reset" instruction to the ATMega32U4 - if the CDC/ACM port is opened by the PC at 1200 baud and then immediately closed again the 32U4 resets and enters the bootloader. This makes programming (usually) easy, as long as the program on the chip hasn't crashed and left the USB interface in an unusable condition (as sometimes happens).


Most Arduino platforms contain a very low power embedded processor.  As such it is very unlikely such a device will decode an NTSC or PAL signal let alone modern digitally compressed video.

Instead consider using a light sensor attached to your monitor.  This is more in line with what, for instance, the Arduino Uno is capable of.  If you can identify a spot on the monitor that will only change to a certain brightness at the conclusion of a game, you could look for that brightness level using a light sensor attached to the monitor and connected to an Arduino.

Here is a tutorial about using a light sensor with an Arduino.  Most of the circuit is for the display of which you need not bother with.


How to serially communicate arduino uno to PIC18f4550?

yeah you can quite easily do the Serial communication between Arduino and PIC Microcontroller. You need to connect the below pins:

Arduino TX will be connected to PIC RX.
Arduino RX will be connected to PIC TX.
GND of Arduino must be connected to GND of PIC.

Next thing you need to remember is to have same baud rate for both Arduino and PIC. Now you should check these two posts:

Arduino Serial Communication.
PIC Serial Communication

First one is explaining the Serial Communication of Arduino while the second one is Serial Communication of PIC Microcontroller. You should also read What is Serial Port? to get more idea about Serial communication.

I hope they will help you out. If you still got into some issues then let me know.


It looks like you need to enable the pull-up resistor on D2.  As written D2 is left floating and most likely is a low voltage relative to ground.  Enabling the pull up resistor will force the pin high until you flip the switch.


Best strategy to parse 5 byte arrays to find a pattern

This is really a pure programming problem rather than an Arduino one, but to get you started, you could do a table lookup, like this:
#include <stdio.h>
#include <string.h>

// number of items in an array
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

unsigned char patterns [] [5] =
  {

    { 0x7F, 0x08, 0x08, 0x08, 0x7F },   // H

    // other byte patterns here

  };  // end of patterns

char patterns_converted [] =
  {

  'H',

  // other letter equivalents here

  };  // end of patterns_converted

char convert_pattern (unsigned char what [5])
  {
  for (int i = 0; i < ARRAY_SIZE (patterns_converted); i++)
    if (memcmp (what, patterns [i], 5) == 0)
      return patterns_converted [i];

  return '?';

  } // end of convert_pattern

int main ()
{

  unsigned char test1 [5] = { 0x7F, 0x08, 0x08, 0x08, 0x7F };
  unsigned char test2 [5] = { 0xAA, 0xBB, 0xCC, 0xDD, 0xEE };  // won't be found

  char x = convert_pattern (test1);

  printf ("Result for test1 is %c\n", x);

  x = convert_pattern (test2);

  printf ("Result for test2 is %c\n", x);

}

You would find out all your bit patterns and put them in the patterns array, and then put the equivalent letter in the patterns_converted array.
The function convert_pattern does a linear search of the table of patterns, returning the corresponding letter, or "?" if not found.
I coded that in pure C++, but since the Arduino IDE basically uses C++ you should be able to convert it for your use.


Remove blocking delay() toneMelody function?

Define  global vars befor setup()

unsigned long timeStamp = 0;
bool pauseOn = false;

and use it

void speelMelodie(int melodie) {

  if (melodie == 1) {

    for (int thisNote = 0; thisNote < 8; thisNote++) {

      int noteDuration = 1000 / noteDurations1[thisNote];
      if (millis() - timeStamp < noteDuration && pauseOn == false) {
         tone(speaker, melody1[thisNote], noteDuration);
      } else { // reset value and change pauseOn to true
        pauseOn = true;
        timeStamp = millis();
      }
      int pauseBetweenNotes = noteDuration * 1.30;

      //delay(pauseBetweenNotes); // <-- this one has to be changed
      if (millis() - timeStamp < pauseBetweenNotes && pauseOn == true) {
          noTone(speaker);
      } else {
         pauseOn = false;
         timeStamp = millis();
      }
    }
  }
}

We need the state variable pauseOn to differentiate between the two states play note or silence. The code compiles, but you have to finetune in your program.A final tip Tutorials using delay() other than

for debuging or
in setup for initializing hardware

are of very low quality
-> Its like a blind person talking about color composition.


Can the Leonardo Arduino be used as a USB HOST for CDC Com devices?

No, the Leonardo cannot be a USB Host. You may be able to use a USB Host Shield in conjunction with the Leonardo, though I have never tried it and cannot vouch for compatibility with the Leonardo.

USB is a host->device protocol, not a peer-to-peer protocol. You cannot just connect two devices together. Only a USB Host can communicate with a USB device.


Arduino Standalone - photo shows incorrect pin wired to MOSI

I have programmed AVR microcontrollers for a while. I would follow the datasheet, instead of the guide you have.

The Atmega168 Pin Mapping shows SS on 16, MOSI 17, MISO 18, SCK 19 and you will also need to connect to RST 1


Hardware logic gates for a simple demo with LEDs

The SN74HC04 has a documented output driver capability of ±4 mA when running at 5V:

Assuming you are using red LEDs with a forward voltage of 1.6V (as I measured one of mine lying around on the bench to be), then to not exceed this you need to get a resistor of:

(5 - 1.6) / 0.004 = 850 Ω

A reasonable (and safer) value would be a standard 1k resistor, which you are likely to have lying around (and if not, get a few hundred of them). That would give you 3.4 mA current through the output pin, which is in range.

  I found something very similar to my demo on YouTube ...

Yes, well, people on YouTube aren't always doing things exactly like they should. :)

See Mike Cook's tutorial The care and feeding of LEDs. As he points out, a lot of people use the wrong, or no, resistors because "it seems to work".

It may well seem to work for a while, but if you want a design that will last for a long time, you work within the manufacturer's specifications.

The problem with people disseminating wrong information is that someone will then copy it, and repeat it, and before long you find people saying "everyone does it this way".


dB is volume (sound pressure), frequency is pitch. The two are entirely different concepts and can't be converted. A bit like you can't convert the roundness of a doughnut into blue. Roundness and blueness (it has blueberries in it by the way) are two different properties of the doughnut.


Possible arduino burned (5V shorted to Vin), explanations and suggestions

If you have another Uno then your best bet is either:

1) Swap the suspect processor into the known good board, test it.

2) to buy a replacement chip (ATMega 328-PU), use this link to flash it, if it works you win, if not you can at least use the new processor again.

I have done this myself & it worked well, it isn't easy to be sure any other way as the chip needn't fail in a predictable manner. The chances are it will take a large current if it's dead, until it burns out & goes open circuit. Once the magic smoke has come out you know it's dead... the Arduino power supply is reasonably capable of looking after itself so your chances are good.


Need a proper diagram to connect my multiple relays (more than 8) with only a few pins on Arduino Uno Board

If you want to drive a normal magnetic relay you will need to add a transistor / resistor to the output of the 74HC595 as the current is too high across the magnet of the relay to be driven directly by the 74HC595. If you don't want to use a transistor for every relay, you could you an 8 channel driver chip like the ULN2803A. You should be able to connect your relay coil directly from 12v and to the ULN2803A.

Have a look at this page for an example. http://www.mcmajan.com/mcmajanwpr/blog/2014/04/18/arduino-how-to-connect-many-12v-relays-en/


Connect the Nano ground to the driver board ground.  Since they do not share a common ground, they can have odd behavior as their ground planes float.

You need only connect the grounds, the USB can still provide +5 to the Nano, and the +9 can still provide power to the driver.  The only energy that will flow through the black wire connecting the grounds is the energy that flows between pins 2,3,4,5 and the driver's AIA, AIB, BIA, BIB, for the logic signals, which I'd bet is in the sub-uA range.


What are the FLASH_ARRAY/FLASH_TABLE macros in this code?

After further digging, this appears to be from Mikal Hart's Flash library.
The reason this library was developed is:

Storing static program data in flash/PROGMEM is a tricky part of
Arduino programming. To save precious RAM, a novice user already at
odds with unfamiliar C++ syntax must digest such daunting concepts as
prog_char, PSTR(), PROGMEM, pgm_read_word(), etc. Even seasoned users
get tripped up by the indirection and typecasting that are required to
retrieve valid PROGMEM data. Add to that a couple of apparent bugs in
the implementation, and it’s clear that PROGMEM is a complicated mess.
I have written a new library, Flash, which abstracts away most of this
complexity. It provides new String, Array, Table, and String Array
types that make ROM-based data collections as easy to use as “normal”
types. Each overrides the C++ [] operator, so to extract individual
elements one uses familiar array access syntax:

Specifically, these are macros and a simple helper class to make it easier to create arrays and tables of values in program memory.
The two macros are declared as so:
// Example: FLASH_ARRAY(float, temperatures, 98.1, 98.5, 99.1, 102.1);
#define FLASH_ARRAY(type, name, values...) \
  static const type name##_flash[] PROGMEM = { values }; \
  _FLASH_ARRAY<type> name(name##_flash, sizeof(name##_flash) / sizeof(type));

// Example: FLASH_TABLE(uint8_t, fonts, 7, {ON, OFF, ON, ON, OFF, ON, OFF}, {OFF, ON, OFF, ON, OFF, ON, OFF});
#define FLASH_TABLE(type, name, cols, values...) \
  static const type name##_flash[][cols] PROGMEM = { values }; \
  _FLASH_TABLE<type> name((const PROGMEM type *)name##_flash, sizeof(name##_flash) / sizeof(name##_flash[0]), cols);

The helper functions include size and override the operator [] so that they can easily be accessed like so
FLASH_ARRAY[0]

I disagree with zmo - this is more than boilerplate. The area of PROGMEM causes a lot of questions from Arduino users, and it is very easy to do things wrong when creating arrays in PROGMEM.


Networking Multiple Arduinos -- Is It "Rocket Science?"

The best solution would be to use an RS485 adapter connected to each Arduino via serial port. This is a tried and true solution that is perfect for a setup like this and only costs a few bucks of extra hardware per node.
If you can't use additional hardware, you can also create a poor-man's current loop system like RS485 using normal Arduino pins since they are capable of sourcing and sinking 20mA.
With either of these solutions, you can send however much data as you want as long as you have some kind of minimal protocol to serialize it into a sequence of bits on the wire. To send 12 bits, you might just define a start condition as an idle "0" on the wire for a certain period of time, followed by a "1" start bit, followed by you 12 data bits, followed  maybe a parity bit or a checksum, and completed by a "1" stop bit.
Check out how, say RS232 or RS485 serialize bits to get an idea of how this works. If you end up using hardware that only supports sending data in 8 bit chunks, then you could, say, send two bytes per data "packet" where each byte has 6 bits of your data, plus one bit that indicates if ths byte is the first group of 6 bits or the second group, and then one bit of parity for error checking.


This answer covers: Which Arduinos support ATOMIC_BLOCK? And how can I duplicate this concept in C with __attribute__((__cleanup__(func_to_call_when_x_exits_scope))) and in C++ with class constructors and destructors?.
Which Arduino's support the ATOMIC_BLOCK macros?

Which Arduinos support ATOMIC_BLOCK?

Only AVR (ATmel AVR architecture) microcontrollers support the ATOMIC_BLOCK macros, because these macros are part of the avr-libc library, which, you guessed it!, supports only AVR microcontrollers.
AVR-based Arduinos include those based on the ATmega328 microcontroller (Arduino Uno, Nano, Mini, etc.), ATmega2560 (Arduino Mega 2560), ATmega32U4 (Arduino Leonardo, Pro Micro), etc.
How are the ATOMIC_BLOCK macros implemented in C with the gcc compiler, and where can I see their source code?
avr-libc is available for download here: https://www.nongnu.org/avr-libc/ --> "source code and documentation" link under the "Downloads" section. Ex: here is the tarball for v 2.0.0: http://download.savannah.gnu.org/releases/avr-libc/avr-libc-2.0.0.tar.bz2.
The entire source code for the ATOMIC_BLOCK macros is contained in avr-libc-2.0.0/include/util/atomic.h.
ATOMIC_BLOCK is an ingenious macro written in C and relying upon the gcc "cleanup" attribute C extension which can call a function you define when a variable goes out of scope. Essentially, this is identical to a C++ class destructor which gets called when an instance of a class in C++ goes out of scope. The gcc "cleanup" attribute extension is a way to get C++-like behavior in C.
Here is the official gcc documentation: https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html. It states:

cleanup (cleanup_function)
The cleanup attribute runs a function when the variable goes out of scope. This attribute can only be applied to auto function scope variables; it may not be applied to parameters or variables with static storage duration. The function must take one parameter, a pointer to a type compatible with the variable. The return value of the function (if any) is ignored.
If -fexceptions is enabled, then cleanup_function is run during the stack unwinding that happens during the processing of the exception. Note that the cleanup attribute does not allow the exception to be caught, only to perform an action. It is undefined what happens if cleanup_function does not return normally.

Its format is like this:
int x __attribute__((__cleanup__(func_to_call_when_x_exits_scope))) = 0;

You use it like this:
RUN A REAL EXAMPLE OF THIS CODE IN C ONLINE HERE.
static __inline__ void cleanup_my_byte(uint8_t *my_byte_p)
{
    Serial.print("my_byte is going out of scope! Its value is ");
    Serial.println(*my_byte_p);
}

void setup()
{
    uint8_t my_byte __attribute__((__cleanup__(cleanup_my_byte))) = 7;
} // The following function call occurs automatically here as `my_byte`
  // exits its scope!:
  //    `cleanup_my_byte(&my_byte);`

Studying the avr-libc-2.0.0/include/util/atomic.h file referenced above, you can see how the ATOMIC_RESTORESTATE macro is implemented, using this attribute. I've put just the relevant pieces from that file here:
#include <avr/io.h>
#include <avr/interrupt.h>

#define ATOMIC_BLOCK(type) for ( type, __ToDo = __iCliRetVal(); \
                           __ToDo ; __ToDo = 0 )

static __inline__ uint8_t __iCliRetVal(void)
{
    cli();
    return 1;
}

#define ATOMIC_RESTORESTATE uint8_t sreg_save \
    __attribute__((__cleanup__(__iRestore))) = SREG

static __inline__ void __iRestore(const  uint8_t *__s)
{
    SREG = *__s;
    __asm__ volatile ("" ::: "memory");
}

Note that cli() clears (turns off) interrupts, and sei() sets (turns on) interrupts.
So, you can see that ATOMIC_RESTORE_STATE gets replaced by uint8_t sreg_save __attribute__((__cleanup__(__iRestore))) = SREG, which backs up the global interrupt state from the AVR SREG 8-bit register into sreg_save, then calls this function call when sreg_save exits its scope: __iRestore(&sreg_save);. That function call to __iRestore() then sets the SREG register back to where it was, restoring the interrupt state (turning it ON if it was ON before, or OFF if it was OFF before).
The official documentation for ATOMIC_BLOCK is here: https://www.nongnu.org/avr-libc/user-manual/group__util__atomic.html. An example usage is this:
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
    my_var_copy = my_var;
}

The ATOMIC_RESTORESTATE part backs up the SREG register and sets up the call for __iRestore(&sreg_save); to occur when sreg_save exits this block scope, as we've already discussed, and the ATOMIC_BLOCK part gets converted into this: for ( ATOMIC_RESTORESTATE, __ToDo = __iCliRetVal(); __ToDo ; __ToDo = 0 ). This means that the entire block is now an ingenious for loop which runs only once! Prior to entering the for loop block, __iCliRetVal() is called once, clearing (turning OFF) interrupts, and __ToDo is set to 1, or true, so the for loop runs at least once, and then at the end of the first run it is set to 0, or false, to stop the for loop after one single run! As we've already gone over, the sreg_save variable now goes out-of-scope at the closing brace and the call to __iRestore(&sreg_save); is made, via the gcc extension, to restore the interrupt state! Ingenious!
How could you implement the ATOMIC_BLOCK functionality in Arduino in C++ (as opposed to avrlibc's gcc C version)?
In C++ (Arduino is C++, so we don't have to be limited to just C plus gcc extensions, as was the constraint in the avrlibc ATOMIC_BLOCK macros), you can get a similar effect using destructors in structs or classes (or, just use the avrlibc pattern shown above if you like, as that gcc C code is also perfectly valid gcc C++ code!).
Option 1: example to create a usage style similar to C++'s std::lock_guard
This, for example, would implement a form of ATOMIC_BLOCK(ATOMIC_FORCEON) {}, using a simple class in C++:
It relies on Arduino's built-in functions interrupts() (same as avrlibc's sei() function) and noInterrupts() (same as avrlibc's cli() function). I wish that Arduino also had built-in saveInterrupts() and restoreInterrupts() functions, but unfortunatley they don't. Someone will have to go file a feature request and request them, or implement them themselves and do a Pull Request (PR) on GitHub to try to get them back into the main Arduino branches.
RUN A REAL EXAMPLE OF THIS CODE IN C++17 ONLINE HERE.
#define ATOMIC_BLOCK_FORCEON AtomicBlockForceOn atomicBlockForceOn_

class AtomicBlockForceOn
{
public:
    // Constructor: called when the object is created
    inline AtomicBlockForceOn()
    {
        noInterrupts(); // turn interrupts OFF
    }

    // Destructor: called when the object is destroyed (ex: goes
    // out-of-scope)
    inline ~AtomicBlockForceOn()
    {
        interrupts(); // turn interrupts ON
    }
};

That's it! Now use it like this:
uint16_t my_var_copy;
{
    ATOMIC_BLOCK_FORCEON;
    // now do whatever you want here, with interrupts disabled; ex:
    my_var_copy = my_var;
} // the `atomicBlockForceOn_` object's destructor is called here
  // and interrupts are automatically turned back ON!

Pretty cool!
This, I imagine, is probably exactly how C++'s std::lock_guard is implemented! Its usage is very similar:
void safe_increment()
{
    const std::lock_guard<std::mutex> lock(g_i_mutex);
    ++g_i;

    std::cout << std::this_thread::get_id() << ": " << g_i << '\n';

    // g_i_mutex is automatically released when lock
    // goes out of scope
}

Option 2: example to create a usage style similar to avrlibc's ATOMIC_BLOCK macros
To obtain a usage style of ATOMIC_BLOCK(ATOMIC_FORCEON) { } in C++ one can definitely use the gcc C style which avrlibc uses, since that is also valid C++, but let's continue with the C++ class style shown just above instead, with just a few tweaks. We will add a couple more helper macros and a couple more functions to the class to make this work. Here it is, with a usage example shown at the end which is identical to how avrlibc's ATOMIC_BLOCK can be used! I think this is pretty cool too.
RUN A REAL EXAMPLE OF THIS CODE IN C++17 ONLINE HERE.
#define ATOMIC_BLOCK(type) for(type; type##_OBJECT_NAME.run(); \
    type##_OBJECT_NAME.stop())
#define ATOMIC_FORCEON_OBJECT_NAME atomicBlockForceOn_
#define ATOMIC_FORCEON AtomicBlockForceOn ATOMIC_FORCEON_OBJECT_NAME

class AtomicBlockForceOn
{
public:
    // Constructor: called when the object is created
    inline AtomicBlockForceOn()
    {
        noInterrupts(); // turn interrupts OFF
    }

    // Destructor: called when the object is destroyed (ex: goes
    // out-of-scope)
    inline ~AtomicBlockForceOn()
    {
        interrupts(); // turn interrupts ON
    }

    // Can we run? Returns true to run the `for` loop or
    // `false` to stop it.
    inline bool run()
    {
        return run_now;
    }

    // Tell the `for` loop to stop
    inline void stop()
    {
        run_now = false;
    }

private:
    bool run_now = true;
};

Use it like avrlibc's ATOMIC_BLOCK() { } macro!
Usage example:
uint16_t my_var_copy;
ATOMIC_BLOCK(ATOMIC_FORCEON)
{
    // now do whatever you want here, with interrupts disabled; ex:
    my_var_copy = my_var;
} // the `ATOMIC_FORCEON_OBJECT_NAME` (`atomicBlockForceOn_`) object's
  // destructor is called here and interrupts are automatically
  // turned back ON!

Further reading:

Nick Gammon's excellent "Interrupts" page, which is how I first got started learning about interrupts in 2012~2014 or so: https://gammon.com.au/interrupts.
Other answer's I've done about interrupts, locks/guards, and things:

global volatile variable not being updated in ISR
My own race condition problem: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why
My own race condition solution, demonstrating 3 (or 4, depending on how you look at it) ways to enforce "atomic access guards" on AVR-based 8-bit Arduinos: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why/39693278#39693278

What's that weird type##_OBJECT_NAME thing I did in the macro anyway? Read more about macro token concatenation using the ## preprocessor operator in the official gcc C++ user manual here: https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html. Note: this also works in C of course.
gcc inline or __inline__, and static inline or static __inline__ rules:
https://gcc.gnu.org/onlinedocs/gcc/Inline.html


Can someone recommend a complete guide for learning Arduino?

Arduino Cookbook (I have 2nd edition) is worth its price in paperback. PDF/etc formats are available. Children like to dig in without deep theoretical preparations. IIRC it covers classes briefly, as well as bitmath. A nice book.

Boxall’s book is better still. A link: https://m.barnesandnoble.com/w/arduino-workshop-john-boxall/1114672111?ean=9781593274481

You don’t really need to do much except give the kids a laptop with no games on it, and a few arduino clones. Just lock the door to their room with a default-closed solenoid connected to an H-bridge. They’ll learn quickly.


What is the necessity of “Prototyping Shield” for an arduino UNO R3?

The prototyping shield can be used to build your own circuits up in a more permanent form which can be plugged direct into the Arduino.

You can think of it as a blank canvass on which you can paint your own shield design.


How to ground a arduino with an external power-source?

Ground is usually (though not always, but in your case it is) the point of lowest potential in a circuit. In your circuit that is the "negative" connection of the power supply. Note that the "negative" isn't actually "negative", it is zero volts when measured from the reference point of itself.

So yes, you need to know which is the "negative" connection and connect that to ground on the Arduino.

Since you already have it wired up the negative is the one which connects to the emitter of your transistor. If you don't know which that is and you just randomly connected a random wire to a random pin then you need to investigate your power supply.

The simplest way is with a Digital MultiMeter (one of the most basic items you need to own if you are working with electronics - if you don't have one then go and buy one immediately). Set it to DC Volts in the right range then connect the two probes (correctly inserted into the right sockets on the DMM) to the power supply's output connections. If the voltage reads positive then the black probe is connected to negative. If it reads a negative value then the red probe is connected to negative.

If you cannot get a DMM but you have an LED (note: a bulb will not work) and a suitable resistor (say 2.2K) you can connect the resistor in series with the LED then connect the two to the power supply. The cathode of the LED (the pin with the flat side on the case) connects to negative. Connect the power both ways round. The way round that it lights the LED is the correct way round, and you know that the connection that goes to the cathode (flat side of the lip round the bottom of the LED) is the negative.


Which reflectance sensor array for a line following robot?

The main difference between the two models, as stated in the PDF you provided, is the output they provide to the MCU.

The QTR-8A will provide an Analog output, requiring a corresponding analog pin on the microcontroller. The QTR-8RC will provide a Digital output, but will allow the same accuracy of the QTA-8A by measuring the discharge time of the capacitor (HIGH to LOW time), with the advantage of higher accuracy due to the use of RC circuit instead of a voltage divider.

Both seems pretty straight forward, but for your needs, the QTR-8RC might seem more compatible, considering the Arduino Uno has 6 analog I/O pins (you didn't mention which Arduino is going to be used, the Arduino Nano has 8 and the Arduino Mega has 16), and that the QTR sensor provides 8 outputs. The way you could accomplish that with QTR-8RC and 8 digital I/O pins is described in the PDF:

  Turn on IR LEDs (optional)
  Set the I/O line to an output and drive it high
  Allow at least 10 us for the 10 nF capacitor to charge
  Make the I/O line an input (high impedance)
  Measure the time for the capacitor to discharge by waiting for the I/O line to go low
  Turn off IR LEDs (optional)


Measuring the speed of an object moving fast through air

You are proposing calculating velocity based on sampled acceleration.  Essentially taking the integral of the acceleration.  This is the first step in a process call dead reckoning. This is discussed in this arduino.stackexchange.com answer.  In that answer there is a link to a web page which implements dead reckoning using an Arduino. You will find this equation on that web page:

velocity(i) = velocity(i-1) + acceleration (i)


Changing the mode when pressing/holding down a buttton

Ok, I'll try to split the code into multiple sections for clarity, but all this goes into one single sketch.

First we define the PINs: defines are pre-processor macros, even better than const in terms of performance and space consumption:

#define BTN_PIN 2
#define LED_PIN 13

Let's initialize the board as per our requirements:

void setup() {
  pinMode(BTN_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
}

Now we define the code which emits and SOS signal in morse code using the standard timing:

a long pulse lasts 3 times a short one
a space lasts 6 times a short pulse

That boils down to the following definitions considering a standard unit of 300ms:

#define UNIT 300
#define SHORT (UNIT)
#define LONG (UNIT*3)
#define PAUSE (UNIT*3)
#define SPACE (UNIT*6)

I'm also going to define another macro to emit a generic light pulse, for simplicity I'll use the delay(...) function, but this will prevent detecting button presses while signalling:

#define PULSE(TYPE) digitalWrite(LED_PIN, HIGH);delay(TYPE); digitalWrite(LED_PIN, LOW);delay(UNIT)

With the above in place we can define a function to send an SOS which should be both very compact and also readable:

void sendSOS() {
  PULSE(SHORT);PULSE(SHORT);PULSE(SHORT);
  PULSE(PAUSE); // inter letter pause
  PULSE(LONG);PULSE(LONG);PULSE(LONG);
  PULSE(PAUSE); // inter letter pause
  PULSE(SHORT);PULSE(SHORT);PULSE(SHORT);
}

Now, let's describe what the mode changing should be notified to the user:

#define QUICK 100
bool autoMode = true;

void switchMode() {
  autoMode= !autoMode;
  for (unsigned int i = 0; i < 25; i++) {
    digitalWrite(LED_PIN, HIGH);
    delay(QUICK);
    digitalWrite(LED_PIN, LOW);
    delay(QUICK);
  }
}

Now our main loop will have to check the button and act accordingly, right?

#define LONGPRESS 500
unsigned long elapsed;
bool clicked = false;
unsigned long duration;

void loop() {
  if (autoMode) {
    sendSOS();
  }
  elapsed = millis();
  while(clicked || millis() - elapsed <= SPACE) {
    // keep waiting to emit a SPACE or until the button is released

    if (digitalRead(BTN_PIN)) {
      // button has been clicked: trace it and start counting time
      clicked = true;
      duration = millis();
    } else if (clicked) {
      // button has been released: stop tracing and verify click duration
      clicked = false;
      if (millis() - duration <= LONGPRESS) {
        // switch mode on long press
        switchMode();
      } else if (!autoMode) {
        // short press has a meaning only when not in auto mode
        sendSOS();
      }
    }
  }

The solution above has great space for improvement:

there is no de-bouncing on the button
the board is unresponsive while signalling
keeping the button pressed forever will prevent any signalling to occur in any mode
the code is afflicted by millis() rollover if you keep the button pressed for long periods (around 49 days)

UPDATE: I've added the inter-letter pause as suggested in the comments.

UPDATE: apparently auto is a reserved word, so I changed it to autoMode.


Arduino piezo-buzzer melody for car alarm

I think what you're really asking for is a library of sounds (in the form of code), rather than a code library in the normal sense.  I'd like such a thing too (specifically a retro-gaming style laser noise), but extensive googling hasn't found anything, though someone has made a sketch of the Tetris theme.
A car alarm is probably fairly easy - a couple of for loops changing the frequency of a tone(); My Arduino and piezo buzzer are at home but playing that YouTube and using a spectrum analyser app on my phone it looks like (using the waterfall display mode):

The first alarm is looping from 1000Hz to 2200Hz over about 250ms, then back down again.  - The next 2 are falling tones, from 1kHz down to about 500 over 250 or 500ms.
Then we've got a rising tone 500 Hz to 1kHz  over 2s
A beep at about 2.2kHz, 250ms on/off
A two-tone siren at 1 and 1.5kHz, 1s of each.

Times and frequencies were indeed a little off, and many of the frequency ramps aren't linear, but here's something to play with.  The more interesting alarms are in there, along with a couple of laser zaps.  The square-wave drive of a piezo (leading to interesting harmonics), and the complete lack of a low frequency response (nothing below about a few hundred Hz on the one I have here) limit things a little, but it compares well to a Lego siren I have
int beep_pin=10;
int gap=1000;

void setup() {
  // put your setup code here, to run once:
  pinMode(beep_pin, OUTPUT);
}

void zap1()
{
    for (float f=3000;f>40;f=f*0.93){
    tone(beep_pin,f);
    delay(10);
  }
}

void zap2()
{
    for (float f=3000;f>10;f=f*0.85){
    tone(beep_pin,2*f);
    delay(5);
    tone(beep_pin,f);
    delay(5);
  }
}
void risefall()
{
  float rise_fall_time=180;
  int steps=50;
  float f_max=2600;
  float f_min=1000;
  float delay_time=rise_fall_time/steps;
  float step_size=(f_max-f_min)/steps;
  for (float f =f_min;f<f_max;f+=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
   for (float f =f_max;f>f_min;f-=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
}
void fall(float rise_fall_time)
{
  int steps=50;
  float f_max=2000;
  float f_min=500;
  float delay_time=rise_fall_time/steps;
  float step_size=0.97;
  for (float f =f_max;f>f_min;f*=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
}
void rise()
{
  float rise_fall_time=2000;
  int steps=100;
  float f_max=1500;
  float f_min=500;
  float delay_time=rise_fall_time/steps;
  float step_size=1.012;
  for (float f =f_min;f<f_max;f*=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
  noTone(beep_pin);
  delay(100);

}

void twotone()
{
  float f_max=1500;
  float f_min=1000;
  float delay_time=800;
  tone(beep_pin,f_max);
  delay(delay_time);
  tone(beep_pin,f_min);
  delay(delay_time);

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

  for (int count=1;count<=10;count++)
  {
    risefall();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<=10;count++)
  {
    fall(300);
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<=5;count++)
  {
    fall(600);
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<5;count++)
  {
    rise();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<5;count++)
  {
    twotone();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<10;count++)
  {
    zap1();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<10;count++)
  {
    zap2();
  }
  noTone(beep_pin);
  delay(gap);
}

It's also on GitHub, and released into the public domain under the unlicense so anyone can use it however they like


Using digital pins 0/1 on Arduino Due when writing/reading over serialUSB port

Yes, you can use 0/1 while using the native USB. The two are completely separate.


Why I'm getting this error: invalid conversion from 'const char*' to 'char' [-fpermissive]?

const char data = "should";

In this case data is a single character, not a string. So it can store 's' but not "should".

Serial.print("this " + data + " work");

No, that will never work, even if you get your data types correct.  You do not concatenate strings like that. All you are doing is attempting to add the addresses of two string literals to the address of a string constant. If that were possible (the  compiler doesn't let  you) you'll get gibberish (or a crash) as it tries to print out whatever is at that address.

Instead break it down:

Serial.print("this ");
Serial.print(should);
Serial.print(" work");


Button and twist knob to send keystroke to PC

As a novice, I would like to create a small breadboard with 5 items on it. 3 toggle buttons, and two constant spin (ie. no stop at 360 degrees) knobs.

Those knobs are called "Rotary Encoders".

Is then like the bottoms to send what ever key stroke (single key pee click) to the pc as if it was from a keyboard (maybe even a shift+key?)

Then you really want an Arduino with a "native" USB connection, like the Leonardo or Micro.

Can anyone guide me in the right direction? Would I need 3rd party software to convert signals to keystrokes on the pc?

Not with a Micro or Leonardo - you just use the Keyboard.h library.  If you want to use your Nano then yes, you can only talk serial, and you will have to have some third party software that interprets serial commands and injects keyboard signals into your OS.  I think there's some Python projects around that do that kind of thing. Or there is "professional" software, like 232key that can do it for you.


This is wrong:

if(digitalRead(k1 == LOW)

You mean:

if(digitalRead(k1) == LOW

Ditto for a lot of other places in your code.


What would the total current requirements be for these items?

According to the data sheet each LED takes a maximum of 3*20mA, so you are pulling 300mA.  You  are going to need a bigger power supply :(


While using Arduino Ethernet shield, do we need to explicitly select/Deselect SD and W5100 in our code?

Here we have a nice example of a single Shield requiring TWO libraries. The Ethernet.h and SD.h where the later appears as an after thought and is not demonstrated by the Example. As it is done so in the SD examples. However, their styles are slightly different.

The Ethernet libary as mentioned (provided within) the IDE is hardcoded to implement the Chip Select for the W5100 on corresponding pin. When using the typical purchased Ethernet Shield, there is no need to configure it. Unlike the SD library, which requires the pin to configured using the SD.begin(4) member function.

if (!SD.begin(4)) {
  Serial.println("initialization failed!");
  return;
}

Where again on the typical Ethernet shield the SD card is at pin D4.

Note being hardcode that the Ethernet library selects the matching pin to corresponding shield.

private:
#if defined(ARDUINO_ARCH_AVR)
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  inline static void initSS()    { DDRB  |=  _BV(4); };
  inline static void setSS()     { PORTB &= ~_BV(4); };
  inline static void resetSS()   { PORTB |=  _BV(4); };
#elif defined(__AVR_ATmega32U4__)
  inline static void initSS()    { DDRB  |=  _BV(6); };
  inline static void setSS()     { PORTB &= ~_BV(6); };
  inline static void resetSS()   { PORTB |=  _BV(6); };
#elif defined(__AVR_AT90USB1286__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB162__)
  inline static void initSS()    { DDRB  |=  _BV(0); };
  inline static void setSS()     { PORTB &= ~_BV(0); };
  inline static void resetSS()   { PORTB |=  _BV(0); };
#else
  inline static void initSS()    { DDRB  |=  _BV(2); };
  inline static void setSS()     { PORTB &= ~_BV(2); };
  inline static void resetSS()   { PORTB |=  _BV(2); };
#endif
#endif // ARDUINO_ARCH_AVR

And in the case of the UNO (or the else case) Port B Bit 2 is D10.

worth noting that SD library has an alternate method of initializing and using the SD card

if (!card.init(SPI_HALF_SPEED, chipSelect)) {
  Serial.println("initialization failed. Things to check:");

where chipSelect would be D10 in this case.


Does direct port access interfere with PWM?

A timer interrupt will be periodically toggling the PWM bit and might do so between your port read and port write.

The easy solution is to turn off interrupts during the read/modify/write portion of your port update sequence. This could cause a stretched PWM cycle. If you don't turn it off, you'd just glitch the PWM - creating an extra, short cycle. Which one is worse for your PWM recipient?

A better solution might be to to watch the port for the PWM bit to change, then jump in right afterward and make your port update. You could do his in either a blocking or a non-blocking manner.

Update:

  Watching the PWM bits seems as if it would be fairly slow, which
  somewhat defeats the purpose of the direct port writes.

Yes, it's less than ideal. There's a tradeoff here. Can your PWM consumer tolerate the potential occasional glitch, instead?

To be complete, there are a number of motivations to use direct I/O:

Smaller code;
Less I/O skew with multiple I/Os, or zero skew if the I/Os are in the same port;
Less execution time on a time-critical path;
Precise output timing;

among others. Those software solutions won't help much in any of those cases.

Can you reassign your output to another pin on a different port, avoiding the whole problem? That might be better than any of the "solutions". Adding hardware might accomplish the same thing - perhaps moving just the PWM to an ATtiny, for example.

Update 2:

  This seems so baked into the structure of the Arduino... does
  digitalWrite() itself actually overcome this?

It "addresses" it - overcomes it? As is so often the case, "that depends".

Here is the the source-code to digitalWrite() from: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino /wiring_digital.c (on a Mac; the top-level folder or two will be different on Windows):

void digitalWrite(uint8_t pin, uint8_t val)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    volatile uint8_t *out;

    if (port == NOT_A_PIN) return;

    // If the pin that support PWM output, we need to turn it off
    // before doing a digital write.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    out = portOutputRegister(port);

    uint8_t oldSREG = SREG;
    cli();

    if (val == LOW) {
        *out &= ~bit;
    } else {
        *out |= bit;
    }

    SREG = oldSREG;
}

Notice that the interrupts are saved and restored around the read/modify/write of the port register. So digitalWrite() already addresses the possibility. This method will stretch one phase of an occasional PWM pulse by a few microseconds.

Alternatively, ignoring the possibility of a collision and having one occur, seems more severe: the pulse could be begun or ended prematurely. This occurrence will take longer - the rest of the disturbed phase - to get back in sync.

So the criterion for how to manage x becomes "Which way has the lesser - or more tolerable - consequence for your PWM consumer?"


I am now having Screen output to log.txt, and the following applescript works just great!

set trigger to 1

set stopString to ""

repeat until (stopString = "stop")

set testTxt to paragraphs of (read POSIX file "/Users/fed/log.txt")
set countTxt to (count of testTxt) - 1
set lastLine to item countTxt of testTxt
if lastLine contains "Start MP3" and trigger is 1 then
    tell application "Spotify" to playpause
    set trigger to 0
end if

if lastLine does not contain "Start MP3" then
    set trigger to 1
end if

if lastLine contains "Stop Loop" then
    set stopString to "stop"
end if
end repeat


Using a 4*4 keypad to enter an integer value

You can easily read by this line of code

value = anyDigitFromKeypad - 48

e.g value = "3"-48 = 3


for the basic function of uploading a sketch your board schematics is indeed correct and going to work.
I can't say much on the PCB as what you have posted is a partial design, in particular it doesn't show the solder mask expansion and other details which might greatly influence the final result.

Please also note you don't need a reset button, a voltage regulator nor an external oscillator for the basic function of uploading a sketch, but I believe you also want to have the ability to run the sketch without the programmer being attached...


Unpredictable behavior on parsing key-value delimited input from serial

Welcome to the I forgot to empty my buffer char club (I lost some days finding a simlar problem)

 strcpy(temp_chars, received_chars)  // strcpy empties temp_chars and adds the received_chars

but you have no (for me) visible routine to empty received_chars
Do this either by setting

received_chars[0] ='\0'; // set the pointer to first index

or

 received_chars ="0";

or

strcpy(received_chars,"0");

after you used the buffer content. By using

static byte ndx = 0;

you just set the pointer and then start to write, as a safequard you should first reset the end terminator and then start to write. This is probably the reason you see characters even if no key is pressed due to a still "full" charbuffer.To prevent heap corruption define your received_chars as a fixed arraybefore setup:

char received_chars[128] ={'\0'}; // 127 chars + terminator

if you use malloc you have to use free, but doing that with a lot of dynamic data causes heap fracturing -> crash in the end

EDIT
The program does now the following

ignores all char not enclosed by <>
check for text and displays everything after = and before;
ignores everything after ; if its not text= again
if its text= again ignores the first and only displays the second param

You do not need strtok here as it deletes chars I use a modified substring routne for char arrays.
Here is the code working as described above:

// command indicators
const char START_MARKER = '<';
const char END_MARKER = '>';

const uint8_t MAX_KEY_VALUE_PAIRS = 3;  // maximum number of key-value pairs in message
const uint8_t MAX_ELEMENT_CHARS = 25;  // the maximum number of characters (+1 for terminator) in a key or a value

// message format: <key1=value1;key2=value2;key3=value3>
const uint8_t MAX_MESSAGE_CHARS = (MAX_KEY_VALUE_PAIRS * (MAX_ELEMENT_CHARS + 1)) * 2 + (MAX_KEY_VALUE_PAIRS - 1) + 2;  // maximum message size

//char received_chars[MAX_MESSAGE_CHARS] = {'\0'};// <- EDIT#1
char received_chars[256] = {'\0'};
bool new_data = false;
char text[25] =  {'\0'};      // the value identified by the "text" keyword, i.e.: in <text=abc;time=814a>, text would be abc.

void ParseData(char *str) {
  // This picks off the ;-delimited key-value pairs and assigns them to a multi-dim array
  char * pch;
  int pairs_count = 0;
  char config[MAX_KEY_VALUE_PAIRS][2][MAX_ELEMENT_CHARS];

  pch = strtok(str, "=");

  while (pch != NULL)  {
    strcpy(config[pairs_count][0], pch);
    pch = strtok(NULL, ";");
    if (pch == NULL) break;

    strcpy(config[pairs_count][1], pch);
    pairs_count++;
    pch = strtok(NULL, "=");
    if (pch == NULL) break;
  }

  for (uint8_t i = 0; i < pairs_count; i++) {
    if (strcmp(config[i][0], "text") == 0) strcpy (text,config[i][1]);
  }
  Serial.println(text);
}

void ReadSerial() {
  // After calling ReceiveText to empty the buffer, if a complete command has been found,
  // parse that command.
  new_data = ReceiveText();
  if (new_data == true) {
    char temp_chars[MAX_MESSAGE_CHARS];  // temporary array for use when parsing
    strcpy(temp_chars, received_chars);
    received_chars[0] = '\0';  // <- EDIT#2
    ParseData(temp_chars);
  }
}

bool ReceiveText() {
  // This dumps the characters on the buffer so far received_chars, searching for an END_MARKER
  // along the way; if it finds one, it goes back to find a START_MARKER; if that is also found,
  // the string within is the ;-delimited set of key value pairs
  static boolean recv_in_progress = false;
  static byte ndx = 0;
  char rc;

  bool new_data = false;
  while (Serial.available() > 0 && new_data == false) {
    rc = Serial.read();

    if (recv_in_progress == true) {
      if (rc != END_MARKER) {
        received_chars[ndx] = rc;
        ndx++;
        if (ndx >= MAX_MESSAGE_CHARS) {
          ndx = MAX_MESSAGE_CHARS - 1;
        }
      } else {
        received_chars[ndx] = '\0'; // terminate the string
        recv_in_progress = false;
        ndx = 0;
        new_data = true;
      }
    } else if (rc == START_MARKER) {
      recv_in_progress = true;
    }
  }
  return new_data;
}

void setup() {
  Serial.begin(115200);
   strcpy (text, "EMPTY");
 //  text = (char*)malloc(25);
//  received_chars[0] = '\0';
}

void loop() {
  ReadSerial();
}

If you could describe what you really want in the end I'm sure we can help with some basic routines.


Does Arduino C++ support dynamic arrays of objects

Even if it would be possible to use dynamic arrays, I would not recommend it, especially not on an Arduino Uno/Mega with only 2 or 8 KB memory.

Instead, create a static data element (e.g. array) that has a (reasonable) maximum number of created elements. This also has the benefit that the constructor will not be called after initialization, thus no variance in execution time (construction of objects can take time).

To manage multiple items within this data element, you can:

Using a ring buffer, this is the normal way to store items on one side, and process them from the other (so-called FIFO, first in first out).
Using a stack (for LIFO, last in last out).
For arrays, keep one variable that holds the number of elements currently filled.


There are two issues at play here:

1 – Limited precision of the float data type

A float has a precision of roughly 10−7, and any number that
is not an exact float is supposed to be rounded to the nearest float.
For example, the two floats closest to 1.234567 are
10356298 × 2−23 = 1.2345669269561767578125 and
10356299 × 2−23 = 1.23456704616546630859375.
The latter is the closest.

2 – Naive string to float implementation in the Arduino core

The Arduino core aims at being small and consume few resources.
Sometimes it cuts corners, at the cost of accuracy. In this case,
although a correct implementation is supposed to round 1.234567 up,
because the nearest float is above that number, the actual
implementation ends up rounding down. Thus you end up with roughly
1.234566927, which is off by 0.61 ULPs (units of the last place), instead
of the expected error of 0.39 ULPs.


Current difference between pinMode(pin, INPUT_PULLUP) and digitalWrite(pin, HIGH)?

It all depends on the external device. If it has high-impedance inputs,
then it makes no difference. The Arduino itself has high-impedance on
its pins configured as INPUT. If the device draws current from this
signal, then chances are it will draw more current from an OUTOUT
HIGH than from an INPUT_PULLUP. How much more? We cannot say without
knowing the specifics of that device.
If you model the device as a simple resistor to ground (which is almost
certainly overly naive), then the current draw is
I = VCC / (R + Ro)
where R is the value of the resistor and Ro the output
resistance of the Arduino: about 25 Ω for an OUTPUT and
32 kΩ for an INPUT_PULLUP.


Is it possible to upload a program from a tablet?

I figured out a way to do this without having to port the compiler to iOS. It only works with the arduino Yún, but the Yún can send code to other arduinos with an spi cable.

Install an SSH app on your device so you can communicate with the arduino
Using that, install Ino on your Yún, a command line arduino compiler
Create a file, put your code in it, then save it
use Ino to upload your code!

kind of confusing, but it could work!


OLED (I2C) and Micro SD card module not working together in Arduino

A pullup resistor is needed for I2C, and adding them might fix some errors.


Substring takes either one or two arguments.

In the single-argument version that you are using the argument specifies the start of the substring. The substring then contines to the end of the string.  So, since you are asking it to start at index 0 the returned value is the entire string - from 0 to the end.

Instead you probably want to use the two-argument version. In that version you provide two numbers - the index in the string to start from, and the index in the string after the last character you want.  So if the string starts with "print" you then want to use l1.substring(0, 5) to get the characters 0 to 4 inclusive.


If I use a biasing circuit for a signal going into an analog input pin, will it affect the ADC operation?

It will give bad results. You're not slowing down the sampling, you're taking samples at a longer interval - a very different thing.

The Arduino uses a Successive Approximation ADC. That uses a clock to control the output of a DAC and compare that voltage with the incoming voltage stored in the S&H capacitor.

In order for the S&H capacitor to get charged to the correct level it has to be connected to the GPIO pin long enough. Since there is only one ADC and 6 analog input pins, it goes through a MUX first.

The delay that needs increasing is the delay between the pin being connected to the capacitor and the capacitor being connected to the ADC.  This is called the acquisition time.

The analogRead() function does these basic operations in sequence:

Connect the SHC to the GPIO pin through the mux.
Wait
Disconnect the SHC from the GPIO and connect it to the ADC
Clock each bit from the comparator to the result registers.

Putting a delay between each analogRead would just delay the connecting of the SHC to the GPIO pin, not increase the time it's connected to the GPIO pin.

You would have to manipulate the ADC registers to do your own sample timing.  Or, just reduce your output impedance.


Does a normal Ultra-Sonic sensor (HC SR04) sense through a Football Net like obstacle?

There is always a chance of picking up the net for a split second, but most likely, you will never accurately detect the net with this type of sensor. There is too little to detect.


Strange issue with FHT library for sound-reactive LED project

Thanks to @TonyStewart for suggesting that I just do a successive A2 read.

I modified the code by just repeating the A2 read.  b1 is the first read, and b2 is the 2nd read.

  while (!(ADCSRA & 0x10)); // wait for adc to be ready
  ADCSRA = 0xf5; // restart adc
  byte m = ADCL; // fetch adc data
  byte j = ADCH;
  int brightness = (j << 8) | m; // form into an int

  Serial.print("b1: ");
  Serial.print(brightness);

  while (!(ADCSRA & 0x10)); // wait for adc to be ready
  ADCSRA = 0xf5; // restart adc
   m = ADCL; // fetch adc data
   j = ADCH;
   brightness = (j << 8) | m; // form into an int

  Serial.print("   b2: ");
  Serial.println(brightness);

And the readout looks good.  B1 is now legible, but incorrect/low.  B2 looks accurate and scales all the way to 1024 as I wanted.

b1: 0   b2: 688
b1: 0   b2: 739
b1: 0   b2: 816
b1: 20   b2: 915
b1: 118   b2: 1016
b1: 152   b2: 1023
b1: 172   b2: 1023
b1: 165   b2: 1023
b1: 180   b2: 1023
b1: 188   b2: 1022
b1: 184   b2: 931
b1: 127   b2: 713
b1: 0   b2: 615
b1: 0   b2: 532
b1: 0   b2: 436
b1: 0   b2: 327
b1: 0   b2: 304
b1: 0   b2: 452

I'm still curious about the reasoning behind this...but I'm glad that there is a solution, and not one that is too painful.


How do I code the release of a momentary touch sensor in IDE?

You have a semicolon that doesn't belong in your code. Your current code (With the indentation cleaned up a little)

void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  if(sensorValue > 100) {
    Serial.println(F("Playing track 001"));
    musicPlayer.playFullFile("/track001.mp3");
  }
  else(sensorValue < 100); { // <<<--semicolon does not belong here.
    Serial.println(F("Paused"));
    musicPlayer.pausePlaying("/track001.mp3");
  }
}

Should be:

void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  if(sensorValue > 100) {
    Serial.println(F("Playing track 001"));
    musicPlayer.playFullFile("/track001.mp3");
  }
  else(sensorValue < 100) { // <<<--semicolon removed from this line
    Serial.println(F("Paused"));
    musicPlayer.pausePlaying("/track001.mp3");
  }
}

With the semicolon after the else, your code reads "...else do nothing" and then I would expect it to execute the pause logic no matter what value is in sensorValue.

You should pick an indentation style and then be absolutely consistent with it. Most C/C++ programmers use K&R style, which is what I used in my edit. (Opening braces are on the same line as the if statement/function that begins the scope, code inside braces is indented, and closing brace is at the same indentation level as the line that contains the opening brace.)


Why Arduino Severino (S3V3) sometimes needs reseting when uploading a sketch?

Why does that happen?

When the serial port is opened by either monitor, avrdude or other it toggles the DTR pin of the serial port. Which in turn is AC coupled through C4 100nF. This toggling is converted to a up and down pulse on the ATmega(CPU)'s RESET pin. The subsequent reset starts initially with the boot loader, which typically in turn waits for a avrdude's semiphore (e.i. Send: 0 [30]   [20] ) and if seen then responds in turn and if not seen after a timeout period (typically 5s) it continues on with the application in flash space.

You behavior is describing either; not hearing the response. Or the reset is not getting triggered. Since it does work some times I suspect its prior, but the later.

Why Severino needs a hard reset during upload?

This statement further supports the later.

Why is the problem intermitent?

the pulse is almost long and strong enough, where the DTR toggle is in code and likely has some significant inconsistency.

How can I fix that problem?

Yes, change the value of C4 100nF and or R11 10K, to better pass the toggle. I could derive some EE explanation of what value to pick. But I would suggest some trial and error.

It should also have 5V clamping, as the RS232 levels can reach +/-12V (typically +/-9V) where the AC coupling prevents the DC and burn out. but the AC will stress it.


It is possible to control brightness of an LED strip (connected using a relay and having a seperate power supply ) using output from an arduino?

As Gerben said relays are only for on/off control. If you need to fade led you should use transistor.

What kind of transistor?

It depends on power consumption (how many LEDs).

How to connect Arduino, LEDs, transistor?

This is schematics how to connect the strip. As i assume resistors are already on the strip.

And little bit simpler image :)


There are some times when it can't make prototypes, and some when it just gets it plain wrong. It struggles if you do fancy things with any of your functions, such as adding attributes or using anything that's even slightly out of the ordinary.

Also sometimes it places the prototypes in completely the wrong place, especially if you are working with structs, etc.


Normal I2C addresses are 7-bit long. On the first frame of an I2C
transaction, the master sends an 8-bit byte containing the address of
the slave followed by a bit specifying whether this is a read or a write
operation. Some people tend to call “address” the whole 8-bit frame,
which causes confusion. Because of this, we end up having three flavors
of I2C addresses:

the 7-bit address, which is the real device address
the 8-bit “write address”, which is the address followed by a 0
meaning “write operation”
the 8-bit “read address”, which is the address followed by a 1
meaning “read operation”

For your RTC, the 3 addresses are the following, in hex and binary:

7-bit = 0x51 = 0b1010001
write = 0xA2 = 0b10100010
read  = 0xA3 = 0b10100011

The Arduino Wire library expects the 7-bit address.


Ok look at this image:

I'm not sure how your keypad is layed out but if you use a probe pin to test your connections via a multimeter, you can mark which ones correspond to the image.

I am ASSUMING you are going to use the code from arduino playground.

This is the format:

Pins of keypad (IN THE IMAGE) - Pins of PFC8547

Here are the pin connections:

1 - nothing

2 - 9

3 - 4

4 - 6

5 - 7

6 - 10

7 - 11

8 - 5

Also include the pull-up resistors.
Your ABCD keys will be ignored

(This is like wiring a bomb...)


Can I program the Arduino without having an actual board with the able to emulate a COM connection to the computer?

You could use the Simulator in Atmel Studio or something like Virtual Breadboard which looks good

The Atmel Studio simulator might take a bit of work to simulate your devices but if you have 2 months then maybe that's okay :) If you want to use the simulator in Atmel Studio then you might also find the Arduino plugin for Atmel Studio useful.

I think there are quite a few other solutions if you search google.


Find a time server for NTP to get the current time (EtherCard library)

The EtherCard library offers a method called ether.dnsLookup(host) where you ask it to look up the IP address for you.

etherCard.dnsLookup("pool.ntp.org");

...only that might fail, so it returns a false:

if (!etherCard.dnsLookup("pool.ntp.org")) {
    // Error! Do something!
    return;
} // if

But if it works...

if (!etherCard.dnsLookup("pool.ntp.org")) {
    // Error! Do something!
    return;
} // if
// At this stage, dnsLookup() worked...

// Can now connect to IP adress in etherCard.hispip

Now: please note that ntp.org would prefer you to use a more precise locale than pool.ntp.org. If you're going to distribute your application worldwide, then that's fine. But I always use au.pool.ntp.org because I'm in the Australian region. There are others that you can/should use instead.


How to determine hardware/software compatibility?

The HC4050M is just used for logic level translation (SD cards are 3.3V devices). It is "enough" that you are talking to an SD card using an SD card library. The SD card is really all the hardware there is - everything else is just interfacing fluff - completely transparent to the software.


It seems to be possible to record with the shield using a library called waverp

  WaveRP is an Arduino library for recording and playing Wave files with
  the Adafruit Wave Shield. It records 8-bit mono files at 4,000 to
  44,100 samples per second.

Some details adafruit blog:

  It records 8-bit mono files at 4,000 to 44,100 samples per second.


Create one server in AP mode and another in station mode

It is not documented, but you can construct WiFiServer or ESP8266WebServer with IP address. If you use the IP address of the AP, the server will be available only on the SoftAP. If you use the IP address of the station, the server will be available only on STA interface.

If the IP of the interface is known before setup(), you can simply define WiFiServer internalServer(apIP, 81); instead of WiFiServer internalServer(81);. But if the IP must be first evaluated in setup() (from DHCP, or config file), then the following example shows how to set WiFiServer IP and port in setup().

#include <ESP8266WiFi.h>

WiFiServer internalServer(81);
WiFiServer externalServer(80);

void setup() {
  ...
  internalServer = WiFiServer(WiFi.softAPIP(), 81);
  externalServer = WiFiServer(WiFi.localIP(), 80);
  internalServer.begin();
  externalServer.begin();


How to store incoming serial data to char array in order to send to other module (XBee)?

NMEA sentences cannot be longer than 80 visible characters + terminators. Even with a CRLF, that's a max of 82 characters. You should be fine with a fixed-sized char array of 82.


What should I do to communicate with GSM module?

The compiler does not know what PString is. It is not declared in any of the libraries you have included.

You could rewrite to something like this.

strcat(buffer, "Pintu Dibuka");
n = strlen(buffer);
digitalWrite(pintu,HIGH);
sms.SendSMS(n,buffer);

Please change the other block in the same way.

There are more errors. You also need to change "int n[20]" to "int n".

That is a good start.

Cheers!


You could change the intensity of each colour in steps till you get to your target colour.

void colorFade(uint8_t r, uint8_t g, uint8_t b, uint8_t wait) {
  for(uint16_t i = 0; i < strip.numPixels(); i++) {
      uint8_t curr_r, curr_g, curr_b;
      uint32_t curr_col = strip.getPixelColor(i); // get the current colour
      curr_b = curr_col & 0xFF; curr_g = (curr_col >> 8) & 0xFF; curr_r = (curr_col >> 16) & 0xFF;  // separate into RGB components

      while ((curr_r != r) || (curr_g != g) || (curr_b != b)){  // while the curr color is not yet the target color
        if (curr_r < r) curr_r++; else if (curr_r > r) curr_r--;  // increment or decrement the old color values
        if (curr_g < g) curr_g++; else if (curr_g > g) curr_g--;
        if (curr_b < b) curr_b++; else if (curr_b > b) curr_b--;
        strip.setPixelColor(i, curr_r, curr_g, curr_b);  // set the color
        strip.show();
        // delay(wait);  // add a delay if its too fast
      }
      delay(1000);
  }
}

To use it:

void loop() {
  colorFade(255, 0, 0, 150); // fade into red
  colorFade(255, 255, 255, 150); // and then into white
  delay(5000);
}

This is untested, so I dont know if it will be too fast or too slow. You'll have to tweak it to your needs.


How to stop uno from running program when powered on?

The simplest thing is to upload the new program before connecting the hardware.

If this isn't practical, connect a jumper wire from the Reset pin to ground (Gnd) before powering it on. This will hold in a reset state, and the program won't run.

Then, compile and upload your program. As it starts to upload remove the reset wire. That should upload it without running any existing program.


Too long for a comment...

Look at some of their docs for examples. seems like they have a very similar platform to Arduino.

  Their forums suggest making the connection is not trivial, but may be
  possible: http://www.libelium.com/forum/viewtopic.php?f=15&t=8811

All that's saying is you can't simply plug in a sensor into your Arduino like a shield, because it's not a shield. You'd have to hook up the connections to the right pins and then use their libraries and code to communicate with it.

That involves reading their documentation and code to figure out what pins it uses to communicate with what. You may have to modify the code slightly to work with Arduino (mainly changing pin numbers).

All in all, I wouldn't invest my time or effort into it. Don't lock yourself into a product that isn't intended to be used the way you're using it. You'll get no support from the company and there's no guarantee future versions of their product will work. Or things like this (from the forum link):

  Anyway, I'm afraid the Libelium's sales policy implies a minimum first
  order including five Waspmotes, five batteries and one Gateway.

Simply not worth the effort. You'd be much better off making your own sensor board to fit your requirements.


I googled "measure speaker resistance" and found http://www.wikihow.com/Measure-Speaker-Impedance

Step by step instructions

You will need a multimeter - a great thing to have in any case.


ESP32 - `Brownout detector was triggered ` upon Wifi begin

Those boards have an inherent weakness in that they don't provide enough decoupling capacitance for the module.
Not all modules are quite the same, and some have more internal decoupling than others (not by design, just due to component tolerances).
I have found that unless you provide adequate decoupling of your own some modules work just fine and some don't. Some brown-out and some fail to flash.
For all my designs now I always provide both a 100nF and an 10uF capacitor right at the power pins of the module. However those boards don't provide anything like that.
You need to modify the board to add a capacitor (about 10uF) directly across the power and ground pins (pins 1[ground]-2
[3.3v]) of the ESP32 module. I like to use an 0805 MLCC capacitor as they fit nicely across the pins and are discrete, but they can be tricky for a novice to solder. So an electrolytic through-hole capacitor can be a simpler proposition (make sure you get the polarity right).


This outputs 8 MHz on pin 9:

#ifdef __AVR_ATmega2560__
  const byte CLOCKOUT = 11;  // Mega 2560
#else
  const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
#endif

void setup ()
  {
  // set up 8 MHz timer on CLOCKOUT (OC1A)
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
  OCR1A =  0;       // output every cycle
  }  // end of setup

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

  How can add a prescaler?

You change the prescaler bits. You can look at the datasheet or my cheat sheet here:

You may not need a prescaler, depending on the frequency. Change OCR1A to some number between 0 and 65535 to slow it down.

Edit by Edgar: I tested the OCR1A values with an oscilloscope. At the end of this answer are the frequencies.

  you use TCR1A, COM1A0 and similar variables. Are these always present and implicitly defined when running code on the ATmega

Registers like TCCR1A and so on are defined in files which are automatically included by the Arduino IDE. If you use another toolchain they may be also automatically included. The start point is:

#define <avr/io.h>

Inside that file it checks your processor type (from a symbol passed to the compiler) and then includes an appropriate sub-file. Inside those files are defines which relate the register names to their address in the address-space of that particular chip. For example:

#define TCCR1A _SFR_MEM8(0x80)

The _SFR_MEM8 basically generates a pointer to a volatile address (because it might change without the compiler knowing it) and then dereferences that variable.

Notice that the number 0x80 in that define agrees with the number shown on my chart.

Underneath that define in the appropriate file are also the bit positions for the bits in that register, like this:

#define TCCR1A _SFR_MEM8(0x80)
#define WGM10 0
#define WGM11 1
#define COM1B0 4
#define COM1B1 5
#define COM1A0 6
#define COM1A1 7

  Secondly, do I correctly understand that the output pin is defined in TCR1A, Output A and Output B, to be on Digital Pin 9 and 10 respectively?

Yes, in effect. The datasheet says that if you set the appropriate bits in TCCR1A (note the spelling) then OC1A (board pin 9 on the Uno) or OC1B (board pin 10 on the Uno) will be unchanged/toggled/cleared/set depending on the bits. You can find these names on the datasheet for the Atmega328P (and other devices) and then use the Arduino schematic to find which processor pins are connected to which board pins.

Atmega328P datasheet snippet:

Uno datasheet snippet:

  Why do you set it to "Toggle" rather than "Set"?

Because every time the counter matches I want to flip the pin. That is, on/off/on/off etc.

  What does CTC stand for?

Clear Timer on Compare. What this means is that (unlike other modes) once the compare match is made, the timer is cleared, thus it starts counting up from zero again.

Edit by Edgar: OCR1A values and frequencies

Value, MHz
 0 8.00
 1 4.00
 2 2.67
 3 2.00
 4 1.60
 5 1.33
 6 1.14
 7 1.00
 8 0.889
 9 0.800
10 0.727
11 0.667
12 0.615
13 0.571
14 0.533
15 0.500


I tested your sketch and it works. I simplified it; it's the same logic, but in a more concise way:

void loop()
{
    reading = digitalRead(buttonPin);

    // if the input just went from LOW and HIGH and we've waited long enough
    // to ignore any noise on the circuit, toggle the output pin and remember
    // the time
    if(reading == HIGH  && previous == LOW && millis() - time > debounce) {
        state = !state;
        time = millis();
    }

    digitalWrite(ledPin, state);
    Serial.println(reading);
    previous = reading;
}

setup is still the same.


Well I guess the signal strength could be measured but clothes hanged in wardrobe are too close to each other to distinguish them. Maybe close range NFC?

I have other solution to be considered.

Maybe you look at the wrong touchpoint of that interaction. What if the desired action occurs not while it's already hanged but when user put the clothes on hanger? During that, it's not with other clothes (as you grab the hanger in your hand to put the clothes on it).

There are a few things to consider. I guess people put things only on one hanger at once while having clothes in second hand. How many % of users puts clothes on hanger by grabbing it outside of wardrobe (as mundane event/behavior)?

Why it's important?

During that interaction there is a moment when user tries to pair single cloth with single hanger separated from the rest.

The hanger could have additional sensor to know when it happens:

Magnetic field sensor and small magnet in collar?
Capacitive sensor?
Accelerometer?

...so the device will know when that interaction occurs and then activate the reading from single rfid tag.

I guess my answer is more about user experience and the aesthetics of interaction but it can give you some clues to finish your project.


Sainsmart LCD 2004 - LiquidCrytal_I2C library issue unable to compile

I just bought 3 of these that work well with this library
 LiquidCrystal_I2C2004V1.zip
(License: CC BY-NC 2012 http://www.wikispaces.com/user/view/TerryKing).

When installing this library in Arduino IDE (version 1.6 or later), use menu item Sketch | Include Library | Add .ZIP Library..., navigate to the folder where LiquidCrystal_I2C2004V1.zip was downloaded, and then open the zip file.

Use the I2C address in the example "HelloWorld" supplied with LiquidCrystal_I2C2004V1:

//YWROBOT
//Compatible with the Arduino IDE 1.0
//Library version:1.1
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup()
{
  lcd.init();                      // initialize the lcd
  lcd.init();
  // Print a message to the LCD.
  lcd.backlight();
  lcd.setCursor(3,0);
  lcd.print("Hello, world!");
  lcd.setCursor(2,1);
  lcd.print("Ywrobot Arduino!");
   lcd.setCursor(0,2);
  lcd.print("Arduino LCM IIC 2004");
   lcd.setCursor(2,3);
  lcd.print("Power By Ec-yuan!");
}

void loop()
{
}

Do not change the other library directory name; this one is compatible with the existing library. Just add it as a contributed library.


Atmega328p programming with Arduino libraries

The clock rate of your board must match the clock rate defined in the board file you used to compile your sketch.  If it does not, the baud rate will differ by the same factor.

If the actual baud rate so achieved is a valid one, you can temporarily achieve communication by setting the computer to that baud rate, but all delays and other clock-rate related functions will be off.

You should use or create a board file entry that matches your board, or use a standard clock source / clock divier setting for which there already is an entry.


Adafruit has a good set of guides to getting started with arduino:
https://learn.adafruit.com/series/learn-arduino

The "Blink" program is the equivalent of "hello world".

When testing you probably should disconnect the Arduino from the 3D printer.


You need to be a little clearer about the time that can exist between the sensor values changing. If you fade to slowly the correct value might never be reached before the sensor changes again. Maybe that's what you want?

You can't use a delay().

You need a currentRed, currentGreen and currentBlue so you can fade to the values of red, green and blue.

unsigned long last_reading_ms;
int red = 255;   // Variables to store the TARGET rgb target values for each pin
int green = 255;
int blue = 255;
int currentRed = 0;   // Variables to store the current rgb values of the pins
int currentGreen = 0;
int currentBlue = 0;

void setup()
{
   last_reading_ms=millis();
}

void loop()
{
  /* read sensor every 100ms and set red, green,blue if changed */
  if (millis()-last_reading_ms > 100)
  {
    /* Get a new sensor event */
    sensors_event_t event;
    accel.getEvent(&event);
    //the rest of your sensor reading code here

    last_reading_ms=millis()
  }

  /* if orientation changes, print out a description */
  if (orientation != lastOrientation) {
   Serial.println(orientationString);
   lastOrientation = orientation;
  }

  calculateRGBFadeTo();

  analogWrite(redLEDPin, currentRed);   // Write values to LED pins
  analogWrite(greenLEDPin, currentGreen);
  analogWrite(blueLEDPin, currentBlue);

  //*** do not use a delay or use a very small one to slow the transition ***
  //delay(100);

}

/* get values 1 step closer to target red, green, blue */
void calculateRGBFadeTo()
{
  /* fade to required rgb values */
  if (currentRed<red)
   currentRed ++;
  else if (currentRed>red)
   currentRed --;

  if (currentGreen<green)
    currentGreen ++;
  else if (currentGreen>green)
    currentGreen --;

  if (currentBlue<blue)
    currentBlue ++;
  else if (currentBlue>blue)
    currentBlue --;

}

Notes:

The fade can be slowed down either with a small delay such as 5 ms. or by using another millis() variable to determine the time since the led was last set.

For example: if (millis()-last_rgb_write_ms > 5)

It's also possible to speed up the fade by using a larger increment. An increment of two, for example, currentRed+=2; instead of currentRed++;

Reminder, the comparison of when the target red, green, blue has been reached will be more complex with an increment greater than 1.

An increment of 2 and a sensor read frequency of 128ms (instead of 100) would ensure the correct RGB values are always reached. Alternatively reading the sensor every 255ms (4-5 times per second) would also ensure the correct RGB values has been reached.

Using millis() and avoiding delays allows many more tasks to be performed with more accurate timings.


How to remove the sketch for the LCD and retaining the sketch for the MPU6050?

As Majenko states, carefully remove all lines with the lcd object in them. Due to the extremely poor formatting and indentation of the code, if you aren't careful you could lose some important syntax, such as the { and }.

Also, there is no need for the LiquidCrystal header file.

In addition, there is a typo in the posted code (it is beyond me why the author would post uncompilable (and hence untested) code), in this line:

case MPU6050_SCALE_250DPS:         Serial.println("250 dps"); break:}

Here is the code with the lcd related lines stripped out, correctly formatted and indented, with the typo fixed:

#include <Wire.h>
#include <MPU6050.h>

#define minval -5
#define maxval 3

MPU6050 mpu;

void setup()
{
  Serial.begin(115200);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);

  delay (2000);

  // Initialize MPU6050
  Serial.println("Initialize MPU6050");

  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  mpu.setThreshold(3);
  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.println();
  Serial.print(" * Sleep Mode:        ");
  Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");
  Serial.print(" * Clock Source:      ");
  switch(mpu.getClockSource())
  {
    case MPU6050_CLOCK_KEEP_RESET:
      Serial.println("Stops the clock and keeps the timing generator in reset");
      break;
    case MPU6050_CLOCK_EXTERNAL_19MHZ:
      Serial.println("PLL with external 19.2MHz reference");
      break;
    case MPU6050_CLOCK_EXTERNAL_32KHZ:
      Serial.println("PLL with external 32.768kHz reference");
      break;
    case MPU6050_CLOCK_PLL_ZGYRO:
      Serial.println("PLL with Z axis gyroscope reference");
      break;
    case MPU6050_CLOCK_PLL_YGYRO:
      Serial.println("PLL with Y axis gyroscope reference");
      break;
    case MPU6050_CLOCK_PLL_XGYRO:
      Serial.println("PLL with X axis gyroscope reference");
      break;
    case MPU6050_CLOCK_INTERNAL_8MHZ:
      Serial.println("Internal 8MHz oscillator");
      break;
  }

  Serial.print(" * Gyroscope:         ");
  switch(mpu.getScale())
  {
    case MPU6050_SCALE_2000DPS:
      Serial.println("2000 dps");
      break;
    case MPU6050_SCALE_1000DPS:
      Serial.println("1000 dps");
      break;
    case MPU6050_SCALE_500DPS:
       Serial.println("500 dps");
       break;
    case MPU6050_SCALE_250DPS:
       Serial.println("250 dps");
       break;
  }

  Serial.print(" * Gyroscope offsets: ");
  Serial.print(mpu.getGyroOffsetX());
  Serial.print(" / ");
  Serial.print(mpu.getGyroOffsetY());
  Serial.print(" / ");
  Serial.println(mpu.getGyroOffsetZ());
  Serial.println();
}

void loop()
{
  Vector rawGyro = mpu.readRawGyro();
  Vector normGyro = mpu.readNormalizeGyro();
  Serial.print(" Xraw = ");
  Serial.print(rawGyro.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(rawGyro.YAxis);
  Serial.print(" Zraw = ");
  Serial.println(rawGyro.ZAxis);

  if (normGyro.XAxis > maxval ||
      normGyro.XAxis < minval &&
      normGyro.YAxis > maxval ||
      normGyro.YAxis < minval &&
      normGyro.ZAxis > maxval ||
      normGyro.ZAxis < minval)
  {
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(300);
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(300);
    delay (1000);
  }
  else
  {
    digitalWrite(7,LOW);
    digitalWrite(8,LOW);
  }
  Serial.print(" Xnorm = ");
  Serial.print(normGyro.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(normGyro.YAxis);
  Serial.print(" Znorm = ");
  Serial.println(normGyro.ZAxis);
  delay(10);
}

The page that you got your code from does not specify which MPU6050 library to use. It is not the library by Jeff Rowberg, as linked to from the Arduino Playground, MPU-6050 Accelerometer + Gyro. It is in fact this library, MPU6050 Triple Axis Gyroscope & Accelerometer Arduino Library.


Millis () funtion fails to perform for extended period of time

In C++, the multiplication operator is “left-associative”. This means
that the expression

12*60*60*1000UL

is interpreted as

((12*60)*60)*1000UL

The left factor, namely (12*60)*60, is computed using the int data
type, but the result overflows that format, resulting in the problem you
see.

The simple solution is to make one of the factors of the first product
be an unsigned long. For example

1000UL*60*60*12

Then, 1000UL*60 is computed with the unsigned long data type. Since
the result is itself an unsigned long, the next multiplication is also
done as unsigned long, and likewise for the last one.

If you find this technique somewhat obscure, you can also add the UL
suffix to every single factor. This would avoid implicit conversions by
the compiler, making all the types explicit.


To use unipolar switches as inputs, you need pulling resistors to give the input pin a defined value when the switch is open.

The ATmega has software configurable internal pullups.  Even if these are not configured, implementation detail may (or may not) yield a very weak unreliable pullup effect.

There is no configurable pulldown on the ATmega.  To operate in that direction (with a switch to high) you would need external pulldown resistors.

A few matrix keyboards include diodes, to combat some of the confusion which results when multiple keys are pressed in a simple matrix.

Also, you should add a tiny delay between driving and reading, in order to allow for capacitive delay.


Can you tell me if this circuit will work?

These servo are driven off of a PWM signal. This means that you need to connect the control line to a pin that is capable of PWM.

For the Uno it is D3, D5, D6, D9, D10 & D11.

Unfortunately there are only 6 PWM capable pins and you need 8.

You could consider bit banging the PWM for the 7th & 8th motor.

Alternatively, if two of the motors are to be driven exactly the same, they could share the PWM control line between them.

If you need to control each motor separately (without bit banging) you may have to upgrade to a Arduino Mega 2560. The Mega has 15 PWM channels.

An Arduino example of controlling the servo motor can be found in the Libraries section of the Arduino website.
https://www.arduino.cc/en/Tutorial/Knob


How to use Arduino Pro Mini without Programmer

You might be on the wrong track.

You do need a crystal (or not, it depends on), and an Atmel programmer if you want to program an empty chip.

However, all Arduino boards come with a chip pre-programmed with a bootloader.
Then it is rather easy: you need an FTDI cable to connect the board to a PC. Then run Arduino IDE on the PC. (The FTDI cable is actually an USB-to-serial converter.)

The Arduino IDE lets you edit a C like code, complile it to binary, and send it out via the FTDI cable to the serial port (Rx, Tx) of the board. The microcontroller on the board comes with a bootloader. Bootloader is a small program which runs at power up, and will receive the data from the computer and put your program to the microcontroller. Then your program will run on the microcontroller.

So, you don't need an external programmer.

On the other hand, you may consider picking a different Arduino board. Arduino Micro, or Pololu A-star Micro (for half of the price of the Arduino Micro) offers a board with a direct USB connection. All you need is one USB cable.

These boards come with a much better microcontroller (32u4) which has a hardware USB connection (allowing you to make a mouse or a keyboard, and control PC (such as buttonbass.com) from your gadget).


The functions Adafruit_VS1053::sciWrite and Adafruit_VS1053::setVolume are functions from the library. They are in the Adafruit_VS1053.cpp file.

You should not copy those functions to your own sketch.

The library has a few examples. Try to stay close to those examples.


How to set PC (Program Counter) register to another function (for scheduler)

This:
SP = (uint16_t)(&dummy)

is changing the stack pointer. Not what you want. You want to instead
push the destination address to the stack. However, rather than
simulating a function return, it should be simpler to perform an
indirect jump:
asm volatile("ijmp" :: "z"(dummy));

Don't forget that your naked ISR has to save all the call-used
registers, as well as SREG, r0 and r1, in its custom prologue. And
restore them in its epilogue. Check the AVR calling
conventions.


Difference in bootloader of ATmega with 16MHz external crystal and 8MHz external crystal

Yes, the ATmega328 will run fine at 8MHz, at 3 volts.

The formulas for clock speed vs. volts are:

Below 1.8V - cannot operate
Below 4 MHz - use at least 1.8V
Between 4 MHz and 10 MHz you require: Volts = 1.8 + ((M - 4) * 0.15)
(Where M is Megahertz)
Between 10 MHz and 20 MHz you require: Volts = 2.7 + ((M - 10) * 0.18)
(Where M is Megahertz)
You can supply an absolute maximum of 5.5V

Plugging 8MHz into this formula: volts = 1.8+((8-4)*0.15) = 2.4 volts minimum (5.5 volts maximum). Note that, as batteries are used, their voltage goes down gradually, so the 0.6 volts difference will mean that your project will run a little longer.

Since your supply is > 2.7V, we can reverse the second formula: 3V=2.7+(M-10)*0.18); 0.3=(M-10)*0.18; 0.66=M-10, so you can run it at 10.66MHz at 3V (but it is likely to stop as soon as the battery starts to drain).

Your second question, I think, is the most relevant one - the bootloader is written for 16MHz, and some things will not work at other speeds - serial communications used for programming for example. The same, for that matter, applies to the program - if you put in a delay() instruction in your code, it will delay() for twice as long as it should.

You can get around the programming side by ditching the bootloader altogether - once your code is ready, select file->upload using programmer. This will still affect the speed your sketch runs at (anything time-related - serial communications, delay(), etc). To change this, you will need to add a custom entry to the boards.txt file. See [HOWTO:] Anatomy of the boards.txt file for custom boards.


How can I use my Arduino sketches on my Raspberry Pi IDE?

To fix this problem I came up with the following procedure which takes out all the underscores from the directories & filenames and capitalizes each word instead.

First, I copied all my sketches and libraries (from my documents/arduino directory) to a USB flash drive.

The Rpi Arduino IDE creates a sketchbook directory upon install, so I

Copied the libraries folder to ~/sketchbook/libraries

Copied the sketches folder to ~/sketchbook/AMSsketches

Then I wrote a custom script that is copied to my home directory on the Rpi, which can be obtained here as a text file (use Chromium or wget to copy it to the file ~/AMS2Rpi)  - Here is the link:  http://calttc.net/AMS2Rpi

which contains this code:

#! /bin/bash
#
#  AMS2Rpi - Converts MS Arduino IDE Sketch names to RPI Arduino IDE Sketch names
#
#                  SDsolar      2017-01-29
#
#  Reason:    Arduino IDE on MS inserts underscore characters in file & directory names
#             Arduino IDE on Rpi rejects all but alphanumeric characters
#
#  Solution:  Remove all but alphanumeric characters
#             and capitalize each word in the names
#
#  Usage:
#    Install Raspbian Arduino IDE 2:1.0.5 on the Raspberry Pi 3
#    Use a USB flash drive to copy sketches and libraries from the MS-based Arduino IDE
#      On the Rpi, copy the libraries directory to ~/sketchbook/libraries
#      On the Rpi, copy the sketches directory to ~sketchbook/AMSsketches
#    Copy this script to your home directory as AMS2Rpi using Chromium
#    cd
#    chmod +x AMS2Rpi
#    ./AMS2Rpi    (This will take some time)
#    cat /tmp/AMS2Rpi | grep "AMSsketches" >~/AMSRpiQ
#    chmod +x ~/AMS2RpiQ
#    ~/AMS2RpiQ
#    Open the Rpi Arduino IDE
#
#  Alternatively, if you have a lot of sketches you might want to
#    change the "mv -i" below to "mv"
#    and cat it into AM2SRpiX above
#    so you don't need to answer "y" for every rename.
#
#  Props to Marco Fioretti for his article at http://www.techrepublic.com/blog/linux-and-open-source/how-to-remove-weird-characters-from-file-and-directory-names-automatically/
# ---------------------------------------------------------------------
rm -f /tmp/AMS2R*
cd $1
find .  | awk '{ print length(), $0 | "sort -n -r" }' | \
        grep -v '^1 \.$' | cut -d/ -f2- > /tmp/AMS2Rpi_1
touch /tmp/AMS2Rpi_2
while read line
  do
  BASE=`basename "$line"`
  NEWBASE=`basename "$line" | perl -e '$N = <>; chomp ($N); $N =~ s/[^a-zA-Z0-9.]//g; $N =~ s/_+/_/g; $N= lc($N); $N =~ s/_([a-z])/_.uc($1)/eg; print ucfirst($N);' `
  if [ "$BASE" != "$NEWBASE" ]
  then
  OLDPATH=$(echo "$line" | sed -r 's/([^a-zA-Z0-9./_-])/\\\1/g')
  DIR=$(dirname "$line" | sed -r 's/([^a-zA-Z0-9./_-])/\\\1/g')
  echo "mv -i $OLDPATH $DIR/$NEWBASE" >> /tmp/AMS2Rpi_2
  fi
done </tmp/AMS2Rpi_1
rm -f /tmp/AMS2Rpi_1
mv /tmp/AMS2Rpi_2 /tmp/AMS2Rpi
exit

Then set it to executable and run it:

cd
chmod +x AMS2Rpi
./AMS2Rpi

When it is finished, I filter out just the directory I want (VERY IMPORTANT):

cat /tmp/AMS2Rpi | grep "AMSsketches" >~/AMS2RpiQ

(You can look at that file to verify it before running it)

chmod +x ~/AMS2RpiQ
~/AMS2RpiQ

Cleanup if you wish:

rm /tmp/AMS2R*
rm ~/AMS2RpiQ

Now the Arduino IDE on the Rpi opens cleanly and all my sketches are there.

Problem solved.   It works great.


Arduino based small LCD screen with camera video capturing

An Arduino doesn't have anywhere near the processing ability to transcode video from a camera unless you had an abysmal frame rate and very low quality. Even then, you would have to add extra storage because the Arduino would be over capacity in a heartbeat.

I recommend converting this project to a higher powered board like the Udoo. I have the Udoo Quad and it's beastly considering its form factor. You're going to need something a lot bigger than an Arduino!


Yes you are correct, the event handlers will not do anything in setup. Main runs "setup()", then loops infinity through "loop()", but gives the serial event handlers a chance to run in between. The actual main that runs on the arduino is this:

int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

this is found (on linux at least) in arduino/hardware/arduino/avr/cores/arduino/main.cpp

"serialEventRun()" is in HardwareSerial.cpp, but is not very interesting.

To be clear, Serial itself will still work fine in setup(). If you want to use the same event handler function, all you have to do is call "serialEventRun()" yourself periodically.