text:
RS485 Multimaster Communication with collision avoidance
I'd like to know if there is an easy way to implement communication between multiple arduinos that avoids collisions using the RS485 module.
My setup would have multiple masters that send messages to only one slave that performs a task upon been given the message.
I've tried researching some libraries for this, but they normally don't fulfil the multimaster requisite, nevertheless I found this library which apparently does implement what I need, but I haven't been able to understand how it works.
My current options are either finding an easier library that is capable of doing what I need, learning how to make the linked library work (which I have already tried) or building my own serial communication protocol that implements collision avoidance and a multiple master configuration.
What path should I follow? Can you give me any recommendation for any of the paths I'm suggesting? Is there a better way of implementing this type of communication?

Collision avoidance is a tricky subject. You can never completely avoid collisions - all you can do is work out how to a) detect them, and b) recover from them.
There's many different ways of doing it, and how you implement it is very much dependent on what your hardware can do, and how you are actually using the protocol.
The best way of detecting a collision is to arrange it so that your master is always reading the bus even when it is sending. You require separate receiver and transmitter modules, so that as you place a byte on the bus you attempt to also receive that byte. If it doesn't get received, or the wrong byte gets received, then you have a collision.
That is a 100% guaranteed way of detecting a collision as it happens. If you know that what you sent didn't make it onto the wire properly then it collided.
A simpler scheme is to be watching the bus before you send. If there has been no sign of any traffic for more than a certain threshold time then you can assume that the bus is currently quiet. You can then try and send your data. You don't know if it got through OK though, since something else could have decided that the bus was quiet long enough for it to send too.
So you would have to have some kind of ACK signal coming back from the other end that says the packet got received OK. Keep retrying until you get that ACK back. Of course, the ACK could be colliding as well, so it may have been received, but you just haven't been told. So your remote device would have to be able to gracefully handle receiving the same packet multiple times and discarding (yet still ACKing) the repeated packets.
What you should do when you do detect a collision (or fail to receive an ACK) is also kind of tricky.  You have to wait and try sending again. But if there are two devices both waiting to send again, how can you be sure that they won't both be waiting for the same time, and thus collide again?
You have to ensure that both devices delay for a random period - and make sure that the random period truly is random. Using the default random() function, unless you can seed it from a truly random source of entropy, will generate the same sequence of numbers for all the devices - so each device would get the same "random" number. And collisions ensue.
So you see, you can't just throw a random library at it and say "This library will stop collisions" - the best you can say is "This library can help reduce collisions, detect them when they do occur, and gracefully recover from them."
For the library you link to it appears to attempt to implement the latter system:

Collision avoidance is implemented through the assignment of a message priority. A node will not start transmission before the bus has been idle for a time determined by the priority. Note that the highest priority is given to messages with the lowest priority number.
Collision detection is implemented by read-verified-write, i.e. all data written is checked on the fly for proper echo-back. If the software detects a frame error or a data mismatch when the echo character is received, it will disable the RS485 transmission and flag the collision status. The included transaction management will resend the message after the bus is idle again.

It waits for the bus to be free of traffic for a specific amount of time (the time is variable depending on the message priority), and expects the message to be sent back again as a form of ACK.
It makes no mention of random back-off times though to avoid collisions between different masters sending messages with the same priority.

There is a ready out the box solution documented in https://github.com/MichaelJonker/HardwareSerialRS485/wiki (This wiki describes the library you referred to).
The problem is quite complex: collision avoidance, collision detection and message retrial, message priority and message filtering. But the library solves it all. The software even provides a solution to interface a host (PC or Android) to the RS485, providing the same features.
In ‘understanding the library’ there are two aspects: how it works, and how to make it work.
The library itself is non-trivial (because the problem is also non-trivial), so to understand how it works is also non-trivial (Majenko, in his answer, gave a nice functional description of some of the features that are implemented by the library. The actual implementation has additional complications due to the direct interaction with the USART at interrupt level.). I guess you do not want to know (in first instance) how it works in such details.
However, the author (me) went to quite some detail to document how to make it work. But I reckon that documentation may be difficult to follow if the documentation does not match the expectations of the reader.
So I would be very interested to improve the documentation and to match the expectations of new users. However, here I need your help (or anyone interested) in pointing me out what and where I can improve.
The preferred way to contact me on these matters is by creating an issue on my Github project page:
https://github.com/MichaelJonker/HardwareSerialRS485/issues
BTW one of the issues addresses the same topic.
I guess that you need to create Github account in order to submit issues. Alternatively, you can contact me through this site (However, I might be less reactive through this channel).
Best regards
MichaelJonker

I did a post about rolling masters here on Arduino Stack Exchange.
The general idea is that you can set up multiple Arduinos to take turns becoming a master, based on waiting for its own "turn" in a time-based sequence, with provision for recovering from one of the units not responding.

I thinks the easiest way for software is not use any software do this at all, using a hardware controller chip/module instead which dedicated to support multi-master and arbitration for RS485 (the same way as CAN bus).
There is a protocol, named CDBUS, witch has stand-alone controller to do the work for you, which is very simple, I can even transfer video stream through it, details:
https://github.com/dukelec/cdbus_doc (Introduction)
https://github.com/dukelec/cdbus_ip (Protocol details & FPGA IP core)

You can also achieve this protocol by software only, if you don't care the speed or CPU usage.
Update: connect the CDCTL-Bx controller to an Arduino:

authors: บุรินทร์ จันทร์แก้ว


text:
Arduino IDE "Tools > Serial Port" grayed out (Ubuntu)
I know this has been asked before, but no one's solutions I've seen have worked so far. I just got started with Arduino and downloaded Arduino IDE from the Software Center. When trying to to set up my Serial Port, the option in the toolbar is gray/unaccessible.
I also downloaded it as a tar.xz instead of from the Software Center and had the same problem.
When I plug in my Uno, the green light turns on so I know it's being connected at least.
One solution I saw said it was a problem with my user group. However, I entered
sudo groups <username>
and came up with <username> tty dialout sudo audio video plugdev input

so I think my groups are okay, right?
Anyway, I would really appreciate some help if anyone knows of a fix. I run 12.04 Ubuntu (I recently re-installed trying to fix this problem; I'm going to update to 14.04) on a Chromebook.

To investigate this, edit the output of ls -l /dev/ttyUSB* and ls -l /dev/ttyACM* (done while the board is connected) into your question.  Also if you recently changed any group memberships make sure you have logged out (or more simply, rebooted) since.

Sorry, can you clarify? I input ls -l /dev/ttyUSB* as well as ls -l /dev/ttyACM* into my terminal and it simply said it was not a directory. Thanks for commenting.

If neither of those is turning up anything, then it sounds like nothing is recognizing your USB serial device.  You can look for differences in the output of lsusb when it is and isn't connected, or you can check for error messages shortly after connection with demsg.  At this point it could be anything - bad board, bad cable, damaged connector, missing kernel modules, or bad/atypical rules for udev or similar.

Within /dev the only "tty" files I have are "tty" and "tty8." Does it seem like I'm missing something?   EDIT: I damaged one of my USB ports last year, though I'm using the other one so I don't think it's that. Thanks anyway

I did what  Chris Stratton's comment suggested,

To investigate this, edit the output of ls -l /dev/ttyUSB* and ls -l /dev/ttyACM* (done while the board is connected) into your question. Also if you recently changed any group memberships make sure you have logged out (or more simply, rebooted) since.
  If neither of those is turning up anything, then it sounds like nothing is recognizing your USB serial device. You can look for differences in the output of lsusb when it is and isn't connected, or you can check for error messages shortly after connection with demsg. At this point it could be anything - bad board, bad cable, damaged connector, missing kernel modules, or bad/atypical rules for udev or similar.

and there was no difference between the output of lsusb with or without the arduino in it (arduino Mega 2560, and my pc is debian 8.6). I tried it with a diffrent cable but that made no difference. I tried it with an other arduino (uno) and then I did saw differnce in lsusb and I could select a port. My mega had the 'on' led on. So even though lights are on and/or binking, it might be that your arduino is broken. If you can, try it with an other arduino. Otherwise you can try an other cable and usb port on your pc.

source: Stack Exchange

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

sort: votes


text:
Using Sprintf() to left pad a string?
I've been at this all day, and I just can't seem to wrap my mind around how to use sprintf() to set a width for my string so that my characters are right justified.
What I'm trying to do is scooch my output over to the right on my touchscreen when the value is positive.
My output string is always a predictable length, so it seems like it should be easy.
I tried concatenating a string with just a space in it, and every other way I could think of to add a space to the beginning of my string. No luck.
char stringval[8] = 1.08;
char juststringval[8];
            if (hashpos > 0 && hashpos < 10) {

                sprintf(juststringval,  " %5s" , stringval);
                Serial.println(juststringval);
            }

output:
1.08 (no spaces in front)

In case you're curious why I need to use a string, my touchscreen will print floats, but my library won't rotate them properly.
Only strings can be rotated the way I need them.
Isn't there some simple way of doing this?
EDIT:
It seems I can use the width trick as long as I include some character besides an empty space.
For example:
void setup()
{
char stringval[33] = "1.08";
char juststringval[33];
char space[] = "rr";         ////THIS WORKS: OUTPUT IS  rr      1.08
float hashpos = 1.08;
if (hashpos > 0 && hashpos < 10) {

    sprintf(juststringval, "%s  %7s", space, stringval);
    Serial.println(juststringval);
}
}

void setup()
{
char stringval[33] = "1.08";
char juststringval[33];
char space[] = " ";     ////THIS DOESNT WORK. OUTPUT IS 1.08 LEFT JUSTIFIED
float hashpos = 1.08;
if (hashpos > 0 && hashpos < 10) {

    sprintf(juststringval, "%s  %7s", space, stringval);
    Serial.println(juststringval);
}
}

But I can't live with other characters in my string.
Isn't there something I can do?

Right justification is the default. Have you tried printing another string above or below it to compare?

Yes, and the default is left justification. When you print something on a new line, it starts on the left, just like words on a page.

Does it work if you supply a left-padded string?

No, it's always as far over to the left as possible. Both in my serial port and on my touchscreen.
Even if I artificially insert spaces into "stringval"

Printing in general starts at the left, but within the field described by the format spec - %5s in your case, the string will be right justified within that 5-char field (assuming the string is 5 characters or less). How wide is your screen? If you're trying to right-justify to the width of a 20-char screen, f/ex, you'll need a (20+1) char buffer, and execute:sprintf(buffer, "%20s", stringval); Serial.print(buffer); This will print a line of 20 characters, space padded on the left, ending in your "stringval".

My text begins at a certain pixel coordinate on the screen. Whenever my output lacks a minus sign, I need an extra space. But what I'm saying is that this method does not work. In both my serial port and on my touchscreen, the output is always as far left as possible.
And unfortunately I cant get away with changing the starting coordinate.

xxprintf() functions don't know about algebraic signs (or any other numeric feature) within strings. For that, you'll have to make a conversion to string from some numeric format that observes the (minus or space) convention for printing signs. As to right justification, I just ran your code, tweaking the field width, and printing to the Arduino IDE terminal window. The output did indeed move farther to the right with larger field widths...

... However, I first tested it in Eclipse, whose terminal uses a variable width font, and the spaces were tiny enough not to make much difference. With the Arduino IDE's terminal and a fixed-width font, it was much more obvious.

@JRobert- I'm currently using Visual Micro for Visual Studio. And my problem isn't with detecting the minus sign. That's unrelated. But I wonder if it's just a quirk of my serial monitor.

It WAS a quirk of my serial monitor.

I just tried and to my surprise a format string of "% 5s" actually prints leading spaces if the string is shorter than 5 characters.

The mistake in question and in comments (except of Bigoldsofty's comment), is missing character for justifying. This character should be in format string before the required width. "% 5s" not "%5s"

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


text:
What is VREF pin?
Was searching for some help on connecting Flir camera w/ Lepton board to arduino and found this thread

for power you can reroute the 3-5V to the VREF pin, then you have a nice clean solution.
You have to use a Ardunio with at least 16k or ram so you can buffer the image.
Was that a typo and he meant AREF?  If so would the VIN from the camera be connected to the VIN on arduino otherwise?
Thread:
https://forum.arduino.cc/index.php?topic=266361.0

VREF normally means Voltage REFerence.  Such pins are usually associated with ADCs (Analog to Digital Converters).  For example a 3.3 volt microprocessor may have a VREF pin fed by 2 volts.  The 10 bit ADC inside the microprocessor sees this as the upper limit.  That is, a 2 volt input to the ADC will produce the maximum value or 2^10 or 1024.

Yes, he meant AREF.  What he is showing there is the board plugged direct into the Arduino's header, but the VIN of the Lepton board connects to AREF not a voltage pin. By connecting your supply voltage (5V) direct to that AREF pin you are then able to provide power to the Lepton board, and it has no noticeable effect on the Arduino since connecting 5V to AREF is a perfectly valid thing to do (though pretty pointless).
AREF and VREF are both pretty much interchangeable. Analog REFerence, and Voltage REFerence. It could be said that one is the Analog voltage REFerence, and the other is the Voltage REFerence for analog. Some chips call it AREF and some VREF. Some even provide VREF+ and VREF- or AREF+ and AREF- depending on the complexity of the ADC in the chip.

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


text:
Sending a text message through a arduino wifi shield
I am using an Arduino uno and need to send text messages and email messages from the device based on certain events occurring.  I have the logic figured out of when to send the text message or email but don't know what shield I need to send these messages.

Do you know how to send them?

No I don't.  This is all new to me

Figure that part out first.

In today's world, you will realistically need an external service provider for both wifi-to-SMS gatewaying and also simple email as most most recipients' email services will conclude messages arriving directly from stand-alone devices are spam.  You can do small-volume SMS directly with a GSM modem if your plan allows.  But in general you should probably pick the service before you pick the hardware.  Do try to select something that is both secure but does not require extremely heavyweight authenticiation libraries on your embedded device.

So, with a valid connection, could I send an SMS using Twilio? It's an online software that uses python to send SMS. So technically if I had an ethernet connection using a shield, I could send a text using that program correct? *I am using an Arduino Uno by the way.

Sending an email you need a network connection of some form.  Options include:

Ethernet Shield
WiFi Shield
GSM Shield (can be expensive, but will work almost anywhere)

To send a text message you need access to a text message service. That can either be directly through a mobile phone operator or through an on-line SMS gateway service. For an on-line service the options are as above, since it's almost the same as sending an email (in fact, some gateways offer an email-to-SMS gateway option). For direct mobile provider access you can only use a GSM shield.
So really it boils down to how mobile you need it to be, and how much you are willing to spend (both on the initial hardware outlay and service provider fees and charges).

In one of project I had seen recently, they used esp8266 for home automation and used TEMBOO.com to send SMS. I am sorry I can't help u further than this, but i am sure, Google will..
You can also refer this tutorial from adafruit on sending an sms with Temboo
https://learn.adafruit.com/sending-an-sms-with-temboo/

If you are trying to send test messages and emails over INTERNET using ETHERNET or WIFi you might need some REST API. There are two ways to get that part done.

You might create your own REST API that contains some AUTHENTICATION KEYS, USER ID, RECEIVER ID etc for emails and same for test messages.
You can use third part REST API that provides these functionality.

I am attaching some link you for help that will tell you how to send emails and text messages over internet.for emails For Text Messages
NOTE :- Email api might get expired, don't get stuck over it found some other ways or third party API for that.

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


text:
Power motor with Uno
I am trying to power a small peristaltic pump using an UNO R3. I have it powered using usb, and I tried running the blink program to see if I could power it using digital write, and extended the delay to troubleshoot voltages using a multimeter. The motor doesn't do anything connected to the digital pins even when the digital write is set to high. If I connect the motor to the 5 V power pin the motor turns on so I know 5 V is enough voltage. I've looked at tutorials for DC motors and they explain how to set it up with motor reversing using components I don't have, and I don't need it to reverse. How can I get the motor to turn for a specific length of time?

Most likely the motor you are trying to drive requires much higher current than what the UNO can provide through its digital outputs.
Check out this summary to find out detailed specs for the I/O ports.
What you could do is to draw power from the 5V line provided by the Arduino. If that can drive your motor, then use the line to power an output stage, driven by the digital I/O. See this example.
In general, the idea is that the digital I/O provides the control logic, while the output stage provides the power required by the specific load.
The typical loads that can be driven directly by GPIOs are low power LEDs.
Anything that involves moving parts is generally out of reach, power-wise.

Thank you for your reply, I managed to get it working using your information coupled with a tutorial from youtube found here: https://www.youtube.com/watch?v=sOz41WQF7wE . Instead of a mosfet I used an NPN transistor, but ran too much current and blew up the motor, oops. Next time I'll use use your 5v suggestion since it is indeed able to be run well on that voltage. Thanks again!

Driving motors in a safe way is a problem on its own. Especially if you want to implement more sophisticated control, like variable speed and/or direction. During some transients the motor can start acting like a generator and pump current back into your driving stage, which might result in damage of either of both of them.


text:
Can an arduino tell between being powered by USB or by the jack?
I have an arduino mega that will be communicating through serial to a pc. One of the things I want it to tell the pc is whether or not it is connected to a wall power to 12V converter (where there is a switch between the arduino and the wall power). I was just wondering if there was a way to do that in software without having any additional hardware.
Thanks!

No, you can't do it without extra hardware.
You need to pass VIN through a voltage divider so it sits within 0-5V when powered by 12V, then feed that into an ADC input. Protect the on-board voltage regulator with a diode between 5V (anode) and VIN (cathode). Then you can measure the voltage on VIN and make a decision on if it is around 4.5V or 11.5V
A 22K/10K voltage divider will reduce 12V down to 3.75V, which gives plenty of "headroom" for over-voltage situations (where your 12V unregulated power supply actually provides, say, 15V):

I don't think the diode is needed. You say it is needed for protection. Are you sure the diode is needed?

Yes. Without it you will be drawing current backwards through the 5V voltage regulator when powered by USB. The diode bypasses the regulator when VIN is at a lower voltage (i.,e., not connected) than 5V.

Ah, oh well. Thanks for the hardware implementation too, at least its super simple!


text:
How to modulate my IR sensor?
I'm looking to use a simple IR sensor out in bright sunlight, which means hell lot of distortion. Is there any way I can modulate it using my Arduino UNO so that it isn't affected by sunlight and other ambient light sources?
The IR sensor is just like this one.

You modulate the source, not the sensor.  Modulation is basically blinking an LED really fast, typically around 36-40 KHz - and is ideally done with a hardware timer rather than delays, but the latter is possible.

@ChrisStratton and is that possible with my sensor? If yes then how?

If you want to do analog IR measurement in the presence of noise, you probably want not only a modulated source, but a synchronous detector or lock-in amplifier.  I don't see much engineering detail of your board, but it looks a little simple to implement that.  An almost entirely software solution should be possible, but will require learning quite a bit in order to write.

There is little information on the Amazon page about these devices.  Only that the output is digital (only on and off) and that the sensitivity is controlled manually by an on board pot.  It would appear impractical to enhance this type of device with out detailed specifications and / or a schematic.
If you would prefer using software to solve some of the problems you listed, I would suggest you use an IR parallax (not the company, the technique) distance sensor with an analog output.  That way the Arduino Uno's analog input can be used to read the sensor and software (sketch) can process (filter) the data before it is put to use.
Added later...
Here is an article describing how to use an IR parallax distance sensor.  Here is an Arduino library design to work specifically with the Sharp IR parallax distance sensor.

I tried reading this sensors data with analog input, all I got were 3 digit numbers which made no sense to me. Any idea of what to do?

The web page you linked to in your question said the sensors' output is digital.  It gave the voltages to expect.  As such, using the complex ADC feature of the Arduino gives no advantage to using a simple digital input.  If you do use the ADC input, you should expect to see only numbers around 0 and numbers around 255.  If you want an analog output from a distance sensor get a Sharp IR parallax distance sensor as suggested in the solution.

Yeah I already was looking for one, will this be good enough?
http://robokits.co.in/sensors/sharp-ir-rangefinder-gp2y0a710k0f-100cm-to-550cm
Also please consider that these sensors are to run in bright sunlight...

No sensor will always work.  Bright sunlight is only 1 problem.  A surface that does not reflect IR radiation is another.  I have not used this specific sensor but other similar sensors work well in bright room light.  The only problem I have had was when a bad florescent light bulb that was failing.  Evidently it was also radiating similar IR modulated signals.  You might consider using ultrasonic range sensors if these IR parallax sensors are difficult to use under bright sunlight.

I used an ultrasonic sensor but the doppler's effect renders them unusable

Moving too fast for ultrasonic?  Well, I'm now starting to think LIDAR or stereo cameras and computer vision.  But now we are talking expensive solutions well past what one would use an Arduino Uno for.


text:
How can I test if pixels are being sent to my arduino?
If I'm using digitalWrite(); to send a clock impulse to a camera and then get analog signal back, how can I check to see if these pixels are in fact returning? Since there is no console how can I see if any values are actually being returned?
I'm using an Arduino Mega with the TSL1401 Linear Array Scanner.

There is a console - it's called Serial.

Send clocks, read the ADC in between, print out the results.  Change the light pattern on the sensor.  Consider the phase relationship between the clock and the ADC conversion time.  Consider using an oscilloscope, or even find a sketch that makes the Arduino into a crude scope with data plotted using processing or something like that on the PC end, and modify that to add clocks to the sensor in between the readings.

@Majenko Where is it in the IDE? Isn't Serial a pin on the Arduino?

@FortunaIwasaki It's the little icon in the top right of a magnifying glass with dots behind it. "Serial Monitor" or something it's called. Any Serial.println() etc you execute will come out there.


text:
How to compile an official VS1003 / VS1053 example for Arduino / ESP8266?
Have anyone ever successfully run any of the official playback and recording examples for VS1003 or VS1053 on Arduino / ESP8266? I mean, I was able to play sound with VS1003, but I just can't make the official example compile on Arduino IDE... It looks like it should be no problem (just provide a few methods and copy the main method code from the PDF file to the setup() in sketch) but I'm just getting a bunch of stupid compiler or linker errors, like "undefined reference to 'VSTestInitHardware()' " while the player.h header file (containing it) is included. I'm not a C / C++ expert so it's either something stupid I do or it's just not possible on Arduino. Can anyone provide a compilable example? I'm trying it with ESP8266 currently (and it is my desired target CPU), but an Arduino Uno version could help too (it throws different errors but doesn't compile neither). Thank you.

The Arduino IDE should only be used to build Arduino code.

@IgnacioVazquez-Abrams They say (in their examples) that their code is plain C and it can be compiled for ANY microcontroller - you just have to supply the device-specific methods. That is exactly what I'm trying to (and can't) do.

You can't compile plain C in the Arduino IDE, only Arduino code.

@IgnacioVazquez-Abrams I would qualify that as "you can't compile it unmodified". And if all he's using is library routines, wrapping them in extern "C" {} should do the trick.

@JayEye: Can you explain in detail what trick do you mean, please? I was trying making the header file's methods extern but it didn't help. I can live with modifying a little the examples - just don't want to rewrite them in different way, especially I want to test more than one chip version, so I would have to change them all separately.

adding this as answer so I can format properly.

Ok, after long battle with C++ compiler I have a working example (at least for VS1003 and ESP8266) with a checklist how to recreate it (with minimal changes to the example files). I'm sure someone else will have this problem so I'm attaching it:
The things that you need to do in player1003.c:

rename to player1003.h (change file extension only)
remove all 5 includes from the top (stdio, string, stdlib, ctype, "player.h")
turn off REPORT_ON_SCREEN (change #if 1 to #if 0) if you don't want to have a lot of serial output
mass replace "FILE *" to "File " - mind the space (change type of file variables in all methods, mark "Case sensitive" to avoid errors in player1053!)
mass replace fopen( to fopen2(
mass replace printf( to Serial.printf(
mass replace fflush(stdout); to //fflush(stdout); (or Serial.flush();)
remove method: VSTestInitHardware(void)
remove SM_SDISHARE flag from WriteSci(SCI_MODE, SM_SDINEW|SM_SDISHARE|SM_TESTS|SM_RESET); line  (in VSTestInitSoftware(void) method)
in VSTestHandleFile() at the bottom add fp.close(); after VS1003PlayFile(fp); and VS1003RecordFile(fp); lines (especially after the record!). We don't want unclosed files on SD card.

The main sketch (.ino):
#include <SPI.h>
#include <SD.h>
#include "player.h"

using namespace std;

// I use these values below for ESP-12 (ESP8266):
#define MP3_xCS 2
#define MP3_xDCS 4
#define MP3_DREQ 5
#define MP3_xRESET 16
#define SD_CS 15
#define SPI_MOSI 11 //SPI
#define SPI_MISO 12 //SPI
#define SPI_CLK  13 //SPI

#define  WAIT_DREQ()  while(!digitalRead(MP3_DREQ))

File song;

int VSTestInitHardware()
{
  pinMode(MP3_DREQ, INPUT);
  pinMode(MP3_xCS, OUTPUT);
  pinMode(MP3_xDCS, OUTPUT);
  pinMode(MP3_xRESET, OUTPUT);
  pinMode(SD_CS, OUTPUT);

  digitalWrite(MP3_xCS, HIGH);
  digitalWrite(MP3_xDCS, HIGH);

  digitalWrite(MP3_xRESET, LOW); // chip off!
  delay(100);
  digitalWrite(MP3_xRESET, HIGH); // chip on!

  Serial.begin(115200);

  if (!SD.begin(SD_CS))
  {
    Serial.println("Can't initialize SD!");
    return -1;
  }
  Serial.println("SD OK!");

  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV32);  // Bus SPI at 1MHz (for Arduino: 16MHz / 16 = 1MHz)
  SPI.transfer(0xFF);  // Write something to the bus
  delay(10);
  return 0;
}

void setup()
{
  if (VSTestInitHardware() || VSTestInitSoftware())
  {
    Serial.printf("Failed initializing VS10xx, exiting\n");
    exit(EXIT_FAILURE);
  }
  /* ... */
  /* Playback example. You can call these functions many times in a row
  because they leave VS1003 in a stable state. */
  VSTestHandleFile("TEST.mp3", 0);  // remember to use 8.3 file names format on SD!
  /* Recording example */
  VSTestHandleFile("RECORDED.WAV", 1);  // original example for VS1003 has a bug here (OGG extension)

  Serial.println("Playing recorded file...");
  VSTestHandleFile("RECORDED.WAV", 0);

  Serial.println("THE END");
}

void loop()
{
}

void WriteSci(unsigned char reg, unsigned char hsb, unsigned char lsb)
{
  // for debugging:
  Serial.printf("Setting %s to: %d (%X, %X)\n", RegName(reg), (hsb<<8) + lsb, hsb, lsb);

  WAIT_DREQ();
  digitalWrite(MP3_xCS, LOW);

  SPI.transfer(0x02);
  SPI.transfer(reg);
  SPI.transfer(hsb);
  SPI.transfer(lsb);
  WAIT_DREQ();
  digitalWrite(MP3_xCS, HIGH);
}

void WriteSci(u_int8 addr, u_int16 data)
{
  WriteSci(addr, data >> 8, data & 255);
}

uint16_t ReadSci (unsigned char reg)
{
  WAIT_DREQ();
  digitalWrite(MP3_xCS, LOW);

  SPI.transfer(0x03);
  SPI.transfer(reg);
  delayMicroseconds(10);

  char response1 = SPI.transfer(0xFF);
  WAIT_DREQ();
  char response2 = SPI.transfer(0xFF);
  WAIT_DREQ();

  digitalWrite(MP3_xCS, HIGH);

  unsigned int resultvalue = response1 << 8;
  resultvalue |= response2;

  // for debugging:
  if (reg != SCI_HDAT0 && reg != SCI_HDAT1)  // these registers are filtered out because they are intensively used during recording
    Serial.printf("%s is: %d (%X, %X)\n", RegName(reg), resultvalue, resultvalue >> 8, resultvalue & 255);

  return resultvalue;
}

int WriteSdi(const u_int8 *data, u_int8 bytes)
{
  WAIT_DREQ();
  digitalWrite(MP3_xDCS, LOW);

  for(int y = 0 ; y < bytes ; y++)
    SPI.transfer(data[y]);

  digitalWrite(MP3_xDCS, HIGH);
}

const char* RegName(uint8_t reg)
{
  switch (reg)
  {
    case 0x00: return "SCI_MODE";
    case 0x01: return "SCI_STATUS";
    case 0x02: return "SCI_BASS";
    case 0x03: return "SCI_CLOCKF";
    case 0x04: return "SCI_DECODE_TIME";
    case 0x05: return "SCI_AUDATA";
    case 0x06: return "SCI_WRAM";
    case 0x07: return "SCI_WRAMADDR";
    case 0x08: return "SCI_HDAT0";
    case 0x09: return "SCI_HDAT1";
    case 0x0A: return "SCI_AIADDR";
    case 0x0B: return "SCI_MIXERVOL";
    case 0x0C: return "SCI_AICTRL0";
    case 0x0D: return "SCI_AICTRL1";
    case 0x0E: return "SCI_AICTRL2";
    case 0x0F: return "SCI_AICTRL3";
  }
}

void SaveUIState(void)
{
}

void RestoreUIState(void)
{
}

int GetUICommand(void)
{
  while (Serial.available() > 0)
  {
    char c = Serial.read();
    if (c != 10 && c != 13)
      return c;
  }
  return -1;
}

void exit(int code)
{
  if (code == EXIT_SUCCESS)
    Serial.println("Exited with no error.");
  else
    Serial.printf("Terminated with error: %d\n", code);
  while (true) { yield(); }  // yield() is needed for ESP8266 only
}

File fopen2(const char* fileName, const char* mode)
{
  if (mode[0] == 'w')  // fast workaround!
  {
    Serial.printf("Opening for writing: %s\n", fileName);
    song = SD.open(fileName, O_WRONLY | O_TRUNC | O_CREAT);
  }
  else
  {
    Serial.printf("Opening for reading: %s\n", fileName);
    song = SD.open(fileName, O_RDONLY);
  }

  if (!(song))
  {
     Serial.printf("File not found: %s\n", fileName);
     return song;
  }
  Serial.printf("File opened: %s\n", fileName);
  return song;
}

size_t fread ( void * ptr, size_t size, size_t count, File stream )
{
  yield();  // this is needed for ESP8266 only (otherwise reboots)
  return stream.read(ptr, size * count);
}

int fseek ( File stream, long int offset, int origin )
{
  stream.seek(offset);
}

size_t fwrite ( const void * ptr, size_t size, size_t count, File stream )
{
  return stream.write((uint8_t*)ptr, size * count);
}

int fflush ( File stream )
{
  stream.flush();
  return 0;
}

#include "player1003.h"

(i had to manually clean this file out of my additional code, but I hope it will compile just fine).
I have a request:
If you run this example, please write me in comment whether the recording worked. I can't make my VS1003 module record sound. I have a suspicion that mic in my module is broken. That's why I was trying the official example (with the minimum changes as possible). It records only noise in my case, but plays mp3 perfectly. If you have a working example of recording, please share too.
And one more to the people with more rep (moderators): Please add a VS1003 (and VS1053 and VS1063) keywords and assign it to my questions about VS1003, because I'm unable to do it and it should be done. The chip deserves a keyword. (It's really good and not expensive.)

This is best given with an example.
foo.h contains:
#ifdef __cplusplus
extern "C" {
#endif
extern int foo(const char* s);
#ifdef __cplusplus
}
#endif

foo.c contains:
#include "foo.h"
#include <stdio.h>

int foo(const char* s) {
  printf("foo: %s\n", s);
  return 42;
}

So first, let's create a "library" from foo.c. Since we are compiling with a C, not a C++ compiler, the stuff in #ifdef __cplusplus is ignored.
$ gcc -c foo.c

This creates a file called foo.o, which we can then use to link with.
as24823.cpp contains:
#include "foo.h"
#include <iostream>

int main(int argc, char* argv[]) {
  int f = foo("called");
  std::cout << f << std::endl;
}

Now I can compile the C++ program (as24823.cpp) and use a C library (foo.c):
$ g++ -c ase24823.cpp
$ g++ ase24823.o foo.o
$ ./a.out
foo: called
42

Why is this necessary?, I hear you ask. Well, for reasons that are way beyond the scope of this posting, C++ mangles entry point names. Observe:
$ nm as24823.o
$ nm ase24823.o
...
                 U foo
0000000000000000 T main
...

(I've removed most of the output). What this is telling me is that the .o file has an entry point called "main", and an undefined external reference (something that will be provided by a library) called "foo". Now, if I remove the ifdefs from the foo.h file and recompile, this is what I get:
$ cat foo.h
extern int foo(const char* s);
$ g++ -c ase24823.cpp
$ nm ase24823.o
0000000000000000 T main
                 U _Z3fooPKc
....

What just happened? Because C++ no longer knows that it's supposed to call a C function, it has mangled the external so as to encode the types of its arguments (this is so that overloading can happen).
If you find this confusing, don't worry -- just edit the .h files that come with your C libraries and you'll be fine.


text:
Why can't my Arduino IDE recognize serial ports? (Mac El Cap, Ard. UNO)
My Arduino UNO I bought directly from Arduino.cc, so I'm pretty certain it's not a cheap clone. I have a MacBook Pro El Capitan 10.11.5. My Java is 1.8, but I'm pretty sure that doesn't matter. I have never used Arduino before, though I know a good bit of programming and some about computers. Whilst setting up Arduino, the only serial port my computer/Arduino recognizes is /dev/cu.Bluetooth-Incoming-Port. Please comment if there is more information I should provide.
My computer recognizes that I have a USB device as seen here:

Here is a screenshot of the Arduino IDE:

Finally, the commandls /dev/tty.* outputs only /dev/tty.Bluetooth-Incoming-Port. Is it possible no other serial ports exist for me?
Sorry for the barrage of pictures but I thought they'd help.
Things I have tried:

Installing CH34x driver

I'm convinced it's not a driver issue though, as users and Arduino say that OS X does not need drivers installed to run Arduino

Turning off System Integrity with csrutil --disable and also tried csrutil --enable without kext
Installing a FTDI USB Serial Driver
Bought a new USB A/B cable, as many reported the cable was faulty. I am getting a green light on my board

Does anyone know why my computer and/or Arduino does not list more serial ports that work? It's as if I don't have any besides the one Bluetooth port. I've been getting frustrated over this for several hours, so a solution would be much appreciated :)! I've tried all the solutions I've seen on SE thus far, but maybe I'm missing something
Thank you ahead of time!

"ATmega16u2 DFU" indicates a USB interface micro that is in a state to have new firmware downloaded to it (DFU), not one which is ready for operational use as a USB interface to program the Uno's ATmega328p target MCU.  If this persists after power-cycling/re-plugging the board, it is probably faulty and at minimum needs firmware repair - though it might be worth trying on another computer (preferably with a different OS or version) just to be absolutely sure nothing in the host software is forcing it to this mode.
If this is a new board you have not modified in any way, you should probably return it as defective.
If you have modified it, or you want to try to fix things yourself, you would need to follow the instructions for reflashing the 16u2 via USB-DFU.  Beware that this is a non-trivial task that looks like it is going to require installing macports and running some terminal commands, and on older boards some soldering.

Thanks. Kinda comforting that I'm not going crazy. I'll order another one online. I've tried it on Linux, Windows, and Mac and all give the same error!


text:
Pro Micro - Measuring voltage between two pins, without using GND
Quite new to this but making pretty good ground. I have an issue I'm not sure how to solve. I want to add a Pro Micro to an RC Toy, I can easily power it from the toys GND and 5V power. But then I want to use the voltage going to an LED on the toy (uses a different ground) to trigger an event within the Pro Micro.
I can power the Pro Micro from USB and and accomplish what I need with AnalogRead(). But if I connect the GND from the toys main power input to the GND from the LED it no longer acts as it should. I'm thinking these GNDs are not common, or are a separate circuit.
What I'm wanting to know is.. I'm using PIN10 on the ProMicro for the AnalogRead(), can I make it so that maybe PIN11 is the GND for that reading?
Thanks.

No, you cannot - the ATmega's ADC is referenced to its ground, and there are also some strict limits on providing inputs more than a little bit outside of the range between its power and ground.
You may be able to read two analog inputs and subtract them for a sort of "software differential" analog input, but the signal on an LED is unlikely to be meaningfully "analog" anyway - it might be pulsed with a duty cycle, but it will probably not have a steady reduced voltage.
It's actually quite likely that the anode of the LED is connected to the toy's positive supply, and it is the negative path to the cathode which is being switched - this is the most traditional way of doing things, because historically semiconductor switches suitable for "low side switching" have had better performance than those suited for "high side switching".  There will probably be a resistor on one side or the other of the LED.
With care and verification of suitable voltage ranges, you may be able to read the voltage on the LED cathode as a digital signal and invert it in software.


text:
7 segment with arduino
I am getting error with this. It is displaying those segments which are not to be displayed, i.e., 3.141 is dark and other segments are red. And I have checked that the seven segment module I am having is common anode type only.
#include "SevSeg.h"

SevSeg sevseg; //Initiate a seven segment controller object

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {2, 3, 4, 5};
    byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
    sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(1000);
}

void loop() {
    sevseg.setNumber(3141, 3);
    sevseg.refreshDisplay(); // Must run repeatedly
}

How did you wire the display. Have a schematic?

What dispatch are you using. Seems like it has  active high hardware on the segments

its schematic is on website sunrom.com , as it's device of the same company with model number 1188. although its been out dated, but I need solution..

sunrom.com    model no. 1188

http://www.sunrom.com/p/4x-7-segment-display-multiplexed

sevseg.begin(P_TRANSISTORS, numDigits, digitPins, segmentPins);

using this,, it correctly works,,....... Thankyuiiiii

If you use this library, then use
sevseg.begin(P_TRANSISTORS, numDigits, digitPins, segmentPins);

P_TRANSISTORS because the schematic has PNP transistors?

@linhartr22 probably, but I just went straight to the source code to see with options had active-low for both the digits and the segments.


text:
How to interpret analog values sent to Arduino from line scanner?
So I have a line scan camera attached to my Arduino Mega and I'm trying to send it a digital clock impulse and get an analog output back. The line scan camera is supposed to return 128 pixels.
So far I've been able to send the impulses and get analog values back which I am printing out. However, the values are different every time, which doesn't make sense because the camera didn't move so I assume that it should give back similar numbers.
Also, is there a way to determine what these numbers mean? Is there some way of turning analog signals into color pixels? My ultimate goals is to be able to determine if something has moved through the vision of the line scanner
Here is the datasheet for the line scanner: http://www.farnell.com/datasheets/315815.pdf
Here is my code:
void loop() {

  int delayTime = 20;
  digitalWrite(syncPin, HIGH);
  delayMicroseconds(delayTime);
  digitalWrite(clockPin, HIGH);
  delayMicroseconds(delayTime);
  digitalWrite(syncPin, LOW);
  delayMicroseconds(delayTime);
  digitalWrite(clockPin, LOW);
  delayMicroseconds(delayTime);

  for (int i = 0; i < 128; i++)
  {
    digitalWrite(clockPin, HIGH);
    pixelValue[i] = analogRead(dataPin);
    delayMicroseconds(delayTime);
    digitalWrite(clockPin, LOW);
    delayMicroseconds(delayTime);
  }

  digitalWrite(clockPin, HIGH);
  delayMicroseconds(delayTime);
  digitalWrite(clockPin, LOW);
  delayMicroseconds(delayTime);

  for (int j = 0; j < 128; j++)
  {
    Serial.print("I received: ");
    Serial.println(pixelValue[j]);
  }

}

It should be noted that analogRead() causes a delay of at least 104 µs, so the delayMicroseconds() right after it is probably not needed.

First, a preliminary note: according to the datasheet, the only time you
need a delay in your program is after reading the whole array and before
sending the next sync pulse. All the other timing requirements are
shorter than a single CPU cycle of your Mega, so no need to add extra
delays.

the camera didn't move so I assume that it should give back similar
  numbers.

Similar: yes. Identical: no. You expect noise to make every reading
slightly different, and you also will have variations due to uneven
timing of your program (e.g. the timer interrupt kicking in from time to
time).

is there a way to determine what these numbers mean?

They are proportional to the amount of light collected by each pixel.
That's about all you know about their meaning.

Is there some way of turning analog signals into color pixels?

No. This is a B&W camera.

That helps a lot, thank you. But even though this is a B&W camera can I still turn the numbers to actual values?

@FortunaIwasaki: What do you mean by “actual values”?

Sorry I mean B&W pixels, also can you let me know where in the datasheet you only need the delay after reading the whole array?

@FortunaIwasaki: You want to turn the numbers into pixels? That doesn't make sense. You want to turn them into pixel values? They are already pixel values. The timings are on page 4, “Timing Requirements”: tql(min) = 20 µs, the other min values are at most 50 ns.


text:
Arduino Pi-3 Ubuntu MATE not compiling
When I try to upload a script to my Genuino Uno from the Linux ARM distro on genuino.cc/downloads it spits out this during compiling.

avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device

Has anyone got any ideas?
Thanks,
Caleb

Have you performed the correct permissions manipulating commands as detailed in the Linux install instructions for the Arduino IDE?

No I didn't, but after doing so the Arduino IDE works! Thanks a lot.

After following the advice left by Majenko, I went to https://www.arduino.cc/en/Guide/Linux and followed the instuctions at the bottom of the page:
If you get an error Error opening serial port ... you need to set serial port permission.
Open Terminal and type:

ls -l /dev/ttyACM*

you will get something like:

crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0

The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is "dialout" (is the group owner of the file).
Now we just need to add our user to the group:

sudo usermod -a -G dialout <username>

where  is your linux user name. You will need to log out and log in again for this change to take effect.


text:
RFID/NFC Tag get data from wordpress MySQL
I have a local workshop for students to teach them 3D printing/woodworking
I want to know if its possible to create RFID/NFC tags using wordpress data from MySQL or HTTP/HTTPS.
Web Scenario :
I have a wordpress website where I setup a gamefication plugin.
Each time a student takes a quiz/posts on forum he gets a "x" number of points that are accumulated on his profile.
I want to know if I can get a RFID/NFC tag to get that number of points.
Each member has a RFID/NFC tag card and with that card he can get access to different things around the workshop .
Workshop Scenario :
For each tool there will be a lock , RFID/NFC reader and a LCD display screen.
When a student want to access that tool he needs a number of points on the wordpress gamefication script that are transfered to the RFID/NFC card.
If he has the needed points a text on the LCD screen will appear with something like " You have access to this tool" and the tool will be unlocked .
Else if the user doesn't meet the needed points the LCD screen will show "You don't have the needed points for this tool, please visit [URL] to get more info" and the tool will stay locked.

I need only info if this is possible, not the way to do it.
[ In case you are kind to hand me some guides on where to start to will be great! ]

Thanks and waiting to see if this is possible!

From what I can tell it's absolutely possible but will take some considerable development time and around $30-$70 of hardware per NFC terminal. Please note I would strongly not recommend this as a first project as it has a lot of individual components that all have to work together flawlessly and each is different. Properly done this will be complex software and hardware wise although more so from the hardware side of things.
Hardware wise you need/terminal:

LCD display (I would recommend segmented for simplicity and cost)
Wifi or ethernet shield/breakout and ethernet cable if the board is not wifi compatible
Arduino (MKR1000 has wifi built in), Feather (Adafruit's boards that are frequently Arduino software compatible and have many shields available and guides written on how to use them), or cheap Arduino knock off (preferably not this option as giving money to arduino.cc, Adafruit, or other designers is important if we want new boards regularly)
NFC breakout or shield (Google/DuckDuckGo/Bing RFID-RC52 for an economical option, they're ~$4 on Ebay)
Power supply corresponding to the requirements of the chosen board + shields + breakouts
NFC tags
Lock able to be unlocked by a servo. If you expect security in absence of supervising shop manager (aka just to be safe, assume dishonesty in people using the shop) from this system, the locks need to be better than a Masterlock as those are insecure to even simple soda can shims. The rotary masterlocks can also be reduced to 100 possible combinations and then the combo can be brute forced easily from there so if you get a rotary based lock system make sure the assembly covering the dial is not easily removed.
Servo or stepper powerful enough to actuate locks
Servo or stepper driver breakout board

Then you'd just want to have the public key (note I don't mean a "public key" in the general cryptography sense but on that subject, you do want the key encrypted) to the user stored on the NFC tag and then use the arduinos+electronics to read the tags and see point values. User data from wordpress could be downloaded periodically to the boards so the individual checks don't use network resources and the system works offline.

Little OLED display (0.96") are available with I2C and SPI interfaces are more versatil, take less footprint and power. And instead of Arduino + WiFi shield, why not NodeMCU?


text:
What is the quickest and simplest way for two Arduinos, with network shields, to communicate?
I have two Arduinos, each with a network shield.  What is the quickest and simplest way to connect a cat5 cable between these two Arduinos and have them exchange strings?

Connect them with a cross-over ethernet cable. Run a client on one and a server on the other. The Ethernet library comes with example clients and servers.

For clarification: a crossover cable has the green and green/white wires swapped with the orange and orange/white wires at one end. This connects the TX of one end to the RX of the other end and vice versa - just like when you're working with serial.

Is there a library that can simply send strings back and froth without a client/server?


text:
MPU6050 acceleration values not 16-bit?
I'm looking at the little code snippet from this (many other projects also use similar code):
void loop(){
 mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

 ax = map(ax, -17000, 17000, -1500, 1500);
 ...

If my reading is correct, it's assuming the value of ax to be between -17000 and 17000. But isn't the value supposed to be 16-bit? If so, shouldn't the range be wider than -17000, 17000? Is the value capped?
Any thought appreciated.

The ADC for the accelerometer is 16 bit, yes. Also the data being sent out is in 16 bit format.
But what you are confusing is resolution and range.
The accelerometer can be programmed to have a sensitivity of 2g, 4g, 8g or 16g.  With it set to the least sensitive, that is 2g, the full range of -32768 to +32767 would equate to ±2g.
That's fine when you're measuring G-forces of up to 2g, but when all you are sensing is tilt then there is only 1g - the 1g the Earth exerts on it.
That 1g is half the 2g range, which is -16384 to +16363.  So round that up and give a little extra headroom to your calculations, and you get -17000 to +17000. It gives enough range in your calculations to give the full ±1g range "plus a little bit".

Very good point! So, suppose I'd like to detect when a rod rotating about the x axis is being accelerated too much (eg 1m/s^2), should I be using the accelerometer or gyro values? I'm guessing it might be gyro since accelerometer measures linear acceleration and I might want instantaneous angular accelerations?

Actually, isn't 2g the most rather than the least sensitive? At 2g, it could pick up more refined changes in acceleration than at 16g.

That's what I meant, yeah. Most sensitive, or least attenuated.

No, the map() function does not cap it's input or output, you would
need constrain() for that. With map() alone, there is no assumption
about the range of the values, other than the calculation not
overflowing 32-bit integers. Thus,
ax = map(ax, -17000, 17000, -1500, 1500);

simply multiplies x by the ratio 1500/17000. It is mathematically
equivalent to
ax = map(ax, 0, 34, 0, 3);

or to
ax = ax * 3L / 34;

C.f. the documentation of map().


text:
How do I read the fuse bits from within my sketch?
How can I read the fuse bits from within my sketch?

You can use the boot_lock_fuse_bits_get function from <avr/boot.h>.
#include <avr/boot.h>;

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

    cli();
    uint8_t lowBits      = boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS);
    uint8_t highBits     = boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS);
    uint8_t extendedBits = boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS);
    uint8_t lockBits     = boot_lock_fuse_bits_get(GET_LOCK_BITS);
    sei();

    Serial.print("Low:  0x");
    Serial.println(lowBits, HEX);
    Serial.print("High: 0x");
    Serial.println(highBits, HEX);
    Serial.print("Ext:  0x");
    Serial.println(extendedBits, HEX);
    Serial.print("Lock: 0x");
    Serial.println(lockBits, HEX);
}

void loop()
{
}


text:
Code runs different on USB vs Battery
I have two Arduino, one is to handle the Bluetooth communication and send a signal to the other Arduino, and the other to interpret the signal and display or hide an image on the E-ink display.
It work just fine when they both are connected through the USB. But when I connect a 9V battery to the Arduino running the E-ink, instead of the USB, the image is displayed and cleared (looping), as if the IF ELSE conditions are not there.
I have tested if it actually runs the method by adding delay to the showImg()-method, and that seems to work.
I have also tested with connecting the USB cable to the E-ink Arduino to a 5V charger, and the case is the same.
Image:

Bluetooth code:
int ledPin = 13;
int state = 0;
int flag = 0;

void setup() {
 pinMode(ledPin, OUTPUT);
 digitalWrite(ledPin, LOW);

 Serial.begin(9600);
}

void loop() {

 if(Serial.available() > 0){
 state = Serial.read();
 flag=0;
 }

 if (state == '2') {
 digitalWrite(ledPin, LOW);
 if(flag == 0){
 Serial.println("Screen: off");
 flag = 1;
 }
 }

 else if (state == '1') {
 digitalWrite(ledPin, HIGH);
 if(flag == 0){
 Serial.println("Screen: on");
 flag = 1;
 }
 }
}

E-ink code:
#include <epd.h>

int displayed = 0;
int val = 0;

void showImg(void)
{
  Serial.print("showImg");
  displayed = 1;
  //epd_clear();
  epd_disp_bitmap("PIC9.bmp", 0, 100);

  epd_udpate();
  //delay(10000);
}

void clearImg(void){
  Serial.print("clearImg");
  displayed = 0;
  epd_clear();
  epd_udpate();

}

void setup(void)
{
  //Serial.begin(9600);
  epd_init();
  epd_wakeup();
  epd_set_memory(MEM_TF);
  pinMode(7, INPUT);

}

void loop(void)
{
  val = digitalRead(7);

  if(val == 1){

    if(displayed == 0){
      showImg();
    }

  }else {

    if(displayed == 1){
      clearImg();
    }
  }
  //Serial.println(val);
  //delay(3000);
}

I am a beginner when it comes to Arduino, So I hope someone can give me some hints to what may be wrong.
Thanks!

Please edit the question to fix the following ambiguity: in “connecting ... to a 5V charger ... the case is the same” it isn't clear whether you mean like the battery setup or like the USB-to-computer setup, ie, whether it fails or works

The USB provides the one thing that is missing from your diagram there: the common ground.
The GND pins of the two boards must be connected together. By using USB the USB becomes that connection. As soon as you use batteries there is no connection, so no communication happens.

Thanks for the reply Majenko. You are absolutely right, and I'm surprised I did not see this.... Thank you!


text:
Arduino OBD library and software serial library
Can I use Arduino OBD library with "custom" software serial or it needs to be used with hardware UART only? For example if I have D5 and D6 pin as RX and TX in my code hooked on OBD board, how do I initialize OBD library from there?
This is the OBD library that I'm referring to.
And I'm using this Allpro OBD board.
Update
Actually I would be satisfied with a answer how to know when entire response from the board is received, because this way is way too messy:
void getResponse(void){
 while(obdSerial.available()){
   Serial.write(obdSerial.read());
  }
}

Here I don't know when the message is received. And if I try to use example from Sparkfun obd-ii-uart-hookup-guide (different board doe) I ended up in infinite-loop since the board never return \r, if I send ELM command to use \n as terminator, and if I disable ELM to echo the command so that I use just one getResponse call I get some readings, but not all the time, I ended up in infinite-loop again.

What / where is an Arduino OBD library? What does its documentation say?

Sorry I have updated my question with links.

That library is hard-coded to use the single Hardware Serial device on the Arduino Uno or the second Hardware Serial1 device on other boards.
#ifndef OBDUART
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168P__)
#define OBDUART Serial
#else
#define OBDUART Serial1
#endif
#endif

You can edit the library's header file OBD.h to define your own serial port though:
#include <SoftwareSerial.h>
extern SoftwareSerial mySerialPort;
#define OBDUART mySerialPort

And then in your sketch create the mySerialPort SoftwareSerial object.

I have updated my question again, sorry :) I would really appreciate if you can take another look. But thanks for this one, this is also something that I needed.


text:
Does serial communication between PC and Arduino has to be in a loop?
I am trying to send a few variables from my python script to my Arduino. I am using pySerial. I am able to send the variables to the Arduino, but my Arduino sketch runs only for a second and then stops. But if I put the ser.write() command in a while loop (which I want to avoid) the sketch runs fine.
For example, I wrote this script on my PC -
import serial
ser = serial.Serial('COM3',9600)
counter = 'Y'
ser.write(counter)

This script should pass a "Y" to the Arduino and should stop executing.
My Arduino code-
int flag = 0;
void setup() {
   Serial.begin(9600); // set the baud rate
   Serial.println("Ready"); // print "Ready" once
   pinMode(13, OUTPUT);
}

void loop() {
   char inByte = ' ';
   if(Serial.available()){
      inByte = Serial.read(); // read the incoming data
      Serial.println(inByte);
      flag ++;
   }
   if(flag == 1){
      digtalWrite(13, HIGH);
   }
}

Now according to me the Arduino should receive the data and increment the flag variable to 1. Next the program checks whether flag is one and if it is turns the onboard LED on. However when I run the python script, the onboard LED flashes for just a second and then goes blank. I again have to run the python script to make it light up or I have to put ser.write in a loop. I can't put ser.write in a loop as my script won't run further.
So how can a value be passed to an Arduino without having to put the ser.write() in a loop.
Thanks!
EDIT :
I wrote a new sketch, but it still doesn't work. Here's the sketch -
int ledPin = 13;
char data = ' ';

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

void loop(){
   if (Serial.available()>0) {
      data = Serial.read();
   }
   if (data == 'Y'){
      digitalWrite(ledPin, HIGH);
   }
   delay(500);
}

Here's an image of the wiring -

Comments are not for extended discussion; this conversation has been moved to chat.

Just put a 10 µF capacitor between the 5v and RESET pins of your Arduino and do whatever you want, just make sure that the capacitor is connected after the board has been powered up, and also, remove the capacitor before uploading any code.


text:
What is the sampling-rate of the `analogRead()`?
I am about to Fourier analyse some data I've taken, but i need to know at which sampling rate the data was written to the serial monitor. I've found a lot of threads about how to increase it and such but not a single one that lays down some information about what the sampling-rate is.
My code is very simple, here it is:
      // the setup routine runs once when you press reset:
  void setup() {
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
  }

  // the loop routine runs over and over again forever:
  void loop() {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    Serial.println(sensorValue);
  }

Roughly 9600 sampl/s, but the sampling rate will not be constant because of the timer interrupt. For an example on how to get a steady and controlled sampling rate on an AVR-based Arduino, see this example of configuring the ADC in free-running mode.

Thanks, will look into it after dinner. If it solves it, i'll get back to you and mark it as answer :)

BTW, could you please tag your question with the type of Arduino? It may make a difference. My comment above applies to most (if not all) AVR-based Arduinos, but not to ARM-based ones. Oh, and the Serial.println() will likely slow down the acquisition by a factor 50 or so once the Serial output buffer fills out.

Yeah, just realized that the serial.println does NOT print 9600 values/sec, This messes up my data. Basically what i want to do is do some tests on some different sounds i expose it to and then find those frequencies with fourier analysis.

Note that you can do other stuff while a conversion is taking place. The implementation of analogRead just wait/block until it's done. What I've done is some cases, is read the data from a previous conversion, start a new conversion, and process the data from the previous conversion , while the new conversion is running (in the background).

you should probably use an arduino due for this type of load(FFT). anyway, tomorrow I will take measures for your code with oscilloscope and report the results. (for uno and due).

The ADC in default configuration will take 104 µs to make a sample (which agrees with Edgar Bonet's comment of roughly 9600 per second).
You can speed that up somewhat by changing the ADC prescaler from the default of 128. See ADC conversion on the Arduino (analogRead). A prescaler of 32 will reduce that to 26 µs and still give quite acceptable results.
You can also run the ADC asynchronously (in the background) so you can transmit the previous result while obtaining the next one. A higher baud rate than 9600 baud would be highly recommended in this case.
People have been doing FFT analysis using the Arduino Uno and similar. I suggest you Google for relevant posts about that.

Yeah, i've done som reading now. The problem i currently have is that i know the rate at which the analogread is updated, the problem is that the serial.println does not print at nearly the same speed which gives me an unknown samplingrate of the data i've access to. Currently i'm considering buying a national instruments Data acquisition card. I've used them in uni and they suit my needs. Also, i can get the labview-software from school

@DakkVader: You can send the data to the computer in real time if you sample at 9600 S/s and send only the 8 most significant bits, in binary form (Serial.write()), at 115200 bps. Otherwise you could buffer the samples in RAM at whatever sampling rate you want and send them later, but this will limit you to short sampling runs.

Could you elaborate on this ? Basically i'd like to get whatever information analogread can get, at it's given sampling-rate. Serial.print won't give me at the true rate

I loaded this program on an arduino uno and measured with oscilloscope the time from the rising edge to the falling edge of the signal on pin13.
void setup() {

    Serial.begin(9600);
    pinMode(13,OUTPUT);
}

void loop() {
    PORTB = B00100000; //pin13 HIGH
    int sensorValue = analogRead(A0);
    PORTB = B00000000; //pin13 LOW
}

results:

time: 110.4 uS
  relevant freuency: 9.06 kHz

in case you are interested in fast analogRead with Due, I suggest you take a look at this.
The author stated that an analogRead with Due takes about 40uS and he also describes a couple of ways to make it much faster.

Your figure of 110 µs agrees pretty-much with my quoted 104 µs. The code in analogRead does more than just the read, so the other 6 µs would be setting up for the read, waiting for it to finish, and then storing the results. Also, there is an extra time before a conversion starts. The conversion starts on the leading edge of the ADC clock, not the moment the code asks for it. In the case of a scaler of 128, there could be 127 extra (processor) clock cycles added, because the hardware has to wait for the next ADC clock cycle. This could add 7.938 µs to the conversion time.

I appreciate the verification via measurement.


text:
Controlling 2 DC motors with L293D and 6 V battery pack?
I'm just starting to delve into robotics and electronics, and my first project was building a small Arduino collision-avoidance robot with a ultrasonic range finder, one servo and two DC motors.
Right now I'm using a 6 V battery pack to power both DC motors, another 6 V just for the servo, and a 9 V battery for the Arduino.
But I'm in doubt if the power supply for the DC motors is enough. I'm using an L293D IC to control both motors, but the robot can barely move under load (and the total weight of the robot is not that much. I already reduced all the weight I could). So, how much power, typically, I should supply for the L293D to control those motors?

As has been covered many times here and on electronics.stackexchnge, the L293/L298 are antiquated devices with high internal losses, meaning you essentially loose one cell in your battery pack just to heating up the chip.  Ideally you would replace this with an FET driver, otherwise you will need to add at least another cell to the battery pack.

Is a FET a IC, like the L293D?

The L293 is bipolar IC, not an FET IC.  TB6612FNG is a small FET dual H bridge used with more success on some newer motor shield type offerings.  There are other choices discussed on electronics.stackexchange as well.

Do you know how much power drains your motors? Because we can't help you if you don't give enough infos.

I do not know which Arduino you are using but the 9V smoke alarm battery is about the worst choice you can make. You do not have much current available nor a lot of capacity.

Posting links to "Technical" information on all the hardware devices would be a big help. Also do you have access to a voltmeter. Measure the voltage across the motor terminals when it is running, I expect it to be about 3.5V with good batteries.

The L293D can handle two motors at a time and as per the data sheet the maximum voltage that you can give to the motor as a supply (on pin 8) is 36 volts.

This is not a valid answer to the original question. The OP knows that he can handle 2 motors with this IC, he does not worry about voltage supported by the IC either. He wants to know what power (or current, if we consider the 6V voltage fixed) he needs to properly make both motors move.


text:
Character array weirdness
I'm using Energia to program one of TI's MCU. Since Energia is based off the Arduino IDE, I'm hoping someone can help me here.
I'm building a simple UDP packet sender and receiver app. The MCU starts up and connects to the local Wifi network and waits for a packet from another device on the same network.
This packet is collected in a char array char packetBuffer[16];
I want to split this array into two separate arrays each of 8 elements. These are char lampCmdRead[8]; and char pwdReadBuffer[8]; Now the network bit works great. I can send the packet through my desktop and receive it on the MCU. However when I split this array I see that the pwdReadBuffer shows the same contents as packetBuffer even though they are of different sizes. How is this possible?
Here is the code:
char packetBuffer[16];
char lampCmdRead[8];
char pwdReadBuffer[8];

// This is code from the 'void loop()' section
int packetSize = Udp.parsePacket();

if(packetSize) {
 int len = Udp.read(packetBuffer, 16);
 if (len > 0) packetBuffer[len] = 0;
 Serial.println();

 Serial.println("packetBuffer:");
 Serial.println(packetBuffer);
 Serial.println();

 for(ctr = 0; ctr < 8; ctr++) {
   pwdReadBuffer[ctr] = packetBuffer[ctr];
 }
 if (len > 8) pwdReadBuffer[len] = 0;

 for(ctr = 0; ctr < 8; ctr++) {
   lampCmdRead[ctr] = packetBuffer[ctr+8];
 }
 if (len > 8) lampCmdRead[len] = 0;

 Serial.println("pwdReadBuffer:");
 Serial.println(pwdReadBuffer);
 Serial.println();

 Serial.println("lampCmdRead:");
 Serial.println(lampCmdRead);
 Serial.println();
}

And here is the output:
Received packet of size 16
From 192.168.1.101, port 55056

packetBuffer:
2qZ@X51Rredledon

pwdReadBuffer:
2qZ@X51Rredledon

lampCmdRead:
redledon

You're overflowing your buffers.

Also you're not terminating your strings properly.

if (len > 8) pwdReadBuffer[len] = 0;

This line is unsafe.  You declared pwdReadBuffer to be only 8 bytes in size, but this line of code will either do nothing, or write outside of the target buffer, with unpredictable results.
You make a related mistake here:
if (len > 8) lampCmdRead[len] = 0;

First the test should be >= but again, such a value would be beyond the end of the target buffer.
Also consider that if you receive 8 or more characters, you will have no room for a terminating null in pwdReadBuffer, and so cannot pass it to anything that expects a null terminated string.
If you want to use null-terminate storage for a string of up to 8 bytes size, you need 9 bytes of storage.  And of course you need to only use in-range indices to access the elements.

This behavior (where contents of pwdReadBuffer print out the same as those of packetBuffer) is occurring because you haven't properly null-terminated your strings.
After you copy the first 8 characters of packetBuffer to pwdReadBuffer the statement if (len > 8) pwdReadBuffer[len] = 0; gets executed.  It sets pwdReadBuffer[16] to 0, ie, references out of array bounds.
Apparently lampCmdRead is allocated directly after pwdReadBuffer, so when you copy the next 8  characters of packetBuffer to lampCmdRead, they are being copied, in effect, to pwdReadBuffer[8] ... pwdReadBuffer[15], so that the println prints a 16-character string,
2qZ@X51Rredledon.
For each of your three arrays, allocate an extra byte for a null terminator.


text:
trying to use millis()
I'm learning how to use the millis() function. Instead of having it in the main body of the program I wanted to place it in a function so I can change the time interval with which an led will flash. I modified the code blinkWithoutDelay. My code is below. The output I get is an LED that is always on. I did print the output of the ledState to the serial monitor. Its changing from on to off repeatedly. So I think the led is really flickering too fast to see. I took a screenshot from the serial monitor. The output is below.
const int LED2 = 2;
int ledState2 = LOW;

void timeCheck(int interval)
{
    unsigned long cMillis = millis();
    unsigned long pMillis;

    if (cMillis - pMillis > interval)
    {
        pMillis = cMillis;

        if (ledState2 == LOW)
        {
            ledState2 = HIGH;
        }
        else
        {
            ledState2 = LOW;
        }
        digitalWrite(LED2, ledState2);
        Serial.println(ledState2);
    }
}

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

void loop()
{
    unsigned long flashtime = 1000;
    timeCheck(flashtime);
}

The problem here is that the variables you declare in your function are not static. The rest of the code works as expected.
Where you declare the variables at the beginning of your function is correct. There is only one variable in question though as it is the cause of the error you are seeing.
What you need to do is change the variable
unsigned long pMillis;

to
static unsigned long pMillis = 0;

By not having the pMillis as a static variable, each time the function is called the value of pMillis is undefined, which means it is unpredictable whether  (cMillis - pMillis > interval) will be true or false. But with the static declaration the Arduino knows to keep the previous value for the next time you call the function.
An excerpt from Wikipedia:

In computer programming, a static variable is a variable that has been allocated statically—whose lifetime or "extent" extends across the entire run of the program....
A static local variable is different from a local variable. It is initialized only once no matter how many times that function in which it resides is called.

each time the function is called pMillis is set to 0 - it's actually undefined, not zero.

@NickGammon    thank you that is a bit more accurate, but it is still loosing whatever value it was before.

Absolutely. I just wanted to clarify that you couldn't rely upon that declaration having an initial value of zero. In fact, if you make it static then it will have an initial value of zero, which might help.

@NickGammon    thanks Nick. I changed it to be clearer/accurate.

It seems you still did not grasp the idea of pMillis being undefined. By writing “that means the if (cMillis - pMillis > interval) will always be true.” you are are making implicit assumptions on pMillis. I edited the answer to make clear you cannot know the result of the test.

Thank you to everyone for your input. I've read about declaring a static variable before but it didn't make sense to me. I do understand how it works now and see it in action. Thank you again.

Put it out, so it will be global. LedStaye should be bool:

const int LED2 = 2;
bool ledState2 = LOW;
unsigned long pMillis;
void timeCheck(int interval)
{
    if (millis() - pMillis > interval)
    {
        pMillis = millis();
...

Did you test this?  I do not think millis() can be called inside the if logical test

You have used pMillis variable locally. Thats why when you call the function, pMillis initialized as 0. So set pMillis variable globally.


text:
Is there any reason not to solder power leads to the lugs for the power in socket on the reverse side of a mega 2560 rev 3 board?
I have a very tight space for a project that requires a mega board , the "power in" plug takes it over the space available. Are there safety or other concerns soldering to the lugs for the "power in" socket on the reverse of a mega 2560 rev 3 board board? the board is fitted with an elctrofreaks TFT LCD MEGA SHIELD v2.2 and a TFT_320QVT LCD screen. (the elctrofreaks mega shield uses vin pin)  1 other PWM  pin is used  and an esP8266 board on a uart channel The power  is from a regulated power supply. If  I do this, am I correct that the regulator and polyfuse will still be used?

You could also use the Vin pin. But using the underside of the barrel, has the added advantage of first going through a (reverse polarity protection) diode.

Soldering to the underside of the connector is exactly the same as plugging something in to the connector.
Yes the regulator will be used.
No the polyfuse will not be used - that is in the USB power circuit not the barrel jack power circuit.


text:
Unable to issue any AT commands to BT BLE Breakout Board
I'm a programmer, more from the software side but I do have hardware working knowledge too. I've completed the Arduino Starter Kit's 15 projects, Now trying to build some things with ESP8266 and HM-10 BLE.
I was able to connect ESP8266 to my network and start a TCP server too via AT commands(using  Arduino's Serial Monitor and FTDI 232RL USB to TTL converter)
I also have a HM-10 Bluetooth Breakout+connector board (Its based on CC2541 by TI (visible on the SMD chip)) brought from here.
Using the same setup I was able to issue AT commands successfully for ESP8266. However I tried many things, different baud rates and \r\n combinations; I just couldnt get the HM-10 to acknowledge my AT commands.
Setup: link
Connections:
Arduino +5V --> +ve input of LDO regulator --> 3.3v OUPUT to Vcc of HM-10
Common GND for LDO regulator input and output pins, FTDI 232RL and HM10

FTDI TX --> voltage divider (1k ohms --> connection output to HM 10 RX --> 1k ohms --> 1k ohms --> GND)

There is no code/sketch as of now. I'm just trying to hook up the HM-10 BLE chip. I can pair my Android phone to it but that's not the concern here.
The concern here is I cannot configure the HM-10 using AT commands.
The HM-10 does not reply an "OK" acknowledge for my "AT" command. Nothing happens in the serial monitor after hitting enter. Just a blank screen.
Is there a way by which I can determine what baud rate to use and what combination of \r and \n?
What am I missing here?

You might find this helpful: ftp://imall.iteadstudio.com/Modules/IM130614001_Serial_Port_BLE_Module_Master_Slave_HM-10/DS_IM130614001_Serial_Port_BLE_Module_Master_Slave_HM-10.pdf

I found out that there is no need for a voltage divider to reduce the voltage being given to RX pin of BLE from FTDI's TX since both FTDI232RL and HM-10 are 3.3V devices (from here)
I connected the TX from FTDI directly to the RX of BLE using female to female jumpers.
Used No Line Ending and 9600 as the baud rate.
Then it worked fine, I got an OK acknowledge for my AT command.


text:
counting ADC samples ( using a light sensor)
i am new to micro controller programming and in need of help. i have managed to interface a light sensor to a micro controller (atmega 32a) and can read the value i.e. (1023) as per the set prescale. however i intended to achieve a single decimal value as the result. in this case (1) every time the sensor is exposed to light and successively perform an incremented tally as lights go on and off around the sensor ( i am using a LDR for this). i am currently having problem getting my micro controller to do this. i have searched all over the internet but no seems to assist me on this... please any insight on how to achieve this will be much appreciated. i know its a simple thing,HELP :(
basically just a means of making my micro controller count the number of times light falls on the LDR

What reading do you have when the sensor is lit? And when it's not? 1023 sounds like you wired the LDR wrong. Forgot a pulldown maybe?

Can you show what code you have so far? This isn't really a code-writing site.

There are 2 common light sensor types.  The photo diode and the photo resistor.  The first produces small amounts of current and operates fast.  The second changes resistance and operates (very) slowly.
There is a good stack exchange response here for how to use a photo diode.  Often the photo diode output is small and additional hardware is used to amplify the signal.  As discussed in this stack exchange response.
The photo resistor or cadmium sulphide cell or Light Dependent Resistor is much easier to interface with an Arduino.  However, the response time is very slow.  On the order of hundreds of milliseconds to seconds.  This is acceptable when controlling street lights.  But is not acceptable in applications requiring fast light detectors such as those used for communication.
Before going on, verify which device you are using in your design.
Generally, Arduinos contain a 10 bit ADC.  This results in values from 0 to 210−1 or 0 to 1023.  Should you consistently get a reading at or near the limits of the ADC check your hardware.  Do this by measuring the voltage at the input of the ADC pin used.  Do this under varying conditions to verify the hardware is operating as expected.
A good software design uses hysteresis to convert an analog value to a logical 1 or 0.  Here is a stack exchange response about using hysteresis with Arduinos.

i have perfect wiring of the LDR and yes i used a pull up resistor. the results range from 0-1023. this occurs when i vary the variable resistor. to add i am not using a arduino. i am using a programmer to push a C++ code into my micro controller then fabricate it on a pcb. what i need is how to manipulate the returned ADC value read from the pins, from a 10 bit value to just a single decimal 1 (at code level ) . i require the micro controller to return the value 1 on exposure, store the value when not exposed and increment the value on every subsequent exposures.

in other words ..is it possible to dictate the value returned. . i intend to use the sensor at its maximum reading. (will use a trimer instead of a pontentiometer for final fabrication ) . all i want to achieve is a tally of number of max exposure times

No, the ADC hardware inside the processor returns a value proportional to the voltage seen at it's input.  The Arduino ADC library configures the ADC hardware and returns this value to your sketch.   It is up to your sketch to interpret this value.  If all you want to do is interpret the ADC value as a 1 or 0 ...  I suggest you use the knowledge in the last paragraph of the answer.

There are hardware hysteresis solutions to this problem.  But they tend to operate at a fixed point and, normally, people tend to address this problem in software.  If you use a compatible hardware solution you should be able to use a GPIO pin and simply test if it is connected to a high or low voltage source.

thank you sir, @st2000 .let me try approach it your way.. much appreciated.. some guys though..smh


text:
Attiny cores with SPI support?
It's been done, but the the tutorials I find seems incomplete. What I'm trying to do is make the ATTiny84 talk to the 2.4 GHz NRF24L01+ radio. I understand that in order to do that I need the MCU to talk to the radio by serial. Attiny84 (and 85) does not have serial, hardware any ways.
But as I understand it you can do software serial by USI, but in order to do so the core for the board has to have this modification?
I've searched far and wide. I bump into the cores on Google Code (https://code.google.com/archive/p/arduino-tiny/downloads). I've installed them but SPI is not listed in the list of libraries.
I've got another tinycore (from where I dont know), when I use this one SPI is a library I can reference, but compiling causes
error: 'SPIE' was not declared in this scope

So, could anyone point me to a known good source of cores to Attiny85 and 84 so I can enable SPI?

This has been discussed on Github. https://github.com/TMRh20/RF24/issues/236

The NRF24L01+ does not use "serial" in the usual meaning of asynchronous serial or "software serial" soft UART libraries.  Instead it uses the synchronous serial SPI interface, which the ATtiny series is intended to handle with a hardware/software hybrid approach.  Doing so in bare AVR code is fairly straightforward.


text:
MPU6050 code explanation
I'm new to arduino and electronics. I've been trying to use the MPU6050 with my arduino but I'm having difficulty understanding the code. I'm referring to the code put up on the arduino website (http://playground.arduino.cc/Main/MPU-6050#short). Is there any way I could get a line by line explanation of the code?

.... link? ....

http://playground.arduino.cc/Main/MPU-6050#short

all my values are always zero, what mistake could I be making?

I've added in a bunch of comments for you:
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; // declare accellerometer and gyro variables
void setup(){
  Wire.begin(); // initiate i2c system
  Wire.beginTransmission(MPU_addr); // be sure we talk to our MPU vs some other device
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true); // done talking over to MPU device, for the moment
  Serial.begin(9600); // initialize serial port to 9600 bps so you can see your debug messages in Arduino IDE via debug channel
}
void loop(){ // main program loop
  Wire.beginTransmission(MPU_addr); // get ready to talk to MPU again
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false); // done talking to MPU for the time being
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  // all the fancy <<8| stuff is to bit shift the first 8 bits to
  // the left & combine it with the next 8 bits to form 16 bits
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  // the above lines have gathered Accellerometer values for X, Y, Z
  //  as well as Gyroscope values for X, Y, Z

  Serial.print("AcX = "); Serial.print(AcX); // share accellerometer values over debug channel
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX); // share gyroscope values over debug channel
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333); // delay a bit to not overwhelm you the user/programmer as you view the results
}

Sure thing!  If this answer suits you, please remember to click the "answered" checkbox =)


text:
ADC timer interrupt when ready
I have a microphone and I need as precise values as possible. I have been told by my teacher, that it is somehow possible to make a ADC timer interrupt, which would interrupt always when the value is ready, so that the reading itself would not slow the program down.
    I know, how to use timer interrupts to read the analog value every other ms or something and I even have a code that lets the ADC read automaticly and takes the value, but I need to make it take the value always when it's ready, so that I would have every value the ADC read. I tried to look into the datasheet, but it's too complicated for me.
   How can I achieve such thing? I am using arduino uno.
this is the code I have that sets up the ADC interrupt:
  ADCSRA = 0;
  ADCSRB = 0;
  ADMUX = 0;
  ADMUX |= (1 << REFS0) + (1 << REFS1);
  ADMUX |= (1 << ADLAR);

  ADCSRA |= (1 << ADATE); //enabble auto trigger
  ADCSRA |= (1 << ADIE); //enable interrupts when measurement complete
  ADCSRA |= (1 << ADEN); //enable ADC
  ADCSRA |= (1 << ADSC);
  ADCSRA |= 0b010;

ISR(ADC_vect) {//when new ADC value ready
  af = af + ADCH;
  aaf++;
}

I found this on the internet, but it didn't work as I expected.

ISR(ADC_vect){...} You also probably want to use a timer to start the conversions at an constant interval.

@Gerben: You can also have the ADC trigger itself at a constant rate if you set it to the so called “free running mode”.

@EdgarBonet that rate would be as fast as it can. Aky-her might want to use a lower speed.

@Gerben: Right, but “as fast as it can” is 9615 S/s, which is not excessive for audio processing, and is easier to achieve since you have only one device to configure instead of two.

By “as precise values as possible”, do you mean accurate voltage readings, or accurately-timed, or what?

At 4 MHz, you are clocking it too fast.

I have been told by my teacher that it is somehow possible to make a ADC timer interrupt.

You might have asked him or he could explain it ;)
Generally, if you want to do anything with an Arduino, which isn't implemented by the Arduino libraries, you're going to have to roll your own code (or copy it from the internet).
The answer from Nick will most certainly be enough to help you with the problem. However, it'd be way more cooler to find out how you can solve these problems yourself.
Getting started
I couldn't find a duplicate of this question, though it's a rather common question. You should've checked some of the tutorials on the web, it'll get you started a lot faster.
But don't forget the datasheet and manuals of the ATMega328(P). In case you can't really find something that fits your needs, or if you want to check some background information.
Setting registers (ADC)
This piece of code (from Nick Gammon), sets up the ADC.
  ADCSRA =  bit (ADEN);                      // turn ADC on
  ADCSRA |= bit (ADPS0) |  bit (ADPS1) | bit (ADPS2);  // Prescaler of 128
  ADMUX  =  bit (REFS0) | (adcPin & 0x07);    // AVcc and select input port

Fair enough, but if you wanted to change anything of it, you'll think: "How did he ever come up with this."
These are the registers of the microcontroller. By setting bits in the right pattern, you can enable/disable functions or change settings of the microcontroller.
You should download the ATMega328(P) datasheet. You can very easily navigate through it (if you've got a PDF reader that supports "bookmarks").
Check for "24. Analog to Digital converter" you should read through it, and go to "24.9 (Analog to Digital converter) - Register description.".
Here you can see, which bits of (in example) the ADCSRA register you have to set to enable the adc (ADEN), start the conversion (ADSC). And enable interrupts for it (ADIE).

Interrupts
Since you also want behavior that has to do with interrupts. You should also check out the interrupts bookmark (#12). 12.1 will show you an table with all interrupt vectors.
It's quite a shame that they don't have a nice C example code, they do have an reference manual though, but you'll implement an interrupt handler like this (from Nick Gammon).
// ADC complete ISR
ISR (ADC_vect)
  {
  adcReading = ADC;
  adcDone = true;
  }  // end of ADC_vect

If you now want to interrupt on SPI you can check the datasheet or reference manual for the vector name. (SPI_STC_vect)

it is somehow possible to make a ADC timer interrupt

The ADC and the timers are two different things. If you mean a timer interrupt, I'm not sure why you would want that. If you mean an ADC interrupt, yes you can do do that.
Here is some example code from my page about the ADC which shows using the interrupt (on a Uno):
const byte adcPin = 0;
volatile int adcReading;
volatile boolean adcDone;
boolean adcStarted;

void setup ()
{
  Serial.begin (115200);
  ADCSRA =  bit (ADEN);                      // turn ADC on
  ADCSRA |= bit (ADPS0) |  bit (ADPS1) | bit (ADPS2);  // Prescaler of 128
  ADMUX  =  bit (REFS0) | (adcPin & 0x07);    // AVcc and select input port

}  // end of setup

// ADC complete ISR
ISR (ADC_vect)
  {
  adcReading = ADC;
  adcDone = true;
  }  // end of ADC_vect

void loop ()
{
  // if last reading finished, process it
  if (adcDone)
    {
    adcStarted = false;

    // do something with the reading, for example, print it
    Serial.println (adcReading);
    delay (500);

    adcDone = false;
    }

  // if we aren't taking a reading, start a new one
  if (!adcStarted)
    {
    adcStarted = true;
    // start the conversion
    ADCSRA |= bit (ADSC) | bit (ADIE);
    }

  // do other stuff here

}  // end of loop

I should point out that if you do an analogRead it blocks until the read is done, so the very next line to be executed after analogRead will be when the data is ready.