Converting a Sketch to a Library.

I am new to the arduino platform, but I have been working with it several weeks, now. I am very interested in the process for converting a sketch to a library file, which seems to be the best way to combine multiple sketches into one sketch.

I have some questions, I have followed the MorseCode example.

But what I am really trying to do is combine into libraries the Master Read, Master Write, Slave Receive, Slave Send, and Serial I2C Scanner sketches into libraries which I can then use when I need them rather than go through copying and pasting the code.

I plan to utilize I2C for a lot of projects. And I would like an efficient way to declare a master or slave in my programs.

Any help would be greatly appreciated just pointers in the correct direction, I have actually started a spreadsheet where I have all of my code per a separate worksheet and I am going to work my way through each one trying to turn them each into their own library file.

My question is do any of you have any experience with doing this and if so are there some obvious errors the seem to crop up?

I am also wondering if you can point out the obvious sections of code (void loop) (void setup) etc. that would go in the header file and/or the CPP file, I think I understand the purpose of these files, and I am just trying to get a handle on doing it properly.

There only seems to be the one example MORSE CODE to go off of.

Thank you So much this community is a wonderful place to learn.

I’m no expert, but for what it’s worth…

You don’t convert a sketch into a library- you need to put the code to reuse into functions first. At least that’s how I went about it when I created the only library I made.

So it’s not setup() and loop() that you need to consider: it’s the stuff you do in there.

It’s good practice to use functions anyway.

So say for example you find you’re reading buttons a lot… make a function readButtons and call it in loop(). The button values in turn might determine how some leds work, so have another function lightLEDS. It’s the readButtons and lightLEDS that might be candidates for putting into some libraries.

Here’s a link to how functions work.

I attach the library BWOD which I made for BlinkWithOutDelay and here’s a sample sketch which uses it.

/* Blink without Delay in a class in a library

#include <BWOD.h>

BWOD anotherBWOD;

void setup() {
  myBWOD.attach(8, 97, 110);      //pin, on interval, off interval
  anotherBWOD.attach(14, 1798, 1015);

void loop()
} (1.21 KB)