Port Manipulation and serial communication

You can modify a single or multiple bits in a register by using a Read-Modify-Write approach. Essentially something like this:

byte temp = DDRD;
temp = (temp & ~(bitmask)) | bits_to_set;
DDRD = temp;

In the above code, bitmask is some value with the bit or bits you want to modify set - e.g. if you want to change bits 4 and 5, it would be (_BV(4) | _BV(5)) or just (0b00110000). bits_to_set is a value with all bits that you want to be one set - e.g. if you want bit 5 to be a 1, it would be (_BV(5)) or (0b00100000).

What the code does is to first get the current value of the register you want to manipulate. Then it will clear only the bits which you want to modify to 0 by using bitwise AND on the temp value. Next it will set only the bits you want to change to be set by using a bitwise OR. Finally it writes it back to the register.

If you are using interrupts which, you may wish to do this atomically (so that the register is not changed by an interrupt occurring before the new value is written back). You can do this by wrapping the above code in:

byte oldSREG = SREG;
cli();
...
SREG = oldSREG;

Which will clear the global interrupt flag to pause any interrupts, and then will restore the value of it afterwards.

If you just want to change a single bit in a register you can optimise this code down to one of the following examples:

DDRD |= _BV(4); //Set bit 4
DDRD &= ~_BV(5); //Clear bit 5

Again you may want to do this atomically as it may compile to a Read-Modify-Write access.


Confused as to how 2 of my interrupts are firing from just 1 pin input?

The interrupt on pin 2 triggers, because the pin is floating. Since nothing is connected to the pin, it reacts to whatever noise is flying by (for example from pin 3). That can lead to the pin changing its state together with pin 3, or to just erratically randomly changing state.

You need to connect a pullup or pulldown resistor (one rather big resistor going from the pin to either Vcc or ground), which sets the pins state, when it is not actively driven otherwise. If you need a pullup or pulldown depends on your wanted behavior.

If a pullup is ok for you, you can activate the Arduinos internal pullup resistor by using

pinMode(2, INPUT_PULLUP);


No Websockets Server for Arduino mkr1010?

Most websocket libraries work over a Client. Client is base class for all EthernetClient and WiFiClient classes.

But why do you want to use a Websocket for communication of two MCU in the same LAN? Websockets are intended for communication over HTTP infrastructure (firewalls, proxies) to a web server in Internet or from browser to a web server.

Use a basic TCP socket over Arduino Client.

WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.

If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read only from the WiFiClient object on the other side.

client socket

if (client.connect(serverIP, PORT)) {
  client.print("request\n");
  String response = client.readStringUntil('\n');
  Serial.println(response);
  client.stop();
}

server side

WiFiClient client = server.available();
if (client && client.connected()) {
  String request = client.readStringUntil('\n');
  Serial.println(request);
  client.print("response\n");
  client.stop();
}


WS2812 HELP. Need name of Unkown component

It's most likely a decoupling capacitor meant to smooth out the voltage supply to the internal control chip.

This is standard practice to add to any chip. Power cables create a small bit of parasitic inductance in relation to the area between the lines. This inductance can induce voltage spikes when current draw changes significantly. A capacitor shrinks the effective area between the power lines.

This is also why the general advice for decoupling capacitors is to put them as close to the chip as physically possible.


The analog input pins are 0V-5V strictly. If you need to measure a 9V input, you need to scale the voltage to test so that it is within a 0V-5V range. Often this is done with a voltage divider circuit.

In the example below, the 9V test voltage is divided in half, so the scale is 0V-4.5V, which is within range of the input pin.

Then your algorithm is

vol = sens * (2.0) * ( 5.0 / 1024.0);

simulate this circuit – Schematic created using CircuitLab


Serial monitor in Arduino IDE for RobotDyn ESP8266-Pro via CP2102

You applied connections like it was a plain esp8266. The board has the necessary pull-ups and pull-downs. Connect it at first only to GND, VCC, TX, RX. The button pulls gpio0 LOW to enter flashing mode at power up.


Arduino powered car not running when touching ground

It cannot draw enough current I suppose. When wheels are free-spinning, the load on motor is very small. When you put it on ground, the load increases, and it is slow because there is not enough current to drive the load


Arduino IDE is a tool used to write and upload code to the Arduino. Embedded C (or C++) is a language or a subset of the language. The Arduino IDE is provided with, and runs the GNU g++ - a C++ compiler - so that is the language you would need to write in. If you're asking for a comparison between C++ and the mythical "Arduino language", there is no Arduino language - it is C++. The Arduino IDE does manage a few details of the language for you to make it somewhat more beginner-friendly. The difference between the full-spec C++ language and C++ with a few shortcuts you can take with it in the Arduino IDE are what have given rise to to the myth of an Arduino language.

(Technically it is possible to program an Arduino in another languages by using an appropriate language compiler for your Arduino's AVR chip.)

Your profile suggests you're planning a career around software and the technologies it enables. In that case, it would be very worth your while to learn and write correct C++ and ignore the Arduino IDE's shortcuts, at least once you have a passing familiarity with the process. The Arduino IDE is well suited to learners but it has some real shortcomings that soon frustrate the serious student/programmer/engineer - meaning sooner or later you'll probably want to move on to a more professional level tool that won't hold your hand for you, but also won't hold you back so much. That transition will be easier if you know the full language requirements from the start, than if you have to re-learn some of them later.

Update:

  Can you tell me how I should get started with using c++ with the Avr
  chip,and what software I need.

The only software tool you'll need is the Arduino IDE. It comes complete with the compilers, loaders, basic libraries, and sample programs. Despite my discussion of its shortcoming, I still recommend it as the easiest entry point for getting started. An Arduino Uno board is the only other thing you'd need and you'd be ready to go.

If you want to work with the bare chips, you'll need to provide the basic support circuitry that provides power, clock-pulse generator and USB to serial conversion. (This latter part is easy - it's called an FTDI cable and has the converter built into it). There are lots of articles on the web about home-building Arduino-compatible boards. You can make one on a printed circuit board, Vero board, a breadboard with plug-wires (instructive, but not too reliable because of all the plug-wires). Or one Arduino with a replaceable chip can be a programming host for all of your other (same part#!) chips. But note those chips will still need the support circuits to be able to do anything more than look pretty on your bench.


Combing two codes to make it work on the same time but not affecting the other code?

Combing two codes to make it work on the same time but not effecting the other code?

the simplest would be to have two arduino and run each piece on one of them.


The following 555 circuit will produce a 170 ms low-going pulse every 24.2 hours.  You can adjust the values of the components using this calculator if you want different timing parameters.

Since the reset line of a microcontroller is configured for open-drain (meaning you can connect several inputs to it, which is a good thing since we are taking advantage of that), we need to drive it with a open-drain output.  That is what the buffer on the bottom of the circuit is for, to convert the push-pull output of the 555 to open-drain.  A typical buffer is one section of a 7407.


What's the difference between ICSP vs ISP?

The difference between ISP and ICSP is a hyphen.

ISP stands for In-circuit Serial Programming, and ICSP stands for In Circuit Serial Programming.

Any arrangement that allows you to program a microcontroller while it is in a circuit using a serial protocol can be called ISP or ICSP.


Do I need an Microchip ATSAM3X8E Evaluation Kit?

I understand some of the Fast Speed Serial options in the Microchip IC cannot be tried in the Arduino Due (such as USBOTG?)?. What I actually need is some Serial Speed close to 2Mbps and a USB Programming Port.

What would make you think that? The chip is the chip regardless of what board it's soldered to. You have the native USB and you have all the UART connections direct to the chip. The board has no effect on that at all.  2Mbps is nothing. You can go much faster than that.

Which are the main differences between the Microchip ATSAM3X8E and the Atmel ATSAM3X8E?

The label. When Microchip bought Atmel a few years back they bought everything. That includes the Malaysian factories where the Atmel chips are made (a friend of mine had the job of inventory combining and spent quite some time in Malaysia sorting it all out). Microchip ATSAM3X8E chips are made in the same factory by the same people to the same designs on the same machines. It's just they are now labelled "Microchip" instead of "Atmel".

I notice there are some functionalities in the Microchip ATSAM3X8E or even in the Atmel ATSAM3X8E not able to be reproduced in the Arduino Due Board?

Is that a question or a statement. Or aren't you sure? The Due is just a chip on a board with some support circuitry. Everything that is in the chip is there, you can't remove it. There may be the case that a specific pin may not be brought out to a header, but you will have to compare the datasheet with the schematic in that case. The chip is not at fault here.

Do The Microchip ATSAM3X8E IC have its own functionalities not present in the Atmel ATSAM3X8E?

No. The two are 100% identical.

As note, there is a Keil ARM SAM3X-EK Evaluation Kit (also also here with its brochure), with a ATSAM3X8H, which is not the same IC series, but somehow exposes my concern (if real).

The ATSAMA3X8H is not commercially available. It was a specific custom chip made only for the SAM3X-EK kit. It is, essentially, a SAM3X8E with more IO pins and the ability to connect to SDRAM.

If my concern about High Speed Serial is real, how should I evaluate it?

Your concern is not real. Only imagined. The only possibility is that the UART to USB chip used on the Due may not be able to keep up at high baud rates. That has nothing to do with what the SAM3X8E can do, just what the interface to your PC is capable of. You can replace that with an external USB to UART interface if you want, such as an FT232R based interface. That is if it's communication with your PC that you're concerned about, in which case you would be better with the native USB interface as it's not restricted by whatever external hardware is added.


Caveat Emptor.

If it's not genuine you can never be sure quite what you are getting. You have to ask with some of then just how they can make them so cheap. Poor quality components is one way. Either counterfeit or reject components which may fail after a short time, or under certain conditions is a big risk.

There are different grades of board each with their own risks...

Genuine. High price, good reliability and quality. Good after sales support. Supports the Arduino cause.
Arduino clone. Genuine Arduino design made by a reputable third party. Almost as good as option 1 but doesn't support Arduino financially.
Arduino Based. A board created for a specific job that is based around genuine Arduino design. Support really only from the (often smaller) manufacturer. Quality varies.
Chinese clone. Low grade components made to original Arduino designs. Little or no support. Poor quality. Often with different USB interface that is unstable and low quality.
Counterfeit. Low quality components. Claims to be a genuine Arduino. Bad build quality.

Options 1-3 are ones I would consider buying. 4 and 5 I would stay well away from.


ESP8266 stops responding when isolated relay is connected to AC tubelight

I suspect that you've connected the relay wrong. I think that the LNP of the relay is supposed to be connected to D8 and the v+ to 5/3.3V and GND to GND....


How can I record a push button sequence and store it in an array

You can create an array like this, make it global to easy access it:

int states[10];

And the current index:

int index_state = 0;

And initialize the array (in setup):

for (int n = 0; n < 10; n++)
{
    states[n] = 0; // Unpressed
}

When a new button press should be stored:

states[index_state] = state;

And add one to the index state, if 10 is reached, start over (this means the last 10 are stored).

index_state = (index_state + 1) % 10;

And to check the states you just iterate from index_state.

Hope this helps you get going.

Note this is called a ring buffer.


How to reduce current from a AC TO DC power supply for arduino use

You don't need to reduce the current.

2000MA (2 amps) means the power supply is CAPABLE of supplying this (without overheating). Anything less than this, and your device will work perfectly.

Your Arduino will DRAW a certain number of milliamps (amps), this is the amount of current that will ACTUALLY run through your circuit.


How can I program a ATmega328 au tqfp32 ( SMD ) chip?

To upload compiled code (.hex) to a bare atmega which doesn't have a bootloader installed you can use ISP. As this stands for in-system-programming you don't have to flash the chip before assembly, but you can flash it in-system, so when already soldered onto your pcb. There actually is no need for those adapters like shown in your first picture, which often are a bit expensive. Also, both pictures stand in contrast to the idea of ISP, they seem to show firmware upload via serial connection, which as far as I know only works with a bootloader already installed...
ISP is based on SPI (serial peripheral interface) and you need to break out the corresponding pins to fit this connector. This obviously has the advantage of being able to update a firmware afterwards without the need of a bootloader.

Atmel provides a tool for flashing firmware via ISP which is called avrdude (tutorial) or you can use the atmel studio. To compile your code, you can use avr-gcc.


compiler says I have to declare my hexidacimal I try to compare

Nothing here that hasn't been covered in comments already but just putting it in the form of an answer to save digging...

How is the compiler supposed to know that a number is hex rather than decimal?

Sure 1234beef is obviously hex but what about 12345678? Is that hex or decimal?

You need some method for the compiler to know.

You also need some way for the compiler to know if something is a number or a variable. Take the code if (x == deadbeef) {...} is deadbeef a hex number or a variable name?

C uses a very simple convention. If it starts with a number it's a number, if it starts with a letter it's a variable. This is why variable names can contain numbers but can't start with them.

If an integer starts with an 0 e.g. 0123 then it's in octal.
If an integer starts with 0x e.g. 0x123 then it's in hex.
If an integer starts with something other than a 0 e.g. 123 then its in decimal.

e.g.

printf("123 = %d\r\n0x123 = %d\r\n0123 = %d\r\n", 123 , 0x123 , 0123);

returns

123 = 123
0x123 = 291
0123 = 83

This convention, especially the 0x prefix for hexadecimal, is very widely used in other programming languages.


What is the smallest duration that can be measured using micros()?

What is the least value of time that I could measure(count) using micro() in Arduino board?

The answer is 64 clock cycles or 4 us @ 16 MHz. Please see the Arduino AVR core[1] for more details.

Cheers!

Ref. [1] https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c#L25


Coding or Wiring? Dual Piezo sensor not triggering LED lights

Well, you never call blink, so leds never get a chance to light up.

Also, you are turning down the led at the begining of each loop. That will cause flickring.

And you don't need so many parameters for blink. In fact, what you need is a little function for blinking just one led.

I think this sketch is what your are looking for (but I can't assure it's correct)

/*
  Dual Piezo Bond Auger Sensor; Blinking LED Light Stack Sketch

  -----------------------------------------------------*/

//Piezo 1 Pin (PiezoPin1)
//Piezo 1 connected to A0
int PP1 = 0;
//Piezo 1 Pin (PiezoPin1)
//Piezo 2 connected to A1
int PP2 = 1;

//Sets the threshold for the detected sound to trigger the LED
const int threshold=0.01;

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

    for(int i = 4; i<12; i++) {
        pinMode(i, OUTPUT);
        //sets the led pins 2-11 to output
    }
}

void loop()
{
    /* Read the Piezos
      Reads both piezos and outputs the values. Triggers LED lights
      to fire when a peak voltage is exceeded
      Adjust the value based on the peak signal voltage you
      want to trigger the LED lights*/
    int Piezo1ADC = analogRead(PP1); // Read Piezo 1 ADC value
    float Piezo1V = Piezo1ADC / 1023.0 * 5.0; // Convert to voltage
    int Piezo2ADC = analogRead(PP2); // Read Piezo 2 ADC value
    float Piezo2V = Piezo2ADC / 1023.0 * 5.0; // Convert to voltage
    Serial.println(Piezo1V); //Print the voltage from Piezo 1
    Serial.println(Piezo2V); //Print the voltage from Piezo 2

    if(Piezo1V >= threshold||Piezo2V >= threshold)  //toggle status of LED pins linked to PP1
        // Blink the LEDs on for both Piezos
    {
        {
            littleBlink(2);
            littleBlink(3);
            littleBlink(4);
            littleBlink(5);
            littleBlink(6);
            littleBlink(7);
            littleBlink(8);
            littleBlink(9);
            littleBlink(10);
            littleBlink(11);
        }
    }
}

void littleBlink(int pin)
{
    digitalWrite(pin, HIGH);
    delay(10);
    digitalWrite(pin, LOW);
    delay(10);

}


How to use 2 serial port when WifiEsp library uses one of both

The esp8266 AT firmware doesn't wait until you listen on the SoftwareSerial instance. If there is a connection to the server it sends +IPD and data. If the SoftwareSerial instance doesn't listen the information about client connection is lost.

You must listen to esp8266 all the time, so you can't use two SoftwareSerial instances.

You could use the RX pin of Uno to received data over hardware Serial, if you only receive on DataPort and only print to SerialMonitor.


The Arduino assumes a US keyboard layout.  The thing with keyboards is they don't actually send the letters or symbols that are printed on the keys.  Instead the send a scan code that defines where on the keyboard the key is.  It is then up to the computer to convert those scan codes into actual letters and symbols, and that is performed by the keyboard mapping selected in the operating system.

Some special keys are known as dead keys.  These don't actually print a character on their own - instead they are used to modify the next key pressed - for instance the key which occupies the space a " would be on a US keyboard, on a Spanish keyboard, is a dead key which modifies the next key by adding an umlaut to it.

Since the Arduino doesn't know that you have a Spanish mapping, when you send a " it just sends what it believes is the location of that character on a keyboard, and of course it gets that wrong since it assumes the wrong keyboard layout.

So there are two things you can do to "fix" it:

Change your keyboard layout to US, but that will mean your normal keyboard will stop working properly.
Change how the Arduino thinks the keyboard is laid out, but that means lots of work to find the right scan codes.

The Arduino's keyboard layout is stored in the file HID.cpp in the Arduino core (hardware\avr\cores\arduino or somewhere like that - I forget off hand) and is the _asciimap array.  It is a list of the first 128 ASCII characters and the keyboard scancode mappings for them, including modifier keys like Shift.  You will have to find the scan codes for the keys you want to map on your keyboard layout and change the codes in that list.  For instance, the character " is listed as:

0x34|SHIFT,    // "

Which is scan code 0x34 (52 decimal) coupled with the SHIFT modifier.  You will have to discover (maybe Google can help) what the 0x34 should be changed to so that it moves the " to wherever it is on a Spanish keyboard.


Communicate with custom usb slave device with DUE?

i found what i needed here: http://arduino.cc/en/Reference/USBHost
and
https://github.com/felis/USB_Host_Shield_2.0


nodeMCU - 2 loops at a time - one continuously and second every 10 seconds

Rather than using delay, use millis() and a variable to check if the some time has expired

void loop()
{
    static int check = 0;
    int now = millis();
    if (now >= check) {
        if (digitalRead(pinD1)==1){
            digitalWrite(pinD0, HIGH);
            check = now + 20000;
        } else {
            digitalWrite(pinD0, LOW);
            check = now;
        }
    }
    loop2();
}

void loop2()
{
    static int check = 0;
    int now = millis();
    if (now >= check) {
        if (json1=="ON"){
            digitalWrite(pinD0, HIGH);
        } else {
            digitalWrite(pinD0, LOW);
        }
        check = now + 20000;
    }
}


Is there a transmission protocol library for SPI?

Each spi peripheral has its own protocol in the sense of commands and addresses if any and data.  Spi simply makes a common ground for chip select vs clocks and clocks vs data and separate miso and mosi data lines.

So a general purpose library doesnt make sense.

Also spi certainly is not limited to a byte, many peripherals and many spi controllers allow for long sequences of data, you are also not strictly limited to multiples of 8 bits either although that is the norm.

Your arduino spi master may have its limitations but that has nothing to do with spi in general.

Integrity testing is not part of the spi protocol, you get what you get.  Ideally all of the parts are soldered down on the same board or through known connectors and the margins have been designed in.  You would need to do something outside the spi protocol, for example if it is a spi flash then after you read a chunk of data you can do a checksum and compare it with a checksum you have embedded in the data (or crc).  If it is a spi ethernet part you may choose to leave the frame checksums in the frames and re-validate each frame yourself.  If you create your own peripheral (hardware design or cpld or fpga) then certainly you can add a crc or checksum to every transfer if you wish.


How to exit out of a timer interrupt (ISR(TIMER1_COMPA_vect))

As some of the comments have suggested, I would either get rid of the ISR or reduce the size significantly. When using ISRs, it is recommended that you keep the code as small as possible. Use it to set variables, for example
//these two variables are global
ISR(TIMER1_COMPA_vect){
    someValue = true;
    numberOfValues++;
}

you should also never use any Serial functions inside an ISR as these use interrupts themselves which can cause all kinds of problems
After using the ISR to update global variables, you can then use if() or while() statements within the loop() function to execute your serial print functions and such
P.S. on a side note, I would recommend changing your code where you calculated mean from
    mean = (add[1]+add[2]+add[3]+add[4]+add[5]+add[6]+add[7]+add[8]+add[9]+add[10]+
add[11]+add[12]+add[13]+add[14]+add[15]+add[16]+add[17]+add[18]+add[19]+add[20])/20;

to
for(uint8_t i = 1;i<=20;i++){
    mean += add[i];
}
mean /= 20;


Converting TinkerKit to native Arduino pins

The TinkerKit Sensor Shield helps understand the mapping. There is also the TinkerKit Header File with symbol mapping.


what the benefit uploading hex file merely to arduino board?

If you want to upload the same sketch to many  Arduinos compiling it again and again would take much longer. Or if you create a firmware ànd don't want to disclose the source code, you can distribute it in compiled form.


Is there a difference between uint8_t and byte data types?

There is no difference in the datatype. byte is defined in Arduino.h:

typedef uint8_t byte;

So, uint8_t and byte are exactly the same. The uintX_t types and their siblings are specifically meant for having the same size on every platform (in difference to for example double which is only 16 bits on Arduino Uno, but can be 32 bits on bigger chips). But byte will also be 8 bits on every platform, so there is really no difference.

  Am I getting the syntax wrong? I get an error - convertion from 'uint8_t' to non scalar type 'CHSV' requasted. I thought the library does that on its own, do I need to add more code? If yes, what code?

You get the error, because you use the wrong syntax here. A CHSV color is not just 3 byte values, it is a class with member variables and methods. So you cannot simply assign 3 byte values directly to the object. You need to actually create the object, using the values as parameters for the constructor:

CHSV led = CHSV( hue, sat, val);

This creates a CHSV object, executes it's constructor, which uses the values from the parameters to set the internal values. That is the context, how this is used in the FastLED library. You can also find such lines in the examples of the library (I found such use in line 15 of the example ColorPalette, but there might be more). Also this is the same principle, as with the other color classes, like CRGB.


Is there any way to connect my old phone camera with an arduino?

Yes, but it may be a huge amount of work requiring expensive equipment and skills that take decades to acquire.

See Mike's Electric - Interfacing a cheap phone camera module to a PIC32 microcontroller. which is a great video and will give you an idea of what is involved. Note that he's using a 32-bit microcontroller with relatively large RAM on the chip. You might need to use a 32-bit Arduino (Due etc) not one of the 8-bit Arduinos (Uno etc).

Mike is the kind of person who could reverse-engineer a random camera module from an old phone but this isn't a project for a typical Arduino user like you or I.

Since these camera modules cost about $1, it is probably best to look for a camera breakout for Arduino that comes with documentation and software libraries.


Since addr_t is a character type, I suspect Serial.print() is trying to output the ASCII character representation of your two values. ASCII codes 0x10 and 0x02 are non-printing characters, so it might just be outputting 0's for lack of anything better to do.

To output the data as actual numbers, try casting them to integers:

Serial.print( static_cast<unsigned int>(childAddr[0]) );
Serial.print( static_cast<unsigned int>(childAddr[1]) );


Arduino Analog Input: why the weird fluctuation?

You need to connect together the grounds from your external power supply and the Arduino.

At the moment the two devices are floating - there's no commonly-agreed 0v point.


I'd like to output something simple like a digital AC voltage to the DAC and have it convert it, but as I understand it from here, I am just using the digitalWritecommand which is basically binary. How do transfer something more complicated to have the DAC convert it?

SPI is a communication protocol.  It uses digital signals, coupled with time, to transfer information.

To use DSPI you need to first define an SPI object

DSPI0 SPI;

From then on it's the same as using the Arduino SPI library.

Start it

SPI.begin();

Then transfer the correct commands (found in the DAC datasheet) to set the voltage of the output

digitalWrite(10, LOW);
SPI.transfer(0x43);
SPI.transfer(0x1A);
digitalWrite(10, HIGH);

The values there are just examples. The 10 is the chip select pin for the DAC, and the values used in the transfers (however many are needed) need to be found in the datasheet.

If you only want to use the pins associated with DSPI0 you can use the SPI library instead (which only supports one SPI channel - the uC32 has two), in which case it is identical to working with the Arduino SPI library.

  Likewise, how do I get the DAC to do the reverse, ADC, where it reads in a voltage and sends the Arduino a digital signal through SPI pins?

You don't. DACs are DACs and ADCs are ADCs. They aren't interchangeable.

For ADC functionality just use any of pins A0 through A11 and the analogRead() function.


Arduino IDE on Linux - directory not found

You need to extract the archive file first.

$ cd ~/Downloads
$ tar -Jxvf arduino-1.8.0-linux64.tar.xz


Problem with Arduuino to breadboard Mega8

I found here: https://www.arduino.cc/en/Hacking/Bootloader?from=Tutorial.Bootloader

that NG / mega8 bootloader doesn't enable the rx pin internal pullup nor it gets out of the bootloader even if receiving junk data on rx  (which was my case due to leaving it open thus floating). It also has a delay of 6 to 8 seconds intentionally.

Probably I'll use another bootloader since the link to source code on the page was broken or just program the L version without any bootloader and better fuse options.


Detect how long a push button is being pressed?

This needs a combination of patterns.

First, the button pin needs to be debounced. This can be done with the "blink-without-delay"-pattern where the button pin is sampled with a low period (40 ms in the example code below).

Second, a simple state-machine is needed to keep track of the button state but also if the return button action function, doReturnButton(), has already been called.

The button is assumed to be connected from GND to pin4. The button action function, doButton(), is called when the button is pushed (goes LOW).

const int buttonPin = 4;
const unsigned long debounceInterval = 40;
const unsigned long returnInverval = 400;
bool buttonState = true;
bool returnButtonState = false;
unsigned long buttonDownMillis = 0L;

void doButton()
{
  Serial.print(buttonDownMillis);
  Serial.println(F(":doButton"));
}

void doReturnButton()
{
  Serial.print(buttonDownMillis);
  Serial.println(F(":doReturnButton"));
}

void setup()
{
  Serial.begin(57600);
  while (!Serial);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
  unsigned long currentMillis = millis();
  static unsigned long previousMillis = 0L;

  // Check if it is time to sample the button pin
  if (currentMillis - previousMillis >= debounceInterval) {
    previousMillis = currentMillis;

    // Did the button change
    if (digitalRead(buttonPin) != buttonState) {
      buttonState = !buttonState;

      // Was the button released
      if (buttonState) {
        returnButtonState = false;
      }

      // Was the button pushed
      else {
        buttonDownMillis = currentMillis;
        returnButtonState = true;
        doButton();
      }
    }

    // Check if button was pushed and time for return action
    else if (returnButtonState) {
      if (currentMillis - buttonDownMillis >= returnInverval) {
        returnButtonState = false;
        doReturnButton();
      }
    }
  }
}

What does the code do?

It samples the button pin with a debounce interval.
If the button state changes:
a. High to Low it calls the doButton() function and captures a timestamp. It also allows detect of return time interval.
b. Low to High. Return time interval is not allowed any more.
It checks if the return time interval has elapsed and if so calls the doReturnButton() function. The detect is then not allowed any more.

The doButton() function is called when the button is pushed (transition high to low), only once. The doReturnButton() function is called if the return time limit exceeds and the button is still low. Both are only called once per push (transition high to low).

To avoid the multiple transitions that occur when a button is pushed a debounce time period is used. The can also be done in hardware with a RC-circuit.

With some abstraction it could be rewritten as:

#include <Timemark.h>

Timemark debounce(40);
Timemark buttonHold(400);

const int buttonPin = 4;
bool buttonState;

void doButton()
{
  Serial.println(F("doButton"));
}

void doReturnButton()
{
  Serial.println(F("doReturnButton"));
}

void setup()
{
  Serial.begin(9600);
  while (!Serial);
  Serial.println(F("started"));
  pinMode(buttonPin, INPUT_PULLUP);
  buttonState = digitalRead(buttonPin);
  debounce.start();
}

void loop()
{
  if (debounce.expired()) {
    bool currentState = digitalRead(buttonPin);
    if (currentState != buttonState) {
      buttonState = currentState;
      if (buttonState) {
        if (buttonHold.expired())
          doReturnButton();
        else
          doButton();
        buttonHold.stop();
      }
      else {
        buttonHold.start();
      }
    }
  }
}

This also demonstrates the callback on the release of the button. The Timemark class hides all the time intervals, expire calculations, etc.

Cheers!


Constant ADC sampling rate on ESP8266 or ESP32

You have several options for controlling the sampling rate.

Software only

This is the simplest, and the previous answer got it almost right. Here
is my take:

const SAMPLE_INTERVAL = 500;  // 500 microseconds

void loop() {
    static unsigned long last_sample_time;
    if (micros() - last_sample_time >= SAMPLE_INTERVAL) {  // note 1
         last_sample_time += SAMPLE_INTERVAL;  // note 2
         // Take your sample here.
    }
}

Note 1: On the AVR-based boards, millis() is not accurate to the
millisecond. It tends to get late, then compensate for this by jumping
by two milliseconds at once. For controlling a process that should
happen every 1 ms exactly, millis() is very clearly not
suitable. I do not know how good is the ESP8266's millis(). It may
well be better than the AVR version. However, even a perfect millis()
will not be good for anything faster than 1 kHz.

The solution to this problem is pretty trivial: just count the time in
microseconds instead of milliseconds. The only drawback of using
micros() is that you cannot measure durations longer than about
71.6 minutes, which in turn means you cannot use it for sampling at
any rate slower than 233 µHz. Obviously this is not something you
should be concerned about. Note that the micros() rollover is not an
issue as long as you are sampling faster than the rollover period.

Note 2: It is impossible to have a steady sampling rate if it is
controlled by software. The best you can hope for is a tight control on
the average sampling period. This is accomplished by updating
last_sample_time as

last_sample_time += SAMPLE_INTERVAL;

Note that this variable holds the time when the last sample was supposed
to be taken, not the time it was actually taken. The sample was probably
taken a little bit behind schedule, as anything the CPU does takes time.
Updating last_sample_time this way means that these timing errors are
not cumulative. They would be cumulative if you did it in the “Blink
without delay” style, namely

previousMillis = currentMillis;

The drawback of this software method is that it inherently has a
significant amount of jitter. The program tests the current time only
once per loop iteration, and it may have other things to do within that
loop that adds to its execution time.

Software triggered by interrupts

I have never programmer an ESP timer but, if you can, it should provide
you better timings than the software-only version. Have the timer
deliver an interrupt at the desired sampling period, and use the ISR for
triggering the ADC. You may wait for the result inside the ISR, store it
in RAM, and set a flag to tell the main loop that a new sample is
available, as in

volatile int analog_sample;
volatile bool analog_sample_valid;

ISR(whatever_timer_interrupt)
{
    analog_sample = analogRead(ANALOG_PIN);
    analog_sample_valid = true;
}

void loop()
{
    if (analog_sample_valid) {
        int analog_sample_copy = analog_sample;  // note 1
        analog_sample_valid = false;
        // handle analog_sample_copy here
    }
}

Note 1: On an 8 bit Arduino, you would have to do this with
interrupts disabled. You shouldn't need to disable interrupts on a
32 bit platform.

This method should significantly reduce the jitter compared to the
software-only version. Now the sampling doesn't have to wait for the
program to run through the loop and reach the point when the time is
tested. Instead, whatever the program is doing, it will be immediately
interrupted for doing the sampling. Well... almost. From time to time it
will happen that the interrupt fires when the program is running with
interrupts disabled. This may be the case if it is already servicing
another interrupt. When this happens, the sampling will have to wait
until interrupts are enabled again. You end up with a jitter that is
most of the time a small fraction of a microsecond, and then
occasionally a sample is late by several microseconds.

Hardware only

On an AVR, you can configure the ADC to be automatically triggered by a
timer, or even to automatically trigger itself in the so called “free
running mode”. I do not know the specifics of the ADC in the ESP8266.
You may want to read the datasheet and see if it offer similar
functionality. If you can enable ADC auto-triggering, then you will have
cycle-accurate timings. The steadiness of your sampling will be just
as good as the quartz crystal clocking your MCU. No software solution
can ever come close to this level of perfection. The only drawback of
this method is that you will have to study the datasheet of your ESP in
order to implement it.


Unable to type in Arduino IDE running on OS X

Make sure that in preferences the option Use external editor is not checked.


What is the right way to query an I2C device from an interrupt service routine?

Just because a pin is called "interrupt" doesn't mean that you have to read it using an interrupt input.  The INTx pins of the ADXL345 are simple "level" outputs.  All the time there is an "interrupt" pending (a signal from the ADXL345 that something has happened) the corresponding INT pin is held LOW.  It remains LOW until the interrupt has been handled by your code.

It's not something that is very brief - it's something that persists as long as you need it to.

You can just read the INTx pins with normal digitalRead() from within your loop() function (polling). Unless you really need to respond right now to an event on the ADXL345 there is no need to use an interrupt input.


Do AVR delay functions (_delay_us() and _delay_ms()) use timers?

No, these macros expand to calls to __builtin_avr_delay_cycles(),
which are compiled into delay loops. It should be noted that:

the arguments to these macros should be compile-time constants, they
can be floating point
the macros are cycle-accurate, e.g. _delay_us(0.125) will take
exactly two CPU cycles on an Uno
whereas the CPU time used by the call is exactly what you ask for,
the physical time will be larger if the call gets interrupted.


I applaud you for your tenacity with the "debouncing" idea, but there is an excellent library for this rotary encoder, and the author has also written an article about it: Ben Buxton - rotary encoders done properly. Here is a link to his library: GitHub - buxtronix.

I’ve used an older version of the library before with interrupts, and it worked perfectly for my application. I see the author has updated the library and has 2 example sketches; one uses interrupts, and the other uses polling. I tried both of them today on an Uno and I was very impressed with the polling sketch’s performance. It seemed to equal that of the interrupt method.

If you take the important bits out of the library files, then add them to a sketch, you can see how little code it takes for this "method" of processing the encoder’s output. Here is a test sketch with the library bits in it.

#define R_START 0x0
#define R_CW_FINAL 0x1
#define R_CW_BEGIN 0x2
#define R_CW_NEXT 0x3
#define R_CCW_BEGIN 0x4
#define R_CCW_FINAL 0x5
#define R_CCW_NEXT 0x6
#define DIR_NONE 0x0
#define DIR_CW 0x10
#define DIR_CCW 0x20

const byte pin1 = 5;  // DT
const byte pin2 = 6;  // CLK
int state = R_START;
int counter = 0;

const unsigned char ttable[7][4] = {
  // R_START
  {R_START,    R_CW_BEGIN,  R_CCW_BEGIN, R_START},
  // R_CW_FINAL
  {R_CW_NEXT,  R_START,     R_CW_FINAL,  R_START | DIR_CW},
  // R_CW_BEGIN
  {R_CW_NEXT,  R_CW_BEGIN,  R_START,     R_START},
  // R_CW_NEXT
  {R_CW_NEXT,  R_CW_BEGIN,  R_CW_FINAL,  R_START},
  // R_CCW_BEGIN
  {R_CCW_NEXT, R_START,     R_CCW_BEGIN, R_START},
  // R_CCW_FINAL
  {R_CCW_NEXT, R_CCW_FINAL, R_START,     R_START | DIR_CCW},
  // R_CCW_NEXT
  {R_CCW_NEXT, R_CCW_FINAL, R_CCW_BEGIN, R_START},
};

unsigned char process(){

  // Grab state of input pins.
  unsigned char pinstate = (digitalRead(pin2) << 1) | digitalRead(pin1);

  // Determine new state from the pins and state table.
  state = ttable[state & 0xf][pinstate];

  // Return emit bits, ie the generated event.
  return state & 0x30;
}

void setup(){
  pinMode(pin1, INPUT_PULLUP);
  pinMode(pin2, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop(){
  unsigned char result = process();
  if(result == DIR_CW){
    counter++;
    Serial.println(counter);
  }
  else if(result == DIR_CCW){
    counter--;
    Serial.println(counter);
  }
}

Heres a simplified sketch (It works the same but I didn't like the hex numbers and I don't use define):

const byte pin1 = 5;  // Connected to DT on KY-040
const byte pin2 = 6;  // Connected to CLK on KY-040
int state = 0;
int counter = 0;

const unsigned char ttable[7][4] = {
  {0, 2, 4, 0},
  {3, 0, 1, 0 | 16},
  {3, 2, 0, 0},
  {3, 2, 1, 0},
  {6, 0, 4, 0},
  {6, 5, 0, 0 | 32},
  {6, 5, 4, 0},
};

void setup(){
  pinMode(pin1, INPUT_PULLUP);
  pinMode(pin2, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop(){

  unsigned char result = process();

  // Clockwise rotation.
  if(result == 16){
    counter++;
    Serial.println(counter);
  }

  // Counter clockwise rotation.
  else if(result == 32){
    counter--;
    Serial.println(counter);
  }

}

unsigned char process(){

  // Grab state of input pins.
  unsigned char pinstate = (digitalRead(pin2) << 1) | digitalRead(pin1);

  // Determine new state from the pins and state table.
  state = ttable[state & 0xf][pinstate];

  // Return emit bits, ie the generated event.
  return state & 48;
}


So the problem was that I did not read this comment carefully

/** SPI slave select pin. Warning: SS may be redefined as another pin
but the hardware SS_PIN must be set to output mode before any calls to
WaveHC functions. The SS_PIN can then be used as a general output pin */

"SS_PIN must be set to output mode before any calls to
WaveHC functions"

I read this and thought that meant whatever pin was being used as the SS pin needed to be an output, but it meant literally that pin 10 (the hardware SS pin) had to be set as an output regardless of whether it was being used or not.

So the solution is to add

pinMode(10, OUTPUT);

to anywhere in the code

Edit : also thanks @per1234 for pointing out the correct answer, I just didn't read your comment properly.


Arduino Serial Port. COM1 does not exist

Never used Visual Basic but:

There is no such thing as Serial1 on Arduino Uno. There is only Serial. (Serial1, 2, 3 are available on ArduinoMega) Reference: Arduino
For COM port you should check your device manager. Often it appears at COM3 so probably you should check this issue.

Just for curiosity: Why VB? Is it only your choice or it use less ram or memory, works faster or anything?


The Arduino IDE means well, really it does. It copies your source, the device core, and any libraries used by your source all to a separate directory so that it doesn't poison any of their original locations unintentionally.

But of course, there's something missing from that list. The IDE doesn't copy libraries used by other libraries. Therefore if you don't include Wire.h in your .ino file then Wire will be missing from the build and you get the error observed. Cracktastic.


3.3 V Pro Micro clones flashing LEDs after 1200 bit/s touch

I was finally able to solve this by using one of the Pro Micros to re-burn the bootloader of the other one.

For reference, the process is like this:

Flash the example sketch "ArduinoISP" into the first Pro Micro
Connect the two Pro Micros like this:

Programmer (on USB)   Target
GND ----------------- GND
VCC ----------------- VCC
15 ------------------ 15
14 ------------------ 14
16 ------------------ 16
10 ------------------ RST

Choose "Arduino as ISP" as Programmer
Because both are Pro Micros, selecting a different board is not necessary.
Click "Burn Bootloader"


I would suggest to connect one pin of the with to 5v and the other to ground. The Arduino will be able to detect 5v as logic HIGH.

The code looks correct except for better programming technique I would suggest to indent you code, this make debugging easier for longer programs:

#include "DigiKeyboard.h"

void setup() {

   pinMode(0, INPUT);

}

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

  if(digitalRead(0)==HIGH){

    DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT,KEY_R);
    DigiKeyboard.print("test");

  }
}


Arduino and ESP8266 Two-way Communication

See How can I verify that my ESP8266 is working? asked 2 hours before.

use something like https://www.sparkfun.com/products/12009 or https://learn.adafruit.com/arduino-tips-tricks-and-techniques/3-3v-conversion

Usual way is let the Arduino direct the ESP, but if you are able to program ESP too, then any communication can work the same way as between twou ESPs or two Arduinos (with the level shift in mind)


Are these components connected correctly?

in short: Definitely Not.

1 : you do really need to connect the trigger pins of the ultrassonic sensors, or else you will not be able to "trigger" them.
Read the ultrassound library examples, they may help you.

2 : I am pretty sure an analog (or digital for that matter) pin in arduino nano cannot sink the current needed to make the motor spin. You are going to fry that pin/port or even brick the entire arduino.
Read on power mosfets for the solution of that.

Moreover, i don't think the 5v out of the arduino feeding the motor is a good idea as well, as the current given by its internal regulator may not be enough for the motor as well.


Use Delay(  ).
Or this code

long previousMillis;

void setup(){
  previousMillis = millis();//in void setup
  bool lS=LOW;//in void setup
}

void loop(){
  long currentMillis= millis();//in void loop

  if(currentMillis-previousMillis>=20000){
     if (lS==LOW){
       digitalWrite(pinNo,HIGH);
       lS=HIGH;
     }
     else
     {
       digitalWrite(pinNo,LOW);
       lS=LOW;
     }
     previousMillis= millis();
  }
  delay(1);
}

While this does not serve your purpose, it shows you an how to switch on and off and LED after every 20 sec without keeping the Arduino idle for 20 sec.You could improve on it and make your own code.


Need help with the basics on serial control

You are assuming that Serial.readString() will magically know how long a string you meant to send, and wait until it's all there.  It doesn't guarantee that.

If your PC uses Linux or Mac, you can use Serial.readStringUntil('\n'), which will read until a line end, and send on<ENTER> as your command.

If you use Windows, the line endings are \r\n so it's a bit more awkward.  Build up your string piece by piece, perhaps

int relay=8;
String serialInput;

void setup() {
  Serial.begin(9600);
  pinMode(relay, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    char c = Serial.read();   // get one byte from serial buffer
    if ('\r'==c || '\n'==c) {
      // End of line - process the string
      if(serialInput=="on") {
        digitalWrite(relay, HIGH);
      } else if (serialInput=="off") {
        digitalWrite(relay, LOW);
      }
      serialInput = "";
    } else {
      serialInput += c;     // add it to readString
    }
  }
}

Brief description of how it works:

The string SerialInput starts empty.  We do the following repeatedly:

If there is a character available on the serial port, read it.
If it is not an end-of-line character, add it to the end of our string
If it IS an end-of-line character, we know we've got to the end of the line, so...

check whether it matches one of our "target" strings, and act on it if so
clear it back to an empty string


when WTV020 is playing sound, speaker goes completely mute. When it doesn't play sound, little scratchy sounds can be heard from speaker. Maybe it could help with analysis

Indeed - what you are describing sounds like the DC component of the Arduino's output is outside the workable range of the amplifier, effectively cutting it off.  When there is no output, the voltage is within range and little bits of noise are able to be amplified.

You should be able to fix the cutoff problem with a series capacitor to block the DC component of the input, allowing only the AC signal through - a common technique for coupling between stages in Audio and RF systems.

The value of the capacitor will depend on the impedance of the circuit it is driving.  A bare input to many chips could use a quite small value, while a circuit with feedback or a voltage-divider volume control might require a larger or carefully chosen one.


Feeding microcontroller and linear actuators (motors) with the same power supply

First of all I would look to see if the two motors will actually run at the same time.
If not then the 10A power supply, is fine.
If they do run together, for how long? (you mention 25% duty cycle), power supplies usually have a over capability for a short period of time, and batteries will supply more current but at a slightly reduced voltage, so if going slightly slower isn't an issue then this would be fine.
Then there is the question of do they really use all 5Amps, I very much suspect not, unless you are fully loading the actuator(750N), they prob run at 2-3 amps at most.
Secondly
Circuit protection, fuses or thermal shutdown links for the motors is required, better still instant overcurrent protection for them set at 1.2x nominal current.
Do some worst case tests and measure the current, set the protection to 1.2 x this.
Remember if there is an issue the supply voltage will start to drop, its now that the micro will suffer if the voltage dips too much and you have no protection/sensing.

So suspect the power supply is more than ok.


GSM module connected with arduino uno giving garbage values in response

Serial.println(myserial.read());

myserial.read() returns an integer. That integer is either the ASCII code of the next character in the buffer, or -1 if there is no character to read.

You then print that integer, each one on its own line.

So the response "OK\r\n" from, say, "AT\r\n" would look like:

79
75
13
10

Instead you need to write the data, not print it:

Serial.write(myserial.read());

Also, the way you have written your code, you will get no response for 30 seconds - that is, until everything has already happened. Only after it has all finished will you get some feedback - and that may not be complete since you may overrun the buffer depending on what the modem sends.


MCUs mounted on Arduinos don't have the horse power to handle https connections.

Yún does handle https on the linux side, with software like curl, wget or python. Your sketch can just delegate the task to the linux side.

While curl works fine, despite having python preinstalled, you need to manually install python-openssl, since it's not available out of the box (due to disk space constraints)


The Yun is a bit different to other Arduinos. The main microcontroller is a ATmega32U4 with a build in USB interface. This is used for the connection to the PC so the single USART is not used for this purpose.

However, the single USART is used for connecting to the built in wireless processor. This means that you can't use the wireless and hardware serial at the same time. I presume you are using the Yun for wireless, so disabling this is not desirable.

SoftwareSerial is relatively good, but does consume a lot of cycles. You can only listen on a single port at a time. It is possible to use pin change interrupts to listen for activity on multiple ports and switch to the one required, but this requires that the other end can wait for a response.

SoftwareSerial will tie up the microcontroller whilst sending, which can lead to problems when supporting low baud rates. Conversely, because it is CPU heavy, it can also have problems with high baud rates. There is a window, between 9600 and 38400 baud, where it seems to work best.

There is another software serial version called AltSoftSerial. This works faster than SoftwareSerial and can transmit and receive at the same time.

You can use the USART, SoftwareSerial and AltSoftSerial all at the same time. Be warned that because all three of these use interrupts and some use timers, you are highly likely to end up with complex, hard to debug interactions.

Note than in older versions of Arduino (pre v1), SoftwareSerial was very, very poor. It was replaced entirely with "NewSoftSerial".

Sensors are often have very basic USART hardware with limited buffer sizes, and drop data when they aren't serviced in a timely manner.

I am not a massive fan of the Yun. It isn't popular, the wireless is still relatively hard to use (compared to the TI CC3000), and the wireless interface uses valuable pins. Personally, if I was to work on a project that required multiple serial interfaces, I would either

Use a board with multiple USART, such as a ATmega1280 (2 USARTs) or ATmega2560 (4 USARTs) and a CC3000 (SPI connected) wireless board.
Use SPI/I2C->USART bridges. This allows a single SPI/I2C port to control multiple USARTs. Sparkfun sell one, there are many others available.

Be cautious of falling into the trap of using hardware because it is what you have available.


It looks like you have soldering paste all over the circuit board. If enough paste bridges a gap between the ceramic resonator and the IC, it can attenuate the oscillator signal to the point where the board won't work.

I use an old tooth brush and Isopropyl alcohol to clean excess soldering paste. As the alcohol evaporates, a lot of moisture forms on the circuit board, so it's important to ensure it's completely dry before you power it up.

Try cleaning the circuit board and see if that fixes the problem.

EDIT:

I would like to show you how much soldering paste it takes to stop a 328P from working. The following image shows the bottom of a perfboard with 0.1" hole spacing. You can see the soldering paste bridging the gap between pins 8, 9, and 10 of a Atmega328P DIP IC. Pin 8 is ground, and pins 9 and 10 are connected to the crystal / capacitors. All three pins are connected together via the paste, and since I forgot to clean the board before "final assembly", it's possible other pins are connected together via the paste.

The circuit board is from a "kitchen clock project", and was taken the day it stopped working. There are no mechanical connections to this circuit board except for the 328P's IC socket. This clock worked for 3 months, then it quit suddenly. I re-booted it once, it worked for an hour, then it quit again. The only factor that changed after the first three months was a change of seasons (the ambient temperature in the kitchen was reaching 90+ degrees F during the day). I don't know if the "blobs" of paste were touching each other when I assembled it, but they were when it failed. How does thick soldering paste start moving around on it's own? With some heat and Capillary action of course :)

Cleaning the board with Isopropyl alcohol fixed the problem, and the clock has been running for the past 6 months without issue.

EDIT 2

When I monitor pin 9 of a 328P on a 5V Arduino Uno, this is the waveform I see.

You can see the small amount of voltage change the oscillator has to make for the 328P to sense it, and function correctly (800mV peak to peak). If the soldering paste is conductive, capacitive or perhaps both, connecting this signal through the paste to ground, power or several other pins can disrupt the signal to the point where the IC fails to operate.


I would split it down into functions.

First write a function which takes a character and a pair of coordinates, then draws the bitmap corresponding to that character at the given coordinates on the screen.

Then you want a function that is the "next level up". You just pass it a single character, and it remembers the current coordinates and uses those with the character to call the first function. It's then the job of this function to move the coordinates to the next character location ready for the next time it's called.

Finally you want an outer layer (or a few outer layer) functions that take different data types (const char * for example) and send each character in turn to the second function above.

If you were to make a class to wrap it all in you could inherit the Print class. That means you just need to provide the size_t write(char) function which is equivalent to the second function above (of course you still need the first function). The wrappers for different data types are then all provided for you.


If all those are known tags, you can put them in the source code as
32 bit integers. No
need to convert. Or rather, let the compiler do the conversion:

const uint32_t ID_num[ARRAYSIZE] PROGMEM = {
    Oxbcc0f1c3, Ox821a7d39, Ox4924887c, ...
};

When you read a tag number in hex, in order to compare it with the known
tags, you convert it to the same type using strtoul() from
avr-libc:

uint32_t tag_id = strtoul(tag_string, NULL, 10);


How to re-construct audio from series of analog integer input?

I'm trying to learn how to stream audio from the A0 pin of an ESP8266 NodeMCU board via UDP socket connection over to another windows computer that uses pyaudio to play it.

You have described several problems; one needs to break big problems into small problems:

Sample the audio
Send it to another computer
Decode and playback the sound

  At the moment, all I get on the windows computer are a series of "popping" sounds each spaced about half a second apart.

This sounds like you have got your timebases messed up; it is likely that you aren't recording enough data or playing it back incorrectly. N.b. it looks like you are recording ~92ms of audio data each 'packet' and if you get a series of pops at 2hz you are likely playing less than 1/10 of a second of audio for ever 5/10 of time, so your speaker moves for 1/10th of a second then stays still for 4/10ths and repeats; this produces your 2hz popping noises.

Your code has some other problems as well:

Serial.print() is Slow! Don't use it where performance matters!
Intertwining sampling and sending
Incorrectly scaling the analog reading
11.1khz can only record signals up to 5.5khz

Lets start with the audio sampling. We have some sort of audio circuitry presenting a signal to an analog input, we need to sample it regularly and uniformly! The code presented is trying to sample at 11.1 kHz, but only does so for 1024 samples before hitting a discontinuity. We do not have circuitry dedicated to this so we will have to use the ADC circuitry on the Arduino.

First thing you will want to get you sampling regular and continuous. You will want to use an interrupt on the Arduino for this. The interrupt should take a single sample from the ADC and add it to a buffer or signal the main loop to read/buffer it.

This interrupt will need to fire regularly at the sample rate or the data will be ruined.

Second the audio circuitry should prepare the signal so that it is between 0-5v with a ~2.5v bias, this will use the ADC hardware to its fullest.

so in Pseudo code:

// include any libs etc.
// set up variables ect.
void interupt_sample();
// register and attach interrupt
void setup() {
//do your setup etc.
}
void loop() {
// if(new_sample) add_to_buffer(new_sample);
// if(buffer_full) send_and_flush_buffer();
}


Eeprom write function does not seem to write in more than 100 locations

Looking at the library at https://github.com/thijse/Arduino-EEPROMEx/blob/master/EEPROMex.cpp it seems they limit the number of writes to 100:

EEPROMClassEx::EEPROMClassEx()
  :  _allowedWrites(100)
{
}

There seems to be a way of changing that:

/**
 * Set global maximum of allowed writes
 */
void EEPROMClassEx::setMaxAllowedWrites(int allowedWrites) {
#ifdef _EEPROMEX_DEBUG
    _allowedWrites = allowedWrites;
#endif
}


Assuming you are using a 9V block battery: They don't deliver the current you need for the esp32 to run/create an access point/act as a client. What you can do is connect 6 AA batteries in a row (6*1.5V = 9V) and they will deliver a higher current than the 9V block.


First, make sure that your LCD routines and wiring are working, by trying to display something on it.
Second, the code isn't correct - it will have some fluctuations from one measurement to another.
One way to do it is to start timing only after the first pulse has arrived, and stop timing only after the last pulse has passed.
Something like this:

Wait until a falling edge.
Time0 is millis().
Wait for N pulses to pass.
Time0 is millis() minus time0.

Now with time0 and N you can calculate your rpm.
Edit:
Here is the above code at work, running Arduino on a PIC24.

The input signal is 10Hz, 1 pulse per revolution, aka 600 rpm.
As you can see the rpm read-out is precisely 600rpm. I'm running the code at 8x oversampling.
As I indicated earlier, your code will introduce uncertainty, as much as one period for the pulses. So in a single pulse measurement, the rpm can be anywhere from 0.5x of the true value to 1.0x of the true value.


MPU6050 Accelerometer freezes/glitches after acceleration

Your problems are (most likely) related to loose connections in the breadboard. Sudden movements can cause power to be interrupted briefly, or data signals to become corrupted.

Breadboards aren't great for prototyping anything that moves, even slightly.


GPRS shield - Hayes commands to identify a faulty SIM connection

Having exchanged the board for another one (that works!) I can now confirm that the calls above (e.g. AT+CMGL) should work if there is a working SIM connection.


Arduino Pro Micro clone not recognized, flickering RX LED

If your pro micro does not have a reset button, wire one between reset and ground.

Press reset twice, quickly, and immediately hit upload on the IDE.

Secondly, make sure you've downloaded and installed the Sparkfun board files for the pro micro.


It's a typo. My revision of the datasheet (revision G) properly says "INT0".


The problem is that you're mixing different variable types. It's kinda an oil/water scenario.

Basically, the serial.read(); command returns an integer, -1 if there's nothing in the buffer. If there is something, it will return the character code (i.e. 93 = a). Because of that, it's an integer. When you put something in single quotes, it compiles as the equivalent ISO character code.

So, when you do input == 2, it is integer [compared to] integer. When you do input == "string", you're doing integer [compared to] string, thus you get errors. BTW: a string is a type of pointer.

So, what you have to do is this:

string input = "";
if(serial.avaliable()) {
    delay(100); //Wait for all data to be received
    while(serial.avaliable()) {
        string = string + char(serial.read());
    }
}
if(input == "yay_it_works!) {
    //Done!
}


Why is the Arduino IDE ignoring my replacement start up code?

The Arduino builder is case sensitive and will only see files that end in .S and not files that end in .s.

Renaming the new start up file to startup.S and then deleting the precomplied core archive fixed the problem.

Note that committing this change to git slightly complicated!


How to connect MCP4141 digipot and a data logger shield to the same Arduino board

I have done the same thing in the past for a DS1302 RTC that uses the same communication system.  Yes, it works.  Will it interfere with the other communication though? Quite possibly.  It works fine for half duplex communication, but could cause interference with something else on the bus that is full duplex.

If in doubt, and you're not worried about high speed or high efficiency (you're not changing the potentiometer's value often) then use three other pins and bit-bang your own half duplex serial interface - it's not hard.


High power consumption during power down mode

I tried your first sketch on my "bare-bones" board.

With the sketch exactly as written, it used 197 µA.

I wondered why it was that high, so I commented out this line:

  Serial.begin(9600);

That reduced consumption to 122 nA.

See Power saving techniques for microprocessors.

You need to get rid of any "power" LEDs, and disconnect any voltage regulators. If you want really low consumption you need to have minimal hardware.

Of course, if you need the voltage regulator, well so be it. But don't expect 100 nA consumption if you use it.


Synchronization and Implementing hamming code on Software Serial

You can use this info and code: Hamming(8,4) with Arduino.

There's a PDF with documentation about the process of creating a class that implements hamming(8,4) and a link to the source code.

You can use any class that derives from Stream (like Serial or SoftwareSerial).

Edit: If you want to implement a Hamming ECC in a Arduino it would be useful to precompute all the possible message values (you'll find more info at the link above). In a Hamming(8,4) your message is 1byte = 4bits + parity 4 bits; so you must divide your bytes in nibbles. It would be better to put all that stuff (code, decode, manage the upper/lower part of the byte, etc...) in a class. An example using the Hamming class from the link above:

Tx:

#include <hamming.h>

Hamming hamming(&Serial);
char message[] = "Hello World!!";

void setup()
{
  Serial.begin(9600);
  delay(100);
}

void loop()
{
  hamming.write(message);
  delay(1000);
}

Rx:

#include <hamming.h>

Hamming hamming(&Serial);
char message[Hamming::SIZE];

void setup()
{
  Serial.begin(9600);
  delay(100);
}

void loop()
{
  if(hamming.isMessageReady())
  {
    hamming.read(message);
    Serial.println(message);
  }
}

If you need to send other kind of info: a float, integer... you can do it, but I think it's a better idea to tokenize/detokenize your information and handle it like a "string".

P.S. You can use any kind of physical layer insofar as it's a child of Stream: Serial, SoftwareSerial...But I've only tested over Serial.


The code works correctly. The function sizeof() returns the number of bytes in a variable, not the number of elements. Your array is of type int, which consists of 2 bytes each. So in sum you get 6 bytes for the whole array.

What you want to do (calculating the number of elements in the array) is to divide the number of bytes in the array by the number of bytes for one element:

int I = sizeof(Button)/sizeof(Button[0]);

The conversion from byte to int worked correctly, but you really don't need it. You can calculate things with both types the same way. The only difference is the value range. Since a negative element number doesn't make sense and you surely don't want to define more than 255 buttons, you can choose yourself, what you want to use. Using byte would save you one byte of memory.


Why is the BLE device not starting on my Arduino Pro Mini?

This is my wiring: First I connect the pro mini to the uno in order to upload the code looking like this:

Arduino Mini Pro to Arduino Uno

RX --> TX
TX --> RX
VCC --> 5v
GND --> GND
RST --> RST

How would this work? The bootloader in the Uno and Mini Pro will both try to reply. You need a FTDI or a USB-to-UART module instead of the Uno. Alternatively, start by programming the Uno to act as a USB-to-UART converter using Serial and SoftwareSerial.

Cheers!


Powering LCD Displays without a Breadboard

I presume you're looking at this page - the breadboard is merely a convenience, you can just hard-wire the LCD directly - most don't even come with that header plug soldered on.


Getting coordinates from a touch panel with I2C

There is a simple library that works for FT5xx6 display panel.

Other information available:

Application node - https://cdn-shop.adafruit.com/datasheets/FT6x06_AN_public_ver0.1.3.pdf

Datasheet - https://www.newhavendisplay.com/appnotes/datasheets/touchpanel/FT5x26.pdf

In case those links might be no longer available in the future, a quick search on FocalTech FT5xx6 should give you the relevant information.


The problem was that the R/W pin on the LCD was left floating, after I connected it to GND, I started working :)


How to use components that don't have a shield?

Your observation is correct. Everything breaks down to some number of physical connections and some protocol for communicating with the device. Shields and libraries associated with them do most of the work for you, but not everything comes in a shield.

There are some common protocols for interfacing with devices, including SPI and I2C. From a quick peek at the driver interface sheet, it looks like they're using SPI. Well, your Arduino already supports that so you can hit the ground running with this display. You just need to know what commands to send to it, which you can find from the display's datasheet.

Note: It looks like the 2" screen requires 3.3V while the 7" one supports up to 7V.


How to convert a String number Into a int value?

The easiest way is to use the parseInt method available to Serial like this

int val = Serial.parseInt()

But, you will have to be sure that the non-number part of the message ("Slider") has already been dealt with.

You could also put the data into an arduino String Object and use it's toInt method, or put it in a C style string and use the atoi method.


Problem programming Mini Pro via Arduino as ISP

After poking around for a bit more, it turns out my problem was the baud rate.  I could make it work by setting it to 19200, just a little slower.  Alternatively, you can modify the ArduinoISP sketch to enable higher baud rates.  I used this post to enable 115200 baud and I was able to successfully use avrdude at the higher rates.

Not sure how I missed this before, but it's an easy to solve at least.


Cutting off OneWire/SDA line with transistors

For multiple I2C busses, it is allowed to share a single SCL and have a separate SDA line for each I2C bus. That means that as long as the SDA is inactive (high), you can do with the SCL whatever you want.

It might even be possible to share the SCL signal for I2C and 1-Wire, and use both. The SCL signal would then also be the 1-Wire signal. The I2C pulses are probably shorter than the start pulse of the 1-Wire. You would also have to do it right in the software to switch the function of the pins. As far as I know that has never been done, so you might get into a lot of trouble.

Transistors are not the right choice to multiplex signals, and the BD228 is definitely not okay. The I2C bus is a open-collector or open-drain bus with a current of maximum 3mA. The 1-Wire bus is roughly the same. It is possible with mosfets or with multiplexers (see: Nick Gammon about multiplexers). However, if you are going to add extra hardware there are probably better solution than combining I2C with 1-Wire.

Have you thought about the voltage levels ? Are you using a 5V Arduino board ? Most sensors are 3.3V. The DS18B20 will work with voltages as low as 3.0V, so 3.3V is no problem for the DS18B20.

Tell us what else is connected to your Arduino board. I'm sure there are better solutions.

Could you better specifiy what it is that you want to achieve ? When there is only I2C sensors or only 1-Wire sensors connected, you could run a i2c-scanner to check for I2C sensors. If nothing is found, do a Wire.end() and start the OneWire using the SCL pin. That could be done during startup and then you don't need extra hardware.

How long are the wires ? The 1-Wire bus can have long wires, but the I2C bus can only have short wires.


I can't get code transferred to my Arduino Mini Pro

Things have changed in the three years since you last used your FTDI board.

Most importantly avrdude has changed.

You will most likely find that you can program your boards perfectly fine using Arduino IDE 1.0.1.

What has changed is that avrdude has been modified to counter a change in the FTDI drivers. It used to be that the FTDI drivers would pulse the DTR line when the port was opened, but that stopped happening with newer drivers. So AVRDude started asserting the DTR line instead. However it doesn't pulse it, it just holds it low.

The problem with that is if the DTR is connected direct to the RESET pin the main chip is held in reset mode all the time instead of it just being reset briefly to reset the board.

The "fix" is to place a 100nF capacitor between DTR and RESET instead of directly connecting it. That converts the steady low into a short pulse which resets the board and enters the bootloader.


Try to Serial.println(thermocouple.readError()). It will give you an
error code, which is a bit field:

1 = open circuit
2 = short to ground
4 = short to Vcc

C.f. the
datasheet.


What does this notation stands for? Wire.read() <<8 | Wire.read()

Just adding a couple of points to Michel Keijzers's answer.

The expression Wire.read() << 8 takes the value returned by
Wire.read(), which is an int, and shifts it 8 bits to the left,
which is equivalent to multiplying by 256. If you are using a 32-bit
microcontroller (e.g. an Arduino Due), this is safe. However, most
Arduinos are based on an 8-bit AVR chip. On them, an int is 16-bits
and can only hold values up to 32767. If the initial value is larger
than 127, then the bit shift causes a signed integer overflow, which in
C and C++ is undefined behavior (read: “illegal operation”). It is
likely that everything runs fine and you get the expected result, but
it is unwise to ever rely on undefined behavior in C or C++.

The proper way to do the shift is to cast the initial value to an
unsigned data type, which is always safe v.s. overflows, and then do the
shift, like in

((uint16_t) Wire.read()) << 8

You may omit the outer parentheses if you know your operator priorities.

The second point is about the already mentioned fact that the order of
the reads is not specified. The simplest fix is to do one read per
statement, as in:

AcX = (uint16_t) Wire.read() << 8;  // first read MSB
AcX |= Wire.read();                 // then LSB

It is worth noting that the first statement has an implicit cast from
uint16_t (the result of the shift) to int16_t (the type of AcX).
This can also overflow if the shifted value is larger than 32767.
However, an overflow happening during a conversion in not undefined,
but rather implementation defined behavior. This means that the
authors of the compiler must decide and document what happens. Arduino
code is usually compiled by gcc, and the gcc docs document this
behavior as

  • The result of, or the signal raised by, converting an integer to a
  signed integer type when the value cannot be represented in an object
  of that type (C90 6.2.1.2, C99 and C11 6.3.1.3).

  For conversion to a type of width N, the value is reduced modulo 2^N
  to be within range of the type; no signal is raised.

This is exactly what we want here, and since it is the most efficient
choice on a two’s complement architecture, it seems unlikely that
another compiler would make a different choice.


The 'R3' version boards and shields are compatible with 3.3V and 5V. For example the Ethernet Shield V1 version 'R3' can be used with the Due. The new Arduino Ethernet Shield 2 is also compatible with the Due.
Many older shield are not compatible with the Due, but do you really need to use an old shield ?

Most sensors are 3.3V, and also a SD memory card is 3.3V. That is a lot easer with the Arduino Due which runs at 3.3V.

The Arduino Mega 2560 board is the only board with 10k pullup resistors at SDA and SCL, therefor it has a 5V I2C bus. When a 3.3V sensor with I2C is used, you need a I2C level shifter. When a 3.3V with SPI is used, you need more hardware.

The Arduino Mega pins can drive more than 20mA, it can be used to drive 10 leds with 20mA simultaneously, the Arduino Due can't do that.

My suggestion is to use an Arduino Uno for all kind of testing. It's always good to have one lying around. Start with an Arduino Uno if you want to learn programming and have fun with leds and buttons.

The Arduino Zero or MKRzero or M0 have a M0+ processor at 3.3V and they can be used for all kind of nice projects. When you already know a little about programming and electronics, this is a very good choice.

The Arduino Due has more processing power then the M0+.

The Arduino Mega 2560 is still used, because there are many libraries and shields that are compatible with the Arduino Mega 2560.


Do gyroscopes purposefully show erroneous data?

MPU6050 is a chip that has an intenal (closed and unknown) algorith to calculate orientation. Because you ar reading ANGLE, that means you are using that algoritm, and that "time" may be the time needed for the calibration.

what do you have as output on the serial?


Short answer: You have a blocking delay interrupting your button debounce time of 100ms.

Your button library has a debounce time of 100ms. This means you must be holding the button down for more that 100ms before it will register as pressed.

You have a 3 second blocking delay at the end of your loop. When you call delay(XX), your processor cannot do anything during this time (like check for a button), it's just waiting.

Think about how the code is running. In your main loop, you are calling the function button.loop(), and it's checking to see if your button is pressed. If it's pressed, it's starts a timer (your debounce). The goal of this timer is for another 100ms to pass by with your button still being pressed to make sure you actually pressed it. Button.isPressed() fails, and it moves to its next set of instructions, which is move the servo and wait 3 seconds, during which time it cannot check the button. Then it starts all over again, and it calls button.loop() again. This all happens MUCH faster than 100ms. From the start of void loop() to the time it takes for it to wind back up at the 3 second blocking delay is in the nano seconds. This never gives your button library the 100ms of "pressed down" button it needs for button.isPressed() to return true.

I suggest spending some time looking at the behind the scenes of your button library and see how the debounce works. You can do that, or you can use the example debounce sketch off the main arduino website and learn how that works. The next thing you'd want to do is to learn how to make your code "wait" without using the blocking call delay(). This is done by using timers with millis(). A good way to learn this is the example arduino sketch "Blink Without Delay".

Hope that clears some things up.


Can I store an MD5 password hash instead

No. MD5 is a "trapdoor" algorithm. It's one-way. You can make a hash from a password but you cannot make a password from a hash.

You could AES encrypt it, but you would need to have the AES key in your sketch to decrypt the password, which just moves the problem elsewhere.

Typically in a real-world situation you wouldn't have either the SSID or the password in the sketch. Instead you'd create a configuration system which would allow you to set (and of course change) both the SSID and password at runtime, and have the data stored somewhere (either EEPROM or in a file in SPIFFS, for example).

You might want to take a look at WiFiManager which automates that process for you.


How to set sampling rate for digital pin input?

You need:

A timer
A board that is capable of running fast enough to do what you want.

The Nano fits the first criteria, but not the second.

At 16MHz you get a clock period of 63ns.  That means you get a mere 8 clock ticks (actually gives you 504ns) per interruption from the timer. That's at most 8 assembly instructions that can be executed within that time.

Since an interrupt service routine's preamble is longer than 7 instructions you can see there would be a slight problem there.  No time for actually reading a digital IO port - and if you are using a serial protocol to communicate with your ADC you can multiply the reading time by the double the number of bits you need to read. That's a long time compared to 500ns.

So no. Think again. Use a more suitable board. Maybe an ARM based board (like the Teensy 3.x) would be a better fit.


Yes.  You remove the bootloader completely and program the Arduino using a hardware programmer.

If you could "turn off" the wait period you would never be able to get into the bootloader to program the board, so the bootloader would be completely useless.  So either way you would then need a hardware programmer to do anything constructive with the board.

A hardware programmer could be another Arduino, or a real hardware programming adapter.


I suppose you mean the "Galileo integrated Ethernet port" (the on-board RJ45). Then the answer is "no, not directly". The whole code provided by Intel in Arduino 1.6 IDE applies to the W5100 based shield, not the integrated Ethernet interface (which is a bit stupid, imho...)
Technically, however, this is possible, but you will need to create a library in C/C++, which interfaces with the system lib (the Linux one). You can then access to the wonderful world of BSD sockets (much more powerful than then sockets within the W5100)
Note however that the configuration of the integrated Ethernet board is not very easy with the Galileo, because the default Yocto image does not allow you to change default IP parameters (the Yocto image uses DHCP by default). So technically, you need then to deal with a startup script which changes the IP parameters at startup, but it's pretty heavy to do.


Unreliable serial communication from Arduino Mega

As I'm no longer using the software serial library and instead using the Mega's Serial2 port, I thought I could get rid of the module. Is this incorrect? If so, why would the commands work after N attempts as opposed to never working at all?

You still need the module. RS-485 and RS-422 are electrically incompatible with CMOS.

  Previously, while using the above module, I had to have two lines of code that would shift the DE and RE pins high or low depending on if I was sending or receiving data. I realized that these needed to be outside the for (int i=0; i< 8; i++) loop as otherwise, the device would not be able to read/understand the data being passed. Do I need to reimplement some version of this with the Arduino Mega's native serial? If so, how would I do this?

Absolutely. Also you need to flush the serial after transmitting and switching back to receiving:

digitalWrite(DE_PIN, HIGH);
Serial2.write(cmd, 8);
Serial2.flush();
digitalWrite(DE_PIN, LOW);

Flushing the serial pauses your program until the entire command has been transmitted. That means not only sent from the TX buffer to the TX FIFO in the UART hardware, but also the last byte from the FIFO has been shifted out onto the wire. If you don't do that your command will get truncated by the transceiver module as you switch back to receive mode prematurely.

Note: I forget which is which for the DE pin - HIGH/LOW or LOW/HIGH. Change it appropriately. Also note that you don't need to manually loop - the Serial code already has that facility for you.

  The converter must have the hardware and software support to tri-state the transmit buffer following the message transmission.

That is what the DE/RE pins do - switch the module between active drive (transmit) and high-impedance (receive).

  I'd much rather use something like Majenko's pointer way to send data to my device so that I could make the code not rely on the fact that there are always 8 bytes transmitted. However, sometimes a byte will be \0 (or any other termchar) which would stop the loop prematurely. Is there a way to avoid this?

That is only applicable with strings. With binary data you always have to know the length (though that doesn't have to be hard coded). All you need is a maximum length for any buffers you have.

  I'm still pretty new here, Is there some way that I can do this better than the way I'm currently doing it?

Besides my notes above, this method:

while(rep)
{
  for (int i=0; i< 8; i++)
  {
    Serial2.write(cmd[i]);   // Send C string
  }
  if(Serial2.available())
  {
    //device echoed == command recieved
    rep=false;
  }
}

is completely wrong. You are sending a command and then immediately looking for a response. You haven't given that response time to either be generated by the remote end or be received by the Mega.

Instead it should be:

Send the command.
Look for some response data
If some data has arrived then add it to the response buffer
If the whole response has not yet arrived go back to 2

You can also add 2.5: if it's been checking too long then abort with a "timeout".


It's just SPI.

SPI.begin();
SPI.setDataMode(SPI_MODE2);

// ...

uint8_t h = SPI.transfer(0x00);
uint8_t l = SPI.transfer(0x00);
delayMicroseconds(20); // Indicate EOT
uint16_t v = (h << 8) | l;
v >>= 4; // for 12 bit resolution, 5 for 11 bit, 6 for 10 bit etc.

For 8 bit resolution or less you only need one SPI.transfer, and subtract 8 from the right-shift amount.

Wiring is simple: clock to SCK (52 or ICSP 3) and data to MISO (50 or ICSP 1).

The timing diagrams in the datasheet (page 5) describe it all in detail.


How can I measure the point of contact between two wires?

you could try 4 terminal sensing.

I have not used it myself, but the basic idea is to try to normalise for some of the external factors you mention.

As for the Arduino, the analog to digital converters have 10 bits of precision. This means you will get 1023 distinct values as the input voltage varies betwee 0 and Vmax (+5 or +3.3 depending upon the actual device). So that is fairly precise, usually you just use the value from the analog read - but you can convert to a value between 0 and 1 by dividing:

    int analogInt = analogRead(<your port here- e.g. A0>);
    double analogFloat = analogInt / 1023.0

Which begs the question, did you try using a 2 wire system? Assuming just 1000 data points, and a finger being, say, 5cm in length; that's roughly 1 point per .05 mm. I know it won't work out exactly like that, but that is my point - it is likely to be a rough estimate anyway due to the size of a finger at the touch point.


Arduino as ISP with serial monitor for ATmega328

Just burn the arduino bootloader to your tqfp. Then connect the tx and rx on the tqfp to the tx and rx on your arduino, and pull the reset line on the arduino low.

Downside is you have to do a manual reset on the tqfp before programming. If you have an Uno you could remove the atmega from the socket, and connect the reset on the uno to the reset on the tqfp.

Another option is to connect the TX on the tqfp to the TX pin on the Arduino using a resistor. But for this to work you have to modify the ArduinoISP sketch to make it release TX pin (UCSRnB &= ~_BV(UCSRnB);) and set it to input. And reverse it when data is received on the RX. Not trivial, and only works one way (tqfp to PC).


Is a 9v battery appropriate for a piezo and 1 LED?

A couple things to note:

Get rid of the PWR LED on the Trinket so it's not always drawing current.
Sleep the MCU whenever possible, only waking on interrupts.
Converting 9V to 5V with an LDO (in this case, the MIC5225) implies a 55% efficiency, max, which isn't great. But at least the LDO has a low ground current.

Also, ask yourself if you really need a micro for this task.

If you want a ballpark for runtime, find the capacity of your battery, estimate your current draw, and see what your upper bound on runtime is.


Varible Ramp up speed for motors controlled by joytstick

I assume from the 0, 10, 20 …. 120 series, that you want to have a linear ramp to the desired speed. This can be done really easily, if your requirements are not to high.

First we define the interval, in which we want to update the speed, and a constant acceleration, that you can choose. The current speed will be saved in a global variable.

#define INTERVAL        100
#define ACCELERATION    51
int current_speed = 0;

I chose an interval of 100ms and the acceleration value, so that it will ramp from 0 to 255 (full speed) in 5s (which results in 51 PWM values per second). Now, in the void loop() function, we use an if-statement with the millis() function to trigger an speed update at the regular interval. For this to work, we need a (here global) variable, that holds a timestamp. (If you don't know this technique, you can see it in the BlinkWithoutDelay example, that comes with the Arduino IDE, and there are many tutorials about this on the web)

Inside the if-statement, we write a second if-statement. It checks, if the current speed is above or below the set point, that comes from the joystick. If it's above, we will substract one speed step (calculated by acceration and interval and divided by 1000, because we used milliseconds and not seconds for the interval), if it's below we will add one speed step.

unsigned long timestamp = 0;

void loop(){
    int setpoint = analogRead(joystick)/4;
    if(millis() - timestamp > INTERVAL){
        if(current_speed > setpoint){
            current_speed -= ACCELERATION*INTERVAL/1000;
        } else {
            current_speed += ACCELERATION*INTERVAL/1000;
        }
        if(current_speed > 255) current_speed = 255;
        else if(current_speed < 0) current_speed = 0;
        analogWrite(pwm1, current_speed);
        timestamp += INTERVAL;
    }

I also added if-statements to cap the current speed between 0 and 255. Otherwise the value would overflow, when written to the corresponding 8-bit timer register by the analogWrite() function.

Of course, this method also has drawbacks. You will have to find a good value combination of ACCELERATION and INTERVAL, because when the current speed reaches the setpoint, it will oscillate around this value. The best way is to set the ACCELERATION, that you need, and choose a good interval based on that.

There are other ways to program this, but I like this way for being really simple.


How do I order the gcc compiler to generate -S flag in Arduino IDE

Compiler flags are defined in the platform.txt of the board you have selected in the Tools > Board menu. You can also add compiler flags via a build.extra_flags property in the boards.txt entry for the selected board.


Arduino Due: JTAG and SWD do not work after pressing erase button

After uploading via Microchip Studio, go to the GPNVM bits section of "device programming" window. Make sure boot mode is set to "boot from flash". Also check that GPNVMBITS register is set to 0x00000002. Then press "program". The sketch you uploaded to the MCU should now work.
So it seems what happens is that pressing the erase button resets the GPNVM bits so that the MCU boots from ROM, but then Atmel ICE + JTAG/SWD does not set the boot mode back to flash after (succesfully) programming the MCU.


Can I power up my Arduino and MotorShield with four AA batteries?

You won't damage the Arduino if you remove the power to the motors as even though you're using the same power supply to power the motots and Arduino (4 x 1.5 - 6V batteries) you're not powering it from the Arduino pins itself.

What exactly are you trying to accomplish here?  Post some more info.


How to turn servo to a specific location and then turn over

Rather than writing to 180 and 0 write to a variable.

static const int MovementAmount = 30; //degrees
int position = 90;  // 90 is the start position.
...
case 'd':
   servo.attach(12);
   position += MovementAmount;
   if (position > 180)
   {
     position = 180;
   }
   servo.write(position);
   break;


Can I control LED brightness with potentiometer without any code, as well as reading the potentiometer value?

You need to "buffer" the potentiometer to separate it from the LED and resistor. The simplest circuit for that is a unity-gain voltage follower with an op-amp:

simulate this circuit – Schematic created using CircuitLab
You want to choose a "Rail to Rail I/O" op-amp so that it can get right down to 0V and right up to 5V, otherwise you will clip the top and bottom of the range of the potentiometer.


How can I enable the security bit of a teensy board?

The Teensy 3.2 board is based on MK20DX256. The processor core is an ARM and not AVR. The best way to learn about security on the MK20DX256 is to read the documentation.

  Chapter 8 Security
  8.1 Introduction
  This device implements security based on the mode selected from the flash module. The following sections provide an overview of flash security and details the effects of security on non-flash modules.

  8.2 Flash Security
  The flash module provides security information to the MCU based on the state held by the FSEC[SEC] bits. The MCU, in turn, confirms the security request and limits access to flash resources. During reset, the flash module initializes the FSEC register using data read from the security byte of the flash configuration field.

  NOTE The security features apply only to external accesses: debug and
  EzPort. CPU accesses to the flash are not affected by the status
  of FSEC. In the unsecured state all flash commands are available to the programming interfaces (JTAG and EzPort), as well as user code execution of Flash Controller commands. When the flash is secured (FSEC[SEC] = 00, 01, or 11), programmer interfaces are only allowed to launch mass erase operations and have no access to memory locations.

  Further information regarding the flash security options and enabling/disabling flash security is available in the Flash Memory Module.

The next step is to search for an open-source project that uses the FSEC setting. And by chance the mbed does. Here is link to how it is done in the mbed CMSIS Cortex-M4 Core Device Startup File for the MK20DX256. There should be the same setting in the Teensy Arduino core. Locating that is left to the reader.

Cheers!


Better use a regular router and flash DD-WRT or OpenWRT to it (check the supported router list on their websites). Next use something like NoCatSplash, to create a captive portal with login.

Arduino's just are not fast enough for this. Arduino Yuns are typically more expensive.


State machine sketch to drive a DC motor with limit switches

You have created a flow chart.  When discussing state machines it is better to use a state diagram.

In this state diagram of a turnstile (from the state machine wikipedia page linked to above) it is observed that the nodes (bubbles) contain the state of the turnstile and on the edges (arrows) is written the condition required to travel in the direction of the arrow to a new state.

For the question asked here, at least 2 nodes are needed to state the direction of the motor.  The edges likely will state which arrow is to be used to travel to a new state based on which switch is open or closed.  Later, consider adding a new state to stop the motor once an end switch is closed. (Hint: Likely, you will need 2 stop nodes.  One for each end-stop switch.  The reason being you will need to know which direction the motor is to turn when restarted.)

For certain cases, adding a momentary contact switch is complex due to the need to mitigate the contact bounce.  This is true when the meaning of activating the switch changes.  The end-stop switch meaning does not change so there is no need to mitigate the contact bounce or "debounce" the end-stop switches.  However, it is assumed the "Cycle Switch" can start the motor spinning in different directions depending on the history of the motor movement.  Therefor the "Cycle Switch" can benefit from a 4 node state machine where there is clearly nodes which output switch-closed and switch-open.  But to get to either of these 2 nodes there needs to be 2 other nodes where the switch "debouncing" is handled.

When handling multiple state machines in one program it is important not to block the flow.  All state machines need to be continuously checked for state chances (testing the edge conditions for traveling from the current node to a new node).

When writing for an Arduino (in C / C++), the code pattern most often used is a "case" statement (switch / case) where a variable is assigned numbers associated with different nodes.  In such a code pattern, each "case" is a node which contains the edge test(s) and can assign a new value to the variable to switch to a new node ("case") if any of the edge tests are true.

Simplifying the design:  If you do not plan on stopping the motor then you do not need to "debounce" the "Cycle Switch".

Here is why: The meaning of the "Cycle Switch" changes from push-to-start to push-to-stop should you want to stop the motor between the 2 stop-switches.  If all you need is to start the motor after either of the stop-switches are closed, then the number of times the "Cycle Switch" bounces is irrelevant as long as the bounces do not continue for longer then it takes for the motor to reach the opposite stop-switch.


This style of antenna can be very finicky.  GPS on this module may take 15 or 30 minutes to lock, not just 5.  I would suggest you take this outside away from any walls or buildings and see if it will lock then.  I also suggest that you run it off a battery.  (one of those USB battery packs for charging your phone will work great).  Once you get a lock try changing one variable at a time (power supply / location) and see if you can get it to look again.

The reason this module takes longer to lock than your cellphone is that your cellphone is cheating by doing a warmstart.  The cellphone can get a semi-accurate time/date and also your regional location.  This warm start data improves GPS lock time down to 5 seconds or less sometimes.