Controlling EL wire or panels with arduino

upstream slow blinking

The simplest approach:
Use a relay to turn the lights on and off. Control that relay with an Arduino.
("How to turn a relay on and off with an Arduino?" is a separate question).

Cut either one of the wires feeding power into the EL inverter ("upstream of the inverter"),
and connect the 2 cut ends of the (formerly) one wire to the contacts of the relay.

power source ---- (relay contacts) ---- EL inverter ---- (EL wire)
           +--------------------------------+    +---------+

downstream slow blinking

Alternative approach:
Use at least 2 pieces of EL wire.
Wire one always-on;
use a relay to connect or disconnect the other wire ("downstream of the inverter"). (The relay and controlled wire can be either directly connected to the inverter, or end-to-end connected to the always-on wire -- it doesn't matter for this application).

                                   always on
power source ---- EL inverter ---- (EL wire) ---- (relay contacts) ---- (EL wire)
           +----------+    +---------+   +-------------------------------+

Control that relay to control the EL wire with an Arduino, same as before.

dimming and PWM

Many low-cost relays are rated for only about 10,000 operations, so if you use them to blink for a long or short part of each second, they're only guaranteed to last for about 3 hours.
If you want to blink faster than that (and most people dim EL lights by blinking them much faster than that), you'll have to use something other than a relay.

Also, most people seem to want to do the switching "downstream" of the inverter, so they can "share" a single EL inverter and use it to power lots of independently controlled pieces of EL wire.

Perhaps the simplest approach is to use an off-the-shelf zero-crossing solid-state relay (SSR).
("How to wire a SSR to an Arduino?" is a separate question).

power source ---- EL inverter
          +-----------+   | |
                          +----- EL wire (always on)
                          | +-----+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          ... etc.

Because most SSRs are overkill for this application -- most of them have heatsinks bonded to high-power triacs designed to handle far more current than we need to light up a EL wire --
some people save a few dollars by assembling their own SSRs out of zero-crossing optocouplers, triacs, etc.
(A lower-cost, low-power triac is more than adequate for controlling EL wire, even without a heatsink).

The SparkFun EL Escudo Dos Arduino shield for controlling electroluminescent wire(c)(d);
Diana's SparkFun EL Sequencer(e)(f)(g);
the seeedstudio EL Shield(h)(i)(j)(k);
Tully Gehan's Cool Neon Arduino Shield(m)
etc.
uses such zero-crossing optocouplers, triacs, etc.
(requires a separate EL inverter).

According to some people on the Arduino forums talking about EL wire(n)(p),
some people save a few pennies by using normal optocouplers rather than zero-crossing optocouplers. Non-zero-crossing optocouplers seem to work fine for short pieces of EL wire but seems to destroy the triacs (failing "always on") with a few dozen feet of EL wire.

Some people save a few more pennies by skipping the optocoupler,
wiring the Arduino directly to the control gate of the triac, and the VCC pin of the Arduino directly to the MT1 pin of the triac.
(q) (r) (s) (t)
If there were some way to only turn the triac on near the zero-crossing, this could work great; but without zero-crossing control, this has the same problems as the above normal non-zero-crossing optocouplers.

always-on

The "extra" always-on bit of EL wire is because some people say
"never run the inverter without at least 1 foot of EL attached"(a) because running some EL inverters with no load "can damage the inverter"(b).


How to make servo rotate for angle bigger than 180°

No. The continuous rotation servo rotates continuously and you can not control where to stop. You can control the rotation direction and the speed at a little.

What you need is either a special 270 degree servo, or you can use some mechanic, e.g. gears to transform the 0..180 rotation to 0..whateverrotation you prefer, depending on the gearbox ratio.

Alternatively, you can use stepper motors, where you can control steps in 1.8 degrees, and at the same time free to move as many turns as you prefer. Note though that steppers have two disadvantages compared to servos:

steppers require electrical current to hold their current position - for servo, the gearbox works ok for this
steppers don't know their initial position. So you need an optointerrupter or other means to learn the initial position first, then drive the steps to get to any position.
steppers require a more serious driving circuit, as well as a good power supply. Not for DIY robot running on batteries.

In industrial solutions, the stepper motor + some gearbox + an absolute rotation encoder is used to compose an industrial servo drive. (Similarly as a DC motor + some gearbox + an inexpensive potentiometer works in a model servo.)


Sensor to measure distance on inverted pyramid filled with maize

The surface of corn is hard enough to reflect sound from an ultrasonic sensor. It reflects from fabric, skin and of course, plastic, and corn fits into the realm of reflectivity.

An Arduino with an ultrasonic sensor may scatter a good bit of the reflection, but some of it will get back to the receiver in sufficient condition to be registered.

The components necessary to test this are low enough cost to suggest a prototype. A simple pail or bucket filled with the grain and attached to a rope and pulley will give you distance information, and that would be for a relatively small surface area.

Ultrasonic sensors typically have a minimum distance and of course, a maximum distance. If your concern is for both full and empty conditions, dual sensors placed a sufficient distance apart with suitable range considerations are likely to work. The code would be written to avoid cross-pulse readings, which is likely to be trivial, as these devices operate at the speed of sound.

Lasers are point devices and may not necessarily reflect to the sensor for reading.

I have constructed a DME (distance measuring equipment) that displayed passing vehicles within a range of ten feet (~3 meters) down to slightly less than three feet (<1 meter) with good results. There was tremendous lag in the reading, but that's due to code ignorance, not hardware problems. I suspect the depth finder is not going to have much lag in determining its value to this application.


Const Array still using dynamic RAM during compile, causing failure

In a Princeton architecture const arrays are stored purely within the text (i.e., flash / read only / ROM) area.

In a Harvard architecture (which is what the Arduino is) the RAM and Flash both use completely different memory spaces, and instructions that work on RAM don't work on Flash, and vice versa.

Because of that it has to copy the const array from Flash into RAM so it can be accessed as normal variables.

To combat this you can use PROGMEM to force it to remain only in Flash, but then you have to use special functions to access the data - you can't use it like normal variables.

You can read more here: https://www.arduino.cc/en/Reference/PROGMEM


First of all, you'll soon blow up that LED. (Or the Arduino if you're really unlucky.) You need a current limiting resistor.

Secondly, most relays have two switch contacts: normally closed (N.C.) and normally open (N.O.). If you want your device to be off, unless the Arduino turns on the relay, use the N.O. connection. If you want your device to be on, unless the Arduino turns on the relay, use the N.C. connection.
It looks like you need N.O.

N.b: 'closed' means on (i.e. the switch is closed and current is allowed to flow).

Finally, you seem to be using an external pull-up resistor for you switch, which is completely unnecessary: the Arduino has an internal pull-up resistor on every digital pin that you can enable using pinMode(pin, INPUT_PULLUP).

Edit: you didn't connect the relay to the button pin instead of the LED pin, did you?


How to pad an ascii number with leading zeros?

This is the kind of situation where printf() comes handy:

printf("%03d", number);

prints the number in the format you described. Alas, printf() is not
part of the standard Arduino API. But you can have it, nonetheless, at
least on AVR-based Arduinos, as it is provided by the avr-libc, which is
always linked with all Arduino programs. Some setup is needed to tell
avr-libc about where is its “standard output”. We can use the macro
fdev_setup_stream() to tell it to just push the bytes through
Serial.write():

static int Serial_write(char c, FILE *) {
    if (c == '\n') Serial.write('\r');  // convert LF -> CRLF
    return Serial.write(c);
}

static FILE mystdout;

void setup() {
    Serial.begin(9600);
    stdout = &mystdout;
    fdev_setup_stream(stdout, Serial_write, NULL, _FDEV_SETUP_WRITE);
}

void loop() {
    static int count;
    printf("%03d and counting...\n", count++);
    delay(500);
}

C.f. the manual of avr-libc's
stdio.h
for details.

Pros of this method:

printf() has plenty of options to control the formatting of your
messages.
It's very standard C, understood by anyone having programmed in that
language.

Cons:

This can make your compiled program bigger than it would be if
sticking with the Arduino API.
It's not the “Arduino way”.


Can't you see what's hooking the serial port with sudo lsof -n | grep cuaU0 ? If so, sudo kill -9 12345, where 12345 is the offending PID. Your FTDI chip may need a driver, try sudo dmesg after pluggibg it in, or use systemprofiler.


is it possible to program an arduino with usb/ttl adapter

The Arduino onboard USB to serial is connected to D0 (Rx) and D1 (Tx).

And without a USB connected to the Arduino you can use a USB/TTL adapter connected to D0 and D1 like this;

Arduino  - USB/TTL
Tx       - Rx
Rx       - Tx

And to get the Arduino inte "programming" mode:

Automatic way, if the USB/TTL have CTS, connect it to Arduinos reset pin.
Manual way, press the reset button when the Arduino IDE starts to upload the code.


Is possible use Macro F() with Integer and Other types of variable?

For a constant array of integers you need to use PROGMEM and the various pgm_read_*() functions.

You can read more, and find examples, on the Arduino PROGMEM manual page.


How to write a library that support both HW and SW Serial communication and allow user to chose which one to use?

The trick here is to go "up a level".  Both HardwareSerial and SoftwareSerial inherit from the Stream class.  It is that class that provides the majority of the interface that you actually use.

So you can provide a constructor with a Stream object alone and use that:

class Foo {
    private:
        Stream *_dev;

    public:
        foo(Stream *dev) : _dev(dev) {}
        foo(Stream &dev) : _dev(&dev) {}

        void begin() {
            _dev->println("I am ready");
        }
};

Foo myFoo(Serial1);
SoftareSerial btSerial(11,12);
Foo myOtherFoo(btSerial);

What the Stream class doesn't provide, though, is .begin() for setting the baud rate. It has to be left to the user to configure the port before using it.

Serial1.begin(115200);
myFoo.begin(); // --> "I am ready" on Serial 1

or:

btSerial.begin(9600);
myOtherFoo.begin(); // --> "I am ready" on Software serial pins 11/12.

This is known as polymorphism, where an object is seen as one of the parent classes in the inheritance chain and is one of the most powerful aspects of object-oriented programming.

Not having begin in your library is no big deal really. It increases the flexibility (a user can more easily select their baud rate), and it means you don't force them to include SoftwareSerial if they don't need it.

There are other things that inherit Stream, as well, such as a networking Client. So instantly you class can be used with network connections as well as just serial.

So stick to using Stream. It's the accepted way of doing things, and perfectly normal. For example, it's how my ICSC library handles serial objects.  (I used to use the multiple pointer method, but it really really got messy when trying to support other platforms. I ended up with HardwareSerial, SoftwareSerial, USBSerial, Client... a real mess. So much simpler to just use Stream.)

BTW, before you ask, I have two constructors with very slight differences so that you can construct an object either by passing a Stream object by reference (as I do in the examples) or as a pointer (which can be great if you want to use this in another class which itself has a pointer to a Stream object).

Another option is to combine the Stream pointer with a dynamic_cast to try and identify the type of object being passed.

void Foo::begin(int baud) {
    if (HardwareSerial *hs = dynamic_cast<HardwareSerial *>(_dev)) {
        hs->begin(baud);
    } else if (SoftwareSerial *ss = dynamic_cast<SoftwareSerial *>(_dev)) {
        ss->begin(baud);
    } else {
        // We don't know what to do here
        // so do nothing?
    }
}

In this way dynamic_cast is being used like Java's instanceof operator to work out what kind of object it is that is being used.

Of course, that then means that you're really restricting the library to only working with those two types of object, but it is still possible to pass other class types as long as the user pre-configures them before calling your begin function. Which gets confusing - which type does the user need to .begin() and which types have .begin() called for you? It's just cleaner to always have it as the user must call .begin() themselves - there's no ambiguity then.


SerialGSM for GSM shield without SoftwareSerial

SerialGSM is designed to work with software serial, as you can see that from the class declaration in the SerialGSM.h header:

class SerialGSM : public SoftwareSerial {
...
};

Unfortunately, changing it to use hardware serial is more complicated than it looks. There are two potential ways you could go about it:

Derive from HardwareSerial instead of SoftwareSerial. This would give you flexibility, but you'd have to take care of passing all the right data to the HardwareSerial constructor, which is quite messy.
Don't derive from anything. Use the global Serial object, and manually replace all serial function calls with their Serial.xxx() equivalents. This is probably easier, but it restricts you to a specific serial port.

Both approaches involve quite a lot of coding, so they aren't trivial tasks. It's also important to note that SerialGSM currently uses the global Serial object to output debug information. You'd have to remove or modify that before converting to hardware serial, or else it could interfere.


You can't use two softwareserial devices together (or not reliably, and not without knowing exactly what you are doing).

It's not even easy using one software and one hardware serial together unless you know what you are doing.

SoftwareSerial blocks everything else from happening while it's sending or receiving, so using it for things that send unsolicited messages (as GPSs do all the time) causes havoc.

The best you can hope for is to use HardwareSerial for the GPS and SoftwareSerial for the GSM, which is call-and-response most of the time.

Better would be to use a better board that has multiple hardware serial ports.


Invalid conversion from 'const char' to 'uint8_t*'

In ESP32 Arduino package the WiFiUdp.h doesn't pull in all Print class write functions. As consequence the WiFiUdp class doesn't know write(const char *str).

Use Udp.print(message); if message is a zero-terminated char array

or Udp.write(message, size); if message is a byte array


I think you want to look at interrupts.  You are right, unless the button happens to be pressed when you read the state of it you won't see it as pressed.  If you foos take a long time to execute the you will miss button presses.

What you can do is use 'interrupts'.  Certain pins can be configured to stop the main program and run a small bit of code (that can't do certain things).  For instance they can change the value of a global volatile variable.  Next time the program reads the variable it will read the new value (volatile prevents the value being cached by the processor).

With you current code, you would remove the digital read line, and the if (buttonState == HIGH) block and move those into you ISR.  This would mean every click would be counted.  If you wanted the ISR to stop the current foo and move on then you foos would need to check a flag that the ISR also set and when they see it they return.

In the ISR you can't call Serial.print() etc, it takes too long and your ISR won't work.  Keep it fast and small.

https://www.arduino.cc/en/Reference/AttachInterrupt
https://www.arduino.cc/en/Reference/DetachInterrupt


ESP8266 Arduino MQTT callback with dynamic topics

I think using sscanf may help you

void MQTTcallback(char* topic, byte* payload, unsigned int length) {

  sscanf(data, "ObjectTL/TL_%d", dynamicTopicName);
  // handle message arrived
  your_dynamic_function(dynamicTopicName,byte* payload, unsigned int length)

}


It seemed to be a hardware problem on the board. Thanks for the effort.


Displaying when Button has been pressed for LED and returning 1

In your button() function, the line

if (current and not last) {

is less common syntax. The more common equivalent is:

if (current && !last) {

(see https://stackoverflow.com/questions/2376448/the-written-versions-of-the-logical-operators)

This line:

current == last;

Has no effect and is incorrect. This ( “==“ ) is not an assignment but a comparison and does not do what you want it to do.

I also think you have this the wrong way around. You want to save the “last” button state to compare it with the current button state when you call button() the next time. So you would need to set “last” to the current button state, like this:

last = current;

The next time you call button(), “last” contains the previous button state, so your comparison to the current button state will work.

And I think your button detection code would work better if you set last = current each time you call button(), whether a button has been pressed or not. Otherwise your code would repeatedly keep printing “Hey” until you stop pushing the button (unless that’s what you want). Like so:

int button() {
  pinMode(Button, INPUT);

  int current = digitalRead(Button);

  if (current &&  !last) {
    ...
    ...

    Serial.print("Hey");
    last = current; // Insert here
    return 1;
  }

  else {
    pinMode(Button, OUTPUT);
    ...

(This has not been tested but should give you a general idea).


Make Arduino send and receive at the same time

I am using SoftwareSerial for both.

As others have said, you cannot listen to 2 SoftwareSerial ports at the same time.

  Should/can I use HardwareSerial and SoftwareSerial?

  ... can the Arduino receive from GPRS and GPS module data at the same time?

Yes, but...

This answer provides full details on choosing "good" combinations of hardware and software serial ports.  To summarize:

Use the HardwareSerial port (i.e., Serial) for one of the devices.  You can still use it for debug prints, as long as the device has some kind of command "format".  For example, if commands start with "AT", just make sure that none of your debug prints start with "AT".  It is the absolute best choice.  You would have to disconnect RX pin 0 from the device in order to upload new sketches over USB.
Use AltSoftSerial for the other device.  It is the most efficient software serial port, and it can be used at the same time as Serial.  It only works on two specific pins.
NeoSWSerial is the next best choice, at limited baud rates.  It can be used with the above choices, but transmitting on NeoSWSerial prevents them from receiving.
SoftwareSerial is the worst choice.  Receiving or transmitting on SoftwareSerial prevents all of the above from receiving anything.  It disables interrupts for long periods of time.


You are looking for a thermocouple.

They need some specific chip to be read, so you'll probably want to spend a bit more and get a chip with a digital interface, there are some witch has arduino library, like MAX6675 (output at 1Hz, 0.25° precision).

As this chip read "C type" thermocouple, you just have to find the right probe for your needing, with probably can be found in many specialized store.

You may even buy a normal k probe, and then wrap it up in some protective case. Obviously that case should be designed to let the heat flow easily, but without short circuiting the probe; a food plastic bag;

or just spend a little more money and buy a stainless steel probe


Distance Readings Getting Manipulated When Calling Unrelated Function

The tone function uses timer interrupts to toggle a GPIO pin to make noise. That's quite intense from a CPU point of view and is most likely skewing the timing of the pulseIn function.

I would suggest not using tone if you can help it. Maybe change the frequency of a PWM output to something suitable and use analowWrite to create a 50% duty square wave.

Also learning how to use the Input Capture peripheral of the MCU (read the datasheet) will enable you to perform asynchronous sampling of your pulses and obtain much more accurate results.


Is there an easy way to turn integer values to pixels?

Simplest thing may be to write down your image in plain Portable Gray
Map format. This is a very
simple (and inefficient) ASCII format consisting of a signature (the
string "P2"), followed by the width and height of the image, followed by
the maximum possible gray level (1023 in your case), followed by the
pixel values. It's a free form format, meaning you can mix spaces and
newlines at your convenience.

Here is an example image: two rows of pixels, five columns, and
brightness increasing left to right and top to bottom:

P2
5 2
1023
  0 111 222 333 444
555 666 777 888 999

Then, any image conversion software should be able to convert that into
the format of your choice (PNG, JPEG, whatever...).


Is it support to use Infrared radiation module in ESP12E?

is it possible to use the IR module in esp8266?

Yes.

  how to do(sent and recive)?

You send by pressing a button on your remote control. You receive by measuring the timing of the changes in the pin state.

  what is the packet format of IR module?

Whatever packet format your remote control sends.

It's no different using IR on an ESP8266 compared to an Arduino. There's a library that everyone uses (IRRemote.h), and there are plenty of examples and tutorials on the web (or on YouTube if you can't be bothered to read). I suggest you ask Google for some.


Using ethernet, how do I navigate to a page on my local server

I discovered the answer after some testing.

The server var:

char server[] = "192.168.1.2/zombie/arduino.php";

should only contain the ip address.  So it should look like this:

byte server[] = { 192,168,1,2 };

The additional URL elements should be added using:

client.println("GET /zombie/arduino.php");

after a connection has been established

The final code should look like this:

#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1,3 };
byte server[] = { 192,168,1,2 };

EthernetClient client;

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);

  delay(1000);

  Serial.println("connecting...");

  int res = client.connect(server, 80);

  Serial.println(res);

  if (res) {
    Serial.println("connected");
    client.println("GET /zombie/arduino.php");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.println("data:");
    Serial.println(c);
  }else{
    Serial.println("NA");
  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}


There is no "variable A" - there is only a macro called "A" which gets replaced by the contents of the #define for "A" at compile time.

You have to remember that the "A" that the Arduino receives is just a number.  It is only us humans who choose to associate that number with the letter A, and write software that takes that number and display it as an A.  The letter A is number 65.  The mapping between numbers and letters is called ASCII - or American Standard Code for Information Interchange.

What you do with that number is entirely up to you.  If you want to use it to display pre-defined messages, then there's a number of ways you could do it.  You could:

Use a series of if statements to compare the number you have
Use a switch/case construct in a similar way
Store the messages in an array and use the received number as the index

For string constants the last option is tricky to get right on an Arduino where there is very limited RAM - you have to ensure that you use PROGMEM and access it properly, and doing that from an array is not as trivial as it would otherwise be.

The best method would probably be the switch/case option:

switch (letter) {
    case 'A': Serial.println(F("First Message")); break;
    case 'B': Serial.println(F("Second Message")); break;
}


Stepper not working properly using L298N

The motor you got is a unipolar stepper motor. The five wires are one end of the four windings inside the motor, plus a common wire that connects all the other poles together.
Bipolar motor offer more torque than unipolar, at the expense of a more difficult control. 6 wires unipolar stepper motors can be converted to bipolar motors just selecting the correct wires. I am not aware of any method to convert a 5 wires unipolar motor to bipolar that does not imply tearing it apart (which is not really a great idea).
The L298 is not really made to drive this kind of motor, it is best suited to drive bipolar motors (can still drive it tho, please read the next paragraph). Good news, driving unipolar steppers is rather simple. You basically have to connect the common wire to you V+ rail and connect the other wires to GND via BJT/MOS. Don't connect them directly to the Arduino! It's the perfect recipe for fried chips. You can either choose to use discrete transistors or arrays like the ULN2003.
If you still want to use the L298 to drive the motor you can exploit the lower transistors of the H-bridge. Connect Vss and the enable pins to 5V, Vs to your positive rail voltage and pin 1, 8, 15 to GND. Then connect each phase to each output and the input to 4 pins to an Arduino/microcontroller. Leave the pins normally on and turn one off in turn (1->2->3->4->1...) and your stepper should run! This works because when you leave the pins on, the upper side of the H-bridge is powered on, thus shorting the winding. When you turn one pin off the lower part of the bridge will actually turn on and let the current flow to GND, closing the circuit and powering the winding. Using this kind of circuit you could also omit the freewheeling diodes needed to discharge the windings (as said before, you short them, allowing current to freely circulate).
EDIT/TLDR: Connect the windings to the output of the L298 and the common one to the positive rail. Keep the pins high and turn one sequentially off, you should see the motor move.


The additional 80uA drain is almost certainly coming from the pull-up resistor being shunted to ground though the reed switch.

https://www.wolframalpha.com/input/?i=(3+volts)+%2F(50k+ohm)+in+uA

As suggested by @Edgar Bonet, one way to greatly reduce this drain is to disable the pull-up immediately when you wake from the pin going low. At this point it is possible for the pin to stay low even if the switch is no longer grounding the pin, so you need to periodically check it using a watchdog.

Wake from pin going low pin change interrupt
Disable pull-up (stops current flowing though resistor)
Do your logging operation.
Enable a watchdog wake up
Go back to sleep.

At this point you can wake either from (1) a watchdog or (2) pin change if the pin goes high again.

If you wake from a pin change...

re-enable the pull-up
disable the watchdog
go back to sleep

If you wake from the watchdog...

re-enable the pull-up.
if the pin is high now, disable the watchdog and go back to sleep.
if the pin is low, disable the pull-up and leave the watchdog running and go back to sleep.

The watchdog timer on this part should only use single digits of uA while running, and it should only need to be running while the switch is grounding the pin. You can set the watchdog timeout to be quite long- on the order of seconds even, to reduce the frequency you  wake to check with the pull-up (and therefore the net power used, at the cost of latency for detecting pin changes). The main downside to this strategy is that you can miss activations that happen inbetween your watchdog wake-ups, so for example if the pin goes low and then you set the watchdog for 8 seconds, and then the pin changes high and then low again during the next 8 seconds, it is possible (but not assured) that you could miss the second event, so set the watchdog timeout to be short enough that you will not miss consecutive events that you care about (you might not care if the door is opened twice in the same minute anyway).

Also, as noted by the famous @nick gammon, you might be able to get lower than 5uA when sleeping without the watchdog. Check to make sure you are disabling everything in the power register and that all unused pins are in input mode (these will be disabled when sleeping as long as there is not a pin change interrupt on them).  There are lots of googleable articles on minimizing ATTINY power during sleep.

You also mentioned that your dominant case is that the switch is closed rather than opened. Since this is the higher-power case with the current switch consider using a normally open switch rather than normally closed one if possible.

Finally, if you just want simplicity and you only care about events of a minimum duration (saym then door much be open for at least 1/2 second to be noticed), then you can skip the pin change interrupt completely and only use an always-running watchdog to wake periodically and very quickly enable the pull-up and check for the desired pin state, and then disable the pull-up and go back to sleep. You should be able to do this in less than a dozen cycles so the net power usage should be almost as low as the watchdog timer drain by itself.


Is there a simple HTTP(S) library that doesn't rely on WiFi?

The TinyGSM library implements Arduino networking Client base class over GSM modem's AT commands. The library is available in Library Manager.


Is it possible to burn a bootloader to an ATTiny85 with USB TTL and avrdude?

No, you can't because a USB -> TTL serial device is not made for that. You CAN however use an Arduino Uno to burn a bootloader to another Atmel micro, including the Attiny85.

Now you may ask, can you use the Digispark in place of the Uno (and thus burn more Attiny chips). The answer is a qualified yes.  Another Arduino can do this -- search the web and find many examples.

You might (?) even adapt that sketch from the Uno to the Digispark (saving the cost of an Uno). I can't advise further and you're looking at a rabbit hole of possible issues.

Sparkfun does sell a chip which can perform boot-loading using minimal components:
https://learn.sparkfun.com/tutorials/how-to-install-an-attiny-bootloader-with-virtual-usb


Look for a repetition in your code.

  //Repeating code..
  if (analogValue > GreenOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00000000 );
    digitalWrite(latchPin, HIGH);
    delay(1);
  }

  if (analogValue > GreenTwo) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B10000000 );
    digitalWrite(latchPin, HIGH);
    delay(1);
  }

You will notice that you have a lot of repetition of the general structure of a if-comparison (always with a different value) and then a shiftOut with a different value to be shifted out.

  //General code structure
  //Only things to change is someComparisonValue and someDataValue
  //the rest is the same.
  if (analogValue > someComparisonValue) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, someDataValue);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }

You can generalize and simplify the code by storing those different comparison values and data values in a look-up table (LUT). Now you could use two arrays to hold these values but you could also further condense it in a C struct, a "data structure".

Let's define a data structure which holds a threshold value and then the data to be shifted out as  struct.

/* Defines a LUT entry */
struct LutEntry {
    int treshhold;  /* threshhold value */
    byte data;      /* data to be shifted out */
};

We can then pack the actual data into a single variable. Because this is constant data, it will take up flash memory instead of RAM.

static const LutEntry lutTable[] = {
    { GreenOne, B00000000},
    { GreenOne, B10000000},
    { GreenTwo, B11000000},
    { GreenThree, B11100000},
    { GreenFour, B11110000},
    { YellowOne, B11111000},
    { YellowTwo, B11111100},
    { RedOne, B11111110},
    { RedTwo, B11111111},
    { MaxHold, B00000000}
};

From there we can also see that there is a computable relationship between the index of the treshhold value and the data to be shifted out - an entry at index i will be associated with the data bitstring in which all bits from the MSB up to i inclusive are 1, the rest being 0. Except for MaxHold as special value. We could exploit this property to get rid of that data member entirely, but that is an exercise left to you.

Now we can re-write the loop code by simply taking a analogRead sample and then iterating through the entires of the LUT to shift out the corresponding data.

void loop() {
    int analogValue = analogRead(analogPin);
    int numLutEntries = (int)(sizeof(lutTable) / sizeof(lutTable[0]));

    for(int i=0; i < numLutEntries; i++) {
        if (analogValue > lutTable[i].treshhold) {
            digitalWrite(latchPin, LOW);
            shiftOut(dataPin, clockPin, MSBFIRST, lutTable[i].data);
            digitalWrite(latchPin, HIGH);
            delay(1);
        }
    }
    Serial.println(analogValue);
    delay(1);
}

Which transforms 69 lines of repeating code into 12 lines of non-repeating code.

After this general code cleanup it becomes easier to add another shift register: You can define a new look up table, or modify the structure of the old one, to hold the information you need (treshholds, data to be shifted out, the clock, data and latch pin for the register, ...). What logic needs to be there is something only you know, because the description "add another chip [to this code]" is quite broad.

In short:

DRY: Don't repeat yourself. If you use a piece of code over and over again with only slight variances in used values, make it a function
recognize the differences of the used data values in used code pieces and try to group them neatly together. Use the language feature of structs or class to express the meaning of this data
exploit certain properties / relationships of your data to save even more memory / computing time.


There are multiple ways to do that.

You could use an Arduino Leonardo as a keyboard, then send a shortcut command to shut down or sleep the computer. You can edit these from System Preferences>Keyboard>Shorcuts>Services.
The keycode 0x66 does not work for mac, but may for other operating systems source
You could write a small program (I'd do it in Python) which communicates with the Arduino over the serial port and shuts down the Mac if the Arduino wants it to.
You could sacrifice an USB keyboard and use a relay to "press" the power key.


Can't send HTTP request using ESP8266 and Arduino Uno

The domain is missing. Try this instead:

GET http://www.linysoft.com/arduino/?light=on HTTP/1.0\r\n\r\n

Cheers!

Ref. http://contractorwolf.com/esp8266-wifi-arduino-micro/


Kind of.

You don't have to change pins_arduino.h.
Try the LED_BUILTIN_TX and the LED_BUILTIN_RX.
The pins are turned on and off by the code for the SerialUSB port. That can not be changed without changing the Arduino libraries. Setting that pin to INPUT in your sketch in the setup() function will turn them off:

pinMode(LED_BUILTIN_TX,INPUT);
pinMode(LED_BUILTIN_RX,INPUT);

If you have troubles with the LED_BUILTIN_TX and the LED_BUILTIN_RX, then you can use this as well:

bitClear(DDRD,5);
bitClear(DDRB,0);

The code for the SerialUSB port still writes to that pin, but once they are set as INPUT, that code will turn on and off the pullup resistor. That is no problem since those leds are connected to VCC.

To turn them on is also possible, but then those pins needs to be OUTPUT and LOW. They will not stay on when the SerialUSB port is used.


How does an LED in an LED-strip like WS2811 know when it should be on or off

The WS2811 is the driver chip, that is embedded into the strip. In principle it is some kind of shift register, that outputs PWM values, and on the strip they are daisy-chained (data output of one is connected to data input of the next). With the Arduino you shift out a stream of bytes, when using a RGB strip 3 bytes per LED (1 byte per color). The first WS2811 reads these 3 bytes, sets it's outputs (PWM) according to them and outputs the rest of the datastream to another pin, so that it can reach the next WS2811. The LEDs on the strip are connected to the WS2811's outputs.

So all in all the WS2811 chip saves the current desired state of it's LED, which it got through the data stream from the Arduino. The chips don't have a direct address, but can be identified by their position in the strip. So you cannot only write to the 5th LED without also writing values to the LEDs before it. But, if you don't want to set the whole strip, you can output less data, than the strip as LEDs, effectively ignoring the LEDs at the end.

EDIT:

  but How does it recognize the first led?

The strip has somewhat like a data line. When you look at the markings for this line on both ends of the strip, you normally should see something like "DI" and "DO", which means Data In and Data Out, each at one end of the strip. Each LED has it's own Data In and Data Out, which are chained to the next and the previous LED. The first and last LED expose their Data In or Data Out (respectively) to the outside of the strip. You feed the data into Data In of the first LED driver, which outputs the rest of the data at it's Data Out pin, where the data can go to the next driver. So the direction, in which the data flows through the strip is already defined and hardwired. You cannot send data in the other direction through the strip. So the first LED is that one, that is directly attached to the Data In line of the strip and will be connected to the Arduino.

Keep in mind, that this is not an address. You can cut the strip at an appropriate place (so that you don't destroy the circuit. Most strips have these pieces regularly after every or every third LED) and get a new first LED, if you now connect the Data In, where you cut the strip, to the Arduino. An LED strip with WS2811's is not an array or a matrix of LEDs, it is a chain of LEDs. This difference is important in how you control them.


I'm afraid that with PWM controler I won't be able to do that.

Chances are that any PWM controller is going to let you control each output independently.

According the the servo library documentation, the library can handle up to 12 servos on a single Arduino, so your project should be feasible. It will however reduce the number of PWM pins available from 6 down to 4.

  Will a 9V battery power all these servos?

No! Not a chance.

Typical 9g servos consume 150 mA without any load, and stall at ~700-900 mA. A typical 9v has ~500 mAh capacity, and most data sheets show loads of ~100-150 mA max. Your 9v might be able to supply a few amps for a few seconds before they heat up and slow down.

If your load is very light 9 servos will consume ~900 mA; an ideal 9v would last at most 30 min with this load, but real batteries aren't ideal and will heat up and loose efficiency.

Near maximum load your 9 servos will draw ~7000-9000 mA, well beyond the capabilities of a 9v. However those numbers are for 5v so you could cut them all in half.

If you used an appropriate 5v step-down DC-DC supply you might be able to power all 9 servos for a few seconds before the batter overheats and gives up.

If you powered them directly, the servos will have to dissipate more heat, and will draw extra power, could damage the servos if the batter could supply enough juice.


PIND refers to the arduino's IO register for input in port D

Without arduino, one has to refer to pins by specific bits in 3 different sets of registers for each port (PIN*, DDR*, and PORT*; B,C, and D).

The arduino code makes it simpler to pick out a single pin by hiding all of this, but it does make reading a pin take much longer.

In the code, the specific pin is being selected by masking off all but the "irpin" bit in PIND, so changing irpin will pick a different bit and thus a different pin.

Pin 9 is actually bit 1 of port B, not D, so see if this works:

#define IRSENSOR PINB
int irpin = 1;

alternatly, using a reference instead of define,

volatile uint8_t& IRSENSOR = PINB;
int irpin = 1;


AVRdude does not read the FUSE byte values correctly

A couple of things.  That you can't change fuses from the bootloader and that optiboot can't report fuse values correctly, even if you change them.
No self-programming of fuses
A bootloader can't write fuses, at all.  The chip just doesn't allow self-programming of fuses.  If you want to change fuses, you'd need to resort to external programming (usually using the ISP protocol) with an AVR programmer (or another Arduino set up to behave as one).
Optiboot and reading fuses
Optiboot doesn't report fuses, at least not as compiled for UNO.
The "arduino" bootloader protocol used by the avrdude -c arduino option is a modified version of the STK500(v1) protocol.  The are two commands there that would need to be implemented to read fuses, Cmnd_STK_READ_FUSE and Cmnd_STK_READ_FUSE_EXT.  They have corresponding definitions in the AVR Arduino core's copy of optiboot source.  But the places where they would be implemented in the series of if-elses are absent.  Unlike writing fuses, reading fuses is possible from AVR code.  So it's not a limitation of the chip, the code to do it just isn't there.
Sidenote: You may notice that there are also definitions for commands that write FUSES.  These exist for STK500v1 programmers rather than bootloaders, which can implement these to support writing fuses.
For what it's worth optiboot doesn't actually read the signature of the chip either.  It just reports whatever values have been baked in at compile time.  Both this and the not-reading-fuses above are probably done to keep optiboot as small as possible, which is its goal.
In any case, if you do change your fuses using a programmer, expect optiboot to continue reporting them as zero.
Current fuse values
If you're curious about your actual fuses values, you run sketch that reads them and prints them over serial by using #include <avr/boot.h> and
Serial.print('E');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS), HEX);

Serial.print('H');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS), HEX);

Serial.print('L');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS), HEX);


How can I receive signal from remote control using tcrt5000 sensor module

The TCRT5000 and the TSOP31238 are very different. The TCRT5000 is actually a reflective distance sensor. It has an IR LED and a simple IR phototransistor, not more. The TSOP31238 in contrast is meant to receive data from IR remotes. IR remotes work with modulation of IR light. The IR LED is pulsed with a frequency of 38kHz (in the case of the TSOP31238). This frequency is modulated with the actual data, meaning there are different time lengths were there is no IR signal and where there is a 38kHz IR signal.

The TSOP31238 detects the IR light with a phototransistor, like the TCRT5000 has. But then the signal is processed with an amplifier, a band pass to filter out all frequencies but the 38kHz and then demodulated, so that you don't see the 38kHz signal on the output, but only the pulse lengths.

The demodulation should actually be the least complex part to build yourself. That can be even done by code. But to get good results, you also need the other parts. You would have to build an amplifier circuit with an opamp. And would have to build the bandpass (for example with an LC element).

You can build these things yourself, but: The sensor, that you have, is not meant for receiving IR remote signals. The parts, that you would need to make the signal usable, will cost way more, than just buying a TSOP. Also it will be a lot easier and most likely better working (processing the signal from a phototransistor can be tedious). I suggest, that you buy a TSOP chip fitting to your remote control.


error: expected primary-expression before ',' token

Two things:

You have a comma missing: 1260,12601635,1635,
You have an extra comma: 1180,1180,,1255,1255

If you reformat your list into a nice regular table (say 10 entries per line) across multiple lines these things instantly become apparent.


It is not easy to find the problem remotely. Here is what I would do:

My first problem have always been connections. I gave up using breadboards and other connectors. Use soldering instead to be sure your circuit is properly connected.
Add some Serial.println() in both codes to see what exactly is going to be sent, and what has been received.
On the sender code, add a delay(100) to the loop. That would give the module buffers a chance to process.
You can improve it more by checking for the button value you read with the old value, and only send the value if the state has changed.


Pass templated function as attachInterrupt parameter

Try this:

template<int PIN, int CHANNEL> void initPin() {
    attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
}

template<int PIN, int CHANNEL> void rising() {
    startTimes[CHANNEL] = micros();
    attachInterrupt(PIN, falling<PIN, CHANNEL>, FALLING);
}

template<int PIN, int CHANNEL> void falling() {
    values[CHANNEL] = micros() - startTimes[CHANNEL];
    attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
}

The problem is actually the Arduino preprocessor. It adds illegal forward declarations if template functions are formated as your original code.


In the datasheet I read 14 mA @ 12V, which is below the recommended current of a GPIO pin of 20 mA.

Note that 40 mA for a GPIO pin is the max current, recommended is 20 mA. But 14 mA is way less.

To see if it changes for 5V, try connect it without an MCU (directly to a 5 V adapter/USB/breadboard power) and measure the current using a multimeter.

In case it uses more than 20 mA @ 5V, than use a transistor/mosfet to drive the buzzer.

In case you want to have the buzzer at full power, connect a VCC 5V power rail pin to a boost converter, which is controlled by a transistor/mosfet controlled by a GPIO pin.

Thus

Arduino VCC 5V -> Boos converter to 12 V -> Transistor/Mosfet -> Buzzer -> GND
                                                 ^
                                           Arduino GPIO pin


Set control register to low in ds3231 rtc

I also have a DS3231 RTC in my robot project.  Here's my complete setup code.  This can be placed anywhere in setup():  I don't think you have to mess with individual registers to get what you want.
    if (rtc.begin()) //02/19/19 this now returns FALSE if RTC doesn't respond
    {
        Serial.println("Found RTC...");
        delay(100);
        bRTCLostPower = rtc.lostPower(); //added 10/17/18
        mySerial.printf("rtc.lostPower() reports %d\n", bRTCLostPower);

        if (rtc.lostPower())
        {
            Serial.println("RTC lost power.  Setting RTC to last compile time");
            rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));// sets RTC to last compile date/time
        }

#ifdef FORCE_RTC_TO_LAST_COMPILE_TIME
        Serial.println("Forcing RTC to last compile time");
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));// sets RTC to last compile date/time
#endif

        DateTime now = rtc.now();
        char buffer[100];
        memset(buffer, '\0', 100);
        mySerial.printf("Retrieving Date/Time from RTC with rtc.now() =  %ld\n", now.unixtime());
        GetDayDateTimeStringFromDateTime(now, buffer);
        Serial.print("Date/Time: "); Serial.println(buffer);
        RTC_Avail = true;
    }
    else
    {
        Serial.println("Couldn't find RTC. Real-time clock functions won't be available");
        RTC_Avail = false; //use this instead
    }

    if (RTC_Avail && rtc.lostPower())
    {
        DateTime Comp_dt = DateTime(F(__DATE__), F(__TIME__)); //__DATE__ & __TIME__ are environment variables)
        uint8_t mydayofweek = Comp_dt.dayOfTheWeek();  //returns 0 for Sunday, 6 for Saturday dayOfTheWeek
        int mymonth = Comp_dt.month();
        int myday = Comp_dt.day();
        int myyear = Comp_dt.year();
        int myhour = Comp_dt.hour();
        int mymin = Comp_dt.minute();
        int mysec = Comp_dt.second();
        long unixtime = Comp_dt.unixtime();
        char* dayofweek = (char*)daysOfTheWeek[mydayofweek];

        Serial.print("day of week value = "); Serial.println(mydayofweek);
        Serial.print("day of week value = "); Serial.println(Comp_dt.dayOfTheWeek());

        mySerial.printf("RTC lost power - setting to datetime of last compile %ld (%s %4d/%02d/%02d at %02d:%02d:%02d)\n",
            unixtime, dayofweek, myyear, mymonth, myday, myhour, mymin, mysec);

        rtc.adjust(Comp_dt);
    }


How to interface OV5640 to Arduino Mega using Embedded C?

Arducam gives you all the info you need on the necessary register settings. The register values for each color space and resolution are defined in this header while the initialization sequence, image format selection and image capture process among other stuff, are implemented here and documented if you look closely at the variable names and compiler directives.

EDIT: More details

Lines 327 - 372 contain the relevant initialization sequence for this specific camera. For instance, assuming you want JPG images, line 335 marks the start of the needed settings:

delay(100);
wrSensorReg16_8(0x3103, 0x11);
wrSensorReg16_8(0x3008, 0x82); delay(100);
wrSensorRegs16_8(OV5640YUV_Sensor_Dvp_Init); delay(500);
wrSensorRegs16_8(OV5640_JPEG_QSXGA);
wrSensorRegs16_8(OV5640_QSXGA2QVGA);
wrSensorReg16_8(0x4407, 0x0C);  # assuming you arent using the Arducam shield or OV5640 5MP Plus

What wrSensorReg16_8 does is pretty obvious: write the 8-bit 2nd argument into the register specified in the 16-bit 1st argument. wrSensorRegs16_8 merely does the same thing for multiple register-value pairs passed into it. OV5640YUV_Sensor_Dvp_Init, OV5640_JPEG_QSXGA and OV5640_QSXGA2QVGA are all structs defined in the header I mentioned earlier; they contain the rest of the register-value pairs you need to know about. Ultimately, these settings should give you 320x240 JPEG, I think.

You can't use the start_capture method since you don't have the ArduCAM FIFO so you'll have to start grabbing frames yourself (and buffering them somewhere very quickly; transmitting the bytes as you read them is out of the question) by paying attention to VSYNC, HREF and PCLK. Look at the timing diagrams in the datasheet. I assume you'll only be taking frames occasionally since a Mega won't do for video. If you're very lucky, you'll get a nice image on your first try but on the whole, be ready to spend serious time studying the datasheet, ArduCAM code and other 0V5640-related code on the web or just go with the OV7670 which has more examples/tutorials.


How to insert a power button on Arduino Nano

Cutting a usb wire would be the easiest. Otherwise you'd have to cut traces in the pcb and attach wires. Not recommend for beginners. You can actually buy usb cable with a switch.

Another alternative would be to put the microcontroler in sleep mode and have it use very little power.


Stepper Motor is not working with A4988 board

You have to connect the sleep and reset pin together. I assume that you took this schema on how to mechatronics. In his video you see that the sleep and reset pins are connected. I don't know why but it has to be like that.
Then, if the motor vibrates or click, it may be one of these problems:

You didn't connect the motor properly
The current is set too low on the board (screw on the motor driver)
The battery (Vmot) isn't powerful enough

If it's not one of those problems, the A4988 chip might have an issue. I have a similar problem where it turn in one direction and only when the pwm signal goes throught the direction pin  instead of the step pin.


Sensor for very low temperature (liquid nitrogen)

You probably want a K-type thermocouple (the most common type).

They have a range of around -200°C to +1350°C (depending on probe).

Alternatively a Resistive Temperature Device (RTD) can be used, since these have a typical range of around -240°C to 650°C with higher accuracy.

This might be of help to you: http://digital.ni.com/public.nsf/allkb/C50FA55B3B2F85D9862572D00083350E


The Teensy 2.0 is a completely different MCU from the 3.0 with very different libraries.

USB on the 32U4 on the 2.0 typically uses the LUFA library for USB.

So to answer your question: I doubt it will be possible to port code written for the 3.0 SAMD based teensy to the AVR based 2.0 teensy without basically rewriting it from scratch.

The Arduino Leonardo also uses a 32U4 so you might want to look for examples code written for the Leonardo.

The examples from the LUFA library may be useful but they are not designed to be used with the Arduino IDE.

UPDATE From the comments, there is this project:
https://github.com/bootsector/XInputPadMicro that uses LUFA and targets the Leonardo.


Something like this, with variable declarations & setup() left to you.  All time elements are of type unsigned long.

pwmValue {} = [51, 102, 153, 204, 255];

void loop(){
  if (digitalRead(startButton) == LOW && pwmCycling == 0){
    // start button pressed, and not already running
    startTime = millis(); // capture the time of the button press
    pwmCycling = 1; // keep track of the running state. 0 for off, 1 for on.
    }
  if (pwmCycling == 1){ // cycling is running
    // this is where the blink without delay is:
    currentTime = millis(); // capture the time now
    elapsedTime = currentTime - startTime; // see how much time went by
    if (elapsedTime >= eventDuration){  // enough?  start next brightness
      currentTime = startTime; // set up for next event time
      brightNumber = brightNumber +1; // keep track of brightness level
      if (brightNumber >= 5){ brightNumber = 0; } // reset after the last level
      analogWrite (ledPin, pwmValue[brightNumber]); // write the LED pin
      }
    }
  if (digitalRead(startButton) == LOW && pwmCycling == 1){
    // start button pressed while LEDs are cycling, stop them
    pwmCycling = 0;
    analogWrite (ledPin, 0);
    brightNumner = 4; //reset the brightness level to the end
    delay (100); // little bit of dumb debounce delay
    }
}


Factor 8 in timing smells like wrong fuses.

Perhaps you don't use an external oscillator, but the internal one?


The code in your sketch is unlikely to be the problem. It works fine for me after I enter the IP addresses and password for my network.
According to the pubSubClient API documentation, the rc = -2 code returned by client.state() is due to the network connection having failed. As your code has already checked that it is connected to WiFi before trying to contact the MQTT broker, it is probably the communication between the two devices that is the issue, not the WiFi connection itself.  Things to check:

Are both devices are on the same network, and do they have a route to contact each other? From the laptop running the MQTT broker, try running ping XXX.XXX.XXX.XXX (replacing the XXXs with the IP address reported by the ESP32), and check you get a response. You might wish to comment out line 67 of your code so it doesn't disconnect from WiFi after every attempt at sending a message, otherwise you will see lots of lost packets.
Have you got the right IP address for the MQTT broker in your sketch? It should be the IP address for your laptop, not the loopback address, 127.0.0.1.
Can you use another device on the same network to connect to the MQTT server? (e.g. a cellphone running a MQTT dashboard app)
Is Mosquitto configured to listen out for remote connections? If you are running v2 of Mosquitto, you have to deliberately configure it to accept incoming connections, otherwise it will only listen to the localhost interface. You would also have to either set up an authentication mechanism or explicitly configure it to allow anonymous connections. This might be why you can connect from the laptop running the broker, but not from other devices.
On the MQTT server, can you see any connection attempts in Mosquitto's log file (/var/log/mosquitto/mosquitto.log)? There might be some error messages that give you further clues.


Why does the ADC overflow when using an external Aref?

The minimum reference voltage is 1.0 V according to the atmega328 datasheet. See table 29-15. ADC Characteristics.


After some more searching I found it in /usr/share/arduino/examples.


Will 5V to input pin damage the Arduino board?

No, no short. Arduino (Atmega) pins default to inputs. Pins configured this way are said to be in a high-impedance state. Input pins make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 megohm in front of the pin.

Answer provided by Look Alterno and converted from a comment.


Possible to put the ESP8266 in bootloader mode without a FTDI?

The cable you point to is fine for programming the ESP8266. The only reason it's not "good" for an Arduino is the lack of a DTR signal to trigger a reset for you - which you can do manually anyway and still use it for an Arduino (if your reactions are fast enough).

You have no such problem with the ESP8266. Once you have it in bootloader mode it stays in bootloader mode until you tell it to exit bootloader mode.

First make sure that the ESP8266 is actually set up to run properly. That means:

Connect CH_PD to 3.3V, not GND, through a pull-up resistor.
Connect GPIO0 to 3.3V via a pull-up resistor.
Connect RST to 3.3V via a pull-up resistor.

Then for simplicity of programming:

Connect a button between RST and GND
Connect a button between GPIO0 and GND

To enter bootloader mode simply hold the GPIO0 button in, tap the RST button, then release the GPIO0 button.  When you have successfully uploaded your firmware just tap the RST button to exit bootloader mode.

ESP8266 boards with a built-in USB interface usually use both the DTR and the RTS pins to control both those buttons virtually. That's somewhat complex to arrange for an external USB to TTL UART adaptor, so it's simpler to just press the buttons manually.

Here's a link to a website that details the circuit and operation using an ESP-01 as an example.


XBEE WiFi S6B RSSI for Smartphone localization

Just incase anybody stumbles onto this page googling, I am posting my solution below (I think it will work for any xbee radio)

Basically for some reason the RSSI values are getting nulled out before I can read them, both in my API mode tests and AT commands.  I'm not convinced that there is not some way around this in API mode at least, but it is irrelevant for my current purpose.

What I did was wire pin 6 on the xbee to a digital pin on the Arduino (I used 7) then use a pulse detector to find the period of the wireless signal coming in.

int pin = 7;
unsigned long period;

void setup(){
  Serial.begin(9600);
  pinMode(pin, INPUT);
  Serial.println("Getting started");
}

void loop(){
  delay(100);
  period = pulseIn(pin, HIGH);
  Serial.println(period);

}

It is not perfect, but for now it works, might help someone else in the future.


How to get a button state change within a for loop?

You aren't reading the state of the button within your loop.

You only read it the once at the top of your loop():

void loop() {
  // read the state of the pushbutton value:
  switchState = digitalRead(buttonPin);

You need to replicate that every time you want a new reading from the button - so in your loop you need to add that digitalRead line:

// Play tone after light fully bright
for(int i = 1; i<100; i++){
  // Turn off tone on button press
  switchState = digitalRead(buttonPin);
  if (switchState == HIGH) {
    noTone(TONE);
    break;
  }
  tone(TONE, notes[random(0,3)]);
  delay(100);
}

Or you can do away with the variable altogether and just test the return value of the digitalRead:

// Play tone after light fully bright
for(int i = 1; i<100; i++){
  // Turn off tone on button press
  if (digitalRead(buttonPin) == HIGH) {
    noTone(TONE);
    break;
  }
  tone(TONE, notes[random(0,3)]);
  delay(100);
}


LED Strobe based on switch press through Arduino

This is a modified Example program that i have tested and seems to do what you expect. I have used a 2 position switch instead of a button. using a pointer "ledState" to indicate that the LED has flashed and have then combined 2 conditions with the "&&" in the IF statement.

/*
  Button

 Turns on and off a light emitting diode(LED) connected to digital
 pin 13, when pressing a pushbutton attached to pin 2.

 The circuit:
 * LED attached from pin 13 to ground
 * pushbutton attached to pin 2 from +5V
 * 10K resistor attached to pin 2 from ground

 * Note: on most Arduinos there is already an LED on the board
 attached to pin 13.

 created 2005
 by DojoDave <http://www.0j0.org>
 modified 30 Aug 2011
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Button
 */

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status
int ledState = 0;
void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if ((buttonState == HIGH)&&(ledState == 0)) {
    // Flash LED:
    ledState = 1;
    digitalWrite(ledPin, HIGH);
    delay(500);
    digitalWrite(ledPin, LOW);
    delay(500);
  } else if ((buttonState == LOW) && (ledState == 1)){
    ledState = 0;
    delay(50);
    }
}


millis() and micros() overflow periodically. However, this is not a
problem: as long as you compare durations instead of
timestamps you can
forget about the overflows.

The liked answer also gives the trick for resetting millis(). Can be
handy for testing purposes, but you do not need this to handle the
millis() rollover problem. Notice that there is no clean way to reset
micros(): it relies on a static variable, i.e. a variable private to
the file defining it.


Arduino LED Dimmer Proportionate to Ambient Light

For certain Arduino models, the PWM pins are different. For the iteaduino lite, a usable PWM pin is pin D5.

Here is the code updated to use D5 instead of D1, which lacks PWM abilities:

//set pin numbers
//const won't change
const int ledPin = 5;   //D5 PWM the number of the LED pin (OR to MOSFET input wire for controlling high power LED
const int ldrPin = A0;  // A0 the number of the LDR pin
//10K OHM resistor as voltage reference.

void setup() {

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
  pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
}

void loop() {
  digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
  int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
  int dim = map(ldrStatus, 0, 1023, 0, 255);     // scale it to use it with the LED (value between 0 and 255)
  analogWrite(ledPin, dim);               //Flash LED at that rate to adjust brightness.
  Serial.println(dim);
   }

There is still flickering, but that is to be expected. map() ranges can be adjusted to set when the LED will be fully off or on.

It is still unclear how to allow the light sensor to take a reading while the LED is OFF, then power back on rapidly enough to not have a visible flicker.
If anyone has thoughts on that, it would be appreciated!
Thanks everyone for helping.


Arduino Nano IoT 33 Char Array size constraints

You can use the flash memory of the SAMD21 MCU used on Nano 33 IoT, if you don't write to often. Flash memories have limited count of write-erase cycles. It is guarantied for 10000 writes.

For Arduino SAMD boards like the nano 33 IoT you can use the FlashStorage library. The library is in Library Manager.


It doesn't get much easier than a shift register :) Why do you think it's a hard-to-use component?

The tutorial you pointed claims to be a Nixie driver, but omits the hardest part about nixies: driving them at 170V. IN12B nixies are easy to come by, they cost about $3 each on ebay, but you may also want to consider http://www.tayloredge.com/storefront/SmartNixie/index.html

I am not affiliated with Tayloredge, I'm just a happy customer.


Problem with interrupts and 4x encoders on Nano 33 BLE

Best practice would be to use a single interrupt for the encoder.  BLE has a faster processor and your code is not frame-based so that just might affect it also.  This code doesn't do exactly what your code did but it will use val to track position as a number.
It can also be made a bit finer using CHANGE instead of RISING, but for debugging bare bones means less that can go wrong.

#define PIN_A 2
#define PIN_B 3

volatile int val = 0;
int oldVal;
//volatile bool newVal = true;

void encoder() {
  if(digitalRead(PIN_B)) ++val;
  else --val;
}

void setup() {
  Serial.begin(57600);

  pinMode(PIN_A, INPUT_PULLUP);
  pinMode(PIN_B, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN_A), encoder, RISING);
}

void loop() {
  if (val != oldVal) {
    oldVal = val;
    Serial.println(oldVal);
  }
  delay(500);
}


As you might have already seen, a position sensing system can be really complex. Here I will list some possibilities, that come to my mind and might be fitting for your case or not.

Matrix based solutions: Here I mean sensors a some sort arranged in a matrix underneath the game table, which can sense the object placed on them. As you know from your wiring, where a specific sensor is located, you know from the triggered sensor, where the object was placed. The resolution directly corresponds to the numbers of sensors, that you place. You can use different sensors, which will give you different information, but are also very different in handling and costs:

Reed switches and magnets on the bottom of the objects. The magnet on the object would close the reed switch. A read switches are rather cheap (have seen 40 pieces for about 10€ on amazon; on aliexpress or others you might get them even cheaper) and can be easily placed in an electrical matrix or (depending on the number and places of object at any time) checked via shift registers, which are also not very pricey.

Hall sensors and magnets on the bottom of the objects. You would measure the magnetic field of the magnets with the hall sensors. You could use different magnet strengths to get different readings and thus directly distinguish between different object types. The hall sensors will be not that easy to read. Mostly they have an analog output, thus you would need extra ADCs and multiplexers to read them all.

RFID readers and RFID chips in each object. Very pricey and rather low resolution. Also very difficult to read from all of them with the Arduino. But you could go for the reed switch version and use a single RFID reader to first tell the Arduino, which object you are placing. In the game you would first hold the object to the reader, then place it on the board.

Lidar system: A Lidar scanner could scan over your board (it measures the distance in a circle around it). Each object would be a negative peak in the measured distance distribution. From the angle and the distance, you could calculate the position on the board. Though you would need to carefully place the sensor, as one object might hide the other behind it. You can tackle that with an additional Lidar scanner, but the processing will also be rather complex. And Lidar scanners are rather expensive.

Ultrasonic sensors out the board: If you place enough ultrasonic sensors around the board and measure with one after the other, you might also get fitting results. But I would guess, that you won't get good positioning results with them, especially for the rather small objects and distances used on a game table.

Computer Vision: Away from Arduino you could use OpenCV on a Raspberry Pi together with a small camera above your board to detect objects. General object detecting is rather easy with OpenCV and python; getting it's position in the camera image is trivial then (from where you can calculate the position on the board easily). With more work it should also be possible to detect the object themselves (meaning distinguishing between different objects). We might need to train OpenCV with top-down images of the objects for that. If you don't get good results with the normal camera mode, you could try the IR camera mode (by removing the IR filter of the Pi's camera) and put some good IR reflective stuff on the top of the objects. Then OpenCV only has to find the bright spots in the image. All that is possible, though I cannot help you with that and also it is off-topic on this site.

If you can have a board with fixed positions, you could make direct electrical connections between the objects and the board. Though that means, that you would have metal contacts all over the board. I recently used such electrical connections to distinguish between different objects, which can be put into a small number of bays. I have 7 pins on each object, one of them ground. On the object I connected some of the other pins to the ground pin to create a binary pattern. The pins of each bay get read by a shift-in register. All registers are chained together and connected to the Arduino with a total of 4 pins.

Depending on your needs you could combine some of these options. I would try the OpenCV solution, or alternatively the reed switch with one RFID reader solution.


So I finally succeeded to read a register value. I don't really know where was the problem. Here is the code if it can help someone (the scanner still does not work btw) :

#include <Wire.h>

#define DEVICE_ADDRESS 0x30

#define PIN_RST 8
#define PIN_VDD 9

void printOutput(byte *out, int out_len){
   int y=0;
  Serial.print("out = ");
  for(;y<out_len;y++){
    Serial.print(out[y],HEX);
  }
  Serial.println("");
}

void coldReset(){
  pinMode(PIN_RST, OUTPUT);
  pinMode(PIN_VDD, OUTPUT);
  digitalWrite(PIN_VDD,LOW);
  digitalWrite(PIN_RST,LOW);
  delayMicroseconds(2000);
  digitalWrite(PIN_VDD,HIGH);  // sartup the Trust X module
  digitalWrite(PIN_RST,HIGH);
}

int I2C_get(byte reg, byte *out, int out_len){
  int i=0, nbSend=0, nbAvailable=0, ret=0;
  Wire.beginTransmission(DEVICE_ADDRESS); // transmit to device #48 (0x30)
  nbSend=Wire.write(reg);            // sends instruction byte
  Wire.endTransmission();     // stop transmitting
//  Serial.print("nb send = ");
//  Serial.println(nbSend);

  delayMicroseconds(50);
  Wire.requestFrom(DEVICE_ADDRESS, out_len);

//  nbAvailable=Wire.available();
//  Serial.print("nb available = ");
//  Serial.println(nbAvailable);

  if(Wire.available()==out_len){
    for(;i<out_len;i++){
      out[i]=Wire.read();
    }
  }
  else ret=-1;

  return ret;
}

void setup() {

  Serial.begin(115200);
//  Wire.begin(); // join i2c bus (address optional for master)
//  coldReset();
//  delayMicroseconds(15000); // Startup time
}

void loop() {
  int y=0, out_len, ret;
  byte res1[]={0x00,0x00,0x00,0x00};

  Wire.begin(); // join i2c bus (address optional for master)
  Wire.setClock(400000);
  coldReset();
  delayMicroseconds(15000); // Startup time

  out_len=4;
  ret=I2C_get(byte(0x84),res1,out_len);
  if(ret!=-1){
    printOutput(res1,out_len);
  }
  else{
    Serial.println("Error I2C_get");
  }

  Wire.end();
  Serial.println("");
  delay(5000);
}


Setting baud rates in a C program isn't a trivial task. You need to use the low-level open() instead of fopen() and act on the returned file descriptor with ioctl() or tcsetattr() / tcgetattr().  The former method allows the setting of non-standard baud rates while the latter only allows specific baud rates to be used.

I wrote a C++ class to deal with it all for me a while back. You are welcome to examine the methodology and/or steal whatever bits of it you like to use in your own program.

https://github.com/majenkotech/SerialPort


Replicate output of pwm pin on another output pin?

As Jot wrote, you cannot simply route a signal from pin to pin inside the chip/Arduino. So - unless you redesign the PCP, which would be the cleanest way, or use jumper wires, which is not so clean - you are down to using software PWM. There are also libraries for this, if you don't want to write this yourself, for example the SoftPWM library. These libraries have their own limits, especially in frequency. Be sure to check, if they fit your needs.


Bluetooth HM-10 in central mode bonding with another bluetooth device

The manual for the HM-10 can be found here.

Page 11 has the AT command you are interested in: AT+PIN:

AT+PIN123456
OK+Set:123456

By default the PIN is 000000.

(The manual is quite vague about the role of that command, so I assume since it is the only reference to PIN codes that it does what you require).


Issue in installing Arduino unit library and running with Firmata test application

The compiler is giving a lot of information. The warnings can be ignored but the "multiple libraries" indicates that there is at least two copies of Firmata installed. Check (search) that you have not got several downloads of Firmata. Worst case reinstall to clean up that.

Cheers!


Sure... if the RAM started at address 0, which it doesn't.

According to the datasheet the RAM starts at address 0x0100, below which are all the SFRs:


Just found this on Digi website. "The XBee is a 3.3V only device, connecting 5V to any pin may damage the radio. If you had connected the XBee to a 5V microcontroller or power source, it's possible that the radio is damaged beyond repair". On this link, the last topic, knowledge.digi.com/articles/Knowledge_Base_Article/…. I really think that the XBee is gone. One way to avoid this problem is to get one of this regulated breakout board. http://www.hobbytronics.co.uk/xbee-explorer-reg. As it says in the description, it regulates ALL pins to 3.3V, making me believe that I needed to take care of that before making such a mistake. Hopefully this prevent someone from doing this mistake in the future. So, bye-bye XBee.


Assign and control Digital pin from String

C and C++ programs get compiled in multiple passes through various programs/steps. One of the first is the C Preprocessor, which handles the #define preprocessor directive.

It's basically a big find/replace function. After the preprocessor is done, anywhere you had D8 outside of a string literal, would have the value 13. It's not a variable or a string -- it's simply the number 13.

But the String p, which has content "D8" doesn't get replaced by the #define directive because it's part of a string, and the preprocessor doesn't modify strings in that way.

Also, p converted to a byte array of length 2 does not have anything like 13 as the value. It has 0x44 and 0x38 (or, in decimal, 68 (ASCII 'D') and 56 (ASCII '8')). Disregarding that digitalWrite() and pinMode() do not accept byte arrays, only bytes, you are passing in a byte that doesn't represent pin 13.

If you want to assign the pin via a string, then you would need to use programming to examine the string and pick the right byte value, and each possible value would have to be explicitly enumerated and checked for.


Sending data from Arduino to the server where arduino (sketch) acts as a client

A simple HC-05 module will give you a wireless bluetooth connection.  They're fairly simple to setup, and you can write data to them the same as one would the Arduino serial console.  Obviously they can read data too.

SoftwareSerial bt_serial(2, 3); // RX | TX
bt_serial.begin(9600);

[...]

if (led_state != last_led_state)
{
    if (led_state == HIGH)
        bt_serial.print("1");
    else
        bt_serial.print("0");
    last_led_state = led_state;
}

On the "server" side, a simple program reading the mapped bluetooth serial port would do the job.  For example, some python code:

import serial
import sys

serial_port = serial.Serial(port='COM8:', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE)

try:
    serial_port.open()
except:
    print("Failed to open port")
    sys.exit(2)

while (True):
    try:
        led_state = serial_port.read()
        if (led_state != 0):
            print("LED is on")
        else:
            print("LED is off")
    except:
        pass

serial_port.close()   # yes, it never gets here


I realize that your question is based around using multiple connections to the arduino, however if you wish to simplify the setup/operation have a good look into I2C interface, this only uses 2 pins SDA and SCL to operate, you can get an interface board on Ebay for $1.00....just a thought.


You should just not call the releaseKey function, until the button is released.

int oldVal1 = 0;
int oldVal2 = 0;

void loop()
{
    val1 = digitalRead(inpin1);
    if( val1!=oldVal1 )
    {
        oldVal1 = val1;
        if(val1 != HIGH)
        {
            buf[2] = 80; // Left Arrow
            Serial.write(buf, 8);
        }
        else
        {
            releaseKey();
        }
    }

    val2 = digitalRead(inpin2);
    if( val2!=oldVal2 )
    {
        oldVal2 = val2;
        if(val2 != HIGH)
        {
            buf[2] = 79; // Right Arrow
            Serial.write(buf, 8);
        }
        else
        {
            releaseKey();
        }
    }

}


Name of the Arduino Nano clone in the device manager

If you do a windows search for the device manager you will be able to see all the com devices currently connected to your computer. Unplug and replug your Arduino and it should be pretty easy to spot.

Mine is the USB-SERIAL CH340


Best way to ask Arduino for data from Python?

This is not a complete answer to your problem, but currently you seem to have some misconceptions, that prevent you from pin pointing the actual problem.
The data transmission from the sensor, over the Arduino to your python script on the PC has multiple places, where a bottleneck can appear. The total data rate will then be at maximum as large, as the smallest bottleneck allows it to be.
First you have a potential bottleneck in the communication between sensor and Arduino. You haven't stated, what kind of IMU chip you have and how it communicates. Typical IMU chips like the MPU series are interfaces via I2C or SPI. SPI can be sped up rather greatly, while I2C is not that easy to speed up. But it depends greatly on the capabilities of the used chip. You can find information about that in the corresponding datasheet of the chip.

The next interface is the Serial (UART) interface between Arduino and PC. This interface has a fixed baudrate. When you use Serial.write() or its siblings, you simply fill the send buffer of the Serial library. The data will then be send out automatically at the correct timing for your baudrate. The transmission always happens, if the python script is reading or not. The transmission also happens, when the serial buffer of the script is full. The Arduino does not know about the buffer being full. So in this case the data is not delayed, but lost.

The last - and probably most important - potential bottleneck is how you read and send the data on Arduino and in the python script. Here I'm covering the Arduino side.
You should not use functions like Serial.readString(), as they work with a timeout, which will slow down your code drastically. Instead you should read the Serial data byte by byte into a buffer, delimiting your message with a special character (for example the newline character \n). You check, if there is any data Serial.available(), and if yes, you read one byte into a char array, which is your own buffer. You are doing that repeatedly, until you read the delimiting character. Then you process the complete message. That way will give you some important improvements:

You can do things in the meantime (for example reading new data from your sensor)
It works without any arbitrary timeout, thus not slowing down your code unnecessaryly
The delimiting character frames a full message, so that you can distinguish two different messages from each other and thus easier process them

Considering the above, you should make the requirements clearer:

How much latency between the actual sensor measurements and the receiving in the python script is ok for you, meaning: How old can the measurements be, that the python script gets? (You just stated, that it is too large, but you have not mentioned how large)

Do you need continuous data transmission, or just one or a few sets of the IMU data?

Then you can check for the needed speed and data rate. Check, if all involved interfaces and codes can really handle your requirements.
Also it would be easier for us to help you, when you show your current code in your question.


How can I discard power from a device I want to read from?

You don't need to "discard" power. You just ignore it.

If you don't need a connection, then don't connect it.  The only important connection is the ground connection. Everything else can be used, or not used, at your discretion.

There's nothing "magical" about a power connection. It's just a voltage that comes from a source that happens to be able to provide more current.  If you want to use it to power something, you can. If you want to just sense what the voltage is, you can. If you want to ignore it, you can.

It's not like a mountain: just because it's there, it doesn't mean you have to climb it...


Arduino RS485 shield to RS485 temperature & humidity sensor

i'm tray change this code to readStringUntil, is OK

if(Serial.available() > 0)
  {
    temp = Serial.readStringUntil('\n');
    Serial.println(temp);
    delay(1000); //Delay for some time, waiting for data transmitted
  }

Thank all for help me
^^


I see two possible options for achieving what you want:
Voltage divider
This is the solution proposed by William Roy: you make a voltage divider
circuit and check whether it gives a voltage above the threshold of the
digital input. For example:
+5V ---+
       |
       R
       |
       +--- digital input
       |
      LDR
       |
GND ---+

There are a couple of issues with this approach though:

Every digital input is fitted with a Schmitt trigger which makes
it hysteretic, meaning the voltage threshold for switching from LOW
to HIGH is higher than the threshold for switching from HIGH to
LOW. If the pin voltage is between the two thresholds, it will read
either HIGH or LOW, as determined by the history of that voltage.
Depending on your application, this may not be a problem, and may
even be desirable. But if you want, as you wrote in your question, “a
specific set threshold of light”, it sure will be problematic.

You do not know what those threshold voltages are. The datasheet of
the ATmega328P (the main chip of the Uno) states that
they should “typically” be around 2.1 and 2.6 V, but it only
guarantees that the low threshold should be no less than 1.5 V
and the high threshold no more than 3 V. For any input voltage
between 1.5 and 3 V (which is a very significant range), the
chip manufacturer doesn't guarantee what the pin will read.

The first issue can be solved by using a write-before-read protocol:
first you set the pin to OUTPUT LOW, which will force the input Schmitt
trigger to the LOW state. Then you set it to INPUT and take a reading.
This way you will read HIGH if and only if the pin voltage is above
the high threshold. The low threshold becomes irrelevant. Example code:
/*
 * Read the given pin avoiding the input hysteresis.
 *
 * Returns HIGH if the pin voltage is above the upper (LOW to HIGH)
 * threshold, LOW otherwise.
 *
 * WARNING: The pin is set to OUTPUT LOW for a very short time.
 */
int anhystereticRead(uint8_t pin) {
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
    pinMode(pin, INPUT);
    return digitalRead(pin);
}

The second point can be solved by calibrating your input using a trimpot
instead of a resistor. You would adjust the pot until the threshold is
exactly what you want. Using fixed resistors instead of a pot will make
it very difficult to achieve your “specific set threshold of light”,
unless you can live with a very rough precision.
Capacitive measurement
The second option is use the LDR as the resistor in an RC circuit, and
measure the charging time of the circuit, like this:
digital output --- LDR ---+--- digital input
                          |
                      capacitor
                          |
                         GND

Starting with a discharged capacitor, you set the output to HIGH and
measure how long it takes for the input to read HIGH. This time is
typically something like 0.73 R C, where R is the
resistance of the LDR and C the capacitance of the capacitor. The
exact numerical factor is not know, as it depends on the high threshold
voltage of the digital pin.
For details and example code, you could check the Capacitance Meter and
RC Time Constants Arduino tutorial, or search the Web for
“Arduino capacitance meter”. You will find material about how to measure
an unknown capacitance using a know resistance, but you can use the same
technique to measure an unknown resistance using a known capacitance.
And you should replace the waiting loop:
while (analogRead(input) < THRESHOLD) {}  // wait

by a similar loop using the digital input threshold:
while (digitalRead(input) == LOW) {}  // wait

The interesting thing about this technique is that you do not need a
trimpot to set the illuminance threshold: you will measure the
charging time and set the threshold in software. Also, this technique is
not affected by the input hysteresis. The main drawback is that the
measurement takes longer than the voltage divider technique.
Edit: I found a blog post describing this exact method in greater
detail: Measuring resistance or voltage with 1 digital I/O,
by Moser.


Controlling bigger motors with an arduino board

DC motors are typically driven with some sort of BJT/MOSFET solution that will be able to sink enough current to drive the motor because a microcontroller pin can only usually provide a few mA of power.  See this link for info on basic microcontroller DC motor control.  If slow response is acceptable and only one level of power is required (i.e. no PWM) even power relays could be used to turn on off the motor.  Some applications could use this.  However, for your application, it sounds like you will want more responsive control over the motor and need a particularly high power MOSFET to properly drive your application as your motor is very high power.  Such FETS such as these could be used to properly control such a motor using the microcontroller.  Do note additional protection circuitry will be necessary and is probably the topic of another feed, but this would be a place to start if you wanted to build it from scratch.  Otherwise go with an over the shelf driver board which will probably have something like the link above used on it.


How to increase the serial port's data throughput

If you are looking for throughput then stop sending the ASCII conversion of numbers and just send the numbers.
In other words, use Serial.write() rather than Serial.print(): you can send ~25k integers per second with a 52k baudrate.

As you are actually remapping the ADC output to a single byte, that means you can easily achieve a 48k/s throughput with this simple change.

If you are also looking for low latency please consider the USB connection is actually packet based, not stream based, which means you will receive the data in chunks, no matter how frequently you write. You can speed it up a bit flushing the channel, at the cost of throughput.


Using PWM pins on the UNO to generate Stereo Sound

You can generate "stereo sound", but I don't think you'll like it.  The PWM frequency is only 490 or 980 Hz, which is going to be plainly audible unless you filter the output very severely.  So you'll only be able to produce low frequency sounds, about like what comes out of the woofer speakers in your home stereo.  In other words, nothing like music.  Might be OK for certain experiments, but nothing you'd want to listen to for pleasure.
As far as additional circuitry, you'll need to convert the DC outputs of your two low-pass filters to AC before you try to drive headphones.  This requires a big decoupling capacitor for each channel. If you are going to drive a separate amp, you might be able to skip the capacitors since most amps have them built into the inputs.


Negative voltage output Or Controling negative voltage

No, it's not possible, since the voltages and currents involved (12V) are too high.  It will damage your board.

Your arrangement with N-channel MOSFETs is the correct arrangement.

By the way, you are not working with "negative" voltages at all - it's all positive - you just happen to be between the "load" and ground.

This is called a Low Side Switch since it is on the "low" (i.e., between the load and ground) side of the circuit.

The LEDs you have are in an arrangement called Common Anode in that the anodes (+ pins) of the LEDs are all tied together (common) and you control the cathode (- pins) of the LEDs.  It means you can use cheap N-channel MOSFETs that are (as you have seen) easy to control with a microcontroller.  The other arrangement, Common Cathode, where all the cathodes (- pins) are tied together and you switch the power to the anodes (+ pins) requires P-channel MOSFETs and N-channel MOSFETs to switch the P-channel MOSFETs, which increases costs.


Welcome to SE Arduino!

Long Version

You have a couple of things to look at:

Don't use String class it has too much overhead for Arduino.
Your conversion function is not really necessary because you can convert it on your Serial.println() by specifying binary as output. eg: Serial.println(number, BIN);
The Serial.read returns an integer, but that int only contains a byte (unsigned) value anyway (unless there's nothing to be read, in which case it returns -1). Because you're taking a number (not really relevant) and you want it to be a number on the return, just use int or byte (unsigned: 0 <-> 255) or char (signed: -127 <-> +128).
You could/should/doesn't matter if you use Serial.available() or not, it is a matter for yourself, I usually do, but it's non blocking anyway and if there's nothing there to be read, it'll just continue on anyway. Although if you're not going to use it, you should test for that -1 as what you're doing at the moment is taking that and converting it to binary (which is 0xFF which is everything on). This is one of your major problems in the code (the other is in the Short Version section.
You're using "0" and "1" which are ASCII values, and you haven't indicated how you're getting the number. So it may be ASCII (byte) or actually a byte value. ie, "0" is 48 (dec) or 30 (hex). Whereas a 0 is just zero. Funnily enough, because you're using modulo (%) it doesn't really matter because you're only interested in the lowest nibble, which for the sake of your code, doesn't matter what's encoded at the higher end. ie: 1 (0b00000001) is the same as "1" = 49 (dec) = 0x31 = 0b00110001 when used with %2.
Ditch your delay(2000). Delays are evil* :) You could write the values to the pins all day, you're not going to cause any problems, if you want to output less to your serial port (which you should do), you could do timed outputs back to Serial. ie, do your Serial.println() once a second, or record the values into backup/old variables and compare them, and only print the output if the value changes
The big one is in the next section

Short Version

This is your main problem, on this line:

digitalWrite(lights[i+11], (binaryNumber[i] == '0' ? LOW : HIGH));

I think you need:

digitalWrite(lights[i], (binaryNumber[i] == '0' ? LOW : HIGH));

You already have the pin value encoded in the array, you don't want to add 11 to the index, that's going to throw you above your three light values :)

* Delays are evil: It's a matter of opinion, and that's just how I feel, I actually googled it and this is just a random response. But it contains the crux of what I'd say anyway: http://www.makeuseof.com/tag/arduino-delay-function-shouldnt-use/


Measure how many times per second was main loop called:

bool secondPassed()
{
  static long lastTick = 0;
  long now = millis();

  if (now <= lastTick + 1000)
    return false;

  lastTick = now;
  return true;
}

int counter = 0;
void loop()
{
  analogRead(A0);
  counter++;
  if (secondPassed())
  {
    Serial.println(counter);
    counter = 0;
  }
}


Why does my stepper motor run when I open the Serial port?

When you open or reopen the Serial port, the Arduino resets (depending on how you open it; some programs don't send the signal on DTR or RTS, which result in the reset).
My guess is, that the stepper driver reacts to the Arduino configuring its pins for the stepper. Difficult to say, what exactly happens there. To mitigate that, you can add an external pulldown resistor (assuming you have an active high stepper driver. For active low use a pullup resistor). That should keep the step line of the driver low even when its not actively driven by the Arduino.


The show() function already has support for specifying the first pin of the display. So if the second digit is starting at pin 8 and connected in the same order then it should be as simple as:

// Output a 2 digit decimal value.
void show_2digit_decimal(int num) {
  // force value to displayable range because show() doesn't do any sanity checks
  if (num < 0)
    num = 0;
  if (num > 99)
    num = 99;
  // display it.
  show(0, num%10);
  show(8, num/10); // int/int always rounds down to the nearest int
}

You will also have to add the appropriate pinMode(<pin>, OUTPUT); commands to the setup() function to make the pins outputs.

----- update

To get the temperature to display first get rid of these lines, they aren't doing anything useful

static int temp = DHT11.fahrenheit();
static int digit_0 = temp % 10;
static int digit_1 = temp - digit_0;
static int digit_2 = digit_1 / 10;

And then change the loop function to being

void loop() {
  show_2digit_decimal(DHT11.fahrenheit());
  delay(500);
}

Although unless the teacher is completely incompetent you should have been able to work that out yourself, it's not exactly rocket science. If unsure take a guess and try it first before asking. The logic is simple enough that you should be able to work it out. For syntax errors the compiler error messages will normally tell you exactly what's wrong.


Using Due (SAM3X8E) native USB port for programming?

The SAM3X8E comes with a bootloader in ROM.

Memories

256 to 512 Kbytes embedded Flash, 128-bit wide access, memory accelerator, dual bank
32 to 100 Kbytes embedded SRAM with dual banks
16 Kbytes ROM with embedded bootloader routines (UART, USB) and IAP routines
Static Memory Controller (SMC): SRAM, NOR, NAND support. NFC with 4 Kbyte RAM buffer and ECC

Since this bootloader does all that the Arduino IDE asks of it, and has a freely available cross-platform command-line upload tool (bossac) the IDE just uses that. No need to invent the wheel when the wheel does everything you need and even comes with a tin of axel grease.

While technically it is possible to use your own bootloader in conjunction with the existing one (use the existing one to install yours, and then use yours to upload sketches) it requires in-depth knowledge of both the chip and GCC linker ("ld") scripts to set aside a block of memory for your bootloader to reside in and relocate the compiled code around it properly. Too much work when the bootloader that already exists does what you want.

However other chips either don't have a bootloader (like the M0 in the Feather) or don't have one that works as desired (like the DFU bootloader in the ATMega32U4) so a custom bootloader is used on those.

The IDE itself is pretty dumb. It just has a configuration file that says "Execute this command with these parameters to upload the HEX file". It neither knows, nor cares, what the bootloader at the other end of the connection is, nor how it works. As long as there is a command-line executable to do the work it just hands over to it.


strcat appending multiple times when called in loop

Appends a copy of the source string to the destination string.

source

Congratulations, you've broken your string literal. Either stick to using String or make sure you allocate a string properly and then concatenate into that.


You're assuming that the microcontroller is going to wait until you choose LED state, which is wrong. Try this:

int state = 0;
int led;
int ledState;

void loop() {
  while (Serial.available())
  {
    if (state == 0)
    {
      led = Serial.read() - '0';
      if(led >= 0 && led <= 7)
      {
        state = 1; // Here we have got the LED number, go to state 1
        continue;
      }
    }
    if (state == 1)
    {
        ledState = Serial.read() - '0';
        if(ledState == 0)
        {
          shiftWrite(led,LOW);
        }
        else if(ledState == 1)
        {
          shiftWrite(led,HIGH);
        }
        state = 0; // Here we ended the operation, return back to state 0
    }
  }

}

You need what we call a state machine, here I use state=0 for the state corresponding to choosing LED number, state=1 is for the state that waits for the operation ON/OFF.