Binary addressing and coding to control a 96 input mux matrix

OK. First, how the multiplexer works. I have a page about multiplexers in which there is this example of the 74HC4051:

Depending on the "binary" input to A/B/C (shown as S0/S1/S2 on your schematic) there is a low resistance path between one of the 8 inputs and the single output. The CD74HC4067 works in a similar way, except it switches 16 inputs.

So, if you set up the binary number 2 (010) in A/B/C then the third input is selected (number 02 because it is zero-relative).

In your schematic you have 6 x CD74HC4067 which therefore can have 16 x 6 inputs (96 inputs in total). The outputs of those 6 are fed into the 54HC4051 (2 aren't used) so therefore the 54HC4051 can select which of the 6 16-input chips it is interested in right now, by setting up a number between 0 and 5 on the 8-input multiplexer.

The four binary inputs to the 6 x CD74HC4067 are all tied together as you can see on the schematic.

Thus your method would be:

Loop from 0 to 5 on the master multiplexer (the 54HC4051). This selects which of the 6 16-input multiplexers you are interested in right now.
For each of those, loop through 0 to 15 on S0/S1/S2/S3 so that the currently-selected CD74HC4067 routes its input through to its output.
Read the resulting value

Those two loops will give you 96 inputs, which is what you are trying to read.

This technique takes 7 output pins to output the binary numbers (3 bits plus 4 bits). It also needs one input pin to read the result.

Judging by the schematic it uses SPI (serial data) to control the 6 x TLC5940 shift registers which lets it turn LEDs on and off with only two control pins (SCK and MOSI named SCLK and SOUT on your schematic).

The chips are daisy-chained together so all of those TLC5940s are controlled by those two pins.

This fairly minimalist design has therefore left some spare pins on the Arduino Pro.

  Mostly having a hard time visualizing the code, especially how to write correctly the 7 binary digital write commands. Is it possible for you to correct what I've written above, so I might be able to see the pattern?

I know you changed the question by the time I saw this, but the code below illustrates what I mean by the two loops:

const int MUX_CHIPS = 6;
const int LEDS_PER_CHIP = 16;
const int TOTAL_IR_INPUTS = MUX_CHIPS * LEDS_PER_CHIP;
// Master IR -mux sensor pins for Arduino Pro MINI
const byte  M_S0 = 2;
const byte  M_S1 = 4;
const byte  M_S2 = 5;
// Slave IR mux sensor pins
const byte  S_S0 = 6;
const byte  S_S1 = 7;
const byte  S_S2 = 8;
const byte  S_S3 = 12;
//  ANALOG PIN :
const byte INPUT_FROM_MUX = A0;

int  recv_state[TOTAL_IR_INPUTS];           // IR Readings - FROM mux set-up

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

    // CONFIGURE ADDRESS PINS
    pinMode(M_S0, OUTPUT);
    pinMode(M_S1, OUTPUT);
    pinMode(M_S2, OUTPUT);

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);
    pinMode(S_S3, OUTPUT);
    pinMode(INPUT_FROM_MUX, INPUT);

    // set ADC prescaler of 32
    ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
    ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
} // end of setup

void loop() {

  unsigned long start = micros ();

  // read from IR diodes

  int whichLED = 0;
  for (byte master = 0; master < MUX_CHIPS; master++)
    {
    // select appropriate slave on the master MUX
    digitalWrite(M_S2, (master & 0b100) ? HIGH : LOW);
    digitalWrite(M_S1, (master & 0b010) ? HIGH : LOW);
    digitalWrite(M_S0, (master & 0b001) ? HIGH : LOW);

    // take each slave reading
    for (byte slave = 0; slave < LEDS_PER_CHIP; slave++)
      {
      digitalWrite(S_S3, (slave & 0b1000) ? HIGH : LOW);
      digitalWrite(S_S2, (slave & 0b0100) ? HIGH : LOW);
      digitalWrite(S_S1, (slave & 0b0010) ? HIGH : LOW);
      digitalWrite(S_S0, (slave & 0b0001) ? HIGH : LOW);

      // store this reading
      recv_state [whichLED++] = analogRead (INPUT_FROM_MUX);

      } // end of for each slave
    } // end of for each master

  // display results here ...

} // of loop

The exact code above took 5148 µs (around 5 ms) to execute the loop once on my Uno. If we remove the speedup of the ADC (analogRead) it takes 13252 µs (13 ms).

To allow for your exact wiring you need to ignore the low-order bit on the master MUX because you are not using input A0_13 in which case you need to add 2 to the master value in the outer loop:

    // select appropriate slave on the master MUX
    byte master_plus_2 = master + 2;  // allow for not using input A0
    digitalWrite(M_S2, (master_plus_2 & 0b100) ? HIGH : LOW);
    digitalWrite(M_S1, (master_plus_2 & 0b010) ? HIGH : LOW);
    digitalWrite(M_S0, (master_plus_2 & 0b001) ? HIGH : LOW);


Not sure if you found it, but there I created an SNMP Manager: https://github.com/shortbloke/Arduino_SNMP_Manager
There is also an SNMP Agent: https://github.com/0neblock/Arduino_SNMP
I know this is a bit later than when you requested this info. But posting here in case it's still helpful to you or others that stumble over this question.


The piezo element acts like a capacitor, not like a more-or-less resistive element as in a conventional speaker. You need to discharge the capacitor during the 'off' time or you just get a click and little sound after that. That's why your resistor helps. Push-pull would be much better, and an H-bridge would give you much more output (maybe too much for the speaker).

Also the IRZ44 is not specified to be driven from 5V (it's specified at 10V Vgs) so you may not get much current. Further, if you're trying to get 10's of kHz, you won't be able to drive the MOSFET gate that fast with a 1K resistor, in fact the Arduino may not be able to source enough current and you may have to use a gate driver.

If you can measure the capacitance and provide the frequency of interest, more specific recommendations would be possible. At 2kHz about 3K would be okay with a 10nF element, but that resistance would decrease with increasing resistance and with increasing capacitance, and at some point the power dissipation in the resistor will become excessive.

Edit: You can do something like the below with a 10nF/20kHz requirement:

simulate this circuit – Schematic created using CircuitLab

You could even duplicate the above circuit and add an inverter in series with one of the halves and get 24Vpp across the piezo, but you might want to use somewhat beefier transistors (Zetex perhaps).


How to find how much data in the transmit buffer?

If you really want to know (not that it would do you any good) you can use the Serial.availableForWrite() function (which returns how much space is left in the buffer) and subtract the returned value from the size of the buffer.

int used = 64 - Serial.availableForWrite(); // Assuming a 64 byte buffer

I haven't tested it, but you may be able to use SERIAL_TX_BUFFER_SIZE instead of the 64 to make it properly portable.

int used = SERIAL_TX_BUFFER_SIZE - Serial.availableForWrite(); // Possibly portable


the loop does not and won't upload to the Arduino

Most likely because RELAY_OFF has never been defined anywhere. Change that to HIGH (if that is what your relays need to turn off), or define it somewhere.

Also there is no loop() function - is that just you being economical with the paste?

  Secondary question is how to convert the counter i to a string to concatenate the message.

Simple: don't.  There's no need.

Serial.print("Relay ");
Serial.print(i);
Serial.println(" set HIGH and as OUTPUT");


Arduino: How to get the board type in code

Thanks to the help of Charlie Hanson and jantje I found the universal solution!

Because it is a pity that every Arduino programmer has to go through the same pain to figure out how to get the board name, I will offer my code to the public so everybody can just copy and paste it.

Here it is:

#if defined(TEENSYDUINO)

    //  --------------- Teensy -----------------

    #if defined(__AVR_ATmega32U4__)
        #define BOARD "Teensy 2.0"
    #elif defined(__AVR_AT90USB1286__)
        #define BOARD "Teensy++ 2.0"
    #elif defined(__MK20DX128__)
        #define BOARD "Teensy 3.0"
    #elif defined(__MK20DX256__)
        #define BOARD "Teensy 3.2" // and Teensy 3.1 (obsolete)
    #elif defined(__MKL26Z64__)
        #define BOARD "Teensy LC"
    #elif defined(__MK64FX512__)
        #define BOARD "Teensy 3.5"
    #elif defined(__MK66FX1M0__)
        #define BOARD "Teensy 3.6"
    #else
       #error "Unknown board"
    #endif

#else // --------------- Arduino ------------------

    #if   defined(ARDUINO_AVR_ADK)
        #define BOARD "Mega Adk"
    #elif defined(ARDUINO_AVR_BT)    // Bluetooth
        #define BOARD "Bt"
    #elif defined(ARDUINO_AVR_DUEMILANOVE)
        #define BOARD "Duemilanove"
    #elif defined(ARDUINO_AVR_ESPLORA)
        #define BOARD "Esplora"
    #elif defined(ARDUINO_AVR_ETHERNET)
        #define BOARD "Ethernet"
    #elif defined(ARDUINO_AVR_FIO)
        #define BOARD "Fio"
    #elif defined(ARDUINO_AVR_GEMMA)
        #define BOARD "Gemma"
    #elif defined(ARDUINO_AVR_LEONARDO)
        #define BOARD "Leonardo"
    #elif defined(ARDUINO_AVR_LILYPAD)
        #define BOARD "Lilypad"
    #elif defined(ARDUINO_AVR_LILYPAD_USB)
        #define BOARD "Lilypad Usb"
    #elif defined(ARDUINO_AVR_MEGA)
        #define BOARD "Mega"
    #elif defined(ARDUINO_AVR_MEGA2560)
        #define BOARD "Mega 2560"
    #elif defined(ARDUINO_AVR_MICRO)
        #define BOARD "Micro"
    #elif defined(ARDUINO_AVR_MINI)
        #define BOARD "Mini"
    #elif defined(ARDUINO_AVR_NANO)
        #define BOARD "Nano"
    #elif defined(ARDUINO_AVR_NG)
        #define BOARD "NG"
    #elif defined(ARDUINO_AVR_PRO)
        #define BOARD "Pro"
    #elif defined(ARDUINO_AVR_ROBOT_CONTROL)
        #define BOARD "Robot Ctrl"
    #elif defined(ARDUINO_AVR_ROBOT_MOTOR)
        #define BOARD "Robot Motor"
    #elif defined(ARDUINO_AVR_UNO)
        #define BOARD "Uno"
    #elif defined(ARDUINO_AVR_YUN)
        #define BOARD "Yun"

    // These boards must be installed separately:
    #elif defined(ARDUINO_SAM_DUE)
        #define BOARD "Due"
    #elif defined(ARDUINO_SAMD_ZERO)
        #define BOARD "Zero"
    #elif defined(ARDUINO_ARC32_TOOLS)
        #define BOARD "101"
    #else
       #error "Unknown board"
    #endif

#endif

You can even put this code into a new header file and #include it into your project.

P.D.
If you want to know additionaly to the board also the CPU model, search for the file avr_cpunames.h


How can I pass an object as a parameter to a function?

You are doing everything right, but you need to move the class outside of your .ino file for this to work.  I'm not sure why the arduino IDE makes you do this  (see edit) , but it is something I've run into before.

I just tested this, and moving the class declaration outside the ino and into a header file in the project folder makes it compile correctly. Just remember to include the header you make in the ino and to #include "Arduino.h" in the header to get access to "String" again.

Technically, only a forward declaration of the class needs to be in a different file.

Edit:

I'm relatively sure what is happening is the IDE is generating forward declarations for all your functions but not the class, which are placed before your class definition.
This means that breaking the function regex the IDE uses with a dummy "throw()" fixes your problem. for example:

void writeHighscore(Highscore hs) throw() { ...

should work just fine (it worked for me)


At 2 Mbps, a 32-byte packet (40 bytes with preamble, addresses, CRC) will be approx 160 microseconds long.  The round-trip time is likely to be much longer, since the microcontroller or radio will need additional time delays for auto-retry, sending and receiving the response packet, PLL lock, reading the data registers, etc.  In my experience a 2 ms round trip is possible, and the best way to do that is make use of the nRF built-in features:

-- IRQ interrupt: interrupts = fast

-- Enhanced Shockburst: this automatically handles lost packets and failed transmissions.  You can't get that capability any faster via the microcontroller coding.

On top of this, there is scope to use fast SPI libraries (or use SPDR/SPCR registers directly) to transfer data to and from the radio module.  If speed is your goal, don't rely on plug-and-play libraries that others have written.  Read the data sheets carefully and minimize unnecessary delays within the Arduino code.


How can i receive data from Mega2560 on PC with Visual C#

I haven't tried the code below, but it should point you in the right direction.

All you have to do is write a C# program that opens the Serial port that your Arduino is connected to and read and write from there like you would from a file.

Open Visual Studio, create a C# command line project.
Paste this code inside main()

    System.IO.Ports.SerialPort port = new SerialPort("COM1", 9600);
    try
    {
        while (true)
        {
            int readData = port.ReadByte();
            System.Console.WriteLine("Read {0} from the port", readData);
        }
    }
    catch(Exception)  // Press CTRL-C to exit.
    {
    }
    port.Close();

Compile the code and run it.


The Arduino Servo class is intended to accept positive values only, in the range of 0-180.

In addition to reversing the values for one servo by subtracting from 90, your code is also negating the values by multiplying by negative one.

That results in an invalid argument to the Servo function.  It's unclear exactly what happens, but likely possibilities include an invalid pulse, or no pulse at all.

At the end of your for loop, you subtract 90 from 90 producing zero, and invert it to still zero.  Zero is a valid input to the Servo function, so a valid output is produced and the "reversed" servo finally has a position it can seek to.


Is it advisable to reload Pro Mini with the bootloader originally designed for UNO to save 1.5 KB flash space?

You can just flash the newest optiboot_atmega328-Mini.hex. That one should also be only .5k in size, as it starts writing at the same address (7E00).

If you divide 7E00 by two you get 3F00 (This is because AVRs use 16-bit words for addressing while .hex files work with bytes (8-bit)). (I figured that one out, just now)

3F00 is exactly the start of the Boot Loader Flash Section when you  have selected a 256-words Boot Size (page 291 of the datasheet). 256-words is the 0.5kb you want.

Just make sure you have the BOOTSZ1, BOOTSZ0 fuses set to 1

As for the boards.txt. I think you only need to change mini328.upload.maximum_size=28672 to mini328.upload.maximum_size=32256.


Frequency of Retrieving Data from Website

Your two best options would be MQTT and WebSockets.
Both would open a long lived TCP connection that the ESP8266 and browser could use to transmit and receive data. Both would avoid constant polling to see if there's a new command.
MQTT requires an external broker. There are MQTT services with free tiers you could use for this or you could run one locally - Eclipse Mosquitto is a popular MQTT broker that runs nicely on a Raspberry Pi. MQTT is particularly useful for networks with multiple publishers and subscribers (it's a "pubsub" protocol) and is probably overkill if you just have a single device and endpoint.
It's easy to use MQTT from a browser using Javascript. The Paho Javascript MQTT client works well. The ESP8266 would establish a connection to the MQTT broker, subscribe to a topic name and set a callback function that would be called when data was published to that topic. The browser would also establish a connection to the MQTT broker and would publish a message to the topic when responding to events from the user.
WebSockets would allow the ESP8266 and browser to establish a full duplex connection between them. The ESP8266 would create a websocket server which the browser would connect to. The ESP8266 would check for data on the websocket during while running code in loop() and would assemble messages from the browser.
Either works easily if both your devices are on the same network (for instance, at home). If your browser is outside the network, it won't be able to communicate directly with the ESP8266.
MQTT has the advantage that an MQTT server located outside of the network (not one running locally on a Raspberry Pi) would allow the browser and ESP8266 to communicate with one another through it. WebSockets would require the use of a proxy server (there are modules for popular web servers like NGINX and Apache, but this requires control of the web server to configure). If you only ever want to use the browser to control the ESP8266 while they're both on the same network you don't need to worry about this.


Singletons aren't a thing in Arduino. Sure, you could do it, but in general you'd make a class then instantiate a global object for that class. Most often that global object is instantiated in the library itself, not the sketch.
Unless you're using an advanced chip with an RTOS (such as ESP32) and making use of the threads of that RTOS heavily there is no benefit to having a singleton.
But to answer your actual question: it's probably because you are trying to use the Sensors() constructor at a time before the compiler knows what the Sensors() constructor is. You would have to add some form of forward declaration so that the compiler knows what you mean when you talk about the Sensors() constructor.  In general a simple:
class Sensors;

at near the top of your header before the class is actually defined can help in these situations;


USART, SPI or Bit-Bang for the continuous transfer of bytes without inserted extra bits

Are both these statements true?

Neither of those statements are true.

SPI never inserts extra bits. That would break everything if it did. What you are probably seeing (or think you are seeing) is a delay between bytes being sent. That delay is irrelevant, since the data is only ever sampled on an edge of the clock signal (which edge depends on the mode of the SPI communication) and with no clock edge in that delay period there is no data.

USART in synchronous mode is SPI. There are no start or stop bits in synchronous mode, since the clock is used to synchronise the communication rather than needing start or stop bits.


GSM and Bluetooth modules on 1 Arduino Uno board

Take a look at the SoftwareSerial library which allows other pins to be used for Serial at speeds <= 57600

https://www.arduino.cc/en/Reference/SoftwareSerial


Adafruit motorshield disconnected but getting current from Arduino

If all else fails, read The Manual

The manual indicates that it is intended that the MS electronics may be operated by the Arduino power supply while using a separate external supply for the motor.

Pages 37 to 39 explain about powering options.
The Arduino and the shield interconnect all of : 3V, 5V, Vin.
3V may not be used by the shield.

Arduino Vin to MS V+ is broken by jumper "PWRJMP" - purple rectangle in diagram below.
Arduino 5V to MS Vcc is not interrupted by a jumper - See labels in red squares below.

You did not say what version shield you had or which Arduino or what you mean by "disconnected from battery" or supply any links to relevant documents. ALL of these things will help people to help you better.

Assuming latest MS version,

adafruit motor shield v1.2  - discontinued.

github v1.2 schematic this appears to be pre V2 BUT is linked to from a ference in the V2 manual so is probably "more or less correct".

adafruit motor shield v2 manual - probably what you have

adafruit current MS page

This probably tells you what you need to know.  Manual page 37-38

How to set up the Arduino + Shield for powering motors

Servos are powered off of the same regulated 5V that the Arduino uses. This
is OK for the small hobby servos suggested. If you want something beefier, cut the trace
going to + on the servo connectors and wire up your own 5-6V supply!

The DC motors are powered off of a 'high voltage supply' and NOT the regulated 5V.
Don't connect the motor power supply to the 5V line. This is a very very very bad idea unless you are sure you know what you're doing!

There are two places you can get your motor 'high voltage supply' from. One is the DC jack on the Arduino board and the other is the 2-terminal block on the shield that is
labeled EXT_PWR. The DC Jack on the Arduino has a protection diode so you won't be able
to mess things up too bad if you plug in the wrong kind of power. However the EXT_PWR
terminals on the shield do not have a protection diode (for a fairly good
reason). Be utterly careful not to plug it in backwards or you will destroy the motor
shield and/or your Arduino!


Use virtual functions. On object of type Child, fnc2 defined in Parent will call fnc1 of class Child:

class Parent {
public:

  virtual void fnc1() {
  }

  void fnc2 {
    ...
    fnc1();
    ...
  }
}

class Child : public Parent {
public:
  virtual void fnc1() {
    ...
  }
}


Super-fast USB communication; how is it possible?

Is it possible to get these speeds? How?

Not without a 32-bit Arduino with a USB interface.

  If it's, why is it not in the default Arduino library?

Because you can't use it on an 8-bit Arduino without a USB interface.

  In case there's no easy answer for the other questions, is switching from UART to CDC easy, so that I could continue my testing?

Yes, get a 32-bit Arduino with a USB interface such as the Arduino Due that the poster of that thread used.


IoT gabage monitoring system with my own Android application

Does your campus have WiFi? If so, go with EPS8266 if its pins are OK for your sensors.
ESP Pinout

You'd want to keep an eye on power consumption; you'd sample your sensors per desired interval and deep-sleep at all other times. Check out available sleep here. It also has en example of how to sample and send a sensor, and sleep afterwards.

On the application end, you could either use a ready service such as Blynk, or go for a custom solution and send the data on your server. Of course, you would then need to write an API and some sort of application to present your data.

Let me also point out that for measuring garbage level, you should calculate the total volume of your bin and subtract the volume of garbage your sensor detects. Having non-uniform trash would give you some trouble, but it's a good technique for an estimation of garbage volume. Also, if using ultrasonic distance sensors, given the fact that you have temperature readings available, you should compensate your measurements; check this out.


Arduino IDE - scope of the pre-processor "#define"

The scope of a #DEFINE macro is the translation unit. That is the current .c or .cpp file that is currently being compiled.
In you code PIN_NUMBER is defined in test.ino. The #include macro literaly copies the content of testLibrary.h into test.ino. So for the compiler this is working perfectly fine as PIN_NUMBER is defined.
Your testLibrary.cpp however is not happy with that. Including testLibrary.h for compilation lacks the definition of PIN_NUMBER.
The Arduino IDE is very limited and does not offer you a way to define PIN_NUMBER globally. This is usually done with the compiler argument -DPIN_NUMBER=3. All translation units will get this argument and thus the compilation would succeed. No need to define PIN_NUMBER in code.


Wiring light sensor OPB704WZ to Arduino Due

You expect that the white surface to reflect the infrared light and the black surface does not.

Your theory is correct; white surfaces should reflect pretty much all light and the black surface should absorb all light.

The problem is that the black surface is reflecting enough light to turn the photo-transistor on.

The theory is correct but in the real world this is not perfect. For example a white surface is not completely white. Likewise no black surface is completely black.

We also know that a mirror is much better at reflecting light than a white surface. The black surface could be shiny. I am looking at my shiny black monitor stand, and even though it is black I can still see the reflection of the window.

I suggest trying with a number of black surfaces (such as paint, card, cloth) and finding the one that works best. I would imagine that chalk board paint would work well at absorbing and diffusing the infrared light. Also experiment with the distance away from the surface. You may have to move it further away from the surface.

If I am imagining your tachometer right, your sensor will see a reflective surface and then it will see empty space (and then repeat). This should work fine. Give it a try.


What you want to do is send "unmodulated" IR Codes, but the library is trying to modulate them with a 38khz carrier. (The TL1838 device has a built-in demodulator.)

While your question is not a duplicate, this answer applies.


The arduino is a "small memory" device. So it probably does not have a big serial buffer. On say "linux on a PC" you get a 4096 byte buffer, but on an arduino, probably only say 16. Now as luck will have it "+CMGR: "REC READ" is precisely 16 characters....

From the code that I see, you seem to be sending commands to the modem and then reading/echoing them. I would have liked to use two different serial ports or something like that.

In any case, if it sort of works for those first 16 characters, remove all the delays and put one of them near the end of the loop() function. Remove the initial print to the modem in the setup function.


Appears to be a touch sensor that can be found on various on-line retail web pages:

http://www.satistronics.com/

https://www.arduiner.com/

Also, the back may have a URL as this one does:

...however, the URL appears not to function.


this is a nice question. Once for a project I stumbled upon this problem too.

The way you described the connection should work perfectly fine.

  To me it makes sense to connect it like this:
  Connect pins 9 and 10 from atmega --TO--> pins 1 and 3 from the crystal.
  Connect pins 2 and 4 from crystal --TO--> Ground
  Connect the 22pf ceramic capacitors to pins 1 and 3 from crystal and ground like in the first diagram.

Keep it going and greetings from Switzerland.


A good place to start would be the "TimeSerial" sketch that comes with the Arduino Time library: https://playground.arduino.cc/Code/Time.


You don't seem to understand how to wire an OP-AMP. Here is a quick tutorial on their basics:

https://www.youtube.com/watch?v=kqCV-HGJc6A

The thing is that you are missing a LOT of resistors. An usual OP-AMP circuit contains many resistors to determine the amount of amplification and more...

The tutorial explains quite well what resistor and where do you need to put them in order for your circuit.


Can i use a range in a switchcase like in pascal?

There are some GNU extensions available in the avr-gcc/avr-g++ compilers (used in Arduino IDE for AVR based Arduino boards). One of them is suport of ... for the case:

  switch (i)
  {
    case  10 ... 100:  Serial.println(F("First"));           break;
    case 101 ... 1000: Serial.println(F("Second"));          break;
    default:           Serial.println(F("Everything else")); break;
  }

But, it's not the part of C/C++ standard, it's just compiler extension, so there is possibility it fails to compile on different platforms (mainly different compiler). So it's better to avoid it in portable code.


Write to serial only if the state of a light sensor changes

You wrote: “I am using the Arduino Uno to print to the serial monitor
its state every second.” This is exactly the right thing to do. Make a
record of the analog readings for a few days, then plot the readings as
a function of time.

Once you have a nice plot, take a close look at it. You should be able,
by reading the plot, to decide on a threshold value that you can use to
tell whether the LEDs are on or off. Or, better yet, two thresholds in
order to have some hysteresis.

Then you can write something like this:

const uint8_t LDR_PIN = ...;
const uint16_t THRESHOLD_LOW = ...;
const uint16_t THRESHOLD_HIGH = ...;

uint8_t state = LOW;

void loop()
{
    uint16_t reading = analogRead(LDR_PIN);
    if (state == LOW && reading >= THRESHOLD_HIGH) {
        Serial.println("Reading is now HIGH.");
        state = HIGH;
    } else if (state == HIGH && reading < THRESHOLD_LOW) {
        Serial.println("Reading is now LOW.");
        state = LOW;
    }
}


The subtle clue is in the voltage that is available. That is, the only voltage provided on the board is 3.3v. That's a slight hint that the board might run at 3.3v. And you would be right in that assumption.

The ESP8266 chips, as are most modern MCUs more powerful than 8-bit, 3.3v devices.

So you would choose 3300 as your "Logical Voltage" value.  Or better still, measure the 3.3V and find exactly what it is and use that value x 1000 (for example 3317 or 3295).


Use command line to upload hex code to teensy.ex

This is starting to drift off topic for this site, but the best solution for making an automated programming utility for the Teensy on Windows, short of writing one yourself, would be to use some kind of UI automation framework to automate the process described in my earlier answer. My favorite one that I have used in the past is AutoIt. It has tools to inspect applications so that you can programmatically click buttons and fill out fields. There are even ways of having it run programs without them being visible to the user. There are plenty of tutorials on the web on how to use AutoIt so I would suggest googling for that. If you have further questions on how to do that, they would be more appropriate on a site other than Arduino.SE.


The Arduino itself has a limit of about 800mA. That is imposed by the voltage regulator that converts the incoming voltage to 5V.

If you need more than 800mA then you need to provide your own regulated 5V power source and feed it in to the 5V pin (not VIN).

Suitable power sources are mobile phone chargers (modern USB ones).  They generally come in multiples of amps.

And to answer your theory question - the current is the maximum that the supply can provide. It's the voltage that is fixed and the current varies depending on the load.


Notoriously unstable ESP8266 MQTT-client

I use adafruit mqtt library. After a few fixes, it is running very stable.

Tips:

1) Make sure you put subscribe line BEFORE connecting to mqtt (you can put it in setup and connect to mqtt in loop)

Like:

Setup: mqtt.subscribe(&motor);

Loop: MQTT_connect();

Yes, you can both publish and subscribe at the same time.

2) IN THE LINE: Adafruit_MQTT_Client(server,port,user,pass)

CHANGE TO THIS: Adafruit_MQTT(server,port,clientid,user,pass)

Use this with client id (MUST BE UNIQUE (EG: Different for all clients))
or your client will be kicked off when other client with same id connects.

3) Convert value.lastread from char* to int : int val = atoi((char *)sensor.lastread);

More about ESP8266 & ESP32 : http://github.com/ajaybnl


Is it possible to read extended ASCII from the serial port?

Yes, of course, you can read any byte sequence. As you have experienced,
if you send the byte values 194 and 165, your Arduino reliably reads 194
and 165.
Now, you have to be aware that there are tons of incompatible character
encodings that could all be called “extended ASCII”. I do not know which
one you have in mind. Maybe there is such an encoding where “¥” has the
code point 157. Nowadays, however, almost any modern computer system
uses Unicode, and serializes the characters using UTF-8. The character
“¥” is serialized in UTF-8 as the pair of bytes 194 and 165.
If you want to use the Grbl protocol, send interrupts as bytes, do not
think about them as “characters”.


what library should I #include when using switch-case statement

It seems you have a syntax error: write switch instead of swith.


Arduino - Playing WAV files with a buzzer

When driving a passive buzzer, you should always have the signal output from the Arduino go to a transistor tied between the ground and the (-) negative side of the buzzer. Also, if you use a regular NPN transistor, you should also have a small resistor between the Arduino and the transistor base.

The transistor is providing two functions; it's potentially amplifying the signal (if the (+) positive side of the buzzer is at a higher voltage than the Arduino) and it's also isolating (partially) that voltage from the Arduino. This helps save pins!
The resistor is to limit the current going through the transistor and helps keep both your Arduino and the transistor healthy. Voltage thrills, current kills and resistors limit current. If you use a MOSFET you want to change this from a low-ohm series resistor to a high-ohm pull-down resistor -- 4.75K or 10K is fine. A MOSFET is much higher impedance than an NPN transistor and should not be left floating.
Additionally, you want to add a diode between the (+) and (-) terminals on the buzzer. This may be the most important part of the circuit! When oscillating, the buzzer (whether magnetic or piezo) acts like an inductor and will accumulate a charge over time. This will be heard as a slowly diminishing volume from the buzzer. This charge will eventually overcome the protection diodes built into the GPIO pin (or any transistor) and destroy it! The diode blocks that charge loop and saves your chips.


Reading multiple DI pins in parallel as one byte/word

Without knowing the encoder in question (which you seem extremely reluctant to disclose for some reason that I have trouble understanding) it is hard to give a good answer. However ...

The 8-bit AVR processors can only read 8 bits atomically. This is indeed called a port. The Atmega328P (used in the Uno) organizes its I/O ports as ports B, C and D (I don't know where A went).

Exposed on the board are PORTB (bits 0 to 5), PORT C (bits 0 to 5) and PORT D (bits 0 to 7) - that's 20 pins in total.

Thus, port D is the closest you will get, as you could read 8 bits at once. However having said that, two of those bits are used for serial I/O so you couldn't use the serial hardware at the same time.

To read all of port D you could just do this:

byte foo = PIND;

(For inputting it is PINx, for outputting it is PORTx).

What could help is an I/O expander such as the MCP23017.

  I'm hoping to avoid additional hardware

Well, that's a pity.

I'm a tiny bit surprised that the device doesn't support some sort of "latching" of the data which gives you a finite time to extract the information from it. However without reading the datasheet I can't comment further.


What are the negative PINs for on the IndustrialShield M-Duino 58 Analog

It looks like those inputs are opto-isolated. That means that the "input" goes through a resistor and the internal LED of an opto-isolator, which then comes back out of the "-" pin:

simulate this circuit – Schematic created using CircuitLab

So "-" connects to the ground of the remote device, and the "input" connects to the signal.


Keyboard Control Not Working As Intended

The problem I see is that your servo is attached to pin 0.

Pins 0 and 1 are used by arduino unos and megas for serial communication, so you can't output to a motor and send/receive serial at the same time. Try moving the servo to pin 3 and see what happens.

In response to your comment, any character sent from any terminal (or other piece of hardware) will work; you do not need to use Processing to communicate with an arduino.


Can I connect more than one IR receiver to an Arduino Uno?

That library only supports one IR receiver at a time. Try this fork that seems to have added multiple receivers support.


What is the maximum prescaler you can set for an ATtiny85 Timer Interrupt?

I don't know the objectives of your project, or its constraints and requirements.  Thus, portions of the following might not apply.

If I were using an ATtiny85 in an application that needed to “maximize the amount of power saved” and also needed to wake up about every 33 ms, I'd use the factory-calibrated 8 MHz clock (rather than attaching a 20 MHz external crystal), and use system clock prescaling [see §6.3, System Clock Prescaler, on page 31 of the ATtiny85 specs, and Table 6-15. Clock Prescaler Select, p. 33] to scale that 8 MHz down to 250 KHz.  As implied by Table 21-1, DC Characteristics, page 162 of specs, this will drop CPU current draw down to under 0.1 mA if powered by 2 V, or under 0.35 mA if powered by 3 V.

With the system clock running at 250 KHz, you can use timer 0 prescaled by a factor of 1024 [see §11.3.1, Internal Clock Source with Prescaler, p. 166 of specs] to get an interrupt every 33 ms or so.

If 250 KHz is too slow to get done with whatever computation needs to be done every 33 ms, upon waking I would change the system clock prescale factor per §6.3.1, Switching Time, to 8 MHz or 4 MHz or whatever it needs to be to get the computation done at lowest power cost.  That might or might not be the same as getting the computation done most quickly.

Then, after the periodic computation is done, I'd revert the system clock to 250 KHz, and go to sleep in Idle mode (Ref §7.1.1, Idle Mode) with almost everything except timer 0 shut down via the PRR. (Ref §7.3, Power Reduction Register.)


In general, ESP-NOW uses the WIFI radio in an ESP processor as a physical layer.  But uses it's own protocol which likely looks like garbage to a normal WIFI equipment.  So, it's like being in a meeting room with a bunch of people only knowing German and occasionally someone pipes up taking French.  As no one understands the French speaker, the French speaker is ignored.
Other things you need to know.  ESP-NOW is more like UDP.  There is not a higher layer looking out for you like in TCP.  Any number of reasons can cause your ESP-NOW "blurp" from being received.  For this reason ESP-NOW is better suited for periodically repeating information.  Like reporting the temperature.  Or for situations where the user can provide immediate feed back of success.  Such as a remote control.

The esp32 will mostly send data to esp8266

This infers reversing the direction of data flow over the ESP processor's WIFI radios.  While this may be possible it may not be a trivial task.

Is it possible to do this (communicate between an esp32 and esp8266) if yes how.

This shouldn't be problem.  This link provided by Majenko appears to be a good place to start.  Espressif them selves maintains this ESP-NOW web site.  Likely, after programming the ESP8266 and ESP32 using the correct libraries, they will be able to send data over an ESP-NOW link.


At first I thought that the main problem was not that you too slow at sampling, but that you were too slow at transmitting the data. As Edgar already stated, at 9600 b/s you need 22.88ms to send a line, so the maximum frequency is less than 50Hz.

However as you experienced, the speed you are getting is 200Hz. This is because that calculation is right in the case of a real serial interface. Arduino Leonardo, on the other hand, emulates the serial interface. But.. There is no such thing as baud rate. If you look at the CDC emulation source code you will see that the baud rate you pass to the begin function is ignored.

So... Why is it still slow? Because you are using the delay function! You are waiting for 1ms every time you perform an acquisition, and then you still have to perform all the sending. This has two errors embedded: 1) using the delay function breaks the timing - better use a timer - and 2) you are too slow.

Now, if you want a 1kHz sampling (or any delay multiple of 1ms) you already have a timer running (so you can just use that):

#define INTERVAL_LENGTH_US 1000UL

unsigned long previousMicros;

void loop()
{
    unsigned long currentMicros = micros();

    if ((currentMicros - previousMicros) >= INTERVAL_LENGTH_US)
    {
        previousMicros += INTERVAL_LENGTH_US;

        int val_a0 = analogRead(A0);
        int val_a1 = analogRead(A1);
        int val_a2 = analogRead(A2);
        int val_a3 = analogRead(A3);

        Serial.print(((double)currentMicros) / 1000000UL, 1); // 1 is the number of decimals to print
        Serial.print('\t');
        Serial.print(val_a0);
        Serial.print('\t');
        Serial.print(val_a1);

        Serial.print('\t');
        Serial.print(val_a2);
        Serial.print('\t');
        Serial.println(val_a3);
    }
}

NOTE: The millis() function is replaced by micros() according to Edgar's and Nick's comments.

Change just the define to change the sample time. Now its set to 1000us (i.e. 1ms, so 1kHz), but don't go much higher otherwise you will have to check accurately the sampling time and the transfer speed. The t variable is not needed anymore.

Just a side note: this will also fix the bug in your code that prevents the program to display the current timing (instead of printing 2.5 it prints 2.0).

If you need a faster sample rate you should use another timer to get the correct timing, but again avoid delays. Not needed anymore


Raspberry Pi with Arduino, Serial connection stops working

If none of the code is yours, and all code from the Firmata library, then the most possible cause that comes to mind after reviewing the library code is memory leak, which makes the next allocation to fail and by thus breaking the code.

The Firmata library does perform dynamic memory allocation, checkout Firmata.c, so it is realistic - I would suggest to take it with the Library's author.


Answering my own question, I think I found some way to get the solar panel face the sun.

As said before, the inclinometer reads the position and makes some calculations using lookposition() function, then this happens:

void lookforsun() {
  while ((targetElevation + 3) < realElevation | (targetElevation - 3) > realElevation) {

    Serial.println("Elevation is not correct");

    while (realElevation < targetElevation)
    { Serial.println("Moving to south");
      digitalWrite(south, LOW);
      lookposition();
    }
    digitalWrite(south, HIGH);

    while (realElevation > targetElevation)
    { Serial.println("Moving to north");
      digitalWrite(north, LOW);
      lookposition();
    }
    digitalWrite(north, HIGH);
  }

  while ((targetHourangle+3) < realHourangle |  (targetHourangle-3) > realHourangle  ) {

    Serial.print("Hour angle is not correct");
    while (realHourangle > targetHourangle)
    { Serial.println("Moving to east");
      digitalWrite(east, LOW);
      lookposition();
    }
    digitalWrite(east, HIGH);

    while (realHourangle < targetHourangle)
    { Serial.println("Moving to west");
      digitalWrite(west, LOW);
      lookposition();
    }
    digitalWrite(west, HIGH);
  }

As you can see I took the frightening way of nested while loops, but appears to work.

The first while measures if realElevation is between +-3 degrees of targetElevation, if realElevation is far away (target+-3) enters the second while loop, which determines if needs to go up or down.

I included the +-3 because the sensor is so very sensible.

Thank you very much  Russell McMahon and portforwardpodcast for your ideas!


Combining two different coding program into one sketch

The simplest way of combining two programs is this:

Copy the content of the two programs into a single new .ino (program) file
Rename the first setup function setup_one
Rename the first loop function loop_one
Rename the other setup and loop functions setup_two and loop_two
Add the following code to the bottom of that file.

Code:

void setup()
{
  setup_one();
  setupr_two();
}
void loop ()
{
  loop_one();
  loop_two();
}

This is a very simplistic approach and it won't work for all cases.  It will work in this case, but you will find it will do program one then program two.  It will work because your constants don't clash (at the top of the program) you aren't using the same pin in the different programs, etc.

You need to learn what the code does though to really merge the programs, you will see better ways of doing it.  The best way to learn is to right down, in your native language, what each line of code does, so in the case of program one:

turn on the motor
turn on the LED
wait for 'watertime' seconds
turn off the motor
turn off the LED
wait for 'waittime' minutes

For program 2:

  read the state of the pushbutton value:
  If the button is in state low
    Turn off the LED -- Not sure  this might be on
  else
    Turn on the LED -- Not sure this might be off

Hopefully you should recognise those descriptions (they are the comments) and when you read through the descriptions you will realise why the code you put together using the above method "doesn't work".  It does, you just need to wait for 'waittime' minutes before you get a few microseconds to press the button.

If you want the motor to respond to the button then rearrange the natural language description to do what you want and then replace the English with the code and you should have a program that is close to working.  (Hopefully)


Segmentation fault and huge SRAM need for Serial.println

Note, this answer is not MY answer, but approximately the combination of the first 5 comments from my original question.

What I did was:

(Juraj) Changed the compiler version to 6.21
(juraj) Added an F in F(__FILE__)
(KIIV) Removed func; this did not work with the F flash helper, but I can find back the code anyway unambiguously because of the file name + line number.
(Majenko) I removed the class and use a macro. This costs some more Flash memory (depending on the number of asserts I use, but I'm still around 40% (was 35%).

The SRAM usage is now 1125 bytes, even less than where I'm started with.

The resulting code is below:

#define assert(expression) \
  if (!(expression)) \
  { \
    Serial.println(F(__FILE__)); \
    Serial.println(__LINE__, DEC); \
    Serial.flush(); \
    abort(); \
  }


I want to be able to upload a batch of tweets to a twitter bot to be qued' for tweeting

First create an array of all the messages:

#define NUM_MESSAGES 3
const char *msg[NUM_MESSAGES] = {
    "This is the first message",
    "This is the second",
    "Third time lucky" };
int msg_num = 0;

Then in the loop, switch between messages and add a delay

void loop()
{
  Serial.println("connecting ...");
  if (twitter.post(*msg[msg_num]))
  {
    int status = twitter.wait();
    if (status == 200)
    {
      Serial.println("OK.");
    }
    else
    {
      Serial.print("failed : code ");  //stuff happens here idk
      Serial.println(status);
    }
  }
  else
  {
    Serial.println("connection failed.");
  }

  //Next message
  msg_num++;
  if (msg_num >= NUM_MESSAGES) msg_num = 0;
  delay(1000*60*60);
}


Can I call functions from a different sketch?

You can only use one sketch at a time, meaning one sketch can be stored inside an Arduino to be executed.

This means all your code (and functionality for all devices you want to access) needs to be within that single sketch.

So what you mostly need to do is:

Add a library for every device that you want to use.
Call functions from that library in your .ino file.
If you want to add functions which are not part of a library, you add both the function code and the call (where you need it) in your .ino file.

Also if you are new, don't start with everything at the same time.

First find an example how to control the display (that's probably easier than the CAN shield).
Add the library for the display
Change (or copy from an example) code for the display
Run and debug it until it works.
Create a new sketch for the CAN shield.
Add the library for the CAN shield.
Call functions from that library (or use an example if available).
Once you are convinced you know how to use both devices (display + CAN), combine the sketches (create a new sketch, add both libraries, copy code and make it one sketch).


What is the meaning of [type]* for arrays?

You are asking about Pointers -
 https://www.tutorialspoint.com/cprogramming/c_pointers.htm.


How to get text to flash on ssd1306 i2c screen

As approved by the OP, the error was caused by not having reset the cursor to a visible position on the display. The text was written outside of the OLED.

It seems as the clearDisplay() method does not reset the cursor.

The solution is to change the following methods

void testdrawstyles1(void)
{
  display.clearDisplay();
  display.setCursor(0,0);
  display.print(F("test1"));
  display.display();
  delay(500);
}

void testdrawstyles2(void)
{
  display.clearDisplay();
  display.setCursor(0,0);
  display.print(F("test2"));
  display.display();
  delay(500);
}


You can use one (or more, daisy-chained) shift register for that.

It will normally take you 3 pins and provide 8 outputs, or 8n where n is the number of chained shift registers still using only 3 Arduino pins.

One example of a shift register that fits your situation is the 74HC595.

On Arduino, you can use shiftOut function to help handle those ICs.


I'm not a C# programmer but this StackOverflow answer might be what you're looking for.


It seems as if there is a 220K pull-down resistor on analog pin 0

They don't connect a resistor as such, but analog input pins do have an impedance which can affect your readings.

If your output impedance (the resistance of your resistors) is within about a tenth of the impedance of the input pin then you will (and have) noticed skewing of the results.  This is normal.  The input impedance is somewhere in the region of 1MΩ - 10MΩ.

You have to keep your output impedance to a value below the order of a few tens of kΩ to minimise the effect the measuring of the value has on the value.

If you want to measure higher resistances then you will need to buffer the voltage with a very high impedance op-amp buffer.

Incidentally, your volt meter probably has an input impedance in the region of 10GΩ - around 1000x higher than the Arduino's ADC.


A const parameter to a function doesn't define what can be passed. It is, instead, a "promise" by the function that it will not modify the data you pass it.
In C when you pass a "string" (which is actually an array of characters) to a function you don't actually pass the string (as in the content). You really just pass a pointer to the location in memory where the string is stored.
It is perfectly possible for a function to then make modifications to that passed "string", which will be modifying the original data in memory. That is not really desirable in many situations.
So by flagging the parameter as const you tell the compiler "From this moment onwards the data pointed to by this variable must not be changed". All attempts to write to the memory using that variable will be blocked by the compiler.
There's no actual difference between, say, a char * and a const char * other than how the compiler treats attempts to write to them.
When you pass a char * to a function that is expecting a const char * the pointer is "upgraded" to a constant so that no attempts to change the data will be allowed.
The converse is not allowed though - you can't (or shouldn't) try and convert a const char * to a char * as on some systems ("Princeton" architecture systems with a single monolithic memory address space) the pointer could be pointing to data stored in flash, and an attempt to write to that will obviously fail.
The function you are calling to set the SSID is merely promising that it won't attempt to change the data you pass it. It doesn't matter if it's a constant or not - both will be treated as a constant and not be changed.


That should work, but it's overkill. Those devices are made for bidirectional signaling. You should be able to use a single transistor that is driven to saturation at 3.3V. A Suitable "logic level" MOSFET with a 3.3 gate voltage should do the trick.
And, as Chris L said in his answer, you may be able to drive an input on a 5V Arduino directly with 3.3V. That's a high enough voltage to be read as a logic level 1.


Yes you can use the Plot menu command in the new Arduino 1.6.6 or you can use the Visual Micro debugger to create graphs in Visual Studio


For SoftwareSerial, at 115200 bps data rate is not going to be reliable. Try 9600 bps.


Controlling 3 stepper motors simultaneously

You need a struct for each stepper with a timestamp, a position and rate of change and a loop that updates the postion based on rate which is the change in position over some time:

struct stepper {
  unsigned long timestamp;
  int position;
  int rate;
};

// init steppers array

while (keepGoing()) {
  unsigned long now = millis();
  int si;

  delay(10);

  for (si = 0; si < 3; si++) {
    struct stepper *stepper = &steppers[si];

    if (steppers[si].timestamp > now) {
       steppers[si].position += steppers[si].rate;
       steppers[si].timestamp = now + 100;
    }
  }

This is a back-of-a-napkin sketch of course. It is only supposed to illustrate how you can update any number of things concurrently.

The important thing is that you only call delay once. And presumably it would be only a very short delay compared to the unit of time for the rate. In the above example it would adjust the stepper position every 100ms. You would need to experiment with the timing to find a good behavior given the speed of the stepper, speed of the code and maximum permitted rate.

Beware that there is a lot to think about beyond this. For example, you should initialize the timstamps with different timestamps so that the motors are not all running at the same instant and thus try to minimize the total power consumed by the motors at any particular time.

Note that I have never played around with stepper motors but this type of loop is a common programming idiom for handling things concurrently.


Linking the Arduino Bootloader In Atmel Studio

This isn't exactly 100% the answer I was looking for, because I still want to know how I can use a static library build, as I mention in my post, and compile everything as a single binary. This method is essentially gluing two binaries together.
I found this great and informative post over here:
https://www.avrfreaks.net/forum/can-you-combine-appbootloader-using-as7
It uses srec_cat to concatenate two binaries after building them:
https://www.keil.com/support/docs/2666.htm
I use the offset specified from the '.ld' file using
srec_cat <firmware1.bin> -Binary <firmware2.bin> -Binary -offset 0x2000 -o <firmwareOut.bin>
As the post suggests, I set this up as a post-build event and set my build dependencies accordingly so that a full clean and make will produce a consolidated binary including the bootloader.
If anyone tries this, make sure you only use the non-bootloader binary generated by your main project build. The bootloader places new firmware at location 0x2000 and your firmware will break if it finds a bootloader at the location where the firmware is supposed to be. When uploading firmware to the bootloader, it does not overwrite the bootloader.


The Vin pin serves the same purpose as the barrel jack.  The only difference is (usually) that it doesn't go through the schottky protection diode that causes a small voltage drop.

Normally its voltage is at around 0.3-0.4V below whatever you feed into the barrel jack.

If you power from USB then the USB voltage (~5V) is "back-fed" through the 5V regulator to appear on the Vin pin.  It's not safe to use that power for anything since you could damage the 5V regulator if you do.

The pin is designed to either be used to power external higher voltage devices with power (almost) direct from the barrel jack (motors, etc), or to feed power in from an external source without using the barrel jack (great for a shield that can provide its own power source).


Starting usb on pro micro after deep sleep (ATmega32u4)

I found an answer to a similar question here:
https://forum.sparkfun.com/viewtopic.php?f=32&t=39214&start=15#p175098

Note: it requires you to close and open the serial monitor at proper timings.

// disable the USB prior going to sleep
USBCON |= _BV(FRZCLK);  //freeze USB clock
PLLCSR &= ~_BV(PLLE);   // turn off USB PLL
USBCON &= ~_BV(USBE);   // disable USB

// and wake it up after
//routine to properly wake up
sleep_disable();
delay(100);
USBDevice.attach(); // keep this
delay(100);
Serial.begin(9600);
delay(100);


PROGMEM doesn't cause Sketch size to change

all constant data are part of the sketch. where else should they be? in runtime they are loaded into RAM. PROGMEM directive prevents the loading into RAM.


Convert a Bitstring into an integer value

If you only need the string for printing you can store value in an integer and then use the Serial.print(number,BIN) function to format the output as a binary value.  Appending integers to strings is a potentially costly operation both in performance and memory usage.

int Number = 0;
int tmp;

for (int i=9;i>=0;i--) {
  tmp = analogRead (A0);
  Number += (tmp % 2) << i;
  delay(50);
}
Serial.print(Number, BIN);


Arduino Micro not providing regulated power

In comparing this with another Arduino Micro, it appears that the regulator is malfunctioning.


Problem with programming an ATtiny85: Error - avrdude: Yikes! Invalid device signature

Try connecting the RESET pin of the Attiny85 to GND the second before you hit "program".

In my experience, the Arduino does not always send the RESET signal when it should (or on the pin that you think it would send it).

In these cases, manually resetting the Attiny by connecting the RESET pin to ground makes it programmable.

You can keep RESET low during the whole programming process, but if you keep it low for many minutes before programming the chip, it might not always work. In those cases, set RESET high for a moment before setting it back low, and the Attiny should be good for another round of programming.

And of course, when you want the Attiny to start doing what you have programmed it to do, you have to pull RESET high again.


Use the OneWire and the DallasTemperature libraries. They are both in the Arduino IDE in the Library Manager.

The DallasTemperature library has the example "Multiple". You need to make an array of DeviceAddress.

To tell them apart, you have to label each temperature sensor with its device address (a unique identifier inside each DS18B20). Therefor you have to connect them one-by-one and write down the device address.

Start with one sensor, and if that works, try to make arrays.

For 24 temperature sensors, you need a lot of wires. That could make it less reliable. You can use two or three or more pins as well. Then you have to create more than one "OneWire" bus in the sketch.

There are many examples for multiple DS18B20 sensors. For example this one is with an array: Arduino forum: "multiple temp sensors ds18b20".


ESP8266 - does it really have terrible wifi range by default?

The very first thing I notice is that your WiFi antenna is shielded by the PCB. That is the antenna is placed right over the top of the ground plane of the PCB and your range is going to be severely limited.

You will notice on the NodeMCU design below that they have placed a PCB cutout where the antenna is located. In other pictures you can also see that the ground plane does not go past where the antenna starts.

On other boards the antenna sits proud of the main PCB such as this one from Tronixlabs:

If money is tight and new hardware is out, you could try cutting a cutout where the antenna sits using your Dremel (or other rotary tool). If there are any traces underneath the antenna you will need to fix them up with wire worms. Of course it is best to remove the ESP module first.

Alternatively, you could redesign the PCB and send it out for another manufacturing run. I use PCBShopper.com to find the best price for the bare PCBs.

Edit:
Something else you could do is to unsolder the ESP and mount it 90 degrees to the PCB. You would need to solder wires from the base PCB to the terminals of the ESP. This should work and you won't need to cut the base PCB.


IR module sensor query for Line Follwer Robot

The sensor you have used is fine. There is a potentiometer on the sensor PCB that is used for the range. For the line following robot you would want the range small, between 1-4cm. However, for the obstacle avoidance robot you would want to set this for a much larger range, say 10-45cm.

To make an effective line following robot you need at least 2-3 sensors.

Here is one using 2 LEDs either side of the line:

And here is a 3 sensor robot:

Notice that one LED stays on the line.

And finally a 5 sensor robot:

The following websites have good step by step guides where they explain the various techniques:

https://www.learnrobotics.org/blog/how-to-build-a-mobile-robot-using-arduino-part-4/
https://circuitdigest.com/microcontroller-projects/line-follower-robot-using-arduino
http://www.robotc.net/wikiarchive/Tutorials/Arduino_Projects/Mobile_Robotics/VEX/Using_the_line_tracker_to_follow_a_line

When I made my line following robot I used 2 of the following sensor:

These sensors were great as they pointed in towards each other, making a focal point. You can do this to your sensor by bending the LEDs slightly towards each other.


Reading sensor with current ouput with Arduino

The "sensor" is just a photodiode that is sensitive to UV. You use it the same as any photodiode.

The simplest (and crudest) way is to use a very large (eg 1MΩ) pullup resistor to 5V on an ADC pin, then connect the sensor (reverse biased) between the ADC pin and GND.


Stepper motor not working in Arduino 101

After reading the Stepper library and searching for several, I saw that in an example using an EDISON ( I want to thanks to Guimficus for posting his code here: https://communities.intel.com/thread/99133) they changed the pinMode of the GPIOS they were using in the setup function :

pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);

And after adding that seems to work like it is supposed to work.

Cheers!


Why is my passive buzzer clicking instead of buzzing when set to HIGH?

those problems were due to the fact that the people asking the questions were not aware that the buzzer was a passive one.

You seem to know, that you have a passive buzzer, but you don't know, what that means for you.
A buzzer consists mostly of a piezo element, which vibrates and thus makes a sound, if you provide it with an alternating voltage. Here we have 2 types of buzzers:

The ones, that generate the alternating voltage themselves, thus only demanding a simple constant voltage from you to operate (these are the active buzzers)
and the ones, that only have the piezo and thus demand to be provided with an alternating voltage by you (these are the passive buzzers).

You have the second type, a passive buzzer. The following is happening:
digitalWrite(pin, HIGH) will only set the pin to HIGH. On the transition from LOW to HIGH, you get a click, because the piezo in the buzzer is reacting to that change. analogWrite() on the other hand generates a PWM signal, which is an alternating voltage (alternating between LOW and HIGH).
When changing the number for analogWrite(), you are not changing the frequency, but only the duty cycle (the ratio of HIGH and LOW times in one period of the signal).

analogWrite(pin, 255) means 100% duty cycle and thus a constant HIGH signal. Actually it is equivalent to digitalWrite(pin, HIGH), because analogWrite() is doing exactly that, if you provide 255 (similarily it uses digitalWrite(pin, LOW), if you provide 0). Thus you again hear the same click.
As the piezo in the buzzer needs to oscillate to make a sound, you need to give him time for getting back to the LOW state. With the analog value 254 the LOW time of the signal is rather small, so that the piezo cannot reach its complete LOW state again. The oscillation amplitude is rather small that way. Thus you only hear a very faint buzz.
With analogWrite(pin, 250) you reached the maximum, because now the piezo has enough time to get to its LOW state again. The amplitude is at its maximum here, thus it is the loudest value.
When going lower than 250 towards zero, you are also reducing the amount of energy, that you give to the buzzer, thus the volume will reduce (though this is certainly not a linear process and depends also on the characteristics of the buzzer).

Just as Juraj already wrote in the comments, a passive buzzer can be interfaced with the tone() function. It will generate the alternating voltage for you and you can even set the frequency to your liking, so that you get tones with different pitches. There are tons of tutorials about the tone() function on the web.


I suggest using a union:

union {
    char myByte[4];
    long mylong;
} foo;

Char to Long:

Then you can just add the bytes:

foo myUnion;
myUnion.myByte[0] = buf[0];
myUnion.myByte[1] = buf[1];
myUnion.myByte[2] = buf[2];
myUnion.myByte[3] = buf[3];

Then you can access the long as:

myUnion.myLong;

Long to Char:

The same if you want to go the other way from long to char array:

foo myUnion
myUnion.myLong = 1234L;

To access bytes:

myUnion.myByte[0];
myUnion.myByte[1];
myUnion.myByte[2];
myUnion.myByte[3];


While you should use a voltage divider on the Arduino TX --> BT RX signal, you honestly don't need to. Many people, including myself, have used HC-05s without voltage dividers and haven't let "the magic smoke" out of the device. Adding a voltage divider may, though, may increase the lifespan of the HC-05.


Difference between DS1307 and IN1307N, I am using RTClib for making rtc module using IN1307N getting RTC is not running

Following this circuitry solved my issue but still i've not understand the difference between DS1307 and IN1307N.


Getting FFT arduino code to run over 9+ hours, utilizing micros()

Chris Do, there is indeed a rollover problem when micros is used that way. When that happens, the samples are taken at full speed without interval. That will create bad data for the FFT.
The solution is in the Blink Without Delay example. The magic to avoid a rollover problem is the substraction with two unsigned long values.

The arduinoFFT library is in the Library Manager of the Arduino IDE.
The example "FFT_03.ino" uses micros in the wrong way.

The next sketch shows how to avoid the rollover problem:

// Use micros() without rollover problem for a fixed sample rate
// for a certain amount of samples.

#define SAMPLES 128

unsigned long previousMicros;
const unsigned long intervalMicros = 1000UL;   // 1000 Hz is 1000 us

float vReal[SAMPLES];
float vImag[SAMPLES];

void setup() {
}

void loop() {

  previousMicros = micros();  // set the previousMicros just before entering the for-statement
  for(int i=0; i<SAMPLES; i++) {

    // A while-statement to wait.
    // Note that the ';' at the end means 'do nothing'.
    while( micros() - previousMicros < intervalMicros);

    // The 'previousMicros' is increased with a fixed number, for a fixed sample rate.
    previousMicros += intervalMicros;  // for next interval

    vReal[i] = float(analogRead(0));
    vImag[i] = 0.0;
  }

  delay(1000);
}

Take the current value of micros and substract the previous value of micros. The result of that substraction is a valid number, even during a rollover. It is the only way that always works.

The line to calculate the sample period has too many things in it that can go wrong. These lines:

unsigned int sampling_period_us;
sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));

In my example, I set the intervalMicros to a certain number. Could you do that as well? When everything works, you can try to calculate it.

Added: The answer by Edgar Bonet is exactly the same. That is no surprise because there is no other way.


How to burn bootloader and upload sketches on custom arduino?

You can use a second Arduino as a standalone programmer for it, either to upload your sketch directly, or to upload a bootloader (after which you'd upload your sketch in the normal way). The example program, ArduinoISP, uploaded into the second Arduino is what can do this. Here is a link to a how-to article for doing just that.

If you haven't already populated your PCB, good - sometimes your external (to the MCU) circuitry can interfere - but it's worth a try, even if you have.


You can turn off the entire Arduino and let it wake by your RTC. That way you can conserve a lot of power. (link)

Also you will have losses from the power regulator when powering the Arduino from 12V. You might consider using a Arduino Pro mini with 3.3V powered by two AA batteries. That should last for years.


Most compact method of powering Arduino from wall socket

I can suggest you to try this : AC DC Step Down Converter

It is as small as the Apple's tiny cube, and it can be placed inside of a wall easily. (I'm personally using this with an arduino micro)


File Size Problem with EyeFi SD Card and Arduino Mega

After some testing and research, I found out that the Eye-Fi SD card starts a transfer once a file reaches 20kb or more and will not upload a file again once it has been transfered already.  The solution, as suggested by ChrisStratton, is to log to a temporary file and trigger a transfer once the file is ready.

I took advantage of the fact that the Eye-Fi only transferring files in the standard camera folders.  In my case, I used the Nikon naming convention: DCIM/100NIKON/DSCNxxxx.JPG  (xxxx is the photo number ranging from 0000 to 9999), but there are also others.  Check on the Eye-Fi website for compatible cameras.  I created a temporary file called TEMP.TMP and stored it to the root folder of the card and logged to it.  Once I'm ready to transfer the file, TEMP.TMP gets renamed to "DCIM/100NIKON/DSCNxxxx.JPG" and the whole file is transferred all at once.

Here's my code.  I'm using the software serial (pins 10, 11, 12, 13) of the Mega:

//Running with 256kb serial buffer (modified HardwareSerial.cpp)
//Added file time stamps

#include "SdFat.h"
#include "SdFatConfig.h"
#include <Wire.h>
#include "RTClib.h"

#define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
uint32_t syncTime = 0; // time of last sync()

#define ECHO_TO_Serial     1 // echo data to Serial port
#define WAIT_TO_START      0 // Wait for Serial input in setup()
#define MESSAGE_SIZE      11 // Message size of "!G N +1234" + CR
#define SOFT_BUFFER_SIZE  256// 25 Messages of 11 chars each

const uint8_t chipSelect = 10;

SdFat sd;
SdFile logfile; //create log file

RTC_DS1307 RTC;
DateTime filedate;

uint16_t date;
uint16_t time;

int i = 0;
int x = 0;

char directory[] = "DCIM/100NIKON";
char filename[] = "DCIM/100NIKON/DSCN0000.JPG";
char tempfile[] = "TEMP.TMP";

/*************** ERROR ***************/
void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);
  while(1);
}

/*********** TEMP FILE CREATION ***********/
void newFileName()
{
  sd.chdir("/"); //check DCIM/100NIKON directory
  // create a temp file
  for (uint16_t i = 0; i < 10000; i++)
  {
    filename[18] = i/1000 + '0';
    filename[19] = (i/100)%10 + '0';
    filename[20] = (i/10)%10 + '0';
    filename[21] = i%10 + '0';
    if (! sd.exists(filename))
    {
      Serial.print("New file name: ");
      Serial.println(filename);
      break;  // leave the loop!
    }
  }
}

/****** call back for file timestamps *****/
void dateTime(uint16_t* date, uint16_t* time) {
  DateTime now = RTC.now();

  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(now.year(), now.month(), now.day());

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
}

/*************** SETUP ***************/
void setup(void)
{
  Serial.begin(115200);
  Wire.begin();
  RTC.begin();

  if(! RTC.isrunning() )
    Serial.println("RTC is not running");

  // set date time callback function
  SdFile::dateTimeCallback(dateTime);

  // initialize the SD card
  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (! sd.begin(chipSelect, SPI_HALF_SPEED))
    error("Card failed, or not present");

  Serial.println("Card initialized");

  // see if the directory exists, create it if not.
  sd.chdir("/");
  if( !sd.exists(directory) && !sd.mkdir(directory) )
    error("File directory not created");

  // create new file name
  newFileName();

  // Scan root folder for temp files
  sd.chdir("/");
  while( logfile.openNext(sd.vwd(), O_READ)){
    if( !logfile.isDir() ) {
      logfile.printName(&Serial);
      if( logfile.fileSize() < 20480 ){
        Serial.print(" file size too small. ");
        Serial.print(logfile.fileSize());
        Serial.println(" bytes.");
        logfile.remove(); //Delete under sized files
      }else
        if( !logfile.rename(sd.vwd(), filename))
          error(" could not be renamed.");
        else{
          Serial.print(" renamed to ");
          Serial.println(filename);
        }
    }
    logfile.close();
  }

  // create temp file
  sd.chdir("/");
  if(!logfile.open(tempfile, O_WRITE | O_CREAT)) // only open a new file if it doesn't exist
    error("couldnt create temp file");

  Serial1.begin(115200);

  // Rotate the buffer
  for( int j = 0; j < 256; j++) {
    Serial1.read();
  }

  // Look for the '!' character
  while (Serial1.peek() != '!' )
    Serial1.read();

  Serial.println("Logging...");
  Serial.println();

  // Reset buffer index to 0
  i = 0;
}

/*************** MAIN LOOP ***************/
void loop(void)
{
  if (Serial1.available()){
    logfile.print( (char)Serial1.read() );
    i++;
  }

  if (i >= SOFT_BUFFER_SIZE)
  {
    logfile.sync();
    i = 0;
  }
}


Solar Tracker Code - how to limit steppers to max & min angle?

The only sure way is to use one or more position or limit switches. Steps can be lost (motor didn't move as commanded due to, f/ex, overload), the motor could be back-driven while powered down or if over-powered by the mechanical system, or your step counting could be faulty due to a bug or a power glitch.

At power-up or at any time your software thinks it might have got out of sync with the mechanicals, back into the limit switch at low speed (so you don't hard-crash), and reset your software counters, and reposition from there.


Windows troubleshooter is just trying to tell you that you've plugged a USB2 device into a USB3 port, thus wasting its USB3 capabilities which could be useful for another device. Of course, if you only have USB3, you can't do otherwise.

USB3 is fully backward-compatible with USB2, so whatever your problem is, it is not related to the fact that you plug the Nano into a USB3 port. Perhaps your problem comes from the fact that your Nano is "third party" - I suppose that means it's not the original device and thus it may not be fully compatible. If my guess is right, try to find out what programmer your Nano clone supports: chances are you just need to select a different programmer type in Arduino settings, or buy a separate programmer supported by your device.


Script on pc only gets 640 characters via serial

You are not using a serial connection, you are using a USB CDC/ACM connection, and that is a very very different thing.

With a serial connection when you send data it gets sent regardless of whether there is anything listening for it - the TX IO pin toggles high and low regardless.

However, with a CDC/ACM connection it's only possible to send data when there is something actively listening at the remote end - that is, when the port /dev/ttyACM0 has been opened by an application.

Until that port has been opened any data sent will remain in internal buffers.  These buffers are 64 bytes each in size (that's the size of a CDC/ACM packet), and there are (I would guess) 10 of them on the Teensy3.  After these buffers are full, because there is nothing receiving the data, there can never be any more room made for more data, so instead of blocking like a serial connection does it just discards the data.

So you have filled the buffers with 640 bytes of data and thrown away the rest.  That data just sits there.

Then eventually you open the /dev/ttyACM0 port and the Teensy3 is now able to send CDC/ACM packets through the USB.  And it has 10 of those packets sat there waiting to go out, so it sends them.  So you receive the 640 bytes of data that you had buffered up.

Your mistake is basically not waiting for the port to be opened before sending data to the remote end.  You can test the state of the port (kind of, but that's a whole other subject) by examining the Serial object:

if (Serial) {
    // ... the port is open
}

In general you can usually just wait at the start of your program before starting anything else with a simple while:

while (!Serial); // Wait for the port to be opened


ATMega1284 and Relative Humidity libraries

Per the library instructions, you will receive INVALID_VALUE in the following situations:

The readXX() functions return:

DHTLIB_OK (0) : if the sensor sample and its checksum is OK.
DHTLIB_ERROR_CHECKSUM (-1) : if the checksum test failed. This means that data was received but may be incorrect.
DHTLIB_ERROR_TIMEOUT (-2) : if a timeout occured, communication failed.

In case of a DHTLIB_ERROR_TIMEOUT, humidity and temperature will both get the value DHTLIB_INVALID_VALUE. In case of DHTLIB_ERROR_CHECKSUM the values of humidity and temperature are left unchanged as it is impossible to determine which byte failed in the checksum. It is up to the programmer to decide what to do. One can compare with previous value, but better reread the sensor.

So read the value returned by the read11() or read22() functions to verify that it's an DHTLIB_ERROR_TIMEOUT condition, and if so try to figure out why the library is having trouble talking to the device.


How do pins on an arduino mega 2560 work?

there should be two pins for every node one acting as the negative terminal and other as the positive terminal.

No, there is one pin per node, and a common "Ground" pin which is the negative terminal. On your Mega2560 are 5 ground pins (effectively equivalent because they are connected). They are circled on the photo below, and marked GND on the board.

As Majenko says in his answer you must use a resistor in series with any LED you connect, or you will damage both the LED and the processor.

You may find a "breadboard" handy for making connections, most prototyping boards have a long connected strip for sharing the Ground wire between different places, like this:

The continuous blue lines indicate pins which are connected together (for Ground) and the continuous red lines are connected together for +5 V (usually).

  Btw can you tell me why there are two pins on the bottom horizontal row?

Just for convenience. You often want an extra ground pin, for example if you are trying to connect up two LEDs.

  Secondly, yes each pin can be set as input or output but is there any specific difference in the type of pins?

Some of the pins can optionally be used for extra hardware-supported features.

PWM: Pulse-width-modulated output
COMMUNICATION: Serial input/output (4 serial ports)
ANALOG IN: Analog-to-digital converter (ADC) input
DIGITAL: Digital (not analog) input/output
SDA/SCL: I2C communications
Pins 50-53: SPI communications (not marked on the board)

However all pins, as you noted, can - if you wish - be used for digital input or output.


Nothing wong, if your power supply is trustworthy enough, then , if u even provide 100000 Amps of current with 5 volt,
your IC won't burn, in your case , it burnt because your power supply seems to be defective, and please check the voltage of the power supply which is supposed to be defective, so it output more than 5 volts burning or crashing your ic...
Note:
I have personally worked with 5 volt 6 amp power supply which is very well precise and my ic is working full fledged without any problems.


C++ Undefined reference to 'Class:Function()'

As Juraj rightly points out, you have a typo, which should give you the following compile time error:

In file included from sketch/Sensor.cpp:1:0:
Sensor.h:17: error: 'pivate' does not name a type
 pivate:
 ^

Here is the correct code for Sensor.h

#ifndef Sensor_h
#define Sensor_h

#include <EEPROM.h>
#include "IMU/L3G.h"

#define CUTOFF_FREQ 30
#define FREQ 400

class Sensor {
public:
    Sensor();
    ~Sensor();
    void Init(void);

private:
    L3G gyro;
};
#endif

Using Arduino IDE 1.8.5 with Teensyduino 1.42 with:

https://github.com/pololu/l3g-arduino
https://github.com/nox771/i2c_t3

However, once the typo has been corrected, as above, then I too can reproduce your problem (sort of), with these link errors:

/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp.o: In function `Sensor::Sensor()':
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp:3: undefined reference to `L3G::L3G()'
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp.o: In function `Sensor::Init()':
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp:14: undefined reference to `L3G::init(L3G::deviceType, L3G::sa0State)'
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp:19: undefined reference to `L3G::enableDefault()'
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/core/core.a(main.cpp.o): In function `main':
/Volumes/Home/Users/user/Local_Apps/Arduino/Arduino1.8.5-Teensy.app/Contents/Java/hardware/teensy/avr/cores/teensy3/main.cpp:53: undefined reference to `loop'
collect2: error: ld returned 1 exit status
Multiple libraries were found for "Servo.h"
 Used: /Volumes/Home/Users/user/Local_Apps/Arduino/Arduino1.8.5-Teensy.app/Contents/Java/hardware/teensy/avr/libraries/Servo
 Not used: /Volumes/Home/Users/user/Local_Apps/Arduino/Arduino1.8.5-Teensy.app/Contents/Java/libraries/Servo
Error compiling for board Teensy 3.5.

You are probably getting this error, because you have placed the files L3G.cpp and L3G.h in a folder called IMU in the same folder as your .ino file. This causes the undefined error, as, while the IDE sees the declaration in the L3G.h file, the IDE can not find the definition in the L3G.cpp file.

This is easy to resolve.

If you download the l3g-arduino-master.zip file from https://github.com/pololu/l3g-arduino, and from within the Arduino IDE you then add the zipped up L3G library to the Arduino library, using Sketch ► Include Library ► Add. ZIP Library... and then change the line

#include "IMU/L3G.h"

to

#include <L3G.h>

Then it should compile and link without a problem


A PID only has one input and one output. In your case, the input will be the temperature. The use of the arduino would be to process the raw data of the temperature sensor and relay the temperature to the PID. Depending on the make and model of the PID, there could be certain transfer protocols you must adhere to. There are most likely open source libraries that will take care of transferring the data properly.

Your PID is the piece of hardware that will "decide" when it is appropriate to turn the heater on and off, therefore it shall be responsible for driving the heater. That is what the output of the PID is responsible for.

Lastly, your PID has a set point. In your case, the set point would be the desired max temperature of the plate. This set point is set and altered manually through user input.

On a side note, if this is a personal project or a non deliverable, I'd recommend not using a PID. Try processing and analyzing all of the data exclusively on the Arduino, as it would be a challenging and rewarding task.


Gesture sensing TV coffee table - what sensors would you use?

Perhaps if you drop the monitor an inch or 2 away from the glass you can use a Frustrated Total Internal Reflection (FTIR) IR scheme.  But at that shallow angle it will be tricky and may require several cameras around the edges.

added later...

Should mention the parallax problem given there is a gap of an inch or more between the monitor and the touch screen.  FTIR is better when you project the image onto the touch screen.

If you don't mind lower resolution, I believe the micro dose dispenser soda machines use a capacitive touch wire mess embedded in the transparent plastic front panel.  Although micro dose dispensers appear to only need to emulate about 100 to 200 buttons.  Not enough to control a mouse with any accuracy.  But enough to control a GUI designed with such constraints.

Loose high resolution capacitive touch screens can be bought with out a monitor.  However they tend to be much smaller then 32 inches.


Why is the IDE not able to find the board despite it being clearly seen and selected?

The SAMD boards connect to computer over native USB support of the MCU. The handling of the USB is done by Arduino core functions linked at build to your sketch.

A consequence of using the native USB port is, if your sketch has a problem, it influences the USB communication. In this case you can activate the bootloader to handle the USB port and the upload. It is done by double clicking the reset button on board.


amblone error :85: error: 'TCCR3B' was not declared in this scope - no fullscreen vlc support

Amblone doesn't work on an Uno. As stated in the requirements list, you require a Mega.


Serial.print() feeds the data into the TX buffer one character at a time (through the Print class's inherited .write() function which HardwareSerial implements). If there isn't enough room in the TX buffer for the next character it waits for there to be room available.

Characters are removed one at a time from the TX buffer and sent through the physical UART by the UART's TX interrupt.

To put it in more detail:

When you call Serial.print() it's actually calling Print.print(), because Print is a parent class of the HardwareSerial class.
Print.print() repeatedly calls Print.write() for each character to print.
Print.write() is a pure virtual function (which means it's only got the definition in the Print class and child classes must implement it).
HardwareSerial.write() implements the Print.write() function which takes the character and (with possible blocking while waiting for space) adds it to the TX buffer.
Serial is an instance of the HardwareSerial class.


You can connect an external antenna to pin 8 on that module. Just use a piece of wire that is 17.3cm long. But since the range is that bad to start with, probably means it isn't tuned very well. I'd return it, or try fiddling with the pot at the back. Not sure why Sparkfun has these crap transceivers for sale. Transceivers without a crystal are very inaccurate in their frequency.

If you only need to transmit, I'd suggest this products: https://www.sparkfun.com/products/10534
 . Those worked great for me, and are currently switching on the power sockets for my lights when it gets dark enough.


Program an Arduino Uno with an Atmel ICE

Your Ardunino is stuck in debugWIRE (The debug wire fuse is set). Here is a tutorial on how to get it back to programming mode.

In the tutorial I am using the AVR Dragon with AS6, but the process is the same with Atmel ICE and AS7.

You have to be in Debug Mode to disable debugWIRE. While in debug, Click Debug>Disable Debug Wire and Close.


Regarding the USB port, what is the difference between Uno/Mega and the older boards?

The older Arduino boards used an FTDI FT232R chip to handle the USB port. This chip is a special purpose, USB to serial UART interface.

In the current Arduino boards, the USB to serial conversion is handled by dedicated Atmel Atmega8u2 processor. This is a processor that is similar to the main ATmega328p processor, but the added benefit of having built-in USB capabilities.

So, why the change? Well, first, it's cheaper than the FTDI chip, and second, it can do much more. Being that it's an actual microprocessor, you can actually reprogram this chip to behave like different USB devices. For example, you can reprogram it to make your Arduino look like a keyboard, a joystick, a thumb drive, a MIDI instrument - anything that you can do via USB. The FTDI chip does not have this capability, and so it can only ever look like a serial COM port to your PC.

Why have 2 microprocessors on the Arduino? By having a dedicated processor to handle the USB communication, it keeps the main processor free to run your sketches. Plus, the Arduino team felt that this design keeps the Arduino more "hackable".

Wouldn't it be cheaper to make a board using just the one processor that has built-in USB? Yes! That is exactly what the Arduino Leonardo is. It uses the Atmega32U2, the big brother to the Atmega8U2.


However, the actual transmission of the message happens inside vw_Int_Handler(). But this function is never called in vw_send() or vw_tx_start(). So the only way this could be happening is if there was some sort of multi-threading correct? Because by setting vw_tx_enabled to true, the transmission process would begin inside vw_Int_Handler.

The vw_Int_Handler function is called from the interrupt handler of one of the timer modules in the chip. Yes, you could say it was some form of multi-threading in that it happens interleaved with the main processing of your sketch.

  Moreover, this library uses digitalWrite to transmit the bits. Wouldn't it just be faster to toggle the bits at the registry level?

Yes it would, but it would be less portable.  VirtualWire has been written to work on a wide range of chips, and doing low-level port access would make the code about 1000x more complex, having to include special code for each and every chip it runs on.  Easier (though less efficient) to just use digitalWrite().

  Lastly, in VirtualWire, they send a 36 bit preamble, I assume this is for synchorinzation purposes. So if I want to send 128 byte packet length, how much of a preamble should I use? I believe the reason for VirtualWire only transmitting 27 byte packet length is because the 36 bit preamble will only keep the data synchronized for that long. So is there a certain formula used to determine the preamble size?

VirtualWire uses a coding system called 4b/6b (actually a sub-set of 5b/6b coding). In that system it takes 6 symbols to transmit 4 bits. It is a way of encoding the clock into the signal in a reasonably efficient manner.

The encoding system means that there can never be 36 alternating 1/0 bits in a message. That unique stream is used as the synchronisation because it can't be confused with anything else.  From then on it's just data encoded as 4b/6b. The limit on how much data can be transmitted in one packet is a purely arbitrary value. Since this is a low-speed protocol to low-power devices it is expected that they will have limited RAM, and so limited space to receive data. So small packets are the default.

The numbers in use, incidentally, have been chosen because they fit into the 4b/6b coding scheme quite nicely.  For instance 36 symbols of preamble is equivalent to 24 bits of data. The packet size is 30 bytes, three bytes of which are used for control information (checksum, byte count, etc), leaving 27 bytes of actual payload.  30 bytes is 240 bits, which is, in 4b/6b, 360 symbols. 360 symbols could be packed cleanly into 45 bytes for simple transmission (pre-encoding from binary to 4b/6b before transmission).

Other values won't fit quite so neatly.


This may not be a direct answer to your question but... when I see so
much code repetition, I cannot help but suggest you try to avoid
repeating yourself. All your Step() functions do exactly the same
actions, only with different data. You can then factor the actions
into a single function, and provide it different data as parameters.
There are many ways to achieve this in C++. I am going to show four of
them, in order from the most basic to the most esoteric.

The simplest one is to use a plain function and give it the angles as
parameters. This is basically what Michel Keijzers’ answer suggests. My
take on it would be

void Step(uint8_t hip, uint8_t knee, uint8_t ankle)
{
    HipR.write(hip);
    HipL.write(hip);
    KneeR.write(knee);
    KneeL.write(knee);
    AnkleR.write(ankle);
    AnkleL.write(ankle);
}

which you can then use in the main loop as

Step( 80, 100,  20);  // right 1
Step( 90,  70,  20);  // left 1
...

The next step in code modularity would be to group all the angles for a
single step into a compound data structure called a struct, then the
function to perform a step takes a single parameter which is this data
structure:

struct Step {
    uint8_t hip;
    uint8_t knee;
    uint8_t ankle;
};

void doStep(Step s)
{
    HipR.write(s.hip);
    HipL.write(s.hip);
    KneeR.write(s.knee);
    KneeL.write(s.knee);
    AnkleR.write(s.ankle);
    AnkleL.write(s.ankle);
}

These structs would be defined as

Step RightStep1 = { 80, 100,  20};
Step LeftStep1  = { 90,  70,  20};
...

and used in loop() as

doStep(RightStep1);
doStep(LeftStep1);
...

One step further, you can embed the function within the data structure.
The embedded function then becomes a “method” of the data structure
which is now called an “object”:

struct Step {
    uint8_t hip;
    uint8_t knee;
    uint8_t ankle;
    void perform() {
        HipR.write(hip);
        HipL.write(hip);
        KneeR.write(knee);
        KneeL.write(knee);
        AnkleR.write(ankle);
        AnkleL.write(ankle);
    }
};

The structs can be defined just as before, and used as

RightStep1.perform();
LeftStep1.perform();
...

One last technique involves making the objects themselves behave as
functions that can be called. This kind of callable object is called a
“functor”, and is kind of syntactic sugar over a method call. We just
have to rename the relevant method as operator():

struct Step {
    uint8_t hip;
    uint8_t knee;
    uint8_t ankle;
    void operator()() {
        HipR.write(hip);
        HipL.write(hip);
        KneeR.write(knee);
        KneeL.write(knee);
        AnkleR.write(ankle);
        AnkleL.write(ankle);
    }
};

The structs are still defined in the same way, but now they can be used
as if they were plain functions:

RightStep1();
LeftStep1();
...

I suggest you use whatever technique you feel the most comfortable with.
There is a logic progression though: the more you improve your C++
skills the more comfortable you will be with the latest ones.


Cannot create a PWM with 20% duty cycle using micro() timer

You wrote:

if ((state == LOW)&&(current - previous >= TimeOff)){
    state = HIGH;
    digitalWrite(pin,state);
    previous = current;
  }
else{
  if (current - previous >= TimeOn){
    state = LOW;
    digitalWrite(pin,state);
    previous =current;
  }

While you probably mean:

if (state == LOW && current - previous >= TimeOff) {
    state = HIGH;
    digitalWrite(pin, state);
    previous = current;
}
else if (state == HIGH && current - previous >= TimeOn) {
    state = LOW;
    digitalWrite(pin, state);
    previous =current;
}


Wifi networking with ESP8266 (NODEMCU version)

Here you are the working code allowing you to choose SSID, password, network name and IP address of your ESP8266 acting as an access point. In addition, you can specify wifi channel to avoid interference with other devices. A password must be at least 8 characters long or it wouldn't work.

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

IPAddress ip(192,168,1,81);         // choose IP address
IPAddress subnet(255,255,255,0);

ESP8266WebServer server(80);

void handleRoot() {
  String page = "<!DOCTYPE html>\n";

  page += "\n\n
Some heading

Generated by ESP8266\n\n";
  server.send(200, "text/html", page);
}

// what to do when accessed through http://ip_address/something_undefined
void handleNotFound(){
  String message = "File not found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

void setup(void){
  Serial.begin(74880);                      // so you can see debug messages automatically sent by ESP8266
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(ip, ip, subnet);        // declared as: bool softAPConfig (IPAddress local_ip, IPAddress gateway, IPAddress subnet)
  WiFi.softAP("SOME_NAME", "password", 7);  // network name, network password, wifi channel

  IPAddress myIP = WiFi.softAPIP();
  Serial.println();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  server.on("/", handleRoot);               // what to do when accessed through browser using http://IP_address

  // what to do when accessed through http://ip_address/test
  server.on("/test", [](){
    server.send(200, "text/plain", "This is another page");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started...");
}

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

You can write something like:

server.on("/open_door", [](){
        // the code to switch on the relay to open the door
        // ... <-- put here the code
        server.send(200, "text/html", "Door: opened");
});

so you can open the door with http://ip_address/open_door.

You can try http://ip_address/something_undefined?a=24&b=25 to get an idea how to process the parameters.


Your IF statement is the problem. if (read_rfid == ok_rfid_1 || ok_rfid_2) always evaluates to True. Your condition should be:

if (read_rfid == ok_rfid_1 || read_rfid == ok_rfid_2)

You also need to remove the spaces in the string literals if you want this condition to have the desired effect.

This approach isn't very good though, since you have to add more comparisons to the IF condition if you want to match more cards. You should use the byte arrays as they are, without converting to Strings; it can actually be a lot simpler to compare as well as memory-safe. Store all your allowed card UIDs in a 2-D array:

#define ALLOWED 2   // no of allowed cards
byte read_card[4];   // same purpose as before
bool found = false;  // to know when a valid card match occurs
byte cards[ALLOWED][4] = {{0xC5, 0x12, 0xE3, 0x52},
                         {0x9A, 0x48, 0x3A, 0xD5}};

Then you should get rid of dump_byte_array() and compare cards like this:

memcpy(read_card, mfrc522.uid.uidByte, 4); // copy UID into array with shorter name ;)

for (int i = 0; i < ALLOWED; i++){
  if (memcmp(read_card, cards[i], 4) == 0){

      found = true;
      break;
  }
}

if (found){
  Serial.println("Open");
  unlock(); // turns LED on
  found = false;
}
else {
  Serial.println("Stay Closed");
}


Reading button presses with the 74HC4067E multiplexer

All your unused MUX input pins for the button MUX are floating. You will need to tie all of the unused inputs (those that do not have a physical button attached) to ground. Floating inputs are undefined and cause undefined output.

Also, when your attached button is not pressed, its input will also be floating. You can avoid this by connecting the input pin on the MUX to ground using a resistor. That way, when the button is not pressed the input will be low (through the resistor), and when the button is pressed it will be high (through the button connection).