With very few exceptions, electronic devices only draw as much current as they need, limited by their resistance.

The current rating on a power supply is the MAX current it can provide before the voltage drops. Having a higher current power supply may waste energy, but won't hurt anything.

According to Ohms law, V = IR

Where V = Voltage
I = current, in amps
R = resistance, in ohms

(voltage = current times resistance.)

Or, solving for current:

I = V/R

current = voltage divided by resistance.

So if you have a 12 volt power supply, and a 100 ohm resistor, you'll get 12/100, or 0.12 amps, flowing through the resistor.


I just want to control a 48 volt and 30 amp current with pwm singnal...i don't nkow what components is needed for this

simulate this circuit – Schematic created using CircuitLab
There are not many P-Channel Mosfets with high current ratings. The circuit is an example of a buck with a high side N-Channel. If you want to use an N-Channel as the high side switch, you use and isolated DC-DC and isolated gate driver. The negative output of the DC-DC regulator gets referenced to the source of the N-Channel. Then the isolated driver's output signal is 15v referenced to the source. I would also recommend using a snubber because you're going to likely see voltage spikes across your mosfet. A 10ohm resistor and 3300pF would probably be a good start. You may need to go to a 200v or 250V mosfet if the spikes are bad enough.


writing and uploading sketch as cpp file

See my post about How the IDE organizes things.

Also see my page about how to avoid the quirks of the IDE sketch file pre-preprocessing.

You can certainly manage without .ino files. As Edgar Bonet says, they are really C++ files with certain pre-processing (see link above).

  but what about these loop() and setup() functions

Effectively, the Arduino IDE supplies a main function that looks like this:

int main ()
  {
  init ();    // initialize hardware, including timers and timer interrupts
  setup ();   // user setup
  while (true)
    loop ();  // stuff to be done repeatedly
  return 0;   // this will never be executed
  }

(It's slightly more complex, to allow for USB where applicable, but that is the idea).

  But still I did not found the step by step guide how to do it.

I'm pretty sure there are a lot of example "make" files around which show the idea.

I have an example here.


You say you have learned these things but were you using a motor shield for the DC motor?  How's about building your own H-bridge. And how many types of stepping motors do you now know how to control?  What about micro stepping? And what about graphical LCDs. Do you know how to make custom characters?

As your list is hardware-centric, I would next task you to learn how to write in C++ and create a library for others to use.  Learn what it means to abstract the hardware down to a few simple function calls.  How to create a class which contains an Arduino library for, say, the graphical features of a particular LCD.


How to communicate the Arduino board with SIM900?

I'll tell you what worked for me, because I didn't find the schematics of this board. But your board may work differently, so it is always good to check the datasheet and the schematic (if you have one).

Power

Be sure to use an external 5V source that can supply up to 2A without dipping significantly.

Code

#include <SoftwareSerial.h>

SoftwareSerial GPRS(7, 8);         //7 = TX, 8 = RX
unsigned char buffer[64]; port
int count=0;
int i = 1;                         //if i = 0, send SMS.
void setup(){
  //delay(10000);
  GPRS.begin(19200);               // the GPRS baud rate
  Serial.begin(19200);             // the Serial port of Arduino baud rate.
  Serial.print("I'm ready");
  Serial.print("Hello?");
}

void loop(){
  if (GPRS.available()){         // if date is comming from softwareserial port ==> data is comming from gprs shield

    while(GPRS.available()){          // reading data into char array
      buffer[count++]=GPRS.read();     // writing data into array
      if(count == 64)break;
    }
  Serial.write(buffer,count);            // if no data transmission ends, write buffer to hardware serial port
  clearBufferArray();              // call clearBufferArray function to clear the storaged data from the array
  count = 0;                       // set counter of while loop to zero
}

if (Serial.available())            // if data is available on hardwareserial port ==> data is comming from PC or notebook
  GPRS.write(Serial.read());       // write it to the GPRS shield
  if(i == 0){
    GPRS.print("AT+CMGF=1\r"); //sending SMS in text mode
    Serial.println("AT+CMGF=1\r");
    delay(1000);
    GPRS.print("AT+CMGS=\"+554988063979\"\r"); // phone number
    Serial.println("AT+CMGS=\"+554988063979\"\r");
    delay(1000);
    GPRS.print("Test\r"); // message
    Serial.println("Test\r");
    delay(1000);
    GPRS.write(0x1A); //send a Ctrl+Z(end of the message)
    delay(1000);
    Serial.println("SMS sent successfully");
    i++;
  }
}

void clearBufferArray(){              // function to clear buffer array
  for (int i=0; i<count;i++){
    buffer[i]=NULL;                  // clear all index of array with command NULL
  }
}

Connection

Testing...

Open the serial monitor Arduino, set the baud rate in 19200 in "Both NL & CR". If not work, set to "Carriage Return". Type "AT" and wait for an OK.

Help

If you need help, these links were useful to me:

http://www.seeedstudio.com/wiki/GPRS_Shield_V1.0
http://www.seeedstudio.com/wiki/GPRS_Shield_V2.0
http://www.elecfreaks.com/wiki/index.php?title=EFCom_GPRS/GSM_Shield


CRC-16 is just a term that describes an algorithm. There are multiple implementations possible. They not only differ by the used polynomial but also by the initial value.

Your particular implementation uses the IBM CRC-16 polynomial.

Other Possible polynomials are for example:
x^16 + x^15 + x^2 + 1 (IBM)
x^16 + x^12 + x^5 + 1 (CCITT)
x^16 + x^10 + x^8 + x^7 + x^3 + 1 (DECT)
(there are more on wikipedia)

Actually you can take any primitive polynomial. (UPDATE: Not using a primitive polynomial will reduce the output space but is still going to work.) So you will have to find out which one you have to use and then know the initial value.

Assume you are right with the IBM polynomial then assume the initial value is 0xffff. You use the function as follows:

uint16_t crc = 0xffff; // the initial value
uint8_t a[]; // your data
crc = crc16_update(crc, a[0]);
crc = crc16_update(crc, a[1]);
…
crc = crc16_update(crc, a[n]);
// done
// crc now holds the value of the data stored in a


Multiple variable shared between threads?

Is the "volatile" keyword really sufficient for exchange of data
between threads (no ISR)?

No - "volatile" just tells the compiler that the variable may change value due to something other than the immediate code being generated and informs the code-generator not to rely on the value remaining static when it would otherwise expect so. When copying the value to a register for instance, it would normally expect that register value to continue to represent the value of the variable in memory but if the variable is volatile, that assumption doesn't hold. This would be used to indicate that an ISR might change it at any time; that the variable is an input register and may be changed from the outside at any time; or that another thread may change it, again, at any time (assuming pre-emptive multi-threading or multi-tasking).
Should "volatile" always be between "noInterrupts()" and "interrupts()", even when there is no ISR function?

No - volatile just describes an attribute about the variable over time

What approaches should be used when exchanging a lot of variables between the threads

Use a semaphore here. A thread that wants access to one of - or the collection of - shared variables asks for the semaphore. The RTOS either returns it immediately, or (because another thread already holds it) suspends the task until it becomes available, and returns it then. The thread holding the semaphore may access the variables (or whatever shared resource this semaphore controls), then returns the semaphore on completion. Semaphores are usually built in to the RTOS.
(As I'm not familiar with your particular RTOS, I'll leave your fourth question for someone who is).


Why is my transistor always transmitting?

Darlington transistors are very sensitive; even putting your hand near it can be enough to turn it on. Either tie the base to ground with a large resistor or switch to a MOSFET with its gate tied to ground through same. In either case put a diode backwards across the coil to absorb the energy from the coil when it de-energizes so that the transistor is not damaged.


Instead of comparing, you can use the modulo operator:

 secondStartHour = (startHour +  6) % 24;

And similar for the others:

 thirdStartHour  = (startHour + 12) % 24;
 fourthStartHour = (startHour + 18) % 24;

While xxxStartHour >= 24, 24 will be removed until it is within range [0, 24).

If you need an offset, you also can add some hours of course after the module (I don't fully understand your example which can have values >= 24.

Also, if you need to do the same task every 6 hours, you can use with one time and 'restart' it every 6 hours (and maybe taking summer/winter time into account).


Press the Windows key using "keyboard.press();"

They Keyboard.press() command accept modifiers per the documentation. You may need to do multiple press() commands before releasing.

For example, if you want to launch File Explorer you could use:

Keyboard.press(KEY_LEFT_GUI);
Keyboard.press('e');
Keyboard.releaseAll();

This is equivalent to shortcut keys Win + E.

The modifier GUI is what stands in for the "command key" which is the Windows Logo on a PC or clover (⌘) on a Mac.

I don't have any restriction on the higher value on my board (Pro Micro), as indicated by @frarugi87.


Most IR remotes send pulses that are at least 400 micro seconds long. E.g. on a NEC IR remote you get pulses that are 560 or 2240 microseconds long (depending on whether it's sending a 1 or a 0).

So with a RESOLUTION of 20 you get at least 20 'pulse counts' for a 0 and 80 for a 1. Because remotes aren't that precise in you'll get somewhere between e.g. 18 and 22 or 78 and 82. Those values are different enough to easily detect whether a 0 or 1 was send.

Changing this RESOLUTION to e.g. 2 will give you 200 or 800 pulsecounts. You'll get a more precise timings from a still imprecise source. But this better precision is useless.

PS setting it to 0 could break the code, as the highpulse and lowpulse are only 16 bit integers so they will overflow after 65536, which will happen pretty fast.

Hope that helps somewhat. Just let me know is anything is still unclear.


The two LEDs in series have a forward voltage of 6v which is more than the Arduino's supply voltage.
Forward voltage is the bare minimum amount of voltage required for the LEDs to start conducting electricity (ie: to allow the current to pass through)
Read this: https://www.baldengineer.com/led-basics.html :

Forward Voltage
The Forward Voltage defines the amount of voltage
required in order to conduct electricity. Any voltages below this
amount will cause the LED to remain “Open” and non-conductive. This
also means any components in-series with the LED will not have current
flowing through them either! Once the voltage dropped across the LED
reaches the Forward Voltage, it will begin to conduct electricity. Not
only that, but the LED will only drop its Forward Voltage at any given
time.
For example, consider a LED with a Forward Voltage rated at 3.0V. Now
what happens if you attach the Anode to the Positive (+) Terminal of a
AA (LR-6) Battery and the Cathode to the Negative (-) Terminal? Will
the LED do anything? No! The AA (LR-6) Battery only has a nominal
voltage of 1.5V. Until you add a second battery, the LED will not
light up.


I personally suggest you MPU6050_tockn library.https://github.com/tockn/MPU6050_tockn

If you use calcGyroOffsets() in setup(), it will calculate calibration of the gyroscope, and the value of the gyroscope will calibrated.

#include <MPU6050_tockn>
#include <Wire.h>

MPU6050 mpu6050(Wire);

void setup(){
  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets();
}

If you use calcGyroOffsets(true) in setup(), you can see state of calculating calibration in serial monitor.

#include <MPU6050_tockn>
#include <Wire.h>

MPU6050 mpu6050(Wire);

void setup(){
  Serial.begin(9600);
  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets(true);
}

Serial monitor:

Calculate gyro offsets
DO NOT MOVE MPU6050.....
Done!
X : 1.45
Y : 1.23
Z : -1.32
Program will start after 3 seconds

If you know offsets of gyroscope, you can set them by setGyroOffsets(), and you don't have to execute calcGyroOffsets(), so you can launch program quickly.

#include <MPU6050_tockn>
#include <Wire.h>

MPU6050 mpu6050(Wire);

void setup(){
  Serial.begin(9600);
  Wire.begin();
  mpu6050.begin();
  mpu6050.setGyroOffsets(1.45, 1.23, -1.32);
}

But if want to do it with Kalman filter goto https://github.com/jarzebski/Arduino-KalmanFilter/blob/master/KalmanFilter_MPU6050/KalmanFilter_MPU6050.ino It will guide you.


Is there any version of arduino that can do something like serial interruption?

It is not a case of "An Arduino" that can do serial interupts. All Arduino boards have serial interrupts, but they are already used to receive the data and store it in a buffer for you to consume when you have the time.

The Arduino API does not define any serial interrupt handling routines. That kind of thing is designed to be handled internally by the API code, not by the user. That's the whole point of the Arduino API - to abstract away such technicalities from the user.

If you want to use the serial interrupt yourself you will have to write your own serial handling code.

Or write your code in such a way that serial interrupts aren't needed.


ESP8266 Serial Communication with ATMega328P

Generally, try to debug the problem.  Evidently either you're not getting data from your esp8266.available() and/or esp8266.read(), or it's not the right data.  Put traces (Serial.println(...)) in, print things out, and find out what's going wrong.

Specifically, I suspect the issue here is that you are relying on all the data being available immediately: you check esp8266.available() which will tell you whether one or more bytes is available.  Then you esp8266.read() until there are no more bytes available.  What if there's a 1ms delay between bytes arriving?  You'll get,perhaps LED O, esp8266.available() will tell you there's no more data (there's not, yet!) and you stop reading.

You could probably get it working by putting a small delay() in:

while(esp8266.available())
{
  command += (char)esp8266.read();
  delay(100);
}

That's a solution (probably) but not a good one.  A better solution would be to make your commands LED_ON\n and LED_OFF\n - and read until you get a \n.


How to differentiate between 2 Micros on Linux

The USB VID, PID and Serial Number are all programmed into the chip when you upload your sketch.  The VID and PID are tied to the board, and the serial number is always the same regardless of which board.

So no matter which board you program it will get the same details as any other board of the same kind.

There's no option to change the serial number (there is, IIRC, actually no serial number defined) but the VID and PID are provided as a pair of macros on the compilation command line: USB_VID and USB_PID.

So you could (cheakily) create a new board definition (based on the existing Micro one) that is "The other Micro" and provide a different (unofficial) PID to that board.  You can then differentiate the two boards in udev using the VID/PID combination.

Of course, you have to then ensure that you have the right board selected when you program them, and the act of entering the bootloader on the "other" board would revert back to the old PID which is programmed into the bootloader, but I'm sure you can cope with that.


Set clockspeed of Arduino Pro Micro a. k. a. AtMega32u4

Absolutely. The built-in prescaler can dynamically change the clock speed for most of the systems on the chip (USB still needs to run at full speed in order to operate properly).

#include <avr/power.h>

 ...
clock_prescale_set(clock_div_32);
sleep();
clock_prescale_set(clock_div_1);
 ...

See the datasheet and AVR Libc documentation for more details.


Global variable won't update inside void loop arduino

Here is my code

your code ran without setup()?

you are conditionally incrementing "x", and if your condition doesn't hold true, the increment doesn't take place.


Why I am connecting positive wire in the circuit?

This is indeed not needed. As you can see in the diagram, the horizontal line which you connected the 5 V pin to.

The horizontal line of holes just above the red horizontal line) are connected. However, since it only connected to the 5V pin of the Arduino, the all pins on that horizontal line have 5 V, but since there is nothing connected to it (thus no closed circuit), the effect is zero.

The reason why the connection is made (the wire from Arduino to 5V), is that it is 'default' to connect both GND and 5V (or 3.3V) as a starting point. It is easy to forget later and than no current will flow when you connect something to the +5 V horizontal line of pins.

Btw, the 3.5 V pin you mention, is 3.3 V, not 3.5 V.


Problem in bootloading my ATmega32U4 chip

If you are developing your own board there are a number of things which can go wrong, although the problem is usually very simple and bootloading will be easy once you fix the bugs.

Possible hardware problems are:

You have bad solder joints / connections.  Even if you think the solder joints are good, try reflowing them again
ISP leads are too long - can lead to data corruption during bootloading
Pins are not correct.  E.g. are MOSI and MISO the correct way around?
Reset pin needs a pullup resistor

Most likely, you have some sort of hardware problem.  Post your board layout (or at least schematic) and we can look at it.  If you have a pro micro board to hand (if not, buy one one ebay or similar), try bootloading that and see whether your procedure works.


7segment display on Multi Function shield - Arduino Uno

So if you click your 2nd link, it includes sample code for various sections of the multi-function shield.
One of them is titled "segment display".
If you look at that code, line 7 defines the bit patterns for each of the digits from 0 to 9:
const byte SEGMENT_MAP[] = {0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0X80,0X90};

If you map them out in binary, you get:
0xC0,   1100 0000   0
0xF9,   1111 1001   1
0xA4,   1010 0100   2
0xB0,   1011 0000   3
0x99,   1001 1001   4
0x92,   1001 0010   5
0x82,   1000 0010   6
0xF8,   1111 1000   7
0X80,   1000 0000   8
0X90    1001 0000   9

A 0 character has all the segments lit except the middle "cross-bar". An 8 character has ALL of the segments lit. But the bit pattern for 8 is 1000 0000. That suggests that a 0 bit means a segment is lit, and 1 means it is off. Since the highest order bit of all of those characters is 1 (off) it suggests that the high-order bit is the decimal place bit. (It's the only bit that never changes.)
So if you replace
const byte SEGMENT_MAP[] = {0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0X80,0X90};

with
const byte SEGMENT_MAP[] = {0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0X00,0X10};

You should get all the digits drawn with their corresponding decimal place lit.
I'd try that first to verify that I'm correct.
I'd then suggest writing code that reads the segments value for each digit, decides if you want a decimal place at that position, and if so, doing a bitwise AND (& in C/C++) on the value with 0X7F to clear the decimal bit for that character. (Remember it looks like a 0 means a given LED segment should be lit.
You could modify the function WriteNumberToSegment() to take a "lightDot" parameter, and have it change the bit if you pass TRUE (1):
void WriteNumberToSegment(byte Segment, byte Value, bool lightDot)
{
    digitalWrite(LATCH_DIO,LOW);
    bool bits = SEGMENT_MAP[Value]);
    if (lightDot) {
       bits &= 0x7F; //To light the decimal for this digit, clear the 0x80 bit
    }
    shiftOut(DATA_DIO, CLK_DIO, MSBFIRST, bits);
    shiftOut(DATA_DIO, CLK_DIO, MSBFIRST, SEGMENT_SELECT[Segment] );
    digitalWrite(LATCH_DIO,HIGH);
}

(I don't remember for sure if bool is a valid type in Arduino C/C++. If not, just replace bool with uint8 in the above.)


Can I power two 5V with Arduino powered with 9V power adapter?

The voltage will be fine - as long as you plug it into the DC barrel jack, and don't try to wire directly to the 5V pins. The barrel jack has a voltage regulator on it that will convert 7-12V down to the required 5V.

But there's a second reading that you need to look at, not just voltage. The 9V adapter will also have a current rating expressed in milliamps (mA) or amps (A, which is 1,000 mA). The Arduino needs around 25 mA to do its thing, and your adapters add to the total current - maybe 20 mA each again. So if your adapter only provides 50 mA, it won't be able to provide enough current and the system won't work.

The USB port provides 5V, but it also provides up to 500 mA, which is more than enough for the job. If your wall adapter is 100 mA or above, that should be enough. And unlike voltage, a larger number for current is better - that's its maximum capacity of supply, rather than something that will burn out the equiment!


One of the first things to know about Arduinos is that that there are a lot of them – and a lot of tools for programming them. For your problem this means that the most likely reason for the problem you are having is a mismatch between the board your are using and the board your tools are set to upload to. Since you've said you're new to the Arduino I'm assuming that you're using the "official" IDE.

So, here are some things to try:

From the IDE main menu, choose Tools > Board and select your board, then
Choose Tools > Programmer and select an appropriate programmer for your board. Without knowing what board you're using and how you're connecting to it I can't offer more specific advice. However, if you Google for something like "beginner tutorial " you're likely to find an answer. Or more likely three answers. You'll need to look at the one that matches the OS you're using on your development machine.
You may also need to select the port that the Arduino is connected to.

If you've gotten this far and haven't solved the problem, here's what I'd do next:

Do a search on the exact error message you're getting – copy it out of the IDE and the paste it into your favorite search engine. Put quotes around the message so that you don't get a bunch of unrelated hits for your search.
Search for tutorials on the board and/or IDE vendor site.
Work through a tutorial from a good beginner's site. I like the materials the Adafruit folks have developed, but there are lots of good resources out there.
Post a question. When you do be sure to:

Describe your environment: the board you're using, the IDE you're using, the OS you're working on, how the board is connected to the development machine, and the basic settings of the IDE.
Explain what you've tried.
Describe, or better, include a screen shot or the actual text of the problem that you're seeing (like you did here).
For some problems it will also be useful to include the code. If you include the complete code then it is possible that somebody could try to actually reproduce your problem.


NEO GPS 6M connecting to Lilypad Arduino

Working code and schematics for Neo 6 and Lilypad.

Try this and, if you still have "not working" situation, please inform problem in more detail.


Arduino web server: redirect to mobile site on SD card?

Yes, it is perfectly possible. you just have to look at the right bits.

Fundamentally there is no difference between an Arduino and any other website, it's just somewhat simpler in how it operates.

All browsers follow the same rules - if they didn't they wouldn't work on the web.  Two of the rules you are interested in are:

Browsers identify themselves along with their OS.
Browsers respond to the "result" code the website provides in a specific way.

Besides the GET request a browser also sends a list of headers.  These contain lots of extra information about the request, including the domain name of the website that is being accessed (so the web server knows which site you want - it's not one webserver per site, that would be impractical.  For instance, the request to show this page from Firefox on Linux has these headers:

Host: arduino.stackexchange.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.6.0
Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: (I won't bore you with this lot)
Connection: keep-alive

The header of note is the User-Agent: one.  That tells the web server that I am using firefox from a 64-bit Intel Linux computer.  If I were to do it from my Android phone it would tell you it's from Chrome on Android.

By looking for that header and parsing it for certain keywords you can find if you're serving to a mobile device or not.

Now the second bullet above - browsers respond to the response code in different ways.  Normally you send the response code 200 which means "I accepted your request and here is the page you asked for".  Another response code that is useful is code 301 which means "The page you asked for isn't at this address any more - here is the new address you should go to instead".  That will then cause the browser to go to the newly provided address instead.

So instead of responding with

HTTP/1.0 200 OK
Content-type: text/html

<web page content here>

You could instead respond with:

HTTP/1.0 301 Moved Permanently
Location: http://myarduino.local/mobile

And the browser will redirect to the new address you give in the Location: response header.

The full list of response codes is here: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

If you want to avoid the overhead of a browser redirect you can just serve different data to the browser depending on what the User-Agent header specifies.  After all, it's entirely down to you what is sent as the content of the page.  Whether you get that from purely programmatical means, or by reading a file off an SD card, is entirely up to you.


Blink without delay for 5 times every 20 seconds

Here is a solution:

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

#define INTERVAL 20000L
#define BLINK_TIMES 5
void loop()
{
    static unsigned long lastBlink = 0;
    static int count = 0;

    unsigned long now = millis();

    if(count > 0) {
        count -= blink();
        lastBlink = now;
    } else {
        if(now - lastBlink >= INTERVAL) {
            count = BLINK_TIMES;
        }
    }
}

/*
 * Do one blink.
 * Return 1 when blink is done.
 */
int blink()
{
  static unsigned long lastFlip = 0;
  static int count = 0;
  bool last = false;

  unsigned long now = millis();

  if(now - lastFlip >= 500) {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    Serial.print(now / 1000); Serial.print(". "); Serial.println("blink");
    lastFlip = now;
    count++;
    if (count == 2) {
      count = 0;
      last = true;
      }
   }

   return (last) ? 1 : 0 ;
}

The count variable controls when to blink and how many times. While it's zero, no blinking.

When not blinking, it keeps comparing actual time with the last time it blinked. When the time exceed 20s, it puts count to five, and in the next loop, the blinking start.

Variables are declared static so they keep their values between loop executions.


your for() loop should end with with either "i=i+1" or "i++" or "i +=1". In your code you are just saying i+1, which doesn't actually affect "i". So the first loop continues endlessly, and the "voltage" variable (which should not exceed 255) continues to go into the "illegal" range. The arduino likely translates the illegal values to 0. Eventually, since 'voltage' is just a 2 byte integer, it will finally become 0 again. This will happen in 65536 * 8ms, which should be about 8.7 minutes. But I don't think that's what you want. ;-)


As Gerben has said, that "golden thing" is a resettable fuse (AKA polyfuse).

It's there to protect the USB port of your computer against excess current draw from a faulty board (which seems to be happening, by the way).

If nothing else is connected to the Arduino and the polyfuse keeps tripping, then the fault root cause is probably a short-circuit in the board. From here there are 2 possible scenarios:

Least likely: an external agent (metallic flakes, dirt, or something like that) might be causing the short-circuit. Inspect the board, clean it and electrically isolate it when plugging it again (avoid the solder joints getting in contact with a conductive surface, use a case or a mat).
More likely: a component has failed in short-circuit mode and is causing the excess current draw that trips the polyfuse. In that case you could try to debug the board (with at least a multimeter, and maybe other instruments) to locate the faulty component and replace it. That's not an easy task unless you precisely know what to do and where to look in the board. You might be better off buying a new board.

If you want to give the repair route a try, check this question. The schematic may be of some help to you. You might want to verify the integrity of the decoupling capacitor in first place.


How to test the sleep / enable function of Stepper Driver?

Just for future reference if anyone needs it I got the following from SparkFun:

On the Big Easy Driver Board, the Step, Dir, Sleep, Reset, and the Microstep pins are all >pulled high with 20kΩ resistors, while Enable is pulled low with the same. So sleep is >disabled (until explicitly enabled) and the stepper is enabled (until explicitly disabled).

For much of the use of this board, there is no real need to adjust these settings, but If you >want to achieve a low-power state you would pull the sleep pin low. This should disable much >of the internal circuitry on the IC. In order to reduce power, Enable should be pulled high >to disable the output FETs.
To test that the sleep function is working on the chip you can just jump it to low (ground). For me it turned out to be an error with the Arduino code rather than the chip. Here is also a good reference about pull-down / pull-up resistors. http://www.bit-101.com/blog/?p=3813


How to make RGB LED blink rapidly one color using FOR or WHILE loop

Simply do this:

int redPin = 8;
int greenPin = 9;
int bluePin = 10;

//uncomment this line if using a Common Anode LED
//#define COMMON_ANODE

void setup()
{
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop()
{
  blinkLed();
}

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
  red = 255 - red;
  green = 255 - green;
  blue = 255 - blue;
#endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

void blinkLed()
{
  setColor(255, 0, 0);  // red
  delay(1000);
  setColor(0, 0, 0);  // off
  delay(1000);
}

This snippet will blink your led in the red color. Put it in your void loop and you are ready to go.

NOTE: Erase the rest of the void loop before putting this in. Don't delete the function though.

EDIT

FULL CODE ADDED


How to control one Mosfet with another mosfet

There's one thing you missed with your arrangement, and that is getting the 12V to turn the MOSFET on.  In your current arrangement it's possible to turn it off, but never on.  Adding a pullup resistor can help:

simulate this circuit – Schematic created using CircuitLab

R1 pulls the gate of M1 up above the switching threshold to turn it on. M2, when on, pulls the gate down below the switching threshold, turning it off.

However: you may have noticed that the switching is now backwards: send a HIGH from the Arduino to turn it off. Which of course has the effect that the output is normally on and you have to actively turn it off.

Again a pullup resistor can help:

simulate this circuit

Now R2 keeps the gate of M2 pulled up (switched on) which keeps M1 turned of. That is, until you actively pull the gate down to ground by sending a LOW from the Arduino.

To ensure that the peltier never turns on when you don't want it to you should also take steps to ensure that the 12V power is never provided without the 5V also being provided - so you could maybe power the Arduino through the barrel jack from the 12V supply.  It doesn't matter if the 5V is provided but not the 12V, but the other way around could mean the peltier comes on with no active control over it.


How to wire up and trigger this SPDT relay?

You can use this connection diagram with your relay

6 pin Relay pin out

Code

int Relay = 8;

void setup()
{
  pinMode(Relay, OUTPUT);
}

void loop()
{
      digitalWrite(Relay, HIGH);  // turn on relay
      delay(2000);
      digitalWrite(Relay, LOW);   // turn off relay
      delay(2000);
}

First check your relay with multi meter then find the Coil, Com, NO and NC points for correct connection.
Hope this will help you.


Yes, you can - if all the "cars" are on the same WiFi network.

If that is the case, then I'd recommend using UDP as your transport layer, and either broadcast or multicast the packets.

I use UDP and Multicast to send sensor data from multiple sensors to multiple receivers on my network. All nodes subscribe to the same multicast address, and the sensors include their own ID in the packet to identify them. A sensor sends out one packet, and all the other nodes can receive it.

However, if there is no active WiFi network already established between the "cars" then no, there's not a lot you can do with an ESP8266. It communicates using IP, and that relies on there being an established layer 2 network (WiFi / Ethernet, etc) already in existence. You should instead investigate more peer-to-peer communication technologies, or communication technologies that don't rely on establishing a connection to a network of any form.  Maybe the nRF24L01+ would be a better fit?


You have to think of your program as having two distinc modes of
operation:

The "fixed servo" mode is entered when you press the button on the
app. In this mode the servo is kept at a fixed position. The mode
lasts for a predefined delay.
The normal (not fixed servo) mode is the default mode. In this mode
the servo is positioned according to the reading of the sensor.

So you need a boolean variable to remember whether the "fixed servo"
mode is active or not, and the code in loop() should take care of
providing the correct behavior depending on the mode, and updating that
variable when needed. For example:

void loop()
{
    static bool fixed = false;  // whether we are in "fixed servo" mode
    static uint32_t fixed_started;  // when the mode started
    uint32_t now = millis();

    // On button press, start "fixed servo" mode.
    if (Serial.available() && Serial.read() == 'a') {
        servo.write(SERVO_LEFT);
        fixed = true;
        fixed_started = now;
    }

    // Get out of "fixed" mode after some delay.
    if (fixed && now - fixed_started >= FIXED_DELAY) {
        fixed = false;
    }

    // If not in "fixed" mode, react to the sensor.
    if (!fixed) {
        if (analogRead(EMG_PIN) >= THRESHOLD) {
            servo.write(SERVO_LEFT);
        } else {
            servo.write(SERVO_RIGHT);
        }
    }
}


Try something like this

void loop() {
  // read the input on analog pin 0 and 1 with delays for stability:
  delay(1000);
  int sensorValue1 = analogRead(A0);
  delay(1000);
  int sensorValue2 = analogRead(A1);

  // print out the value you read:
  Serial.print("val1 = " );
  Serial.print(sensorValue1);
  Serial.print(" val2 = " );
  Serial.println(sensorValue2);

 }


Is an Arduino Uno required to send any sort of command to a NodeMCU?

With erase_flash you deleted the AT firmware from flash. You can load it back with esptool or with Flash Download Tool (Windows only).

AT firmware download page

Addresses for 4 megabyte flash (more in readme.md of AT firmware):

esptool.py -p /dev/tty.SLAB_USBtoUART write_flash 0x0 boot_v1.7.bin 0x01000 at/512+512/user1.1024.new.2.bin 0x3fc000 esp_init_data_default.bin 0xfe000 blank.bin 0x3fe000 blank.bin


Ardunio Mega/ATmega2560: Using Port F or K for both analog inputs and digital outputs

On an ATmega2560, can ports have some pins used for analog inputs but others as digtial i/o?

Yes, the ADC MUX controls the selection of the pin that is connected to the converter. This is independent of the digital pin control.

Cheers!

PS: See the Arduino core source code for further details on the ADC MUX control registers.


Make a new tab in the IDE (top RH corner) with a xxx.cpp file name. Put your code in that. Leave the .ino file blank. Then it will compile. You need to add:

#include <Arduino.h>

... to the start of the .cpp file.

More information: How to avoid the quirks of the IDE sketch file pre-preprocessing

To clarify the question about libraries ...

You do need to put into the .ino file an include for any libraries used in the project. For example:

#include <Wire.h>
#include <SPI.h>
#include <EEPROM.h>

This effectively triggers the Arduino build process to link those libraries into the final executable file.

Related, my reply in this thread: Classes and objects: how many and which file types do I actually need to use them?


ESP8266, sporadically no write access to the file system

I have faced the same issue with my water leak detector, based on esp8266. It was caused by memory leak in the ESP binaries, so, I've updated it to ver 2.6.3

So, you can try to log (print to serial) free memory amount:

extern "C"
{
    #include "user_interface.h"
}
uint32_t free = system_get_free_heap_size();


changing from long to bytes and vice versa

So many problems here:

1) in function call there shouldn't be types, only arguments. byte LongVal_byte = my_function(LongVal);

2) & before variable means "get variable address". However in function prototype long my_function2(byte & LongVal_byte) it means reference to passed variable (and it must be byte), not a pointer.

3) pointer to local variable is returned from my_function. It might be working until pointed memory gets rewrited by something else (another function call or so)

And whole code might look like that:

long LongVal = -4080;
long LongVal2;

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

byte * my_function(long & LongVal) {
  return (byte*)&LongVal;
}

long my_function2(byte * LongVal_byte) {
  return *((long *)LongVal_byte);
}

void loop(){

  byte * LongVal_byte = my_function(LongVal);
  LongVal2 = my_function2(LongVal_byte);

  Serial.println(LongVal2);
  Serial.println(" ");
}

But it is basically exactly the same as before without functions (just no need for memcpy)


You can actually find all the information for what you want to do on the formal Arduino.cc website. They suggest a GSM shield:

But of course you can find many other GSM shields for purchase. Most of them works the same. Arduino.cc also offer a nice GSM Library, with which you can perform HTTP GET/POST queries to a remote webserver (visible over the web).

You can select whatever web server technology you prefer for receiving the data. Using NodeJS, PHP, MVC.NET or any other, you could expose a REST API to perform the update from the Arduino+GSM Shield side using HTTP.

The web server then could analyze the incoming data and display it in any way you like.


Looking for link to Double Pole Single Throw (DPST) relay for Arduino

A relay that can switch 30A on mains voltage is not going to be able to switch directly from 5V. Getting something that can switch from 24V is much more realistic.

High amp relays are often called contactors. 4-pole ones are not uncommon for industrial motor applications. 3 high-amp poles are for 3-phase power and a low-amp one for a control signal.

You can buffer up the signal using a transistor (you'd need one anyway to supply the coil amps) or another relay.


Linear regulators such as the 7805 operate by dissipating the additional voltage until their rated voltage remains.
This - as you noticed - requires a higher voltage  than the rated voltage.
Some variants, labeled as LDO for low drop-out, have reduced requirements for this, but normal 7805 usually require around 7 V to operate correctly.

The difference to the rated voltage is dissipated as heat as per P = U * I, with U being the voltage difference, and I the current pulled by your circuit.

You can use the switching power supply directly, or use a more advanced voltage regulator like the R-78E5.0 directly from 9 V, which has far lower losses.

Another option would be using the 5V from the switching transformer to drive the (less delicate) relays, and use the 7805 only for the MCU and display, but you would still want to use a heat sink in that case.


My Arduino Nano clone doesn't show in the serial this simple code. Why?

You haven't "started" the serial interface.  Before you use the serial you need to tell it to initialize the hardware and how fast you want to communicate.

You need to add, for instance,

Serial.begin(9600);

to your setup() function before you do your Serial.print().


Serial.println for pointers to the byte datatype behaves unexpectedly

A byte is to small to store a pointer value. Instead to casting to
byte, you should cast to uintptr_t, which is guaranteed to be large
enough. On an AVR-based device like the Uno, this is the same as
uint16_t or unsigned int, but uintptr_t is more general.

Edit: From your comment it would seem you want to print the contents
of the array instead of the addresses of the rows. The obvious way is to
loop with two indices:

for (size_t i = 0; i < 16; i++) for (size_t j = 0; j < 6; j++)
    Serial.println(subkeys[i][j]);

If you really want to use subkeys as a 1D array, then cast it to a
byte *, which is the type a 1D array would naturally decay to:

for (size_t address = 0; address < 16*6; address++)
    Serial.println(((byte *) subkeys)[address]);


I assume, that your problem is how to connect everything to the power supply.
You have some different options, depending on your requirements. The linked adaptor (barrel plug to alligator clips) doesn't seem to fit the barrel plug of the power supply. So you cannot use that. Especially it seems, that both are the male part of the connection. For every plug connection you need a male and a female part of the same connector type (much like your power outlet on the wall is a female part, while the power plug on your supply is a male part; in terms of plug systems).

The best way (especially, when you want to not only experiment, but also use it as a fixed product) would be to solder the wires. For this you need a soldering iron, soldering tin and something to clean the iron (sponge for soldering irons for example).

You can buy a barrel jack, solder wires to it and connect them to the Arduinos 5V pin, ground and to the LED strips power lines in parallel (from + pin of the supply one wire each to 5V Arduino and + pin of the LED strip, from - pin of the supply one wire each to ground of Arduino and - pin of the LED strip). Then you can still disconnect the power supply from your project.
If you don't want to buy a barrel jack and you don't need to disconnect the power supply from your project, you can splice up the cable of the power supply (only the LOW VOLTAGE PART!!!). You can use nail scissors, if you don't have other tools for it. Cut off the plug by cutting the cable a few cm before it. Then cut the plastic between the 2 connected parts of the cable for a few cm, so that you get the 2 individual cables (+ and -).  Use the scissors to carefully cut the outer plastic around the cables and remove about 1cm of it, so that you now have 2 cable ends with the bare cable core free. Twist each end, so that it each little copper strand stays in the cable shape. Then solder the cable ends. Now you can take another wire/cable to solder the connections from the two ends to the described parts. Be sure to isolate the connections at the cable (in the best case with shrinking pipes, otherwise you can also use tape).

If you don't want to solder, you can search for fitting connectors for every part. There are breadboard power adaptors, which should work with this power supply. They have pins on them, that you can not only use with breadboards, but you can also connect jumper wires to them. There also exist such adaptors for typical LED stripes, though that depends on the type of strip, that you have. When looking for jumper wires, you should make sure, that they are capable of conducting enough current. The Arduino does not need much current, thus standard jumper wires will be sufficient. But the LEDs can draw much more current, so that the standard jumper wires will start to smolder and catch on fire. Then you need some with a bigger wire diameter.

You can also use alligator clips, but in my experience, they only work for rather specific cases. The connection, that they make, is fragile and can be easily disturbed. They are slipping and rotating easily. When connecting the LED strip, you might easily connect + and - together and destroy the power supply. Also it is almost impossible with most of them to connect to a standard 0.1 inch pin (which are used on the Uno and Nano), without also connecting other pins. Unless you break out these pins with something else (like jumper cables), that is not a good choice.

You can now choose yourself, which way to go. If you plan to do more with Arduino and electronics, I would suggest, that you buy a soldering iron and the needed supplies. You will need it and they only cost a few bucks, if you just buy a simple one (back then I got one for 15€/$, which also had a temperature control, so you can also get it cheaper). If you don't want to buy it, but still want to solder, you could look for a maker space near your location.
I would go for soldering here, because you are very much limiting yourself, when you choose to do not. Then you need to buy fitting parts, which is more difficult.

how do I know what the ground is and the 5v?

For the power supply you can see it on the label. There you will find the following sign:

It means, that the outer shell of the connector is ground (-) and the inner pin is 5V (+). With cables there are 2 possibilities:

Often the wires inside a cable each have an own isolating plastic shell around them, which is color coded. Black is normally ground, while red is 5V/+.

When having a 2 wire cable, the cable is often designed as coaxial cable (which reduces noise on the signal). In that case you have one inner wire, which has it's own isolating plastic shell, and the outer wire, which is laid around the inner wire without any further isolation. The outer wire is normally ground.

When using an extra cable for connecting 2 parts, make sure to use the same wires on both sides (for example the red wire for 5V on both sides).
To be sure, you can check the voltage on the wires with a multimeter (also a very useful tool), when the cable is connected. A multimeter has a positive and a negative lead, which are marked as red and black respectively. When you connect the multimeter to the wires and it shows a positive voltage, you have found the correct association of the wires with their voltage (5V or ground).


Flash "sketch" hex over ISP, without bootloader - possible?

You don't need the arduino bootloader on the chip, if you are programming it using ISP.

It looks like BSD is no longer supported by avrdude.

In the Arduino 1.5 IDE you can add programmers, so you can do the uploading right from the IDE, instead of 'stealing' the hex file and manually uploading from the command line.

If the chips are blank you probably need to change the fuses first.

You don't need a 16mhz crystal. The atmega328 has an internal 8mHz oscillator inside.


Can the Arduino interface with USB devices without the USB host shield?

First things first you need to learn the basics of how USB works.

In USB there are two main "things": Hosts and Devices.

You have one Host (usually your computer) and many Devices (such as Arduinos, Printers, Scanners, Webcams, WiFi dongles, etc).

Being a host involves knowing about what devices you are going to have attached to you and how to communicate with them. Being a device means just communicating with the host in your own way.

As you can see it is a far more complex job being a host than being a device.

Arduinos are devices. The small USB interface chips they use are very low powered and can only be a device, never a host.

If you want to plug a device into something it has to be a host (note: I am purposely ignoring hubs here).

The Arduino Due uses a far more powerful chip, and that is capable of being a host (using what is known as On-The-Go mode).

To do it with anything less powerful than a Due you require additional hardware that is specifically designed to be a USB host - and that is where the USB host shield comes in. It has a chip that is designed specially to be a USB host so you can plug a device in to it.

None of the chips on the Uno are designed to be a host. They just don't have the power.


Okay, lets say the output of your BNO055 is called x and the value for your servo is y. We need to translate x to y and you are correct to use the map() function. But what you are forgetting is that you do not need to map all the values of x to all the values of y. You can split it up.

In your example the values of the BNO055 relate to the servo as follows:

x   | y
0   | 0
120 | 0
300 | 180
360 | 180

The servo only rotates from 0 degrees to 180 degrees between the BNO055 sensor values of 120 and 300. So you only need to map those values, while all values below should result in 0 and all values above should result in 180 degrees for the servo.

This translates into the following code:

//x is the output of BNO055 sensor
if(x < 120){
  servo.write(0);
}
if(x > 300){
  servo.write(180);
}
if(x > 120 && x < 300){
  y = map(x, 120, 300, 0, 180);
  servo.write(y);
}

Another way of coding this is:

if(x < 120){
  servo.write(0);
}
else if(x > 300){
  servo.write(180);
}
else{
  y = map(x, 120, 300, 0, 180);
  servo.write(y);
}


Wiring 5V ultrasonic sensor to Arduino Due

Is this too clunky?

https://www.adafruit.com/products/735

Breadboard Friendly 8-bit Logic Level Shifter, $1.50.


On UNO R3 the HID protocol is handled by the secondary AVR present on the board. Which is the one talking to the PC. So what you should modify is the code implementing the USB protocol on the secondary AVR.

The main (328p) AVR interacts with it through the serial port.

You do not need to alter the Linux driver, since it already supports the driving of the usual LEDs (CAPS, Num Lock, Scroll Lock), if these are enough for you.

So, to recap:

1) enhance the HID implementation to understand LED status commands coming from the PC

2) report such changes over serial

3) on the primary AVR, monitor for such messages coming over serial port from the secondary AVR and use them to drive the LEDs.


LCD prints weird characters when I place the print statement in setup after pinMode statements

The capacitor between 5V and GND effectively acts as a small battery. When a sudden demand in a current relatively large occurs, the system can get that extra small amount from the cap and not experience a voltage drop.


No, you can't. All you have is a UART interface through a USB to UART adaptor. It can only ever be a UART.

The best you could get would be to write a program to run on the NodeMCU that did the monitoring for you (assuming you can get it into a suitable promiscuous mode) and report information back to you through the UART.


Access is denied. Error compiling for board Arduino/Genuino Uno

High likely one of the intermediate/binary files is in use. For example:

When you have it already opened in a debug session
Having it opened in multiple instances of your IDE
Having it opened in another application
Having closed an application that locked the intermediate/binary file(s).

What you can do:

Close the debug session
Close all applications related to the project
Restart your computer


Powering Infrared and Sonar sensors using BEC

I've managed to solve the problem. When external power supply is used to power multiple sensors, connect the GND of that supply with that of the Arduino GND input. For more details, refer to the link below.

http://www.thebox.myzen.co.uk/Tutorial/Power_Supplies.html


You write,

  The blog post mentions a 0.1uf capacitor in the hand-drawn sketch but the Fritzing diagram shows a 10uf capacitor. I am using the 10uf capacitor.

The Fritzing diagram in the high-sensitivity-vibration-sensor at davidhoulding.blogspot.com shows a 10μf capacitor connected from +5V to ground on the breadboard.  This is a reasonable thing to do, to avoid power supply glitching on that board.  It is ok to add an 0.1 μf capacitor in parallel (that is, in addition to, and connected to the same busses) to the 10μf if you want to suppress some noise as well.

The last diagram in the blog, an “updated circuit diagram showing the refinements for reducing the gain to avoid op-amp output lockup, and DC decoupler on the input”, also shows an 0.1 μf capacitor connected between the piezo node and the first op amp input.  This will block any DC voltage coming out of the piezo from going into the op amp input.  It's likely that any capacitor from 0.05 μf up to 0.5 μf will work just as well there.  A smaller coupling capacitor is suitable for higher frequency inputs, and a larger one for lower frequencies.  The presence or absence of that capacitor probably isn't the problem with your circuit.  Looking at your circuit photo, the wiring looks ok[*].  Perhaps try substituting a different piezo element, or a signal generator if you have one, or a low voltage from a pot varied up and down, to generate a signal into your op amp and comparator stages to see if they are working.  If they aren't working, substitute for the LM358.

[*] Although I can't see if the 220KΩ resistor goes to +5 or to pin 1.  Also is your comparator output connected into digital pin 8 on the Uno?  It looks more like 9 or 10 in the photo.  Also, as a personal preference I'd attach the Arduino end of the ground wire to a pin next to the +5 instead of to the ground next to Aref.


Converting three axis magnetometer to Degrees

The answer given by Dave X, namely

az=90-atan(y/x)*180/pi

is on the right track. However, it cannot work as is for two reasons:

The formula fails badly whenever x = 0,
It gives the same azimuth for x = y = 1 and for x = y = −1. In other
words, it cannot differentiate between north-east and south-west.

The formula could be fixed by replacing atan(y/x) by a function that
returns:

atan(y/x) if x > 0
π/2 if x = 0 and y > 0
−π/2 if x = 0 and y < 0
atan(y/x) + π if x < 0 and y ≥ 0
atan(y/x) − π if x < 0 and y < 0

That would be essentially a two-argument, “quadrant-aware” version of
the arctangent, yielding results in (-π, π] instead of
(−π/2, π/2).

Fortunately, such function already exists. It is a very standard
function of the C library and is called atan2(). Thus, the correct
formula is

az = 90 - atan2(y, x) * 180 / M_PI;

Now, since atan(y/x) = π/2 − atan(x/y), the formula above can be
simplified into

az = atan2(x, y) * 180 / M_PI;

This formula gives the direction of the (x, y) vector counted clockwise
from the y axis. It is likely that the OP wants instead to know the
heading of some kind of vehicle. The correct formula depends then on how
the magnetometer has been mounted relative to the vehicle. If we assume
that the x axis of the magnetometer points forward and the y axis points
to the left, then:

the vehicle is heading north (0° magnetic heading) when the horizontal
component of the magnetic field is along +x
the vehicle is heading east (90° magnetic heading) when the horizontal
component of the magnetic field is along +y

From here, it follows that the vehicle heading is

heading = atan2(y, x) * 180 / M_PI;

Obviously, the magnetic declination has to be added if one is
interested in the true (rather than magnetic) heading.


ESP8266 HTTPS post body request with WifiClientSecure

You do it like any other POST. It's just you happen to be using a secure client to make the connection.

Open the connection
Send the right headers, including a Content-Type and Content-Length and maybe a Content-Encoding if you encode it.
Send the body

It's not any different to an unencrypted POST request.


A library for manipulate Intel Hex data?

Why does it have to be in Intel Hex format? You could write out the EEPROM to the serial port one byte to a line, or something. Something like this:

#include <EEPROM.h>

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

  for (int addr = 0x0000; addr < 0x0010; addr++)
    {
    Serial.print ("Address = ");
    Serial.print (addr, HEX);
    Serial.print (", value = ");
    Serial.println (EEPROM.read(addr), HEX);
    }

}  // end of setup

void loop ()
{
}  // end of loop

I'm not personally aware of a library that happens to write out/read in, Intel Hex format from/to the EEPROM.

I have code that uploads and downloads files to the Arduino. Inside that is code to read/write Intel hex format. However it isn't a library.

Inside File_Utils.ino are some comments that show the format:

/*
Line format:

  :nnaaaatt(data)ss

  Where:
  :      = a colon

  (All of below in hex format)

  nn     = length of data part
  aaaa   = address (eg. where to write data)
  tt     = transaction type
           00 = data
           01 = end of file
           02 = extended segment address (changes high-order byte of the address)
           03 = start segment address *
           04 = linear address *
           05 = start linear address *
  (data) = variable length data
  ss     = sumcheck

            * We don't use these

*/

In that file is code to write Intel Hex format (reading from Flash, not EEPROM):

void readFlashContents ()
  {
  if (!haveSDcard)
    {
    Serial.println (F("*** No SD card detected."));
    return;
    }

  progressBarCount = 0;
  pagesize = currentSignature.pageSize;
  pagemask = ~(pagesize - 1);
  oldPage = NO_PAGE;
  byte lastMSBwritten = 0;

  while (true)
    {

    Serial.println ();
    Serial.println (F("Choose file to save as: "));

    getline (name, sizeof name);
    int len = strlen (name);

    if (len < 5 || strcmp (&name [len - 4], ".HEX") != 0)
      {
      Serial.println (F("File name must end in .HEX"));
      return;
      }

    // if file doesn't exist, proceed
    if (!sd.vwd()->exists (name))
      break;

    Serial.print (F("File "));
    Serial.print (name);
    Serial.println (F(" exists. Overwrite? Type 'YES' to confirm ..."));

    if (getYesNo ())
      break;

    }  // end of checking if file exists

  // ensure back in programming mode
  if (!startProgramming ())
    return;

  SdFile myFile;

  // open the file for writing
  if (!myFile.open(name, O_WRITE | O_CREAT | O_TRUNC))
    {
    Serial.print (F("Could not open file "));
    Serial.print (name);
    Serial.println (F(" for writing."));
    return;
    }

  byte memBuf [16];
  bool allFF;
  unsigned int i;
  char linebuf [50];
  byte sumCheck;

  Serial.println (F("Copying flash memory to SD card (disk) ..."));

  for (unsigned long address = 0; address < currentSignature.flashSize; address += sizeof memBuf)
    {

    unsigned long thisPage = address & pagemask;
    // page changed? show progress
    if (thisPage != oldPage && oldPage != NO_PAGE)
      showProgress ();
    // now this is the current page
    oldPage = thisPage;

    // don't write lines that are all 0xFF
    allFF = true;

    for (i = 0; i < sizeof memBuf; i++)
      {
      memBuf [i] = readFlash (address + i);
      if (memBuf [i] != 0xFF)
        allFF = false;
      }  // end of reading 16 bytes
    if (allFF)
      continue;

    byte MSB = address >> 16;
    if (MSB != lastMSBwritten)
      {
      sumCheck = 2 + 2 + (MSB << 4);
      sumCheck = ~sumCheck + 1;
      // hexExtendedSegmentAddressRecord (02)
      sprintf (linebuf, ":02000002%02X00%02X\r\n", MSB << 4, sumCheck);
      myFile.print (linebuf);
      lastMSBwritten = MSB;
      }  // end if different MSB

    sumCheck = 16 + lowByte (address) + highByte (address);
    sprintf (linebuf, ":10%04X00", (unsigned int) address & 0xFFFF);
    for (i = 0; i < sizeof memBuf; i++)
      {
      sprintf (&linebuf [(i * 2) + 9] , "%02X",  memBuf [i]);
      sumCheck += memBuf [i];
      }  // end of reading 16 bytes

    // 2's complement
    sumCheck = ~sumCheck + 1;
    // append sumcheck
    sprintf (&linebuf [(sizeof memBuf * 2) + 9] , "%02X\r\n",  sumCheck);

    myFile.clearWriteError ();
    myFile.print (linebuf);
    if (myFile.getWriteError ())
       {
       Serial.println ();  // finish off progress bar
       Serial.println (F("Error writing file."));
       myFile.close ();
       return;
       }   // end of an error

    }  // end of reading flash

  Serial.println ();  // finish off progress bar
  myFile.print (":00000001FF\r\n");    // end of file record
  myFile.close ();
  // ensure written to disk
  sd.vwd()->sync ();
  Serial.print (F("File "));
  Serial.print (name);
  Serial.println (F(" saved."));
  }  // end of readFlashContents

That should give you some tips about how to write out the file. Look in my code to see the reading code as well. However as I said, you don't necessarily have to use that format if you just want to manipulate the data yourself.


How to write a digitalWrite array for MCP23017 expander chip?

Use a variable ( iterator) and count from 0 to 8 (excluding):

void setup()
{
    mcp.begin(0);
    mcp1.begin(1);

    for (uint8 pin = 0; pin  < 8; pin ++)
    {
        mcp .pinMode(pin, OUTPUT);
        mcp1.pinMode(pin, OUTPUT);
    }
}

void loop()
{
    for (uint8 pin = 0; pin < 8; pin++)
    {
        mcp .digitalWrite(pin, LOW);
        mcp1.digitalWrite(pin, LOW);
    }
}

If the order in which the digital pins are written to LOW matters than split them like in your example, (however, I do not think that is the case).

void loop()
{
    for (uint8 pin = 0; pin < 8; pin++)
    {
        mcp .digitalWrite(pin, LOW);
    }

    for (pin = 0; pin < 8; pin++)
    {
        mcp1.digitalWrite(pin, LOW);
    }
}

Note : for clarity I would call the mcp variables mcp1 and mcp2 instead of mcp resp mcp2, or an even more intuitive name if there is a clear function for both mcp's.

Using uint8 creates an unsigned byte instead of an int which saves also one byte of stack memory.