text:
Would an Arduino Uno be suitable for a simple time-based locking circuit?
Background: I'm looking to start on my first real electronics project and I have an Arduino Uno I bought a while back. I've only done a few of the starter Arduino tutorials and that was a while back as well. Starting from very little electronics knowledge, I'm trying to get a bit of advice on how to tackle my first project.
TL;DR: I have an Arduino Uno but very little experience with it or electronics.
Project: I want an object that locks, I want the duration of the time it stays locked for to increase by ~1-3% every time it locks. I want to put my nicotine products in there to gradually pull myself off nicotine. I have designed a rough 3D model of the box, which I can 3D print so now I'm looking at the electronics.
TL;DR: A box which stays locked for longer, every time it locks.
Electronics: A microcontroller/Arduino/Pi to increase the locking duration; a locking circuit and some form of power supply.
My 2 questions are

Would the Arduino Uno be suited to this type of project?
What sort of components should I be looking for for the locking circuit and power supply (I'm thinking some sort of solenoid actuator and a battery pack)?

Sounds like an excellent project to use an Arduino for. I was thinking about using a servo, but a solenoid will work too. I probably would try to avoid using batteries. It's very hard to make an UNO not use a lot of power. And you probably want it to run for weeks.

Short answers: 1) yes, even if smaller boards are "more" suitable IMHO (but just for aesthetics); 2) power supply: usually I use a 5V USB charger, but any is fine. I suggest you not to use batteries (they tend to discharge...). actuator: a solenoid (with a transistor) is fine, or an RC servo (which complicates a bit the mechanics but is simpler in the electronics project)

@Gerben I usually avoid writing double comments, but I didn't see yours before posting ;) Sorry

@frarugi87 there is some value added by your comment.

An Uno is ideal for prototyping, but it's too power-hungry for the final thing. I recommend you go for a plain AVR microcontroller, aka “barebones Arduino”, and have a look at Nick Gammon's tutorial on power saving.

@EdgarBonet I started using the arduino pro mini boards for the "low" power applications. It lacks the USB interface and excluding the power led you get exactly the same circuit as the barebone one; barebone allows you to choose a different clock speed, so you can save a bit more power, but IMHO it is better to just switch to another microcontroller if you need a real power saving. However a pro mini board usually costs less than the bare microcontroller (and you have to solder the uc)... Then, if the power supply is not a battery using 20mA more is not a big deal, so even the uno is fine

Thank you all for your answers, they're really informative. I will definitely prototype the setup on my arduino uno. Good to know about the batteries, I shall have to see about either a usb cable to outlet or computer. And thanks for the advice on the locking mechanism, I might go for the servo over the solenoid (as a mechanical engineering student).

It is a great occasion to use the Arduino!
There are many tutorials for the Arduino out there, so thats a good place to start. This forum is a good place to ask any Arduino related question if you need to do so.

The following contains MY OPINION
In my opinion, an Arduino Nano would be great for this project. It is really user friendly and can pretty much accomplish many things. A Pro Mini would be better, but seeing sa you're a beginner, stick with the Nano.
A good long lasting batteRY would be a simple USB power bank. It outputs 5V and has a lot of juice. For a locking circuit, a simple servo would work IF THE THINGS THAT IS IN THAT "SAFE" ISN'T 1M $$. A servo does a decent job as a lock.

Good luck!

Thanks for the advice. I think I will use the Arduino Uno simply because I have it laying around and I'm not a stranger to programming. I'd not thought of using a power bank, thanks for the tip. I'm not trying to build something super secure so I don't think safe is the right word. I just want it to be more of an inconvenience to hack it open than to wait for the timer to run out.

Regarding your second question about what components to use, there are a couple arguments for a servo over a solenoid.
A solenoid in the energized state is relatively power hungry compared to a servo, which only requires any appreciable power while actually moving. Also, on power loss or interruption a servo fails as-is; a solenoid goes to the off position, which could cause an unwanted change of state for the lock.


text:
How do you configure ADC7 on the Arduino Pro Mini as a digital output?
I'm attempting to use the pin labeled 'ADC7' from the Atmega328p TQFP package. The Atmega documentation suggests that can be used either as an analog or digital I/O point. I'm trying to configure it as a digital output.
Referencing the documentation (and specifically arduino_pins.h), I determined the associated pin number was 21. Thus I called pinMode(21, OUTPUT). However, this pin does not appear to be working with my SPI device. I previously tested that the device worked, but I made a last second change of pin and am now using ADC7.
So my question, is there an additional step required to configure this pin as a digital output? I noticed that this pin doesn't exist on the DIP Atmega328p (used on the Arduino Uno), so I'm not sure if I have to add another line of code somewhere.
Any ideas?
Regards,

@EdgarBonet PORTC7 doesn't exist in the datasheet. PORTC6 does, but that one is connected to the reset pin and not ADC6.

@Gerben: Oops, you are right, I wrongly extrapolated. I'll delete my misleading comment.

Those are analog pins only. They can't be used as outputs or digital inputs.

I'm somewhat confused then. Is there a mistake in the datasheet then? It states it can be used either as an analog or digital I/O point in the pin out. http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Summary.pdf

Any analog pin on Arduino can be use ad a digital pin and I did it many times. And the AVR datasheet say that explicitly too. The only problem with Ardunino libraries/approach is, that they do not declare constants named as digital pins for pins, which can be also analog (probabelly to not "confuse users with choises").  for (int i=0;i<20;i++){pinMode(i, OUTPUT);digitalWrite(i,HIGH);delay(30);digitalWrite(i,LOW);}; works just fine and as expected (if you add LEDs+resistors to all "digital" and "analog" pins on Arduino). 1-13 are "digital", 14-19 are those "analog".

@gilhad, have you specifically tested A6 and A7, which the question is about?  Note that  Arduino #19 is A5, not A6 or A7.  Don't downvote Gerben's answer on flimsy grounds.

@gilhad ADC6 and ADC7 are only analog pins. The other analog pins also share with digital functions - ADC6 and ADC7 do not. You can see that in the table 6-1 of the datasheet - also they are only available on the TQFP-32 which the Pro Mini uses.

@jwpat7 : My bad, I was wrong. I mistook them with A4+A5 (as my example shows) and fast check with datasheet fig. 5-3, fig.5-4 shows them as digital/analog (also there is 28.9.8 Digital Input Disable Register, that allows to diable digital input buffer on them to save power and Table 32-2 DC characteristic, which adds them to counts for maximal source/sink sums). But I tested it on MiniPro and they are NOT outputs. Also Arduinos digitalRead() does not work with them, regardless INPUT or INPUT_PULLUP mode is selected there.

This may be a little left field, but I use the ADC6 and ADC7 inputs to detect switches.  I just don't use the digitalRead() function, but instead use analogRead() function.  Using a resistor network and switches and some decoder software code in our sketch, we can use a single input pin to interface with many more switches.  The switches can only be on one at a time, but in many instances, this would be OK.

Gerben's answer probably is correct, but there are some interesting discrepancies in Atmel datasheets for various models of the ATmega168 and ATmega328, as outlined below.
Some Atmel datasheets refer to ADC6 and ADC7 as PE2 and PE3, while others just refer to them as ADC6 and ADC7.
Regarding port E, the 2014 ATmega168PA and 2015 ATmega168 datasheets say nothing, don't list any of PE0 to PE3, and don't specify port membership for ADC6 and ADC7.  They show pins 3 and 6 on the LQFP as Gnd and Vcc, vs PE0 and PE1 as in the ATmega168PB sheet.
Regarding port E, the 2015 ATmega168PB datasheet says:
Table 15-12.  Port E Pins Alternate Functions
     Port Pin       Alternate Function
       PE3          ADC7 (ADC Input Channel 7)
       PE2          ADC6 (ADC Input Channel 6)
       PE1          NONE
       PE0          ACO (AC Output Channel 0)

Regarding port E, the 2016 ATmega168PB datasheet, Atmel-42176G-ATmega48PB/88PB/168PB_Datasheet_Complete-03/2016, says the following
and also lists several Alternate Functions while referring to
Timer/Counters 3 and 4 (although there seem to be no registers in the
register summary relevant to such Timer/Counters):
"Port E is an 4-bit bi-directional I/O port with internal pull-up
resistors (selected for each bit). The Port E output buffers have
symmetrical drive characteristics with both high sink and source
capability. As inputs, Port E pins that are externally pulled low will
source current if the pull-up resistors are activated. The Port E pins
are tri-stated when a reset condition becomes active, even if the clock is not running."
Table 19-12.  Port E Pins Alternate Functions
 Port Pin            Alternate Function
 PE3                 ADC7 (ADC Input Channel 7)
                     T3 (Timer/Counter 3 External Counter Input) & PCINT27
 PE2                 ADC6 (ADC Input Channel 6)
                     ICP3 (Timer/Counter3 Input Capture Input)
                     SS1 (SPI1 Bus Master Slave select) & PCINT26
 PE1                 T4 (Timer/Counter 4 External Counter Input)
                     SCL1 (2-wire Serial1 Bus Clock Line) & PCINT25
 PE0                 ACO (AC Output Channel 0)
                     ICP4 (Timer/Counter4 Input Capture Input)
                     SDA1 (2-wire Serial1 Bus Data Input/Output Line) & PCINT24

Interesting. Maybe the successor, namely the ATMega328PB, datasheet can shed some more light.

That's interesting, but it should be noted that the ATmega328PB has significantly more peripherals than the 328P. Now, @Teague could try something like *(volatile uint8_t *)0x2d = 0x0c; with external pullups on ADC6 and ADC7. If those pins go low, that would reveal an undocumented port E. But beware that Atmel advices against poking unassigned I/O addresses.

According to everything you can find in the datasheet about ADC6 and ADC7 they are analog only pins.
The pinout for the TQFP-32 as used on the Pro Mini shows those two pins as only having the analog functions:

I suspect the color coding of the pins may be wrong - they should be solid green. They have no port names on the pins, purely the ADCx designation.
The block diagram for the chip shows the ADC6/7 pins being separate from a port:

As you can see the other 6 pins are referred to by the digital port they share, but ADC6 and 7 are known purely as ADC6 and ADC7.
The pin function table, 6-1, shows ADC6 and ADC7 as the only functions on those pins. No digital port names, nothing - just purely analog input.
So in summary, for the ATMega328P chip used in the Arduino Pro Mini you cannot use those two pins for digital at all, only for analog input.

Fffffff. Welp, better get some new boards printed. Thanks for the response.

I appreciate this is an old question but those pins are subtly different on the ATMEGA328PB compared to the ATMEGA328P which I discovered recently. See the Microchip app note AT15007, page 3.
Microchip AT15007 app note

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

authors: บุญจันทร์ สว่างบ้าน

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
32x32 RGB-LED Matrix displaying Arabic Font with Font Forge more easily
At the moment I am using a separate function to display byte arrays like these:
const PROGMEM unsigned char arab4[] = {
  0x00, 0x00, 0x00, 0x00,
  0xf0, 0xff, 0xff, 0x01,
  0xf8, 0xff, 0xff, 0x01,
  0xf8, 0xff, 0xff, 0x00,
  0x04, 0xf8, 0x0f, 0x00,
  0x00, 0x7c, 0x00, 0x00,
  0x00, 0x0e, 0x00, 0x00,
  0x80, 0x03, 0x00, 0x00,
  0xc0, 0x01, 0x00, 0x00,
  0x60, 0x00, 0x00, 0x00,
  0x20, 0x00, 0x00, 0x00,
  0x10, 0x00, 0x00, 0x00,
  0x18, 0x00, 0x00, 0x00,
  0x08, 0x10, 0x06, 0x00,
  0x0c, 0x70, 0x0f, 0x00,
  0x04, 0xf8, 0x0f, 0x00,
  0x04, 0x78, 0x06, 0x00,
  0x06, 0x20, 0x00, 0x00,
  0x06, 0x80, 0x00, 0x00,
  0x06, 0xc0, 0x01, 0x00,
  0x06, 0xc0, 0x03, 0x00,
  0x0e, 0xe0, 0x01, 0x00,
  0x1c, 0x80, 0x01, 0x00,
  0x1c, 0x00, 0x00, 0x00,
  0x7c, 0x00, 0x00, 0x00,
  0xf8, 0x00, 0x00, 0x00,
  0xf0, 0x07, 0x00, 0x00,
  0xe0, 0x7f, 0x00, 0x3c,
  0xc0, 0xff, 0xff, 0x0f,
  0x00, 0xff, 0xff, 0x01,
  0x00, 0xf0, 0x1f, 0x00,
  0x00, 0x00, 0x00, 0x00};

My function for displaying uses Adafruit libraries
#include <RGBmatrixPanel.h>
#include <Adafruit_GFX.h>

Finally my Function:
void xbm32_n (const PROGMEM unsigned char bild[32],word cchsv) {

int i = 0;
while(i<32){

    for(int k=4*i;k<(4+4*i);k++)
    {

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

       int bit = ((pgm_read_byte(&(bild[k]))) >> ii) & 1;
       if(bit == 1) { matrix.drawPixel(ii+8*k-4*8*i, i, cchsv);}}}

   i++   ;
    }
   }

The inner workings are as follows:
The function draws each 32 bit row with the color chosen on the Panel depending on the 4 bytes in each "row" of the hex array.
Essentially 2 loops (to draw the row in byte increments) with outer while loop (to move to next row).
The calculation of the pixel positions can be seen inside the matrix.drawPixel(x-pos,y-pos,color-value) Adafruit-function, and were made up by experimenting long hours.
See for the whole .ino File here
Notes on the file

It also features among others

(like a displaying shifting 8x8 symbol-array saved in const PROGMEM byte IMAGES2[][8] used in the function bildlauf(1,...)

an updated function void xbm32_4c(char bild[32],word* cchsvar[4], int duration,int cseq[4])) where:

word* cchsvar[4] points to four color data values
cseq[4] is the sequence for displaying the colors in each panel
quadrant

The subdivision of the panel is realized via if() and else if() commands checking the conditions for positions:
x = (ii+8*k-4*8*i) </> some value  && y = i </> some value

Function input:

bild[32] is used for the hex array as in my case arab4[]
cchsv is a color data value . I am using sparkfun 32 LED Matrix and
found the following function for hsv color space to work well:
  word hsvcolor(int h, int s, int b ) { //Try HSV colors http://colorizer.org/
  int hue1, sat1, bright1;
  word result;

  hue1=map(h, 0, 360, 0, 1535);
  sat1=map(s, 0, 100, 0, 255);
  bright1=map(b, 0, 100, 0, 255);
  result = matrix.ColorHSV(hue1,sat1,bright1,true);

  return result;
}

Current Issues to solve:
I am using Font Forge to create XBM Files in helping me create the hex letter array, but found it very clumsy to export, as the width size must be a multiple of eight to adjust height by deleting 0x00 rows.
At the moment I am searching for easier ways to "correct" the exported XBM arrays (like using 8x8 Editor 8x8 Editor, only for 32x32 Matrices).
Is there a possibility for this?
Alternatively it would also help to create a function to truncate hex arrays to fit 32x32 dimensions somehow.
Additionally, in Arabic there is the issue of variant glyphs for the different letter positions (isolated, medial, initial, final). It seems possible to create byte arrays for all variants but "correcting" each bitmap so that a scrolling effect (I plan to upgrade to 64x32 LED Matrix) "adds up" visually seems daunting. I am happy for suggestion on realizing this challenge as well.
I am aware that there is a Adafruit function for bitmaps:
void Adafruit_GFX::drawBitmap()
I couldn't get it to work with my hex array, also the possibility on how to change quadrant colors or other subdivisions lead me to write my own version I modified from 8x8 Panel case. I am not sure whether there are inefficiencies in the code I have written, I therefore am happy for suggestions.

The solution to creating Arabic characters with typographic ligature and scrolling them, is:
Using the application RTB RichText to Bitmap :

Set width-size of bitmap in increments of 32*n while using a height
    initially bigger than 32  (saving the bmp will allow for cropping of rows so that bigger letters can be produced, a bit offset to fit height 32)
Saving the bmp and editing it (take care that bitmap rows are saved in rows, if not switch scanning line mode)
Also the byte    endian for output must be rightly chosen: ("Lsb" for pc-editing, uploading to    arduino for use in the function provided here, it is in
    "Msb")
 The cropped characters bitmap must be then reloaded into RTB Pixel Editor on a fitting canvas (generate an empty one) and set to a different scanning mode (rows now in columns) with byte endian Msb

Group the array of hex elements in pairs of four (you can use
notepad++ and  regex find:
(((0[xX][0-9a-fA-F,]{2})[,]){3}((0[xX][0-9a-fA-F,]{2})))
replace: {/1}

Using a suiting arduino scrolling function (on top of adafruit    libraries)

Insert 32x(4_hex) chunks of your bitmap data in the file provided
above as array element in:  const PROGMEM unsigned char
I[][32][4]= {{here},{here},...,{here}}
Adjust main loop code for scrolling direction (here r to l) via increment or
decrement and number of scrolls (panel-size is here chosen 32):
int es=64; while (es>0) {   scroller01(I,32,dpink,es,go);   --es; }
Verify if you need to load a chunk of your bitmap group to const
PROGMEM unsigned char I[][32][4] , so that scrolling is fluid and
does not jump when the arduino re-cycles

The Question got solved in detour via another question  in this exchange (see  here ). I am answering it to resolve parts of it.
The scrolling is slow when extended fully onto 64x32 Panels with arduino Mega 2560.
For a clip see:

  www.dropbox.com/s/qth8iuygra1wx9b/VID-20170210-WA0000.mp4?dl=0

 If somebody comes up with a more efficient,faster way, please do share!

Seems to get downvoted without explanation after two years. At least share your opinion when doing so.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Push to 2D array (log) but last value pushed is everywhere
I have this simple that is supposed to keep a log for me with a fixed number of entries. When I add to the log the oldest replaced is by the second oldest etc and the new entry added. Except when I add another entry both that and the one before have the same value (My C isn't any good, I'm more a ruby and lua guy).
What am I doing wrong here?
void setup(void) {
  Serial.begin(9600);
}

#define log_size 5
#define line_height 12
char *log_lines[log_size] = {"Hello", "World"};

void addToLog(char *text) {
  for(int i = log_size - 1; i > 0; i--) {
    log_lines[i] = log_lines[i-1];
  }
  log_lines[0] = text;
}

void printLog() {
  for(int i = 0; i < log_size; i++) {
    Serial.print(i);
    Serial.print(" ");
    Serial.println(log_lines[i]);
  }
}

void loop(void)
{
  char msg[20];
  sprintf(msg, "%d", millis());
  addToLog(msg);
  printLog();
  delay(1000);
}

The output after the first addToLog is
0 1000
1 Hello
2 World

second addToLog is
0 2001
1 2001
2 Hello
3 World

It is easy - in your log you store POINTERS to strings.
And you then create variable on the stack (ouch) and put its address to the log.
Then you leave the function (loop) (so that variable is forgotten and can be overwritten by anything). I will not say it is luck, that nothing uses the stack enought to make a problem before the loop is called again, as it disguise the problem. The POINTER in log_lines[0] points to UNALLOCATED place (where the variable msg once was).
Then the loop allocates variable msg (at the same place, as its previous run by the chance) so the POINTER stored in log_lines[0] (still pointing to the same place) points to the variable msg (and its content). By pure (bad) luck.
Then you overwrite the variable msg with a new value, so the log_lines[0] point to that new value.
Then you move the content of log_lines up, so the log_lines[1] now points to the variable msg (and its NEW value) as well as log_lines[0].
Then you assign log_lines[0] with address of variable msg (which it accidetally already contains)
Then you wonder, why variable msg accesed via log_lines[1] is exactly same as the (same) variable msg accesed vial log_lines[0] and why it contains the last (NEW) value, which you assigned into it.

Some of possible solutions are:
1) allocate place on heap (memaloc it) in the addToLog function, copy the text into it and store pointer to THIS place (and do not forget deallocate   last log_lines before overwriting it - if it is not null (as untinitialized values are all 0)) which could lead to (relativelly) expensive heap manipulations and possible memory fragmentation.
2) allocate log_lines as array of char arrays of given len, copy the content of each line in another loop inside addToLog and then copy(and possibly truncate) the text to the log_line[0]
3) keep static index of last used log_line and in addToLog just increment it (wrapping around the len of the array), then overwrite the line pointed by index with (truncated) text and in printLog just start cycle on the index and climb (wrapping around len of the array) until you are again at index (which you would not print again and stop)

Thank you for pointing out those three solutions.
The first on, in loop() was char  *msg = (char *) malloc(20); and you're right, the memory did skyrocket without free(log_lines[log_size-1]); in the addToLog function. Thank you.

That is easy too - you created new variable each time you went to loop() (every second as the delay(1000) on the end), but did not free that memory on the end of loop().  This is why you should (in this variant) allocate memory in the addToLog, copy the text there and deallocate the last log_line there. Otherwise you are heading to problems if you call addToLog more times in the loop (double free ot he same variable, storing the same pointer multiple times and overwrite the logged messages) as well as if you are not calling it at all (not freeing memory at all,skyrocketing heap).

Usually you should deallocate at the same level you allocate and each allocate should be paired with deallocate. Actually having msg as normal variable in loop() is good approach, allocate copy in addToLog (cause there are you copying a text to your array) and deallocate there the array rows from previous calls, when rolled out. This way you can use the log as it is meant - to log some history of interesting points and show it on request.

Here is a solution which does not use dynamic allocation nor does it
copy any log message. It's essentially a zero-copy implementation of
gilhad's solution 3. The idea is: instead of having an addToLog()
function that takes an already prepared message (which it would need to
copy), you have a get_log_buffer() function that tells you where to
write the message in the first place. This way you can snprintf()
directly into the right place in memory.
const size_t LOG_SIZE = 5;
const size_t MSG_SIZE = 20;

char log_stack[LOG_SIZE][MSG_SIZE];  // circular log buffer
size_t log_index;  // next available slot in the circular buffer

// Return the address of the next available message slot.
char *get_log_buffer()
{
    char *buffer = log_stack[log_index];
    if (++log_index == LOG_SIZE) log_index = 0;  // increment index
    return buffer;
}

void print_log()
{
    Serial.println(F("--------"));
    for (size_t i = 0, j = log_index; i < LOG_SIZE; i++) {
        j = (j ? j : LOG_SIZE) - 1;  // decrement index
        if (log_stack[j][0]) {  // should be a non-empty message
            Serial.print(i);
            Serial.print(" ");
            Serial.println(log_stack[j]);
        }
    }
}

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

void loop()
{
    snprintf(get_log_buffer(), MSG_SIZE, "%lu", millis());
    print_log();
    delay(1000);
}

Note that log_stack and log_index are zero-initialized by the C
runtime. Note also the use of snprintf() instead of sprintf() in
order to avoid buffer overruns.

The problem is, that user MUST limit the lenght of the message to the right size everytime. Which is possible to do right in small script, but it will be pain to do right if the log is in its own library and may dynamically react to aviable size of memory. Basically it is better, when functions/objects are responsible for thier internal state, than to rely on correct user input. One mistake then can do a lot of sideeffect, like overwriting other logs, other variables, stack and such, which are really hard to trace. So while this approach works, I would not recomend it if there is other way.

@gilhad: It very much depends on the use case. Obviously, you won't use an arbitrary string limit in a general purpose library. But in a self-contained program, avoiding dynamic memory allocation can make a lot of sense.

Yes, but it is easier to check (and change) on the one place, where you store the message, than everywhere in the code, where you want to log something. So I do not forbid this approach, but I strongly suggest it, as is less error prone and commonly better practice for someone starting to write programs in C and have this kind of problems. And you can see, that 2 of 3 variants in my answer are based on static allocation. But the author have to know, if he needs variable size string, or if fixed leght works for him better. I just elaborate on what he (or you) provided.

I personally would allocate just array of chars , trim messages to its lenght and manage two pointers on where the log starts and where it ends, deleting necessary number of lines to accomodate new message. So buffer would be used to max and history len would depend on size of respective messages. (and I would empty the buffer after dumping it to not have duplicate entries in the log print. And probabely started any log with timestamp too. But it is way more complicated to implement for someone not used to pointers and C strings)


text:
Get data from a running exe on my pc
I have made a button with an LED using an arduino micro. It's connected to my pc and when I hit the button, the LED activates and a recording on Reaper (digital audio workstation) is started. When I hit the button again, the LED turns off and the recording stops and is saved.
I want the LED to flash at the BPM rate of the project in Reaper. So it needs to read the amount of Beats per minute the project is set to.
Is there any way the arduino can read this value?
Without the flashing LED, the program works fine. Here's the code:
#include <Keyboard.h>

boolean toggle = false;
int inPin = 2;
int outPin = 3;

int state = HIGH;
int ledOn;
int reading;
int previous = LOW;

long time = 0;
long debounce = 200;

void setup() {
  // make pin 2 an input and turn on the
  // pullup resistor so it goes high unless
  // connected to ground:
  pinMode(inPin, INPUT_PULLUP);
  pinMode(outPin, OUTPUT);
  Keyboard.begin();
}

void loop()
{
  reading = digitalRead(inPin);
  ledOn = digitalRead(outPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  if ((reading == LOW) and (ledOn == LOW)) {
    state = HIGH;
    Keyboard.press((char) 128);
    Keyboard.press('r');
    delay(50);
    Keyboard.releaseAll();
    delay(300);
  }

  if ((reading == LOW) and (ledOn == HIGH)) {
    state = LOW;
    Keyboard.press((char) 32);
    delay(10);
    Keyboard.releaseAll();
    delay(100);
    Keyboard.press((char) 177);
    delay(10);
    Keyboard.releaseAll();
    delay(300);

    time = millis();
  }

  digitalWrite(outPin, state);

  previous = reading;
}

Never used this program, but apparently it has an API: http://www.reaper.fm/sdk/reascript/reascripthelp.html. If the program does not "publish" the BPM anywhere else where you could read with another software and send to the Arduino via Serial, you may need to write something to talk to the Reaper API and see if you can get it, after, just need to write some other code to send this value to the Arduino via the Serial Port (that's easy to find examples).

I just took a look at the website you provided me. I have been looking through all the variables you can use with Reaper and it seems that for C++ there is: bool GetTempoTimeSigMarker(ReaProject* proj);

There also seems to be: bool GetTempoTimeSigMarker(double* bpmOut)
I'm not sure if the ReaProject* proj means that it takes the tempo of the whole project or if double* bpmOut does that.

Great, now you need to write a software to call this function and "print" to screen. Next is to plug in a Serial library so you can send it to the Arduino while Arduino keep waiting for messages.

I'm kind of a beginner to the Arduino world as I got my first one 3 days ago (which was a fake arduino nano). I didn't do my research on what you could do with it and because of the ATMEGA328 it couldn't control my keyboard. I also poured a drop of solder on the crystal which was destroyed. I now have the (also fake) arduino pro micro. Great little thing.
I don't know however, how to get my code to communicate with reaper.

@Hendriks3D, if you have a hot-air part remover, or if the crystals are thru-hole, you could move the crystal from the fake to the one that needs a crystal.  Note that when ATmega328 fuses are set to use a crystal, you can't use it without a crystal without changing the fuse settings.

well, the one that's broken has a broken crystal. I'm not sure if it works, but when I ordered the arduino micro, I also ordered another 16mhz crystal. Its a big one. The one that was originally on the nano is very small. I hope I can use the big one as a replacement. I could use my nano for other thins.


text:
EEPROM put and get not working on ESP8266 (NodeMCU)
The Arduino documentation provides two examples to store data in the EEPROM.
https://www.arduino.cc/en/Reference/EEPROMPut stores data in the EEPROM and the EEPROMGet example reads the data back and writes it out.
These examples work fine on my Arduino Uno, but on my ESP8266 (NodeMCU) the EEPROMGet example code is unable to retrieve the data EEPROMPut should have stored previously. Instead it's just returning some random bits and bytes.

Any ideas? I haven't found anything about known incompatibilities related to the ESP8266 boards...

The ESP8266 doesn't have any EEPROM. Instead it emulates it using Flash.
In order not to wear out your flash you have to "commit" changes to the flash once they have been queued for writing - otherwise they will be lost.
Instead of using the Arduino examples you should be using the ESP8266 specific examples included with the ESP8266 EEPROM emulation library (but also here).

EEPROM for the ESP8266/NodeMCU
This is a bit different from standard EEPROM class for Arduino. You need to call EEPROM.begin(size) before you start reading or writing, size being the number of bytes you want to use. Size can be anywhere between 4 and 4096 bytes.
EEPROM.write does not write to flash immediately, instead you must call EEPROM.commit() whenever you wish to save changes to flash. EEPROM.end() will also commit, and will release the RAM copy of EEPROM contents.
EEPROM library uses one sector of flash located just after the SPIFFS.

what is size parameter? is it length of data we are going to write or its total size of EEPROM?


text:
Why do I get avrdude: stk500v2_ReceiveMessage(): timeout error when uploading to Arduino Mega?
I have an Arduino Mega clone and I haven't used it for a while. I remember it not working so when I plugged it in and tried uploading the code to it and sure enough it didn't work. So I plugged in an Uno and it worked. The Mega is a 2560 Atmel. Here's my code:

#define distanceForward A0
#define distanceLeft A1
#define distanceRight A2
#define distanceRightAngle A3
#define distanceLeftAngle A4
#define distanceBack A5
int talk = 2;

void setup() {
  Serial.begin(9600);
  pinMode(talk, OUTPUT);
  pinMode(distanceForward, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Front Facing
  pinMode(distanceLeftAngle, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Left Angle
  pinMode(distanceRightAngle, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Right Angle
  pinMode(distanceLeft, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Left
  pinMode(distanceRight, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Right
  pinMode(distanceBack, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, back
}

void hall_roam() {
  Serial.write("forward");
  if (analogRead(distanceLeftAngle) < 30) {
    Serial.write("right");
    if (analogRead(distanceLeftAngle) > 30) {
      Serial.write("forward");
    }
    if (analogRead(distanceRightAngle) < 30) {
      Serial.write("left");
      if (analogRead(distanceRightAngle) < 30) {
        Serial.write("forward");
      }
      if (analogRead(distanceForward) < 60) {
        Serial.write("stop");
        if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
          Serial.write("left");
          if (analogRead(distanceForward) > 60) {
            Serial.write("stop");
          }
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) > 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) > 60)) {
        Serial.write("right");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      } else {
        Serial.write("forward");
      }
    }
  }
}

void roam() {
  Serial.write("forward");
  if (analogRead(distanceForward) < 60) {
    Serial.write("stop");
    Serial.write("left");
    if (analogRead(distanceForward) > 60) {
      Serial.write("stop");
      Serial.write("forward");
    }
  }
}

void talkbb8() {
  pinMode(talk, HIGH);
  pinMode(talk, LOW);
}

void chill() {
  Serial.write("stop");
  talkbb8();
}

void loop() {
  if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
    hall_roam();
  } else if ((analogRead(distanceForward) < 60) && (analogRead(distanceBack) < 60)) {
    Serial.write("left");
    if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
      Serial.write("stop");
      hall_roam();
    }
  } else {
    roam();
  }
}

If there's a bracket out of place or something it's probably nothing. I'm talking about the characters. Is there anything in the characters that would screw up the upload like the three "!!!" problem I heard about or something like that. It's possible that the USB chip in it isn't recognized by my iMac. If so how do I fix that?

The error message basically means that the programmer is unable to contact the boot-loader on the device. The code you're trying to upload has no bearing on the problem.
There could be one of the four possible reason behind it. They are:

Wrong Port Selected:
If TX/RX led is not blinking, then you may have selected wrong port. If one of both of them are blinking then, you aren't using the wrong port. It might be worth checking again though, sometimes USB COM devices install on strange port numbers.
Board is not in Bootloader Mode:
The Arduino Mega is not executing the bootloader for some reason. If the programmer is not resetting the micro before attempting to connect, this might be the reason. Try to reset the board (press and release the button) while the programmer is attempting to connect. Sometimes software that runs in a tight loop will prevent the bootloader from connecting.
Barring that, the fuses might have gotten messed up or the code erased. You would need to reflash the bootloader and proper fuses, again, see the appropriate info page for your device.
Arduino Mega 2560 only: ATmega8U/16U software
Might not be working and would need reprogramming. See the Programming section on the info page, you will need the firmware and Atmel-compatible DFU (device firmware update) software on your computer toreflash the target.
Hardware damage:
There could be hardware damage to the board, AVR(s), or FTDI chip. Time to buy another board.

You can check this answer.

there are only two ports but when i plug in the one that works a third one comes up when with the mega it doesn't. could it be the usb chip

Non of these seem to be the problem or you didn't give the solution to them i don't know.

I tried all the solutions listed on this page:

changed ports,
checked correct port on Arduino IDE,
restarted,
reconnected,
bought a new arduino mega,
etc.

Nothing worked.
Finally gave up and used the web version of the Arduino IDE and it worked just fine.

If you have a timeout issue please ensure the crystal used on board is 16 Mhz.
change
mega.menu.cpu.atmega2560.upload.protocol=wiring
To:
mega.menu.cpu.atmega2560.upload.protocol=stk500v2
Thank you!
Solved my problem!

I had the same issues on MAC OSX El Capitan (older iMAC) using IDE 1.8.x and of course JAVA performed an update.  I regressed the Arduino AVR drivers to 1.6.21 (as instructed online) and this did not resolve the Timeout errors.
I gave up and used IDE 1.8.9 on my OSX MB Pro, and it worked flawlessly.
I think that Java versions and IDE drivers were the issue.

If you have a timeout issue please ensure the crystal used on board is 16 Mhz.
change
mega.menu.cpu.atmega2560.upload.protocol=wiring

To:
mega.menu.cpu.atmega2560.upload.protocol=stk500v2

I had this problem after changing crystal value and changing parameters solved the above problem.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Reading multiple DI pins in parallel as one byte/word
I need to capture a single parallel 'snapshot' from a 10-bit shaft encoder. I understand that I can read individual bits and shift them into position, but any given input pin might change while reading the bits sequentially, which would give an bogus value. In fact, given the asynchronous nature of the device this is guaranteed to happen on occasion.
I've read hints that it might be possible to combine pins into a 'port' for this purpose but I can't find any examples. Is this ability available only on certain processors? Or is there some way to latch the input pins while scanning them into a pair of bytes, to avoid them changing while I read?
If not I suppose I could use external latches but I'm hoping to avoid additional hardware.
It did occur to me that I could sync readings using an ISR triggered by a change in the LSB, but alas, this encoder outputs Gray code. :(

Which encoder? It seems odd you have to read all bits at precisely the same moment. You haven't said which Arduino you have but most of them are 8-bit processors so the maximum you can read atomically is 8 bits.

@NickGammon It isn't so odd, it's just asynchronous. I didn't specify which Arduino in case there are only some that support this, but I'd lean toward the Uno. I realize that with 8-bit ports I'd have to make two reads but I can handle the possibility of data smear with only two sequential reads as opposed to ten.

What encoder? Link to datasheet?

@NickGammon Sorry, but I don't see the point. I'm not asking anyone to diagnose at a different level or to solve any problems. It's a fairly simple question about reading data in parallel which could have many applications. Maybe we could forget the encoder and think of it more generically...?

If you would like to read multiple inputs, you can access port register directly. For 8 bit AVR:
DDRA = 0;            // set pins A0-A7 as input, modeInpit() in Arduino
uint8_t data = PINA; // read all A0-A7 inputs (8 bits)

To read more than 8 bits, you need 32 bit ARM based MCU/board like Arduino Due, other Atmel SAM, STM32Fxxx MCU etc. For STM32, there is Arduino like IDE available - http://www.stm32duino.com/
Even on 32 bit MCU you can read only 16 GPIO simultaneously (GPIO registers are 32 bit but handles 16 GPIO).

Moving over here... the reason I'm asking about examples is that what I've read is inconsistent. Some docs, including the two you reference, use different names for the port registers. Is there a "port A" and a PINA instruction? Not in most docs, which say that "port C" is for the analog pins and PINC reads them. Also, you reference "GPIO_xx designations" which I can't locate in the docs I have, as a way to limit ambiguity. Any docs for that syntax?

in AVR world, PINA and PORTA are both REGISTER names; they refer to same physical GPIOA (general purpose input output) pins belonging to A register (pin might designated as PA or GPIOA); for reading PINA is used, for writing PORTA register is used; so they are kinda aliases; same goes for PINB/PORTB, PINC/PORTC etc; exact physical pin and function (mostly) different on every MCU, so this is where the datasheet is needed; On Atmega328 UNO, PINC/PORTC (PC) are analog inputs (while on Atmega128 it is digital); GPIO is kinda universal naming for physical pins, IMHO it is preferred

Nice drawings here for some Arduino GPIOs

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

The 8-bit AVR processors can only read 8 bits atomically. This is indeed called a port. The Atmega328P (used in the Uno) organizes its I/O ports as ports B, C and D (I don't know where A went).
Exposed on the board are PORTB (bits 0 to 5), PORT C (bits 0 to 5) and PORT D (bits 0 to 7) - that's 20 pins in total.
Thus, port D is the closest you will get, as you could read 8 bits at once. However having said that, two of those bits are used for serial I/O so you couldn't use the serial hardware at the same time.
To read all of port D you could just do this:
byte foo = PIND;

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

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

I'm hoping to avoid additional hardware

Well, that's a pity.

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

It's not reluctance to disclose, it's a desire to avoid distractions. I know the hardware and how it operates; I'm constrained to use it; so the problem domain is 'reading data in parallel'. Thanks for addressing that, and for the pointer to the I/O expander.

Given the answer from @Flanker, would it be possible to combine a read of PORT D (which I gather uses the digital pins) with a read of PORT A (which I gather uses the analog pins) to get a 16-bit wide value in two reads?

I know the hardware and how it operates; - you might, I don't.

... with a read of PORT A - where did you find PORT A on the datasheet? I can't spot it.

it's a desire to avoid distractions - distractions like the people who are trying to answer your question knowing what hardware you are talking about?

I didn't find PORT A, it came from @Flanker's answer, unless I misread him. Is it not possible to do what he shows?

you might, I don't  No need to get shirty, it's not intended as an insult. I'm too well aware of the tendency for well-intentioned and knowledgeable folk to want to "solve the problem" instead of "answer the question", on the (sometimes reasonable) assumption that the questioner doesn't know what he really wants.or needs.

@Jim, there is register PINA (port input) not PORTA (which is port output) in my answer. BTW bad register designation from ATMEL, easily confused with (physical) port/pin meanings (for these better to use GPIO_xx designation)

@Flanker - Thanks, I confused the two by thinking of the generic term "port". If you can point to any docs or example code I'd appreciate it.

@JimMack Please check Direct port manipulation, also How to access IO ports and ultimately ATmega328 datasheet :)

I'm sure time has already passed for this persons project. But for those visiting this page for whatever reason (mine was different than the information here) here is a solution I would implement. Also this is assuming the individual is not willing to use a latched external buffer where they can read from it however they need to. Simply split the total pins among 2 registers making sure the following

The pins used are in sequential order to both the MCU and the encoder (gray coding will require some thought to this).
Group as many on a single register as possible and this will be the low order value.

Read from the low order value first (the one that will be changing at the highest rate). Then read from the high order value (where it will be far less likely to change between the low order and the high order read). You need to understand bit masks and bit shifting to do this...
uint16_t nEncoder = (PINB & 0x1F);   // Example if your 5 pins are the low ones on PORTB
uint16_t nEncoder = ((PINB & 0x7C) >> 2);  // Example if your 5 pins are 6:2 where you pull your set of pins off of PORTB then bitshift them down into their proper place.
then you read in the high order part
nEncoder |= ((PIND & 0x1F) << 5);  // Example if your 5 pins are the low ones on PORTD. However you pull them off of the next port, you will need to make sure you bitshift them into the upper 10 bits of nEncoder to get your final value.
In the above, you can see that the more bits (pins) you can use on your first register (port), the less likely your second read will have a pin change.
Gray coding will be different than binary. The above example assumes binary where the high order bit will change the least and the low order the most. Gray coding is specifically used because of how minimally the bits change in-between each number change (i.e. they are suppose to only have 1 bit change per number change no matter the number rather than 10 bits change when a binary count rolls over - i.e. it minimizes this exact problem). So for the original poster, most of this should be irrelevant (since they said they were using a gray code encoder).
But for those seeking an optimal solution (for binary counters or just because) where they cannot stick all pins on a single port. Splitting it between two registers with only two reads will optimize your read time and minimize the pin change possibility.

I mean, you could look up the port and the pin in the port and read in the portByte. This example does work:
//given two GPIOs on a port(PortC) eg: 12(right button) & 13(left button)
byte portByte = (*portInputRegister(digitalPinToPort(rightButtonGpio)));
rightButtonPinHigh = portByte & (digitalPinToBitMask(rightButtonGpio));
leftButtonPinHigh = portByte & (digitalPinToBitMask(leftButtonGpio));

However, in my experience, your output will look pretty much the same as if you had done two sequential Arduino blessed digitalRead. I suppose you might (in the example above) get the leftButtonHigh value 1 instruction ealier, but I don't know if the register can even update at that resolution.

digitalRead() can be super slow, something like 100 CPU cycles. In contrast, reading a port input register is a single cycle. And the register updates at the CPU clock speed, i.e. 16 million times per second on an Uno.


text:
How can I run HC-05 on 8MHz Pro Mini?
I run an Arduino Pro Mini on ATMega328 3.3V 8MHz, and I am unable to send data over HC-05 breakout board on this frequency, and on 5V 16Mhz, it has no issues.
The Arduino code is down below:
#include <SoftwareSerial.h>
#include <Wire.h>
SoftwareSerial BT(10, 11);
byte value;
unsigned long pmillis_bt = 0;

void setup() {
  Serial.begin(19200);
  BT.begin(9600);
}
///////////////////main///////////////////

void loop () {
  if (millis() - pmillis_bt >= 100) {
    byte Data[3];
    byte cmmd[20];
    int insize;
    char str[256];
    int i = analogRead(A0);
    value = BT.read();
    Data[0] = 'a';
    Data[1] = i / 256;
    Data[2] = i % 256;
    sprintf(str, "%d", i, Data[0], Data[1], Data[2]);
    Serial.println(str);
    if (value == 49) {
      for (int j = 0; j < 3; j++)
        BT.write(Data[j]);
      value = 0;
    }
    pmillis_bt = millis();
  }
}

Basically Arduino Uno Is working On 5v Voltage Level so you can Directly connect the HC-05 Bluetooth module to it using it 4 lines VCC,TX,RX,GND.
But in Pro mini 3.3 V level due to you need to Generic 3.3V To 5V 2 Channel Logic Level Converter Bi-Directional Module
using this you can easily convert the vlotage level.
if you have to make using simple component also using
SparkFun Logic Level Converter - Bi-Directional

You are probably using the HC-05 Module with a power regulator and levelshifter designed for use with Arduinos that typically run with 5V. What you need is the plain HC-05 as can be found on AliExpress. Those run with 3.3V but it can be tricky to use them in prototypes.

I do use the breakout board though, not the ones with the pins.


text:
Manipulating 3 IR led's on Arduino Uno
I have an Arduino Uno and 3 IR led's. Each of my IR led's works fine individually if I connect them to pin 11.
However I want to connect all 3 of the led's to the Uno and have them send different signals according to pin number.
e.g
IR LED 1 connected to pin 11 - send signal 0xABCDEFGH
IR LED 2 connected to pin 10 - send signal 0xSJKLMNOP
IR LED 3 connected to pin 09 - send signal 0xZXYRWVUG
I tried making my own code below but it does not work. If anyone has any pointers i'll be very happy.
//LED 1

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
        for (int i = 0; i < 11; i++) {
            irsend.sendNEC(0xABCDEFGH, 32); //Settings Menu
            delay(1000);
        }
        delay(1000); //1 second delay
    }

//LED 2

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
        for (int i = 0; i < 10; i++) {
            irsend.sendNEC(0xSJKLMNOP, 32); //HDMI Port
            delay(1000);
        }
        delay(1000); //1 second delay
    }

//LED3

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
        for (int i = 0; i < 9; i++) {
            irsend.sendNEC(0xZXYRWVUG, 32); //Switch Off Monitor
            delay(1000);
        }
        delay(1000); //1 second delay
    }

I don't have time to write a proper answer at the minute, but I hope this will get you started: break the problem down into parts. You have the first part working - you can send a code from one LED on pin 11.  Now try to send a code from one LED on pin 12.  You'll see that nothing in your code mentions the pin, so you need to understand how it's decided, or find another way to deal with using a different pin. Only THEN worry about using three LEDs at the same time.

I suspect 0xABCDEFGH, 0xSJKLMNOP and 0xZXYRWVUG are replaced with some valid hexadecimal numbers. I cannot see how repeating the sent command 11 times, 10 times and 9 times (in a for-loop) correlates to the pin number each LED is connected. There is a setup missing that declares which pin irsend supposed to use. Also that code will not compile because you define irsend, setup and loop three times. You need to combine the functions and perhaps need three instances of irsend (but I don't know for sure about that because I haven't used IRsend, yet).

I believe you don't understand what you are doing and you also don't tell us what you are trying to achieve. From your code I think you are trying to do a sequence of simulated IR remote presses. Why do you think you need 3 LEDs for that? Why can't you achieve that with only one LED? And why are you sending those commands every second unconditionally?

Can you tell us which IR library exactly you are using?

I am using  https://github.com/shirriff/Arduino-IRremote

I think what you have done is a perfectly logical thing to do.  You had three programs that worked and so you pasted them all into the same file and compiled it.  The compiler spat its dummy out of the pram and you didn't understand what the h*ll went wrong.  Is that about right?
// You only need to include each header file once
#include <IRremote.h>

// You need to define objects to represent the leds, we could use an array but for now we'll stick to the basics (makes the code a bit longer)
IRsend irsend_led1;
IRsend irsend_led2;
IRsend irsend_led3;

// This is where you do all the setup, it only gets executed once.
// You might need to assign the pin numbers to the irsend_ledX variables here.
void setup()
{
}

// This function is called repeatedly.  You can only have one of these.
void loop() {
    // I don't understand why you have this for loop, I think you think it may have something to do with pin numbers but I don't think it does.
    // I think the data is being sent multiple times, don't know why though
    for (int i = 0; i < 11; i++) {
        irsend_led1.sendNEC(0xABCDEFGH, 32); //Settings Menu
        delay(1000);
    }
    delay(1000); //1 second delay
    for (int i = 0; i < 10; i++) {
        irsend_led2.sendNEC(0xSJKLMNOP, 32); //HDMI Port
        delay(1000);
    }
    delay(1000); //1 second delay
    for (int i = 0; i < 9; i++) {
        irsend_led3.sendNEC(0xZXYRWVUG, 32); //Switch off monitor
        delay(1000);
    }
    delay(1000); //1 second delay
}

Give that a try, it might not work, but it will be closer to what you need, I hope I have explained it well enough.
Read the manual for the IR library and find out how to set the port numbers and if you can find out what that loop is about that might help.

I don't think he did have three programs which worked - I think he had one which worked. There's no clue in his code that he ever managed to get the second and third LEDs working, and yours won't either.

No, because of the pin assignment, anything else?

That's the main one.  It's also strange to be looping for a number of times equal to the pin number - probably a sign of not understanding something.

The loop is there because I want the signal to continuously pulsate so I can test it without having to repeatedly upload code every time I want to send an IR signal. Obviously it's not perfect but I would like to keep the loop there and in any other code someone modifies and posts. That's why I included it in that format.

That makes sense, when I read it I wasn't sure if it was a requirement of the library.  There is no problem with it being there, if you can separate out the pins you might even be able to do all three signals in the one loop.  However since loop() is a loop it could be that it is unnecessary, but that is up to you, you are testing it and know what is easiest.

@Matt has the main problem resolved, but I do want to add a note.
<IRremote.h> has the default IR led pin as pin 3 (last time I checked, maybe it has changed). I don't know how to change it, but if you are considering to use multiple IR leds, you might have to debug that problem!
So try to make 1 code work before you attempt to stick them togheter


text:
Servo motors not working when called upon using I2C
So I'm using this movement() function inside the slave Arduino Uno, which basically handles two stepper motors and one servo motor. When I call this function through the Serial.read() of the Arduino Uno, it works perfectly, both the steppers and the servo.
I have a master Arduino Mega interfaced with the Uno (mentioned above) when I send a wire message from the Mega to Arduino to run the movement() function in the Uno, the steppers work fine, but the servo does not work. Although, again I mention that when the function is called upon using the Serial.read() of the Uno, it works absolutely fine.
I'm using an Adafruit motor shield on the Arduino Uno as well.
OK so this is the Uno (slave code)
void setup() {
  servo1.attach(9);
  Serial.begin(9600);
  Wire.begin(5);
  Wire.onReceive(receiveEvent);
  Serial.begin(9600);
}

void loop() {
  //other stuff
}

void receiveEvent(int howMany) {
  while(Wire.available()) {
    char c = Wire.read();
    int From = Wire.read();
    int To = Wire.read();
    int x = 0;
    movement(From,To);
  }
}

int movement(int from,int to) {
  int X_From = from / 10;
  int X_To = to/10;
  int Y_From = from % 10;
  int Y_To = to % 10;
  /* First we have to get the motor position and move the motor to the from position */
  /* === START === */
  int diff_X = X_From - motor_X;
  int diff_Y = Y_From - motor_Y;
  int Y_Value = abs(diff_Y * Y_Steps);
  servoDown();
  if(diff_X != 0) {
    if(diff_X > 0) {
      /* Positive value means the X_Axis motor will move in the forward direction */
      int X_Value = abs(diff_X * X_Steps);
      X_Forward(X_Value);
    } else if(diff_X < 0) {
      /* Negative value means the X_Axis motor will move in the backward direction */
      int X_Value = abs(diff_X * 400);
      X_Backwards(X_Value);
    }
  }
  if(diff_Y != 0) {
    if(diff_Y > 0) {
      Y_Forward(Y_Value);
    } else if(diff_Y < 0) {
      Y_Backwards(Y_Value);
    }
  }
  Serial.println("Motor movement done");
  /* === END === */
  motor_X = X_From;
  motor_Y = Y_From;
  int diff_X_2 = X_To - motor_X;
  int diff_Y_2 = Y_To - motor_Y;
  int Y_Value2 = abs(diff_Y_2 * Y_Steps);
  servoUp();
  if(diff_X_2 != 0) {
    if(diff_X_2 > 0) {
      /* Positive value means the X_Axis motor will move in the forward direction */
      int X_Value2 = abs(diff_X_2 * X_Steps);
      X_Forward(X_Value2);
    } else if(diff_X_2 < 0) {
      /* Negative value means the X_Axis motor will move in the backward direction */
      int X_Value2 = abs(diff_X_2 * 400);
      X_Backwards(X_Value2);
    }
  }
  if(diff_Y_2 != 0) {
    if(diff_Y_2 > 0) {
      Y_Forward(Y_Value2);
    } else if(diff_Y_2 < 0) {
      Y_Backwards(Y_Value2);
    }
  }
  motor_X = X_To;
  motor_Y = Y_To;
  Serial.println("piece movement done");
  return 1;
}

void servoUp() {
  for (i = 100; i >= 0; i--) {
    servo1.write(i);
  }
}

void servoDown() {
  for (i = 0; i < 100; i++) {
    servo1.write(i);
  }
}

This is the master Mega Code:
void setup() {
  Wire.begin();
}

void loop() {
  //check if a condition appeared from sensor and then send the data to Uno to run the movement function through sendData()
  sendData(From,To);
}

void sendData(int From,int To) {
  Wire.beginTransmission(5);
  Wire.write('f');
  Wire.write(From);
  Wire.write(To);
  Wire.endTransmission();
}

Any suggestions what's wrong?

For the start - I am afraid, that you call the movement from interrupt, and so interrupts are disabled - so if movement uses interrupts, it is blocked. Next thing is, that I suppose the movement is running 'long time' as it manipulates some physical device (motor), which is slow compared to 16MHz of Uno. So you are blocking interrupt for 'long time', which is not good too. I suggest to have the From and To static volatile global (and some locking mechanizmus around to block concurent access) and use that from the loop where interrupts are enabled and not blocked.

Don't cross post questions.

If you are using Servo library, which uses timer (and so interrupts) for manipulating the servos then you may have the problem, that from loop it works (as interrrupts are enabled), but from interrupt (ISR) it does not work, because while serving interrupt (from I2C) all other interrupts are (temporary) disabled.
In receiveEvent() you are inside interrupt serving, so other interrupts are disabled and so anything, what depends on interrupts does not work, until you leave the function.
So it is the more probable cause, why your servo does not move, while called from receiveEvent(), while it moves, if called from loop()
And you wait inside the interrupt routine, until all Wire input is read fully and then while the (slow, as it probabely involves mechanical components like motors or servos) movement(from,to) ends (if it can even end with interrupts disabled).
The solution would be to do all movement(..) in the loop and int the receiveEvent() just store the already aviable values and put them into some static volatile variables, when transfer ends together with mark, that some change was done.
static volatile int from;
static volatile int to;
static volatile int changed;

void loop() {
int my_from,my_to;
  if (changed) {
     noInterrupts();  // critical, time-sensitive code here
       my_from=from;
       my_to=to;
       changed=0;
     interrupts(); // enable interrupts, so I2C, servo and such can work again
     movement(my_from,my_to);
  }
}
void receiveEvent(int howMany)
{
  if(Wire.available())
  {
    char c = Wire.read();
    from = readInteger();
    to = readInteger();
    changed = 1;
  }
}

Not totally perfect (mainly reading the Wire, which I would just tak as much as is ready to some buffer and decode it only when buffer is sufficiently full and syntactically correct, but if would make the idea here more complicated), but should work much better, than the current version.
Better version of `receiveEvent can look like this:
char buf[20];
int buf_pos;
void receiveEvent(int howMany)
{
  while (Wire.available()) {
    buf[buf_pos] = Wire.read();
    buf_pos++;
    if (buf[0] == 'f') { // starts with known command
      if (buf_pos>= sizeof(char)+2*sizeof(int)) { // have all data already collected
        from=0;
        for (i=0;i<sizeof(int);i++) from=from<<8+buf[sizeof(char)+i];
        to=0;
        for (i=0;i<sizeof(int);i++) to=to<<8+buf[sizeof(char)+sizeof(int)+i];
        changed = 1;
        buf_pos=0;
        } // end of buf_pos>= ...
     } else { // not started with 'f' (or anything it should know) - throw all transfer away as bad
        while (Wire.available()) Wire.read();
        buf_pos = 0;
     }
}

This is exactly what I did to resolve the problem earlier. Great!!

I don't know if this is the whole problem, but if you call sendData (0, 270) you are only going to send 3 bytes to the Uno 0x66, 0x00, 0x01.  You should be sending 5, 0x66, 0x00, 0x00, 0x01, 0x0E
The Uno only reads three bytes and receives:
    c = 0x66;  // 'f'
    From = 0x00; // 0
    To = 0x01; // 1
This is because Wire.write() and Wire.read() send/read a single byte (when you call them like this).  What you need is:
void sendData(int from, int to)
{
    Wire.beginTransmission(5);
    Wire.write('f');
    Wire.write(&from, sizeof(int));  // Write an array of 'size of int' bytes
    Wire.write(&to, sizeof(int));
    Wire.endTransmission();
}

int readInteger (void)
{
    int result= 0;
    for (int byte = 0; byte < sizeof(int); byte++)
    {
       result = result << 8;  // Left shift the current data (multiply by 2^8)
       result += Wire.read(); // Add the next byte as the LSB
    }
    return result;
}
void receiveEvent(int howMany)
{
  while(Wire.available())
  {
    char c = Wire.read();
    int from = readInteger();
    int to = readInteger();
    int To = Wire.read();
    movement (from, to);
  }
}

This code sends and receives the complete integers, so it should work.
Sorry I can't compile it, but I think its right.

Oh and like I said this probably isn't the only problem, I don't think you should read all this data from the I2C bus with a blocking loop in you interrupt handler.  And The interrupt should tell the running code (non-ISR) to do the movement by setting a static flag, rather than doing it itself.

Reading the data isn't the problem really, I'm receiving the data accurately. But the thing that I cant figure  out is, during the movement function the steppers work fine, but the servo isnot working. That is the main problem. I've Serial.print out the data received and it looks accurate

It you can read the data you must be using angles less than 256.

No worries I've resolved the problem now

good to hear, please share your solution as example for others solving similar problem, who find this question in future :)

authors: นายประสาน ภัทรประสงค์


text:
Building a low voltage disconnect w/ timer - need help with the timer
I'm trying to build almost exactly this device:
http://www.reuk.co.uk/wordpress/reuk-shop-low-voltage-disconnects-lvd/buy-reuk-programmable-low-voltage-disconnect-with-display/
It is a low voltage disconnect but has an interesting feature that requires the "cutoff" and "reconnect" voltages to be reached for 10 seconds before the connection is actually cut/re-connected to prevent premature status changes from voltage spikes/sags (Such as starting a car, or a motor with high start draw)
I need some example code that handles the timer portion. I can handle the "if this voltage is reached, disconnect the relay" (or transistor in the link I provided) part.
I need help making it "If this voltage has reached XX for 10 seconds then -do something-"

Assuming you have a function voltageIsReached(), here's a very simple way of doing it, which is OK if you don't have anything else to do in the mean time.
if (voltageIsReached()) {
    long end = millis() + 10000;   // 10s from now
    boolean voltageWasReachedFor10s = false;
    while (voltageIsReached()) {
        if (millis() >= end) {
            voltageWasReachedFor10s = true;
            break;
        }
        delay(1);
    }
    if (voltageWasReachedFor10s) {
        // Do whatever you have to do
    }
}

If you do have something else to do while you're waiting for this 10s state, you will need to adapt this, but I hope it'll get you started.

Write a function that has a static variable that keeps the previous time that the voltage has not been reached. That routine will read the voltage and reset the static variable to current time whenever the voltage has not been reached.
Such a routines can either return a logic value or a time value , depending on your implementation.


text:
How to run functions concurrently
I'm building a scale which reads a value (from a load cell) and outputs it on a LED screen.
There is a function for the scale, read which will read the value from the scale.
However this is not instantaneous - it uses the yield function to wait until the scale is ready.
The LED screen has a function, display which will display an integer on the screen with no delay. However, this lasts barely a fraction of a second, so it must be repeatedly called.
These functions as is are called one after another inside loop(), but it causes only a quick flash of the LED screen followed by a half second of reading.
How would I allow the LED screen to keep displaying a value while the scale reads? I know there's BlinkWithoutDelay - but I'm not using specific times. There is no instance of the function delay anywhere in the program. I also am not going to edit the library which reads the load cell.

What LED screen are you using, and how have you connected it?

Which libraries are you using and how does your code look like?

You should post a more complete code, since to make a sort of "multithread" you need to make non-blocking functions. But I think that the problem is not multithreading, but the fact that in the display function you mistakenly reset the display...

@frarugi OP stated that the display is LED (matrix?) and not LCD, and seems it is dynamically driven (have no reset) - so frequently updating it is important.

@Flanker yeah, the only way to have that behavior is through a LED matrix; since I never used them I did not think about that. Maybe it is a couple of 7-segment displays...

Please post your code and schematics.

There is similar questions answered a day ago - Multithreading with Arduino. What your are asking is multitasking or multithreading. Tasks have own loop and task scheduler stops and switches tasks periodically so they appear as if running simultaneously. Task scheduler in turn is usually driver by timer ISR, for AVR a 50-100Hz scheduler timer tick frequency is reasonable.
If there are 2 tasks with same priority (given task scheduler supports priority), they will spare MCU time ~ 50% / 50%. So if timer is 100Hz, each task runs 5ms and interrupted.
Surely task scheduler have overhead, but for small frequency it is negligible, less than 1%. There is no need to modify existing code/library, time sharing is organized transparently.
There are rules to follow when doing multitasking: for example when the scale related function is writing measured value of double type into some variable, this task might be interrupted (by scheduler) during the writing (when only half of the values is written) - and another task will see an incorrect value. The easiest way would be disabling the interrupts during such shared variable update. Google for "race condition", atomic operation, synchronization.

IMHO this is not the best solution, since it can break timings... The best solution is to look at the code and rewrite it in order to get a non-blocking function, so you can switch actions at predefined times without the so-called preemption

@frarugi87 maybe for this particular case updating the the display from timer ISR would be a better solution. To make a cooperative multitasking, OP has to rewrite the scale library code, which OP doesn't want to

I used a timer interrupt, which works fine.
However, when I implemented the solution and uploaded it to the arduino, I became unable to upload sketches to the arduino anymore.

Since it is unrelated issue, you shall create a new question (describe the problem, steps you made etc)

There is only one execution unit in this MCU so you can not truly run multiple tasks concurrently.
However, you can achieve the appearance of concurrency by running a higher priority task through an interrupt. For example, you cannot afford to have flickering disspplay. So set up a timer that invokees the display routine periodically. If you set the timer interrupt sufficiently small (over 25hz for example), the display will not flicker.
Your other routines can be run in other isr or in the main loop so they are interrupted by the display routine periodically. In a way that's fully transparent to you.

This solution is only applicable when the display set function is relatively fast, otherwise you can get problems in other parts of the program

Here is sketch in pseudo-code that can keep your display going and still make frequent weight measurements, without having to do any multi-threading or similar. The value of 'if a measurement is ready' (below) may come from a status bit in the scale, or simply a time difference using the millis() function; I don't know the specifics of your hardware.
I showed weight being an integer. Again, you may need to adapt this to your own hardware. But it is an uncomplicated process for displaying frequently to maintain the display, and reading whenever data is available so the display updates as you get new data, no concurrency required.
void setup()
{
   // initialize everything;
   // start the first measurement;
}

void loop()
{
   static int16_t weight = 0;

   // if a measurement is ready,
      // read the value and store it in 'weight;'
      // start a new measurement
   // endif

   // display 'weight' on the LCD;
}

Put the value variable outside the loop (as a global variable).
Then, call the display function BEFORE the read function.

This is not the best, but if should work fine.

And why should this help with the issue he has? void loop() { read(); display(); } and void loop() { display(); read(); } behave (almost) identically, at least in normal usage


text:
Remote controlled lights
I have a fixed roof light in my room that came with a remote control that can be fully taken apart. The remote control can switch the lights on or off using a radio system. I was wondering if there was any way to use my Arduino to control the remote control (through wires) to control the lights. I do not have any Arduino radio components so it would still need to go through the original remote. I have taken the remote apart and this is what it looks like:
http://go.hma-uk.org/dlt
The buttons are as follows: the top two (K1 & K2) buttons is to turn on/off a coloured LED but these are not important to me. The button K3 is to turn on/off the main light (I want the effect of this button being pressed to be created using the Arduino) and the button K4 is to turn all lights on/off.

Picture = 404. Attach the picture to the post using the picture button.

I have 10 pictures, link works for me

Well, not for me, and probably not for the rest of the world.

Ill see what I can do

Works better.  What voltage does the remote run from?

I don't know the voltage.

It will tell you on the battery.

I used to use gamepads as input device for USB many years ago. I simply soldered wires paralel to buttons and shortcut them to "simulate" the button press - it worked nice and reliable.
With Arduino - I would measure the voltage on the button in question with Voltmeter - if the voltage is less then Vcc of Arduino (5Volts), I would simply connect Arduino ground to lower side (negative) of the button and output pin to the high side of the button. Then I would set that pin for Input to have the button released (from Arduino side) and to LOW + Output to have it pressed. (maybe I would first shortcut the button with Ampermeter to see, that no more, than 100mA is sinking there).
If the sink is more, or the voltage is more, then I would use relay and shortcut the button with the relay, switching the relay with Arduino.
( something like this http://www.instructables.com/id/Home-Automation-How-to-Add-Relays-to-Arduino/?ALLSTEPS )


text:
ATtiny88 ADC reference voltage setting
I'm writing a simple application that reads voltage from analog input 0. Here is the code:
#define OUT 5
#define ADC 0

void setup() {
  ADMUX &= (0<<REFS0); //Setting reference voltage to internal 1.1V
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(0);
  float voltage = sensorValue * (1.1 / 1023.0);
  if (voltage>0.5) {
    digitalWrite(OUT,HIGH);
  } else {
    digitalWrite(OUT,LOW);
  }
}

When I apply 1 V on ADC0, the OUT pin is low. Seems like the reference voltage is not set properly. When I set VREF to VCC (5V), everything works fine.
I cannot find the mistake. Would appreciate any help:)
Edit:
Link to datasheet: http://www.atmel.com/images/doc8008.pdf

In your setup() function, why are you shifting a 0 and ANDing it?  Also, providing a link to the datasheet (so we don't have to use The Google ourselves) is appreciated.

Are you sure that you properly selected internal reference? IIRC, setting both REFS0 and REFS1 selects internal reference. So you need to replace that line with ADMUX |= (0xC0);

Sure, here's link to datasheet: http://www.atmel.com/images/doc8008.pdf

@Rohat Kılıç I believe there is no such thing as REFS1 in ATTINY 88

The statement
ADMUX &= (0<<REFS0);

AND's the current value of ADMUX with zero, resulting in a zero value, and stores it into ADMUX.
To clear the REFS0 bit in ADMUX without affecting the rest of it, one generally would instead say
ADMUX &= ~(1<<REFS0);

which will AND its value with the complement of 1<<REFS0.
However, you should use the statement
analogReference(INTERNAL);

instead of setting ADMUX directly.  One of the first statements executed in the analogRead() source code is
ADMUX = (analog_reference << 6) | (pin & 0x07);

which overrides reference selections made by just changing ADMUX.
Parameters INTERNAL and DEFAULT to analogReference() select either the 1.1 V internal bandgap reference or the default analog reference, Vcc.

Edit 1:  If you replace ADMUX &= (0<<REFS0) with analogReference(INTERNAL) in setup and it still doesn't work, you will need to apply some more-powerful debugging aids.  For example, check that you got the sketch to correctly compile and that you uploaded it ok.  Check that AVCC is connected to Vcc, preferably through a low-pass filter, as noted in datasheet sections §1.1.2 and §17.9, “Analog Noise Canceling Techniques”.  Then, try several voltage inputs to see at what level the LED comes on.  If it doesn't ever come on, look for LED problems using a simple sketch like Blink.  If it comes on consistently at some input voltage, work out what reference is being applied.

Edit 2:  Apparently the source code of analogRead() is different for ATtiny parts vs others.  The code that I see for it in ... /arduino/avr/cores/arduino/wiring_analog.c [your path may differ] is like the following (I've elided some comments and blank lines).
uint8_t analog_reference = DEFAULT;
void analogReference(uint8_t mode) {
  analog_reference = mode;
}

int analogRead(uint8_t pin) {
  #if defined( CORE_ANALOG_FIRST )
    if ( pin >= CORE_ANALOG_FIRST ) pin -= CORE_ANALOG_FIRST; // allow for channel or pin numbers
  #endif
  ADC_SetVoltageReference( analog_reference );
  ADC_SetInputChannel( pin );
  ADC_StartConversion();
  while( ADC_ConversionInProgress() );
  return( ADC_GetDataRegister() );
}

Some ADC_... functions and constants are defined in ... avr/cores/tiny/core_adc.h; and which definition of ADC_SetVoltageReference() is used depends on conditional compilation.  For a definitive check on how analogReference() is defined for your part, look for analogReference() within the assembly listing of your program.  Obtain that listing as explained in several Arduino SE answers, for example in the  “Making assembly listings” paragraph near the end of my answer to question #33033. Also, a forum.arduino.cc thread from late April 2016 has some discussion of reading ADC inputs on tinys; I don't know if it's relevant.

@EmKa, and does it work?

OK, I put analogReference(INTERNAL) instead of ADMUX &= (0<<REFS0) in setup section, but still it doesn't work:( @jwpat7

@EmKa, see edit 1.  What test equipment do you have?  DVM?  Scope? Freq. meter?

I have a scope. When I use VCC, it works, well more or less fine. But I want more detailed measure, that's why I want to use 1.1 internal reference voltage. @jwpat7

When I use "analogReference(INTERNAL)" the output pin is always LOW. However with VCC (5V) it works more or less fine. There's a slight mistake, but it may be due to the fact, that I supply the uC from programmator, and it provides voltage under 5V. In calculations i use 5V @jwpat7

And the sketch is successfully uploaded and compiled every time. Maybe it's sometihng due to the fact that I use ATTINY 88? I mean, for this specific uC the fe. analogRead function may function differently? @jwpat7

@EmKa, see edit 2.  And please feel free to mark this answer (click green arrow)

In your setup section, you want to set or clear all relevant bits in admux.

Is it a question?


text:
How to identify connection lost on HC-06?
I am making an RC car on Arduino Uno. I have connected an L298N motor driver to an Arduino Uno to control 2 DC motors. I also connected an HC-06 to the Uno to receive commands from an Android smartphone. Everything is working fine. But if a connection is lost (because of low battery or disconnected on Android application), when the RC car is moving it is not stopping. It stops only when there is connection and "s"(stop) command is received via Bluetooth.
int in1 = 4;
int in2 = 5;
int in3 = 6;
int in4 = 7;

void setup() {
  Serial.begin(9600);
  pinMode (in1, OUTPUT);
  pinMode (in2, OUTPUT);
  pinMode (in3, OUTPUT);
  pinMode (in4, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    int command = Serial.read();
    move(command);
  }
}

void move(int command) {
    if (command == 'f') forward();
    else if (command == 'b') backward();
    else if (command == 'l') left();
    else if (command == 'L') leftback();
    else if (command == 'r') right();
    else if (command == 'R') rightback();
    else if (command == 's') stop();
}

Now what I want is to identify whether there is connection or it is lost. For example:
if(Serial.connectionLost()) stop();

Is there such a function to identify the connection state? If not, is it possible to implement this function in another way?

My first one or couple of HC-06es brought its LED signal out to a pin on the base board, labeled "STATE" on mine. I tested the LED state on every loop and if it was changing regularly, took that to indicate whether it was waiting for a connection.
Later modules no longer bring out the LED signal but it is available on module's edge-pin 24, according to a (now 6yo) datasheet.

By cutting the plastic sleeve and bringing out the signal to the baseboard again, you use it to monitor the connection.

Two possible ways I see:

Connect the HC-06 LED anode (or cathode, depending on how it's driven) to an Arduino input pin. Since you can tell from the blink frequency if the module is paired with your phone or not, you can use that (through interrupts maybe) as a means to know if you're still connected to your phone.
Find a way to configure the android app (or write your own app) to either regularly ping your Arduino or to respond to ping requests from the Arduino. If the Arduino fails to get a ping request (in the first case) or a ping response (in the second case) after some pre-agreed interval, it decides the connection has been broken and halts the RC car.

Second way is less messy but may require some android programming skills on your part. I remember coming across an app in the Play Store that sends '#' constantly even when idle, with your own characters in between. That would work as well as a ping, if you could find something similar, and the only programming you'd need to do would be on the Arduino's side.

The second option is also often known as "Keep alive". Send a char from the Arduino to the Android App, and the Android App send a knowledge back, Example : Arduino send "Alive" -> Android. Android reply "Yes" to the Arduino.


text:
Arduino and ESP8266 Two-way Communication
I've searched the internet quite a bit and all I find is how to make two esp8266 communicate. What I am trying to do is connect a single esp8266 to the arduino and have a two-way communication between them.
I want to send and receive data on both the Arduino and ESP8266. The concept is to send data to the esp8266 over WiFi connection and then send that data to the Arduino. The Arduino will manipulate it and send it back over WiFi.
I feel like this would be a common beginner example to have a two-way communication over a TX/RX connection, but I can't seem to find any. All examples I find are strictly one as sender and other as receiver.

Are you using the AIThinker AT firmware for the ESP8266?

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)

The best way for connecting ESP8266, Arduinos and devices like displays, RTC, etc., is using the serial protocol I2C.
I2C is a master-slave protocol. In this case, ESP8266 will be your master, and every other device (including Arduino) will be a slave. Every slave had an address, for id purposes. You can have up to 127 slaves, in theory, but real limits is determined by space, distance, capacitance, etc.
Only masters can initiate communication, so you have to program your ESP8266 to poll the the Arduino for sending back the processed information.
Connection is simple. For a I2C device (slave or master), you need Vcc and GND, plus two lines for communication: SDA and SCL.
For programming, you have lots of tutorials and examples on how to use I2C.
Both ESP8266 and Arduino (an many others MCU I think) can speak I2C. I strongly recommend you to adopt this protocol for everything. If you want to buy some device (like a display), always looks for the I2C version.


text:
Replace Wire library with TinyWireM
I want to integrate Pololu's vl53l0x Time of Flight distance sensor into a project of mine. They created a library to interface with the vl53l0x over I2C, which works great on my Uno. The only problem is that Wire.h doesn't work on the ATtiny85.
TinyWireM is a replacement library for Wire that I think would be compatible. My question is this: how can I go about replacing all the calls to the Wire library with calls to the TinyWireM library? Is it as simple as replacing all instances of Wire with TinyWireM? Is there anything else I need to do to make the library ATtiny85 compatible?
Thanks!

States:  Minor changes for consistency with the Arduino 1.0 Wire library (e.g. uses write() instead of send()). Buffer size slightly increased for Adafruit_LEDBackpack use.

In fact, there would be nothing to do now I guess, as TinyWireM is now included tiny boards packages.
If you just include Wire as usual, it should work as on an UNO.
Except for setting a different clock, if I remember well, it is fixed to 400kHz.

I can't guarantee it will work, but it is probably possible to just modify the library. You can find the source code for that ToF sensor library here:
https://github.com/pololu/vl53l0x-arduino/blob/master/VL53L0X.cpp
The first step is to find the reference to Wire.h (line 7 in that file) and change it to TinyWireM.h. After that, you would need to find the functions that call the Wire library and replace them with the appropriate TinyWireM functions instead. Those begin at line 284 (Wire.beginTransmission(address);). You can find the source code for TinyWireM here (which should tell you all of the functions in the library):
https://github.com/adafruit/TinyWireM/blob/master/TinyWireM.cpp
So Wire.beginTransmission(address); would become TinyWireM.beginTransmission(address); and Wire.write(reg); would become TinyWireM.send(reg);
I'm not sure if that's all of the solution, but I think that's a good start.