text:
OOP vs Inline with Arduino
I have been programming for quite a while now but I am new to Arduino and AVR Programming. The main question I have about programming these Micro-controllers is are there major differences in designing code in Object Orientated Classes vs the more traditional inline programming I have seen in many examples?
In other words in the world of Arduino/AVR Controllers are there any savings with Memory and Performance utilizing classes or visa versa?
Say for example we have a Class:
class SomeClass(){

private:
   int x;
   int y;

public:
   void foo();
   void bar();
}

SomeClass thisClass;
thisClass.foo();
thisClass.bar();

Would there be any performance or memory gains designing the program in a more inline fashion like:
int x;
int y;

void foo(){ /*** Do something ***/};
void bar(){ /*** Do more stuff ***/};

I tried doing some searches on Stack Exchange and Google but couldn't find quite the answer I am looking for the closest thing I was able to find was this Stack Exchange Question.
The reason I am asking about this is I have a project that needs to be as light as possible and I am not clear how I should be designing my program in this environment.

Edit
Thank you for the answers, this has shed light on things. There is one thing that I am not quite clear about.
Say you have a class that you are designing that utilizes the u8glib as follows:
class UserInterface{
private:
   U8GLIB_ST7920_128X64 Display;

public:
   UserInterface();
}

How would you get around using "Dynamic Memory" like:
UserInterface::UserInterface(){
   UserInterface::Display = U8GLIB_ST7920_128X64(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE);
}

The main question I have about programming these Micro-controllers is
are there major differences in designing code in Object Orientated
Classes vs the more traditional inline programming I have seen in many
examples?
...
In other words in the world of Arduino/AVR Controllers are there any
savings with Memory and Performance utilizing classes or visa versa?

Yes, there is a great difference between using C or C++ for small scale embedded systems such as Arduino/AVR. C++ allows more information to be provide for compiler optimizations.
If you are implementing an OOP framework, platform or runtime C++ and classes can also help with software architecture and reuse. In Cosa a number of OOP design patterns are used to achieve interfaces for both application programmers and device driver programmers. The most common is delegation.
Using abstract classes, virtual member functions, inlining, and templates can help achieve lower foot-print and higher performance than traditional implementations. As an example the Cosa Pin classes are X5-X10 faster than the Arduino core and at the same time smaller in foot-print. Please see the benchmarks.
One thing to "unlearn" from traditional C++ programming is the usage of new/delete (malloc/free). With SRAM size of only a few Kbyte using a heap is very much a risk. The answer is static classes and stack based data.
There is much more to be said about OOP framework architecture but I hope this helps answer your initial questions.
Cheers!

Nice Answer! I updated my question asking about how to get around the dynamic memory (new/delete/malloc/free). Do you have any input on not using dynamic memory allocation? Should everything that needs to be shared throughout the classes be global? That doesn't sound right to me, I was always taught not to use globals if you can help it.

A short comment on your UserInterface example above. The Display is actually object composition (not reference/pointer) so you do not need new. You do need to initiate the Display. The UserInterface construction should look something like this. UserInterface::UserInterface() : Display(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE) { ... }. The necessary Display constructor parameters should be passed to the UserInterface constructor.

OOP is all about encapsulation, hiding data, so sharing should be a minimum (zero). The goal is to more or less only have a number of global static objects that interact. They hold and hide the global state. For the objects the member data is a non dynamic local state. To achieve the goal you need again a set of tricks; program transformations.

An example; Consider the design of a BitSet class that may have variable number of members. The obvious solution is to calculate the number of bytes required and use new/malloc. An alternative is to pass the storage as a parameter to the BitSet constructor. A third alternative is a template class with number of elements as parameter. This allows a member variable that is the necessary number of bytes. Please see Cosa/BitSet.hh for more details on this variant of program transformation. There are more transformations.

I updated my UserInterface example, is that more or less the correct approach? I think I now have a very good understanding on how to implement what I need to.

The Cosa library sounds like it contains many of the features that I am inquiring about. I went to the website and noticed that it is a complete replacement of the Arduino Library. Is the overhead and footprint of Cosa comparable to the Arduino Library?

Cosa is (according to benchmarks) has higher performance and lower memory foot-print. For instance, the Cosa Pin classes are X5-X10 faster than Arduino/Wiring functions, Cosa UART (Serial) can run at up to 2Mbps and 100% bandwidth up to 1Mbps. There is support for events, timed/queued functions (jobs), fsm, proto-thread, threads, etc. But the most important issue is that the classes are designed to work together.

Your update was not correct. The Display should not be static.

I updated my question again, I was thinking that the Display should be static since I only wanted one instance in memory since there is really only one display.

The reason you can't find the answer is because the answer is both Yes and No.
For basic class stuff - defining your class with methods etc and instantiating objects from it - there's little difference in the end result compared with "vanilla" C.  The compiler's optimizations are so good now that performance is just the same. Yes, there may be slight increases in memory use since you're passing an extra pointer with each method call (instead of foo(int x) you have foo(MyClass *this, int x)) but that's so small as to not be noticeable.
The big differences come when you start playing with polymorphism and other advanced topics.  When start doing these complex programs the compiler is not always unable to work out which functions are required and which aren't, and it's not able to cut out the unused functions ("garbage collection"). So you may well end up with bigger code.
That doesn't mean slower code, just chunks of code that are hanging around that never do anything.
Of bigger importance is managing your dynamic memory better than you are used to.  Since there is such a small amount of memory the heap is very small, and as a result it gets fragmented very easily.  Dynamic creation and destruction of objects (new myClass, delete myClassObject, etc) is very bad.  Class objects really need to either be statically defined (in global scope is the most common) or temporarily allocated on the stack (local instances).  Otherwise you're asking for trouble - and the first you will know of it is strange things happening (no error reports or exceptions, you see...).

Alright so if I understand this correctly in this world of programming, classes are used for more of a organizational and portability role than true OOP and that things should be allocated statically and explicitly rather than dynamically. Great thank you, this makes allot of sense and explains why I have been seeing examples and what not written the way they are.


text:
5v to 4.3v Regulator - For SIM800 module
I want to build a simple voltage regulator  3.8-4.2V with atleast 2A Peak Current Capability for my GSM Shield (It doesn't have regulated power supply), I don't want variation or it may burn the board.
Using voltage divider won't help here as there can be variations.
Somewhere i read LDO are for for this task but i am able to get only 3.3v regulator with 800mA supply.
Can i use 3.3v to power the same ?

What GSM shield?

ISTM that the shield may be designed for being strapped to a Li-ion cell by including a regulator, which is why it has such an unusual input voltage range.

@Majenko http://www.ebay.in/itm/262101582335?ssPageName=STRK:MEWNX:IT&_trksid=p3984.m1497.l2649  This shield

That is one of the worst listings I have come across.

any suggestion for small gsm module easily available ?

Most of the key information derives from the well known SIM800, not the carrier PCB.  That said, if you want something cheap intended for 5v rather than direct lithium cell power, look to USB dongles, though you will need a USB host and to issue mode switch commands and wait for them to take effect.

I have a lipo 3.7v, but can't rely on that, if i add more components there can be voltage fluctuations...USB power is not in list because device   has to be fully portable. I don't think i will be getting 5v as power, i might have to use stepup regulator or so...
I just want device to be as small as possible.I am not experienced in itching ( i tried once at home, unsuccessful) .

If you don't think you will be getting 5v as power, your question is improperly titled.  Further, it's quite a stretch to call this an Arduino question, as it is entirely about the GSM module and not at all about Arduino.

Ah..initially i will be using arduino 5v pins..So this is why...3.3v is just for learning.

There are Variable (LDO) Voltage Regulators available. You can set the output voltage using two resistors. E.g. the LM317

Consider using a buck converter for this.  Search ebay for "buck converter" and you will see items like "Buck Converter Step-Down Adjustable Converter Power Module Regulator LM2596.  That title indicates several things:  the converter is adjustable, it steps voltage down, it's a regulator, and it's based on TI's LM2596 chip.  It's rated at 2 A continuous, 3 A peak.
A buck converter has some advantages over a linear regulator:

Lower dropout (in general), ie, the input voltage has to be at least as much as the output voltage, possibly plus a small margin for one FET loss, but doesn't have to have the 1.1 to 1.3 volt margin typical of an LDO regulator.
Higher efficiency (in general).  For example, 95% is not uncommon.  (The ebay item mentioned above shows 92%.)   A linear regulator, whether LDO or not, turns the input-to-output voltage difference into heat.  A buck converter, on the other hand, uses an inductor and a capacitor to store energy; it refills the capacitor at a controlled rate via the inductor as often as necessary to deliver the required load.  The inductor's DC resistance wastes energy, but that resistance can be kept small.
Smaller parts due to high frequency switching operation.  As operating frequency is increased the inductor can be made smaller.  On the other hand, higher frequencies lead to higher switching losses, so there's a tradeoff.  Note, some SOT3-sized (~1.4 mm x 2.9 mm) transistors eg NTR4503 are rated over 2 A at 25°C and might be usable as an output FET for a buck converter chip, and inductors and capacitors also are available in sizes probably as small as you are looking for, but buying them and building your own converter is unlikely to be cost effective.

Seems a fit for me, I want small circuit, a SMD will do, Any other alternative ?

Many buck regulators are built mostly or entirely with SMD components, but ones meeting your power need won't be tiny.

Is there any stepup buck converter, i searched but i am getting up and down combined, I tested device using arduino 3.3v supply, device powered up but no response, I guess arduino cannot deliver enough power.

No, "stepup buck converter" is a contradiction in terms.  Look for "boost converter".  Boost converter efficiency from a low voltage input often is low.

aha...Thank you...And thank you for explanation, it made things more clear.

I assumed from the title that you have 5V to start with.  Starting with 3.3 would call for a boost converter – but getting 2+ A out of the Arduino 3.3v supply won't happen.  (The amps would be 24.3/3.3, going from 3.3 in to 4.3 out at 100% eff; or 24.3/(3.3*0.85) at 85%)

Hmm...I planned to use 3.7v LIPO batter i guess it has current 800mA...I have another battery, will check.Anyway thanks again.

Just be aware that if you're going to be using this in an RF sensitive application, you want to verify that the frequency that the converter operates at isn't going to introduce spurious signals into your application.

@DavidHoelzer I am newbie in electronics, How to do that, Please point to some article or other resource.

Are you doing anything radio related?  If so, what frequencies will you be using?  Compare that to the frequency of the Buck converter and figure out if they are harmonics of one another.

I planned to use 3.7v LIPO battery

That's what your SIM800 module is intended to be directly powered by, without any intervening boost or buck converter.
Behind all the misdirection of a title that doesn't describe what you are actually trying to do, your question is an exercise in going around in a circle right back to where you started.  Don't try to convert energy from the lithium cell to some other voltage and then from there to the allowed input range of the SIM800 (which is very intentionally that of a single lithium cell), rather use the parts as they were intended to be used.

i guess it has current 800mA..

No, it has a capacity of 800 milliamp hours, not 800 milliamps.
A phone or RC model type lithium cell you would find today would have a "C" rating of 10 or better, but even if we assumed one of only 5, that would predict that your cell should be expected to be able to support pulse loads of 5 times the one-hour draw rate, which would be .8 * 5 = 4 amps.

Thanks for comment, I will give it a direct try, At my place its really hard to get components, i had to wait for 10-15 days for component to be shipped, This is why i didn't try... Somewhere i read that it doesn't operate properly at voltage < 4v. I will give it a try and update.

I've updated the title.

Your title is still wrong, as you've admitted hours ago that your source is not 5v.

Ah..Currently i am testing using 5v source...So...

Don't do that.  It's a completely different problem.

Oh..Please suggest a fair title..i will change ..

source: Stack Exchange

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

sort: votes


text:
Addressing contents of array using incrementing variable
Why would this simple code which prints out array values give the right value 240 when the array is addressed with index directly addressed by number
but give 184 when addressed usin a varibale n that is incrementing?
PROGMEM const unsigned char COLSA[8] = {
      240, 240, 240, 240,
      240, 240, 240, 240};  //Stored pattern

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

void loop() {
  int n;
   for(n=0;n<8;n=n+1)
    {
      Serial.println(n);
      Serial.println(COLSA[1]);
      //n=2;  //If I use n in this way things are fine. It prints 240. Else it prints 184
      Serial.println(COLSA[n]);
    }
     delay(100);
}

Because the array is a constant the compiler can, when it knows the entry number (i.e., using a numeric literal) replace the access to the array with the contents of that array index - so it's not looking up the value of 240 at runtime, instead the value 240 has been used where the access to the array was.
However, when accessing it using a variable the compiler can't do that, so it has to actually access the array in RAM.
BUT the array isn't in RAM, it's in PROGMEM, so the address that it's being given for where the array is located is completely wrong.  You're program is telling it "It's in the bedroom" - but you're omitting the important information of: "... of the house next-door.".
PROGMEM and RAM are two completely different things accessed through two completely separate data and address buses - just like two separate houses, they both have a number of rooms in them, and those rooms are called the same thing, but they're not the same room.
So instead of accessing an array by index like that you have to use special instructions to say "Get this value from PROGMEM", such as:
     Serial.println(pgm_read_byte_near(COLSA + v));

That says "Give me the byte that is located at v addresses on from the start of the COLSA array in PROGMEM.

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


text:
Arduino Uno cannot upload any sketch: avrdude: stk500_recv(): programmer is not responding
I'm newbie in Arduino Dev
I got Arduino Uno R3, at first it just worked fine.
I tried to upload my whole project sketch which almost up to the max size of arduino memory.
Then suddenly the upload failed, and i can upload any other sketch even an empty or simple sketch.
I already remove all cables connected, still failed to upload.
I really dont know how to fix this.

The answer below covers everything I would think to try, and most of us have been in this boat at one time or another. It's frustrating. If you got this going, please come back and tell us what the issue was, it might help someone else down the track. If you're still having issues, update with everything you've tried and include some more details (OS, what you've got connected to the board, alternate port results etc). And welcome to SE Arduino!

First stop for me is always the connections (which you've done), the sketch itself (which doesn't sound likely) and then the COM port / baud rate.  If your sketch involves anything with the serial connection, ISR's or power supplies, that could be an issue with the Arduino not listening.  It sounds like you've covered this as well by trying simple sketches.  Next, check the COM port on the host computer (sometimes it changes in Windows) and inside the IDE, the baud rate, and open the IDE serial port and wander through baud rate settings until you get something legible as a response in the serial window.  Also, double check inside the IDE that you still have the correct board selected.  Occasionally / rarely, I've had to reboot Windows to cure the problem.
The good news is, this pain is significant enough that you don't usually make the mistake again, and will probably never forget how you solved it....


text:
Help putting an Arduino project on the Internet
I'm working on quite a big project and I need few advices. Basically, Arduino will be receiving data (Strings) and will work with it. No problems with that, but I don't know what to do with receiving and sending data. Customers (all over the country, so the program will not run on LAN) will send the data, but the question is, via what? Application, that will make a TCP connection to Arduino, send UDP packet or maybe a website? Customers need to have access to data (it needs to be refreshed when arduino deletes it too). What would be the most efficient, easy to use and reliable system?
Next thing I want to know is how to make a connection. Open a port on router and connect arduino to that router? I currently have a python script that actually sends an UDP packet to local IP and it works great, but it is limited to LAN. Will it work if I just change the IP (to external) and send it to the port?
And the last thing (for now). I know how to programm in python and java. Which one is better for connections and GUIs?
Thank you for your help, and if you need any more info about the project, I will be happy to edit this post.

I modified title to match your question, hopefully that will interest more readers.

I am quite surprised people don't try google chart API if they really want to plot graph of sensor data. Setting up any arduino project over internet open to people just requires static ip and forwarded port, for Arduino projects I do not proffer default 80 port. I run apache on raspberry pi that manages everything.

What would be the most efficient, easy to use and reliable system?

What seems to me is that you need what is called Unified Application Routing. There are various technologies to do that but what I suggest is WAMP  (Web Applicaton messaging protocol, do not get confused with wamp server stack) but you can check this comparison table and select the one that most helps you. Based on that what I suggest is crossbar.io. Is open source with a lot of examples, runs on small devices (raspberry pi for example) and is intended for the use you propose, connect devices and let users/apps to get/give information from them. You can publish/subcribe to topics and all devices or apps connected with that topic can read it. Imagine something like an arduino is reading temperatures from a room and publish that data to topic "Temp1". All devices(other arduino, servers, esp8266)  or apps(websites, programs, what ever you clients you imagine) that also are connected at that moment to topic "Temp1" will get that update and act like you want. Wamp also provides a nice feature that is called RPC (remote procedure call). Imagine that you want some real nasty thing in your arduino but it lacks memory or is too slow for that. You can create a program that is, lets say in a raspberry, just waiting for that calculation and returns the result to arduino.
Take a look at this video as an example of what you can do with this ttype of techonologies. A lot of demos also in crossbar.io page. The beauty is that you can program in almost any language you are familiar with. They rely on websockets for the majority of things but crossbar is not restricted to it only, you can even use raw sockets.
As for the second part.
If you create your on server (crossbar lets say) inside the lan you have to forward the port he is listening in your router so other outside your network can access it( and possibly will need to get some kind of Dynamic DNS service if your internet provider do not have statics IPs). Or you can host your server outside your network (crossbar has a tutorial for Amazon EC2 and for Microsoft Azure I think). You only need to port forward server ports.
Hwo do you connect arduino? Use ethernet shields, esp8266, choose a yun or make a combo like arduino with usb + raspberry. That way you can also use your raspberry as a crossbar server.
Here is an example of my home made crossbar.io server using 2 python programs , 1 rboard and a raspberry pi has a host to manage my home heating system and the webpage is being accessed from internet, not local lan.

wow, thank you! I have standard arduino uno with ethernet shield which will handle receiving and sending data. Data will be simple: string which will contain current time (minutes and hours) and date. Time will be handled via RTC (I think this is the best and most reliable solution). I'll take a look at link that you provided and do something out of it.
I'm also not sure what would be the best for customers that are not familiar with computers. How to make app accessible to more devices (lets say android). Should I upload it to google play, so they can download it from there?

If I'm understanding you correctly, you have your application running on a LAN and now want to figure out how to make it accessible over the Internet (WAN). If you're there the next step is relatively straight forward. All you need is an IP address that is visible on the Internet.
You don't say what your connection to the Internet is, so let's look at both of the likely (IPv4) possibilities:

You have a block of publicly visible addresses (something other than an IP address starting with 10, 172.16, or 192.168 that are allocated by RFC 1918), or
You are behind a single IP address using NAT (network address translation) to provide the internal machines with access to the Internet. The internal machines (and devices) will all have an RFC 1918 address and will not be accessible from the Internet – except by traffic responding to requests made by those machines which are routed to them using NAT. For many users this is the more likely case.

In the first case it is simply a matter of connecting the Arduino to a network segment that is connected to the Internet and assigning an IP address (or configuring DHCP). Also, make sure that the UDP port you are using is not assigned to another service.
In the second case you will also need to connect the Arduino to a network segment with access to the Internet, but because of NAT users outside will not be able to get to the Arduino (yet). To solve that problem you will need to map a port and your external address (the address of your router) to a port and the internal address of your Arduino. For example:

Assume your service runs on port 3142 and your IP address on the Internet is 8.9.10.11 and the Arduino is at 192.168.0.42 on your internal network.
Then you would configure the port forwarding settings on your router to direct UDP traffic bound for port 3142 to the internal IP address of 192.168.0.42. Some routers will only allow you to forward to the same port, others will also allow you to use a different internal port as well.
You may also need to open up a "hole" in your firewall to allow traffic to the port where your service runs. The truly cautious will connect the Arduino to a network segment in the DMZ and there will be another firewall protecting your internal computers and devices.

Once you have this set up anybody on the outside will be able to use the service on the Arduino – if they know the IP address and the port number. Typically you would run the service at a well known host name and use DNS to translate the host name to an IP address. From your question I can't tell how you want to advertise the service, that would be another good question…

Thank you for long reply! I understand the basics (I'm computer science student actually), but I don't have real time practice to do that stuff. I know how to connect it to internet (port forwarding, IPs, NAT..), but I'm not sure if it is safe to work with UDP packets (or if I should make TCP connetion).
And if I make TCP connection, how should I do it etc. The point is that every person, who will buy the product, will have it mounted at their place and I don't know what to do with the App - ie. if he needs app on another phone, how will he connect to the right device?

It might be easier to discuss something like this in specifics (if you feel comfortable talking about what the service is and who you expect to be using it). But in generalities UDP is an unreliable service (you are responsible to making sure that the packet gets there and retrying or other wise handling the error if it does not) and TCP is a reliable service – your packet will be delivered correctly or you will get notified that it fails. There are some excellent examples of TCP based services on the Arduino out there. I'd start by looking at them (if you need TCP).

Yeah no problem, my project is basically bell system for churches. Basically, the guy who has to do stuff manually (get to the church, type it in...), will be able to do it via android app from his home. So, app will send it to arduino that will store the time into buffer and then loop over that buffer to check if current time is equal to the time in buffer. It is already working, but only for LAN.

I'd be inclined to do this via TCP, but since you already have it working on UDP I wouldn't change it. The important thing to keep in mind is that you will need to handle failures (the Arduino will have to acknowledge settings because otherwise you won't be sure they were received). Since you have it working on the LAN, all you need to do is the port mapping and then you can start using the external IP (or hostname) of the church – assuming that they have a web site in the building and your device will be added to their network.

Yes, I took care of that, Arduino sends back a message, that he successfully received the data, but I'll probably remake the whole thing, so it'll work via TCP connection. Hmm, they don't have a website. I'm making this project with my ISP, he will took care of internet connection (router, switch, static IP) and I have to take care of everything else.

How will you actually control the bells? I was assuming that the Arduino would be located with the bell controller. The church doesn't really need a web site, there just needs to be some way for the Arduino to communicate with the bell controller and for the "bell master" to get to the Arduino. As long as there is an Internet connection at the church and the ISP has a way to route traffic to the church I think you're good.

Yeah, arduino will be next to the controller (arduino will send the signals to it via output pins) so you got it right. I know, but I'm not sure what will happen when there will be 20 people using this service, and they will want to have it on multiple devices. I guess I'll make 2 more options at registration page on app and I'll tell them IP and port?

Yes. The usual way you would do this is to have the IP address identify the church/bell system always using the same port. So you'd have something like bells.my.church (the bell controller at the church) or my.church.bells (the church within a bell control service). It sounds like you're doing the latter one. Either way the port would typically stay the same. But I don't know of any reason why the port would have to stay the same. It kind of depends on the resources that are available to you. The scheme you suggested would certainly work.

Oh nice, so I'll just use same ports with different static IP's that my customers will type in at login/registration page. One more thing: java, python?


text:
Speed of built in DAC/ADC in Arduino Due
Can someone tell me how fast the built in DAC (and ADC) in an Arduino Due can be written or read? I currently don't have the equipment to measure but need the information to plan my next steps.
I try to move galvanometer mirrors and want to make the voltage/position updates as small as possible. How fast are the internal DACs compared to an SPI connection (where I have to write 2 Byte).

You can find all the specs on the cpu datasheet: http://www.atmel.com/images/atmel-11057-32-bit-cortex-m3-microcontroller-sam3x-sam3a_datasheet.pdf

Could you give me a hint on where I find this information in that 1500 page document? And how does this chip talk to the arduino?

I think the galvanometer is orders of magnitude slower than the DAC. It has to overcome it's inertia, and requires quite some time to stabilize.

The hardware can handle position updates in the range of around 30kHz. Before moving to the Due, I used an RPi 2 with an SPI DAC and couldn't reach that update rate. I hope that you are right, but some numbers on the update rate would be great.

See sections 43, Analog-to-Digital Converter (ADC), and 44, Digital-to-Analog Converter Controller (DACC), in the Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf specsheet.
In particular, subsection 43.2, Embedded Characteristics, says: “1 MHz Conversion Rate”.  Some time diagrams appear quite a few pages later that suggest 10-bit conversions can be done more rapidly than 12-bit.
For the DAC (or DACC, per the specsheet), section 44.6, Functional Description, says:

The DACC uses the master clock (MCK) divided by two to perform conversions. This clock is named DACC Clock.
  Once a conversion starts the DACC takes 25 clock periods to provide the analog result on the selected analog
  output.

AIUI, the Due's master clock frequency is 84 MHz, so DACC Clock frequency is 42 MHz, whence 25 cycles take 575 ns, which is an update frequency of about 1.74 MHz.
For more details about the ADC, see eg
Analog performance, particularly of Due's 12 bit ADC at djerickson.com.


text:
One workspace, two IDEs - Possible?
How can I create a workspace & projects so that either the Arduino IDE or the EclipseArduino IDE may be used to develop the project, interchangeably?
I have both IDEs installed and working but in separate workspaces.
I need:

One workspace that either IDE can understand and work in;
Either to IDE build with the physically same set of library sources;
Whichever IDE I open to see my sources as I last left them, regardless of which IDE I last used.

I want:

The source files to have conventional names - .C or .C++, not .pde or .ino;
Either IDE to build with the physically same set of library object modules;

My use-case is that I work in/with Eclipse, and I teach Arduino skills to people starting out with the Arduino IDE. I'd like to be able to prepare class work at home with Eclipse but open and project it in class with the Arduino IDE. It would be nice if I could demonstrate the two IDEs using the same code. Clearly, I could hack up a demonstration, but I'd rather do it honestly and without sync issues like having to apply twice any changes we made in class.
Update 20 Apr '16:
At @Jantje's suggestion (in the comments below his answer), I created a github issue, "Importing an ArduinoIDE project with the New Sketch Wizard and using same sketch-name, failed." The new sketch would over-write the .ino file with a new, empty sketch.
That issue got fixed in the April 14, 2016 nightly and now works as his answer to this question says it does.

I came across to this issue, but I found out that it is very tricky to use eclipse with some libraries as they dont compile for "not understand it" or "not c standard". One way would be to code with Eclipse and coimpile with Arduino IDE which sounds stupid but... it works

I'm not sure why you want the source files to be named with conventional names (I mean I know exactly why I would want that, but…) – won't that break the compatibility with the Arduino IDE? It occurred to me that if Eclipse uses something like a standard Makefile that you could probably create a rule that would allow you to work with .ino files.

Help me please. I made changes - warnings appear, after I canceled the changes, warnings remain. https://www.youtube.com/watch?v=Y9doeAvnN70

You might find this useful, so I'm sharing here too: I use Eclipse and Sublime Text for editing Arduino code, and I build in the Arduino IDE with it set to "external editor" mode, or using the Arduino Command Line tools. Eclipse has a fantastic indexer and makes understanding the Arduino core much easier. I've written a detailed PDF about using and setting up Eclipse for professional software development, incl for Arduino, here: https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/eclipse/Eclipse%20setup%20instructions%20on%20a%20new%20Linux%20(or%20other%20OS)%20computer.pdf.

Your requirements for not having .ino files and wanting to be able to work with the Arduino IDE are conflicting. Assume we drop that requirement it is very much possible to do what you want.
The Arduino Eclipse plugin has been supporting .ino files for a long time now. You can simply compile Arduino IDE-made sketches. You do not have to make links and so make the folder where your Arduino IDE makes its sketches the workspace in Eclipse.
In Eclipse, for each sketch you want to edit, start the new sketch wizard and use a project name that is the same as the sketch name in the Arduino IDE.
Now you can work in the Arduino Eclipse plugin and the Arduino IDE on the same files.
Important: In Windows, if you use a version of the plugin from before March 3, 2016, you need to delete the .ino.cpp file before starting the Arduino IDE. In Linux, the Arduino IDE ignores this file, but in 1.6.7 on Windows (just tested it) the file gets picked up by the Arduino IDE. You need to restart the Arduino IDE to tell it the file is gone.
From March 3, 2016 onwards, the code in the .ino.cpp file is inside a #ifdef that is not defined in Arduino IDE.

Thanks, @jantje! Is the the .ino.cpp file an artifact of the Eclipse plugin?

the .ino.cpp is indeed an artifact of the arduino eclipse plugin.

I found that the .ino.cpp is ignored by the arduino ide in linux but not on windows. Making the file hidden in windows (that is what the. stands for in linux) didn't help to hide the file for arduino ide in windows.

"start the new sketch wizard and use a project name that is the same as the sketchname in arduino ide." This fails for me - opeing the ino file in Eclipse, I see an empty sketch template, even though the file on disk has my actual code in it.

If the code is there pressing F5 should make it visible. I may have had a auto refresh workspace when I tested it.

@JRobert. Did you get it to work?

Bottom line: It does, and in fact I just opened ArduinoSE to update this. F5 did not cause any action so I put aside my testing until the next day - and magically, it worked! I don't know why, but I'm glad to have it!

cool, Always nice to hear that it works somewhere else than on your own system:-)

I updated my answer because I provided a fix for windows.Now it works regardless wether Arduino IDE ignores the .ino.cpp file or not.

On Mar 3, I wrote "magically, it worked!". Unfortunately the magic was short lived. I just tried to import an Arduino sketch into Eclipse by wizarding a new sketch over the existing sketch. Eclipse over-wrote the sketch that was there.

I think it is better to make a github issue from this. https://github.com/jantje/arduino-eclipse-plugin/issues

Are you willing / able to work with Xcode? There is a package called embedXcode that enables Arduino development on Macs – I'm just getting up to speed with it, but it does appear to allow you to work either in Xcode or with the Arduino IDE (the .ino file is present and is what you edit in Xcode). In my testing so far it appears that the easiest thing to do is to create a project using Xcode and then you can point the Arduino IDE at the project pretty easily, getting Xcode to pick up a sketch started in the Arduino IDE is currently beyond me.
From the point of view of your students I would think that you'd want to keep the .ino file rather than make them learn about the conventions of C or C++. It would also save you the hassle of somehow managing file names – although you could probably get make to do this for you.
I haven't looked into it at all, but I think you could do something similar with Atom (a quick Google found a blog post called Arduino Development in Atom Editor and an Atom package called nino that is described as a "Toolbelt for Arduino") or Emacs, or for that matter Vim is also like to have some Arduino support.

I want to use Eclipse both to remain platform-agnostic, and because I'm familiar with it. I get the point about using ,INO files, and that alone may make my request unrealistic, or at least require that I change file extensions when I go back and forth. I don't mind that the class see and use the magic that the Arduino IDE otherwise does behind the scenes. Just having the projects accessible by both IDEs would be a huge help.

That makes total sense. Does Eclipse use something like a Makefile, seems like if it did there would be a way to teach it how to handle the .ino file. Or maybe it would be enough to create a symbolic link between the .ino and the matching .cc/.c++.

Symlink is the first thing I though of, too. Or Eclipse can be told to recognize .ino extensions. Makefiles: I'm sure it uses them but it auto-generates them. That's some magic that I'd rather not let out of its box! :)

Wise, very wise.

On further reflection on the IDE's behind-the-scenes processing, I personally prefer the stricter language processing (i.e. no invisible fix-ups). More than "not minding" the class seeing the fixups, I prefer it. They should know what gets done on their behalf and be able to do it for themselves in the real-world. To that end, a switch would be welcome in Eclipse for sure, if not in the IDE as well, to turn off that hand-holding. Most people that stay nvolved will eventually outgrow the basic IDE and will need to know how to write the real language for themselves.


text:
Arduino using LCD
I am building a project that is using A12864ZW 128X64 LCD, the question I have is should there be anything in the circuit to prevent damage to the Arduino Mega or the LCD? I am using this example here for a start.
I think I damaged one LCD with the current circuit because everything was working perfect then all of a sudden it was like the LCD Contrast was set all the way up, displaying only a dark screen but I couldn't adjust it with the U8Glib or with the V0. During programming I would disconnect the ground from the Arduino to the Breadboard, when I would do this the LCD would still flicker as it was being programmed. This is why I am wondering if I am missing something.
I read somewhere that putting a MOSFET on the Ground of the LCD that is connected to the Reset pin helps. Another problem that I am having is I am using Eclipse with the Arduino C++ add in and sometimes I can program easily, everything goes as expected but then it will fail to upload until I unplug and reset the board sometimes several times.
Because the program is using pins 11-13 it can create problems because these are the same pins used for programming if I remember correctly. I tried changing the pins used but didn't seem to help anything.

Disconnecting ground while all the other pins are connected and the Arduino is powered up is a very bad idea.  Either manually, or using a MOSFET.
Simply because the power you are feeding in to the screen wants to try and find a way to ground through some means or other - and if the ground is disconnected then that means muscling its way through the IO pins into the Arduino and through to ground that way.  The result is that you damage the LCD screen's fragile circuitry.
If you want to disconnect the ground pin at any time, you must ensure that either the power is turned off, or the power connections to the LCD are disconnected first.
If you want to have the Arduino's RESET toggle the power to the LCD to force a hard reset then you need to use a P-channel MOSFET in the power connection instead, so the ground connection is always connected.

So what is the proper procedure to keep the Mega from getting into a state where it can not be programmed? I know that continuously unplugging and plugging in the USB programming cable can not be good either.

11-13 are only used for ICSP programming (SPI). For normal USB programming it uses pins 0 and 1.

Okay, maybe it is not the LCD that is causing my problems then possibly? I have tried changing the pins used for the LCD and doesn't seem to make a difference with the Mega hanging up. Are there any "Tricks" to keeping the Mega in a state for programming? I am not sure why my Mega is getting into such a state where Eclipse cannot communicate with it until I disconnect then reconnect the USB cable.

It's highly unlikely to be the mega that is the problem, unless you are doing things with the reset pin.  It's more likely to be the computer doing something with the CDC/ACM port - maybe killing the DTR signal.


text:
Arduino Bootloader availability
When I look at arduino and arduino-like boards featuring ATMEGA328 chip, I see that they either use a micro controller or a FTDI chip to program the ATMEGA through Arduino board pin 0 and 1.
This only works because there is a bootloader available on the chip. Is the bootloader present by default or do I need to install it.
What I mean is can I just buy 10,000 ATMEGA328 from ATMEL, put them on boards and program them through UART or do I need to first flash them with a bootloader?

You can ask Atmel to pre-program chips if you're going to buy 10K of them.

@pjc50 Is it from experience? I have a doubt they will do that even for 10K, as it means setting up a process.

Some distributors of programmable ic's will program them for you... it does cost extra.

Not from experience, but http://www.atmel.com/images/atmel-42215-production-programming-of-atmel-microcontroller_ap-note_at06015.pdf / https://electronics.stackexchange.com/questions/38990/preprogrammed-atmel-microcontrollers

Just to be clear; the bootloader is not requires to upload or run code on the chip. It's just there, so you can program the chip using serial, instead of ISP (or OneWire or parallel).

The bootloader is the feature supplied with the Arduino board, but not a chip itself. If you want to clone Arduino (fully or partially), you will have to burn the bootloader yourself.

Is it possible to find the bootloader online, so that I can ask the contractor (the one that will manufacture the boards and put the CMS on them) to burn the bootloader at the same time?

The bootloader is supplied with the Arduino IDE. Also I believe you can find the files on their website (even the sources).


text:
avrdude: verification error, first mismatch at byte 0x0000 : 0x00 != 0x16 using USBasp
I'm having this strange error, which pops up around 90% of the time. I am trying to program my attiny25 using USBasp and the Arduino IDE / library. Sometimes it works, most times it doesn't.. This error occurs on large sketches as well as new sketches, with just the empty setup() and loop() functions. The error looks quite random to me, because my program just uploaded after trying around 10 times. Compiling goes fine. The error always occurs at byte 0x0000, and always in the format 0x00 != 0x _ _. I have six wires (correctly) connected from the USBasp to the attiny25. I do not use any resistors, capacitors etc.
Could anyone tell me what could possibly cause this error, and what to do to fix it?

The cause is most likely the fact that you "... do not use any resistors, capacitors etc."
Connect a 100nF capacitor between Vcc and GND.  Connect a 10KΩ resistor between RESET and Vcc.

I have the same problem. As suggested, I have a 10k resistor between vcc and reset, and a 100nF capacitator between Vcc and ground. However, flashing is still extremely unreliable. Is there anything more I could try?

The problem has to do with the auto-reset feature, so you have to make sure the Reset pin is connected to VCC via a pull-up resistor. Generally, a 10k resistor will be just fine.

10µF capacitor between GND and RESET may also work

I had the same issue even with capacitor between Vcc and GND and resistor between RESET and Vcc. Finally, I use 5V Instead of 3.3V to power up my ATTINY and the problem was solved!

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


text:
Mac Arduino IDE Connection to Min Seg (Mega 2560). No tty
I own a Macbook running OS X 10.10.3 (Yosemite)
I own a Min Seg.
My Min Seg model is built on an Arduino Mega 2560.
Problem
When I connect the board to the Macbook,
using either of the Macbook's two USB 2.0 ports,
using either of two USB A to B cables,
the board lights up, but I am unable to connect
to the tty device using the Arduino IDE.
Tools --> Port offered:
/dev/cu.Bluetooth-Incoming-Port
/dev/cu.Bluetooth-Modem
/dev/cu.usbmodem621 (Arduino Genuino Mega or Mega 2560)

I was expecting to also see:
/dev/tty.usbmodem621 (Arduino Genuino Mega or Mega 2560)
If I unplug the board, the third listed option
from Tools --> Port disappears, as expected.
Verification 1
I opened the System Information utility application.
USB --> USB Bus -->Arduino Mega:

  Product ID:    0x0042
  Vendor  ID:    0x2a03
  Version:       0.01
  Serial Number: 75435353038351316281
  Speed:         Up to 12 Mb/sec
  Manufacturer:  Arduino Srl
  Location ID:   0x06200000 / 3
  Current Available (mA): 500
  Current Required  (mA): 100

Verification 2
I used the Sparkfun Terminal Basics wiki to check for the device.
I used the Terminal utility application.
ls /dev/tty.* offered:
/dev/tty.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/tty.usbmodem621

screen /dev/tty.usbmodem621 9600 offered a successful connection.
[A white screen, which allowed for exit using Control+A followed by Control+/]
Attempted Solutions
I tried several means from here:
I installed the FTDI drivers.
I ran sudo nvram boot-args="kext-dev-mode=1" in the Terminal application.
Is an alternative driver worth attempting, such as that listed here?
I also attempted to connect through Mathworks Simulink.
When setting connection options, the program states
that a cu device is expected, rather than a tty.

Is it normal that the Arduino IDE picks up ONLY the cu devices and that the terminal picks up ONLY the tty devices?

What you are seeing is normal.
In BSD (which is the OS that Mac OS is based on) a serial port has two distinct devices for two distinct roles.
The tty, or TeleTYpe interface is used for incoming connections, be that from a modem, serial terminal, whatever. You would normally run a process called getty on it to present a login prompt.
The cu, or Call Unix interface is used for making outgoing connections to other devices. Traditionally that was mainly other Unix servers through modems. Nowadays it includes many other devices such as an Arduino.
The theory is that when you try and initiate an outgoing connection through the cu interface it first checks that no-one is connected in through the tty interface and if the serial port is available it disables the tty interface so the listening getty process doesn't interfere with your call. Also the tty and cu interfaces deal with the modem control lines differently.
The Arduino IDE is merely honouring that system by only offering you the outgoing device in the port list. As far as the Arduino communication is concerned there should be no difference.

Why does the Arduino Getting Started guide only suggest the tty interface?

@kando Because it is out of date and the person that wrote it didn't understand the difference.

Oh. Fair. They should fix that : j


text:
How to display variables on 0.96" OLED with u8glib library?
I have Arduino Uno and 0.96" I2C Oled 4 Pinned display. These are my Arduino codes:
#include "U8glib.h"

U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE);    // VDD=5V SCL=A5 SDA=A4

int a = 10;

void setup(void) {
}

void loop(void) {

  u8g.setFont(u8g_font_gdr25r);
  u8g.drawStr(8, 30, "E");
  u8g.setFont(u8g_font_gdr25r);
  u8g.drawStr(30, 30,"l");
  delay(2000);

  //  u8g.println(a);  //This code raw is not working
  //  delay(2000);
}

I am trying to indicate integer type variable is called "a" to the OLED screen, but u8glib library hasn't got

println( (int) a );

function to do this. I only see

u8g.drawStr();

function that this can't handle integer variables to the display. How can I do that?

The U8glib user reference page mentions a couple of ways to print the value of a number using ASCII characters.
Eg, following the idea at the second mention of sprintf at above link:
char buf[9];
sprintf (buf, "%d", a);
u8g.drawStr(33, 33, buf);

Edit: The above follows the example at the link, but I've struck it out because in general snprintf is safer than sprintf.  See below.
enum {BufSize=9}; // If a is short use a smaller number, eg 5 or 6
char buf[BufSize];
snprintf (buf, BufSize, "%d", a);
u8g.drawStr(33, 33, buf);

The other way is via print.  (Search for U8GLIB::print in above link, and also see arduino.cc's Print docs).
Eg:
u8g.print(a);

To get a newline effect, you may need to have a variable keeping track of the current line number; add 1 to it to get next line's number, and use that as a position parameter in a drawStr call.

Ok, I have found the solution (Thank you @jwpat7) Here is my working code:
#include "U8glib.h"

U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE);  // VDD=5V GND=GND SCL=A5 SDA=A4

int a = 0;

void setup() {      }

void loop() {

u8g.firstPage();
 do {
u8g.setFont(u8g_font_gdr25r);
//u8g.drawStr(8, 30, "Eeee");

char buf[9];
sprintf (buf, "%d", a);
u8g.drawStr(18, 3, buf);

  } while( u8g.nextPage() );
  delay(200);
}


text:
Any way to use F macro with a passed variable?
I want to know if it's possible to use the F() macro on text that is being passed to a function.
This is an example function:
void displayMenu(const char * txt, byte &var) {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(txt);
  lcd.setCursor(0, 1);
  lcd.print(var);
}

This is how I'm calling the function:
displayMenu("Backlight:", backlight);

If I didn't separate the repeating code into a separate function, I would've been able to write it out like this:
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Backlight: "));
lcd.setCursor(0, 1);
lcd.print(var);

If I try to do:
displayMenu(F("Backlight"), backlight);

it doesn't work. Also if I try to do this in the function:
lcd.print(F(txt));

that also doesn't work.
I'm just wondering if such a thing is possible.

There is a special type for just this occasion - the __FlashStringHelper type.
void displayMenu(const __FlashStringHelper *txt, byte var) {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(txt);
  lcd.setCursor(0, 1);
  lcd.print(var);
}

Note I removed the & from var - you don't want that unless you are passing a complex class or are wanting to modify the contents of var in the function and have it reflected back outside the function.  Passing a reference to a byte (&var) requires two bytes of data - just passing the content of a byte only requires one byte of data.

That's awesome! Thanks a lot! At first I was getting "cannot convert from type X to type Y..." errors, but I fixed it by enclosing all the passed text inside the macro, like this: displayMenu(F("Backlight"), backlight); And thanks for pointing out the & problem! I probably had accidentally copied that from an older function I was using that actually needed to modify the passed variable.

I feel silly for asking the following, and I'm sure it's just the "Everything feels snappier!" bug, but just to confirm... Is there any way that this change in the code might've perceptibly increased the lcd display speed, like when switching between menus?

The removing of the & may have had a very slight effect on the speed, but it's unlikely the text changes have done anything...


text:
Arduino Micro tone() PWM Pins
according to the tone() documentation using tone() interferes with PWM output:

Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

On my Arduino Micro it seems to interfere with PWM on pin 5. After using tone() the PWM does not seem to work anymore. If I use pin 3,9 instead everything works fine.
So can someone explain why that is happening and if there is a way to circumvent that?

It's called a resource conflict.  The Arduino only has limited resources, and some resources are shared between different tasks. You can use that resource for one task or the other but not both.
In this case the resource is a timer.  You can use that timer to generate PWM or you can use it to drive the tone() system - but not both.
By default the timer is configured for PWM, but once you use tone() it re-assigns the timer to be used to trigger an interrupt at a specific frequency to toggle an IO pin.

ok thanks, but I don't want to use both simultaneously. Can I manually re-assign the timer back to the PWM?

It may be doable, but there isn't (AFAIK) a single function to do it. You will have to undo whatever tone does and re-do whatever PWM does.  Look at the source code to both the tone() command and the analogWrite() command and associated functions to see what they do.

ok I understand. That's not worth the effort for me. I will just avoid pin 5 then.

You could just extend disableTimer, to reset properly timer 3, like it does for timer2. Or force it to use timer 2 (here). Shouldn't be to hard, but might indeed not be worth the effort.

The pin 3 and 11 only refers to boards based on the ATMega328. On these boards timer2 is used by tone, disabling PWM on pins 3 and 11. See Majenko answer about timers.
The Micro (ATMega32u4) tone uses timer 3, which is connected to pin 5 only.
So on the Micro, just don't use pin 5 for PWM when using tone.
Secondly don't trust everything on the arduino.cc website. There quite a bit of misinformation on there.


text:
How to send and receive hex or binary numbers via BLE UART?
I am trying to send hex or binary numbers through BLE UART, but it is taking only char value which is converted into ASCII value.
I am using Adafruit's Bluefruit micro device and Bluefruit LE apps.
https://github.com/adafruit/Bluefruit_LE_Connect_Android
https://github.com/adafruit/Adafruit_BluefruitLE_nRF51
Serial.print(F("[Recv] "));
Serial.println(ble.buffer);
BluetoothData=ble.buffer[0];
Serial.println(BluetoothData);

In the UART box I want to type only a hex number and receive it in the Ble.buffer of the Arduino only.

Perhaps you should post your actual code, and explain what you're trying to achieve, rather than how you're trying to do it.

ASCII is just a pattern of 0s and 1s, and can therefore be represented in binary, hex, octal, or decimal. The interpretation is entirely up to you in your code.

Representation is ok becoz it is possible only after receiving . i am asking about that if i type 0x01 on BLE apps than what value receive by uart.

The hex button toggle switch will show what the value of your characters are in hex. find the character that matches the value you want to send and use that. if you type the string 0x01 the app will send 0x30 0x78 0x30 0x31 0x0A. Since it trys to convert your characters to hex.
this table is pretty handy showing what characters are represented by which hex numbers http://web.cs.mun.ca/~michael/c/ascii-table.html.
unfortunately the character representing 0x01 is pretty difficult to type.
You can work around this issue by using the toInt() function in Arduino if you send the number 1 as a character the toInt() function will convert it to an int with value of 1. The hex equivalent is 0x01.

Following code changes have been made to send the values in hex as input from user

replace the utf-8 conversion

value = message.getBytes("UTF-8");
by hex
int len = message.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
    data[i / 2] = (byte) ((Character.digit(message.charAt(i), 16) << 4)
            + Character.digit(message.charAt(i+1), 16));
}
value=data;

suppress the exception headlining for UnsupportedEncodingException
otherwise it throws a compile time error  UnsupportedEncodingException

Result examples :
3F ( hex ) results in ? ( ascii )
63 results in c

This is a question about data representation. The value you are entering is a string, a sequence of characters, e.g. 0x42. The string can be parsed and converted to binary form either on the transmitting or receiving side.
The string must first be checked that it is valid. In this case a valid hex or decimal number. There are conversion functions that do both at the same time. The standard string function strtol() is perfect for the job. With zero as base argument it will parse both hex, oct and dec number formats.
// Receive string
char buf[BUF_MAX];
...
// Convert string to number
char* bp;
long value = strtol(buf, &bp, 0);
bool valid = (*bp == 0);

There is also an unsigned variant, strtoul.


text:
Two commands in Void loop?
So basically I'm making 2 buttons turn on and off 2 different LEDs using debounce.
I got that settled with one button to turn on and off 1 LED.
But how do I make it so I can use the same lines but obviously different names of pins in Void loop?
So this is the one command line, but how do I make 2 commands with the if statement, may I have an example? Thanks
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int inPin = 22;         // the number of the input pin
int inPin2 = 26;
int outPin1 = 13;       // the number of the output pin
int outPin2 = 6;

int state = LOW;      // the current state of the output pin
int reading;           // the current reading from the input pin
int reading2;
int previous = HIGH;    // the previous reading from the input pin
int previous2 = HIGH;

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

//===============================================================================================
void doIt(int outPin)
{
  Serial.print("Button Switch State Change:");
  if (state == HIGH) state = LOW;
  else state = HIGH;
  Serial.println(state);
  lcd.clear();
  lcd.print("Zone1|State: ");
  lcd.print(state ? F("On") : F("Off"));
  Serial.print(state ? F("On") : F("Off"));
  digitalWrite(outPin, state);
}
//===============================================================================================
void setup()
{
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("System Activated");
  //
  lcd.setCursor(0, 1);
  lcd.print("Ready...");

  pinMode(inPin, INPUT);
  pinMode(outPin1, OUTPUT);
  pinMode(inPin2, INPUT);
  pinMode(outPin2, OUTPUT);

  Serial.begin(9600);
  Serial.println("System Activated");
  Serial.println("Made by Mateo Holguin");
  Serial.println("0 = Light is Off | 1 = Light is On");
  Serial.println("=======================================");
}

//===============================================================================================

void loop()
{
  reading = digitalRead(inPin);
  reading2 = digitalRead(inPin2);

  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    doIt(outPin1);
  }
  else if (reading2 == HIGH && previous2 == LOW && millis() - time > debounce){
    doIt(outPin2);
  }

  previous = reading;
  previous2 = reading2;
  time = millis();
}

So basically I just added the sketch to this post.

Edit: Use the code below as it is, it's working for me:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int inPin = 22;
int inPin2 = 26;
int outPin1 = 13;
int outPin2 = 6;

int state1 = HIGH;
int state2 = HIGH;
int reading;
int reading2;
int previous = HIGH;
int previous2 = HIGH;

int debounce = 150;   // the debounce time, increase if the output flickers

//===============================================================================================
void doIt(int outPin, int state)
{
  Serial.print("Button Switch State Change:");
  if (state == HIGH) state = LOW;
  else state = HIGH;
  Serial.println(state);
  lcd.clear();

  if (outPin == outPin1)
    lcd.print("Zone1|State: ");
  else if (outPin == outPin2)
    lcd.print("Zone2|State: ");

  lcd.print(state ? F("On") : F("Off"));
  Serial.print(state ? F("On") : F("Off"));
  digitalWrite(outPin, state);
}
//===============================================================================================
void setup()
{
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("System Activated");
  //
  lcd.setCursor(0, 1);
  lcd.print("Ready...");

  pinMode(inPin, INPUT);
  pinMode(outPin1, OUTPUT);
  pinMode(inPin2, INPUT);
  pinMode(outPin2, OUTPUT);

  Serial.begin(9600);
  Serial.println("System Activated");
  Serial.println("Made by Mateo Holguin");
  Serial.println("0 = Light is Off | 1 = Light is On");
  Serial.println("=======================================");
}

//===============================================================================================

void loop()
{
  reading = digitalRead(inPin);
  reading2 = digitalRead(inPin2);
  delay(debounce);

  if (reading == HIGH)
  {
    state1 = !state1;
    doIt(outPin1, state1);
  }
  else if (reading2 == HIGH){
    state2 = !state2;
    doIt(outPin2, state2);
  }
}

Oh one question, do I have to do void doIT (int outPin) for both outputs?

I added what you had, but when I press the button, nothing happens, can you review for me please?

I put the code as an edit above

You have a mistake in the loop(), you don't actually need to call digitalWrite(outPin, state); since it's already called in the function doIt().

Another mistake is that you used the same name for two variables which is outPin, this one is already used in the function doIt(). you need to give it another name, say outPin1.

Sorry that I keep bothering you, but I updated the above sketch, and it still seems to not want to do anything.

No problem man, I'm still seeing digitalWrite(outPin, state); in your loop(), all the way down ??

I already removed that, sorry I didn't remove it in this discussion, but in my sketch I did.

Ok, please give me some time, I'll try it out and get back to you.

You're welcome man, do you really need to do the debouncing? why not using a delay after every digitalRead()?

I doubt that's the issue, but the reason why I use it is because its just more reliable, and runs much better for the ram I'm pretty sure, sorry but I am very noob XD

Actually, can you post the same thing but without the doIt? and whatever is in the doIt put it in the if statements? Or edit mine.

If I remove the doIt(), I will just end up repeating the same lines of code in two if statements which is not so pretty ;) anyway try the edited answer I posted since it is working for me.

I'm just now figuring out how to make the Zone1 into Zone2 for the 2nd button, but thanks again!

Easy ;) I've re-edited my answer to do that as well.

Jeez, you are the best XD Thanks Again again again!

I think you are asking
if (value > 5)
{
  StatementOne;
  statementTwo;
}

But I think you might want to write a function, which would look like this
void doThing(int button, int led)
{
  if (digitalRead(button))
     digitalWrite(led);
}

[Edit after reading your comment]
So you need to store the state of the system as a variable in the code.
bool state = false;
if (button1 && !state)
{
  state = true;
  // Your on code.
}
if (button2 && state)
{
  state = false;
  // Your off code
}

You need to add your existing code for turning your LCD and LED on and off where the comments are.
The state variable holds the on or off state of your LCD and LED.
You can of course split it even further so your LCD and LED come on separately of each other.
Does that help?  If so don't forget to mark it as answered.

What I mean is, I have 2 button commands, so if I press it, show something on LCD and led turns on, then when I press it again, do opposite.  I did that with the If command and it worked, but I want 2, so its the same thing but on a different pin

OK, I've edited the answer, because I can't type code in a comment, hope that helps, if not tell me why and I'll have another go :)

Actually, that would work as well! I need to put another command, so ill use this for my sensors! Thank you!

authors: عبد الرحمن عقده


text:
8x8 solenoid matrix
I've been teaching a blind student how to program and build electronics with Arduino. So far I've substituted LED's with piezo buzzers with excellent results. We are getting to the point where more complicated output is required and braille displays are excessively expensive.
I've found these micro solenoids on eBay.

They are 5 volts and small enough to place on a grid to create display. Could I substitute these on a regular LED grid and run it via conventional shift register or MAX7219 methods?
Here is the link to the micro solenoids.

If I understand Chinglish, you won't be able to drive it with the typical LED drivers... it give 350mA for "Current".  That's 30-40 times the normal LED current, and would require special driver circuitry capable of 0.350A * 5 V = 1.75W per device, over 100W to activate all of them!
I think it also says they cannot be continuously activated, which makes sense, given the small package and high power.  Leave 'em on long enough and they would probably burn your fingers.  :(

Well that would explain why no one has tried it this way. When no current is running through them they are extended so I already new that Braille "image" would be inverse. I'm going to keep trying to find a less expensive solution to Braille displays (vibration, air puffs, water cooled, etc). Thanks for your help.

So a 2x3 matrix, the minimum required to display 1 character, it would be 10.5 W? Would the heat be equivalent to a 10 W incandescent bulb?

10W, yes...  Darn close to an incandescent bulb, except for the small percentage of power it radiates as light.  You know, if you have a mechanical aptitude, you might try modifying some "micro vibration motors" used in cell phones (be careful on that spelling :-P), or using geared "micro stepper motor" to lift a rod (rack and pinion).  The stepper has a known rotation, unlike the vibration motors.

The micro vibration motors were my next stop. I'll just have to figure out how to isolate the vibration of each motor.

If you round-over the weight, it might be more like a cam that lifts (jiggles?) a rod.  The pics I've seen seem to show that the weight is crimped on to the shaft.  Dremel work?  The more you take away, the less the travel in the rod.  I think a stepper gear (pinion) next to a "toothed" rod (rack) might be worth investigating.  See here.

I've placed an order of the micro steppers so that I will have them at hand to play with next. My only concern would be refresh rates but when the movement is so small I don't think it will be that big of a deal.

Yes the power requirements are a lot more than LEDs but theres a trick with solenoids which is each solenoid output would be PWM rather than DC.
You could experiment with different frequencies/duties but I reckon start with a 100-200Hz pulse at around 25-50% duty. Can drop your power down by at least a 1/4 or less.
This is obviously a bit more complex than a simple off or on. But solenoids have no problem with holding their magnetic field with a pulse and its recommended to avoid overheating the coil.
Edit: so there are 2 ways to approach it that I see. Either dedicate 1 pin on your micro for each solenoid which would go through a driver (with diode protection) and setup a PWM routine to pulse each output. or..
use a matrix approach with an oscillator on each solenoid. Meaning you would just switch the oscillator on and off
The first approach is more code intensive and would be limited by the micro.
The second is more hardware intensive limited by the components you have.
Also to make sure they retract a short reverse polarity pulse would do that.

I'd just go with all shift registers. No multiplexing. Next attach a PWM signal to the enable pin of all the registers to bring down the power usage. You probably want to disable the PWM when activating the motion, then a few milliseconds later enable PWM to hold the solenoids in position. As it requires more power to change, than to hold a position.

Looking at the description. They have a permanent magnet inside, so they are kind of "latching". So using an H-bridge you can have them move outward or inward.
The only problem will be that a finger will be pushing on the shaft. So unpowered, they will move when a finger goes over them. You would have to add some mechanism that moves another pin, and locks it in place.

I have them present and they take quite a bit of pressure to retract when unpowered.

Never mind, I was wrong. It will retract quite easily.


text:
uint8_t * to integer and string
Convert text array/buffer to integer and string.
hi! i'm sending text to an arduino and the output of that library is a
uint8_t array.
Atm the text send is a number between "0" and "1023"
void something(uint8_t * text){
 analogWrite(13,text);// does not work
}
/*
toInt() also not
int() not
atoi() not
invalid conversion from 'uint8_t* {aka unasigned char*}' to 'const char*'
*/

i need to convert it to an  integer or better to a uint16_t.
As i plan to send custom commands in near future it would also be good to know how to convert that array to a string, that i then split/manipulate/parse.. whatever.
i looked in various posts but i couldn't get it to work on that simple example above. i'm new to c++
if it's needed the length is also aviable inside the function.

Your problem is that you are storing your text in an unsigned pointer (uint8_t *)instead of a signed pointer (char *).
If you change all your text types to char * then you can directly use atoi().  If you have a lot to change, though, you can just cast the unsigned pointer into a signed one (and make it const at the same time):
analogWrite(13, atoi((const char *)text));

its from a websocket lib... i would need to rewriter the whole lib...anyway this worked perfectly

btw i will update this analogwrite at 60Hz . is "cast" slow/are there faster ways to convert the buffer to a string or int?

@cocco Cast makes no difference at runtime, only compile time.  There are faster ways to convert than atoi, but they aren't as safe - i.e., they don't do any bounds checking.

it works but i have a bigger problem now. it crashes really fast. i can't send data faster than 2 times per second. maybe you know more about this.http://arduino.stackexchange.com/questions/17811/esp8266-websockets

analogWrite is a function to set a PWM duty cycle value to a pin on the micro
Usually to control a motor speed or LED brightness or similar.
Unless you plan to use the char value to set the PWM value??
A bit more context would help with your problem.

i control a led with websockets. now it works. @Majenko answered it correctly

This isn't really an answer.

I've converted first four bytes to string, and then to int :
void something(uint8_t * payload){
String str="";
char c;
for(int i=0;i<4;i++)
    if (isDigit(c=(char)(*(payload+i))))
        str += c;

int Val =str.toInt();
Val=Val>1023?1023:Val;

analogWrite(14,Val);
}

This is a very inefficient approach.


text:
Communication via IP adress with Arduino IDE and ESP8266
I have two Arduino boards and two ESP8266 modules with the NodeMCU firmware, and I want to make this:
One Aruino will be connected to one module and a vibration sensor, and when this sensor detects some vibration, it will send some data using the ESP8266 module as a server, then, the other Arduino will recieve the data with the other ESP module and display a message to a LCD screen.
I've already programmed the WiFi modules as a server and as a client using NodeMCU firmware and LuaUploader. The issue I have is that I don't know how to make a program in the Arduino IDE that communicate both Arduino boards using the ip adress assigned to both ESP modules, can you help me? Thanks

First, you need a SoftwareSerial interface, since the hardware serial is already used for debugging. To setup a SoftwareSerial this is an example:
#include <SoftwareSerial.h>

const byte rxPin = 6; // Wire this to Tx Pin of ESP8266
const byte txPin = 7; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
}

void loop() {
  while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got Data from ESP8266: " + inData);
     // The rest of your code...
  }
}

To send data from ESP8266 back to Arduino try something like this:
uart.setup(0, 115200, 8, 0, 1, 1 ) -- Change the baudrate to 115200
-- A simple http server
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive",function(conn,payload)
        payload = payload + "\n"
        uart.write(0, payload) -- send it back to Arduino via Serial interface
    end)
      conn:on("sent",function(conn) conn:close() end)
    end)

uart.on("data", function(data)
    -- When ESP8266 receives data from Arduino, it will trigger this event
end, 0)

And how can I send a data through the Arduino to the ESP8266?

I'll send you a link with my code for both Arduino boards and both ESP modules, hope you can help me Codes for my project

Hello, I'll have a look at the codes and get back to you.

You have the esp8266 talking.  Now you need to come up with a method of passing data from the arduinos to the esp.
You can use serial, you can use i2c, spi? Or something of your own design.  The problem wit using serial is the you are already using serial to communicate with the board from your PC.  You can use SoftSerial on the Arduino, but not sure how you'd do it on the ESP.
There are ways of making both boards work as master and slave i2c and spi, but it's probably overkill.
You could use two pins, one pin sends a binary bit and the other to clock the data, set high when new data has been written and set low when it has been read.
Then just use the same sort of algorithm as you did between you eps.
I have assumed that one Arduino is connected to one esp.  Let the ESPs worry about ip addresses.  If you want the Arduino to specify the destination then use a simpler addressing system than IP and let the ESPs translate that.

Well, can I connect the RX and TX pins to another Arduino digital pins so I can use the SoftSerial? @Matt

Also, I programmed the NodeMCU server like this
srv:listen(80,function(conn)   conn:on("receive",function(conn,payload)     print(payload)      conn:send("<h1> Hello, NodeMCU!!! </h1>")   end)   conn:on("sent",function(conn) conn:close() end) end)

You can use soft serial, but make sure you understand its limitations.
The NodeMCU code just needs a tweak to store the data received from the serial and send it when someone connects to the http socket.

After reviewing your codes, I've rewritten them this way, I didn't get a chance to test them though, so try them and let me know.
Server code: a. Arduino
#include <SoftwareSerial.h>

int ledPin = 13;
int txPin = 2;
int rxPin = 3;

SoftwareSerial wifi(rxPin, txPin);

void setup() {
    pinMode(ledPin, OUTPUT);
    Serial.begin(115200); // This baudrate is better than 9600
    wifi.begin(9600);
    wifi.println("dofile('wifiserv.lua')"); // This where it goes
    digitalWrite(ledPin, LOW);
    delay(2000); // delay is necessary
}

void loop() {
  while(wifi.available())
  {
     digitalWrite(ledPin, HIGH);
     String inData = wifi.readStringUntil('\n');
     if (inData.startsWith("Server IP: "))
        Serial.println(inData); // This is just the Server IP address
     else
        Serial.println("Got new sensor value: " + inData)
  }
  digitalWrite(ledPin, LOW); // This means no data is available
}

Server code: b. ESP8266
uart.setup(0, 9600, 8, 0, 1, 1 )
wifi.setmode(wifi.STATION)
wifi.sta.config("mynet","pass")
print("Server IP: " .. wifi.sta.getip() .. "\n")

srv = net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive",function(conn, s)
        data = s:match("sensor=(%w+)")
        data = data + "\n"
        uart.write(0, data)
    end)
end)

uart.on("data", function(cmd)
    -- When ESP8266 receives data from Arduino, it will trigger this event
end, 0)

Client code: a. Arduino
#include <SoftwareSerial.h>

int ledPin = 13;
int EP = 9;
int txPin = 2;
int rxPin = 3;

int dato = 10;

String ip; // Assign this to your server IP

SoftwareSerial wifi(rxPin, txPin);

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(EP, INPUT);
  Serial.begin(115200);
  wifi.begin(9600);
  wifi.println("dofile('wificlie.lua')"); // This where it goes
  delay(2000); // delay is necessary

}

void loop()
{
  long medida = TP_init();
  delay(50);

  if(medida > 1000)
  {
    Serial.println(medida);
    digitalWrite(ledPin, HIGH);

    String cmd = "ip=" + ip + " " + "data=" + String(dato);
    Serial.println("Sending: " + cmd);
    wifi.println(cmd);
  }
  else
  {
    digitalWrite(ledPin, LOW);
  }
}

long TP_init()
{
  delay(10);
  long medida = pulseIn(EP, HIGH);
  return medida;
}

Client code: b. ESP8266
wifi.setmode(wifi.STATION)
wifi.sta.config("mynet","pass")

uart.setup(0, 9600, 8, 0, 1, 1 )
uart.on("data", function(s)
    uart.write(0, "GoSending!")
    ip = s:match("ip=(%d+.%d+.%d+.%d+)")
    data = s:match("data=(%w+)")
    conn = net.createConnection(net.TCP, 0)
    conn:on("connection", function(c)
        print("connected");
        conn:connect(80,ip)
        conn:send("sensor=" .. data)
        uart.write(0, "Data has been sent successfully")
    end)
end, 0)

Comments are not for extended discussion; this conversation has been moved to chat. (cc @DanielCorona)


text:
How do I connect this string of LEDs to my Arduino Uno?
I'm an electronics noob. I have this string of LEDs but don't know how to connect them to my Arduino Uno. As they are wired in parallel, there are two wires / four ends. What do I plug where?

How many LEDs are in the string?  How much current is the string of LEDs supposed to take?  What voltage are they rated at?  What model number, or do you have a spec sheet we can look at?

Connect the negative ( or cathode ) to ground ( 0V )
and the postive ( anode ) to the output pin of the controller.
Firstly connecting that many LEDS directly to a single micro pin is not a good idea. Usually you would need to go through a buffer/driver first which can deliver the correct power to the LEDS.
I'm not that familiar with the UNO but unless that board has a driver circuit on it you might need a few extra components.

What are the specs of the LEDS?

Just to be clear. The resistor isn't necessarily on the anode (+) side of the leds (as shown in the diagram). To easily figure out, which is which, plug one end in the 5v pin and the other in the GND pin. If they don't light up, swap the ends around. The end placed in the 5v is the anode(+).


text:
Arduino IDE, Underlying Code and Libraries
I'm trying to better understand what is going on behind the Arduino IDE. First off I am no expert in C or writing firmware to boards but do have experience in real development.
I see currently the Arduino IDE is one big vast library we first select our board.
What I don't understand is where are our header files? The source files for the board you select?
Not only that we use a number of functions already detected within the IDE where are these located also is any of this code editable?
I had a look through the Arduino directory and most of this stuff looks like its Java I was hoping for C files. Thanks for any links, help or info anyone can give.

In IDE, click File, Preference.  In 4th line ("Show verbose output during:"), check the "Compilation" box.  On the next compile you'll see a lot of the paths.   Then turn it back off.

Just check the source code. Specifically look at Arduino.h, main.cpp and wiring*.
These files should also be present in the Arduino application folder somewhere, but you'll have to go through quite a few subfolders to find them.
The different boards have different .h file that will specify the pin-numbers and other chip specific data.
The "auto detect" functionality is done by keywords.txt files. At least for libraries. That way if you install a new library with keywords.txt file, the library functions-names are recognized.
The processes of taking all these files, and the users code, and compile it all whole story on it's own.


text:
Flexibility of SoftPot Membrane Potentiometer during the use?
Does anybody have some information or experiences with the flexibility of Spectra Symbol's SoftPot Membrane Potentiometer during the use? Is it possible to partly wind it up on a reel (or something similar) and use the remaining part dynamically without loosing precision and control? Are there "ghost touches" caused by the force/pressure of bending/winding the sensor strip? Or should the sensor always be used in a flattened position?
Thanks for any helpful comments.

As you can see from this data sheet it will show you examples on how it is used. https://www.sparkfun.com/datasheets/Sensors/Flex/SoftPot-Datasheet.pdf
I'd buy a curved one just to make sure, because as it bends, the 2 conductive materials will touch.

If I helped let me know, it's the first time I have answered a question.

Oh and also, it does not need to be flat.

Thanks Mateo for your answer. I know that there are different models of the sensor (length, curve, rotary). But my questions refers to the capability of the measurement accuracy/possibility during the use of extremely roll/winding/bend applications (for example mount it around a small flower tub, or use it as a retractable tape measure). I know that the sensor strips are bendable (as the name and soft material indicates), but I don't know about practical limitation of the maximal winding/bending radius.

Let me do some research, it will take me sometime, and I will also ask someone who I know that is familiar with it.  Sorry for the misunderstanding :)


text:
Is it possible to package a sketch with dependent libraries for cross-platform compatibility?
I have a complex sketch that I spent many weeks working on, which I am backing up frequently because I'm afraid of losing any of my progress.
I'm wondering if it's common practice to make a self-contained package of the sketch and all its dependencies, so that it can be moved easily to another OS if necessary. My concern is that if my OS crashes and I have to reinstall everything or move to another OS, I might run into library and dependency errors, especially with the libraries that I altered/customized. I need my sketch to be able to compile as quickly as possible on whatever OS I end up using, since it's a home-automation sketch that controls dozens of things around me.
Is this a valid concern? And if so, what are some preferred ways to make a sketch become "self-contained", so that everything necessary is included? Is there some kind of a better version-control system for Arduino sketches that an amateur programmer might not be aware of?

I would suggest switching to UECIDE instead of the Arduino IDE. (Yes, shameless plug, it's my IDE).
UECIDE has a facility that I dubbed "localizing" a library whereby it copies it into a libraries folder within the sketch folder itself, and that copy of the library is used in preference to any other library named the same in the system.
That means that a sketch and its libraries then become completely self contained in one folder, and it's perfectly possible to have different versions of the same library in different sketches.

I installed this earlier today, and so far I'm liking it! I'm glad you pointed it out. I'll play with it a few more days before deciding to switch.

A way to do so is to include all the library files (*.cpp, *.h) in your sketch folder and then include them in your code.
There are many solutions that you might find handy in this link: How to organize my Arduino projects' structure for easy source control?

Thanks! That was a good link with lots of useful info. So far I'm liking the idea to include all the library files into the sketch folder. That will also help me with the problem of different sketches requiring different versions of a library.


text:
How do I create a 9 bit number based on values from 9 digital inputs?
I have 9 pins that are inputs from 9 IR LEDs. I want to combine all their results into one 9 bit number.
example:
pin1 = high,
pin2 = high,
pin3 = high,
pin4 = low,
pin5 = high,
pin6 = low,
pin7 = low,
pin8 = high,
pin9 = low
9 bit number = 111010010

https://www.arduino.cc/en/Reference/Bitshift

As far as I know, the minimum variable size is 1byte = 8 bits, so there is no bit type.

In your code you would use a 16 bit unsigned integer as your variable. As there is no such thing as a 9 bit type.
If the pins correspond to different ports on your micro, you basically do this:
Read the pin value from the port register, and bit shift to the right bit position then OR with the variable.
Say you had 8 of the LEDS on PORTB (pin 0 - 7 )and the 9th on PORTC (pin 2)
unsigned int ir_inputs = 0

ir_inputs = PORTB; //just reads the register directly
ir_inputs = ir_inputs|((PORTC & 0x04)<<6); //reads the bit on pin 2 then shifts it 6 places to bit 8 (or the 9th bit remember bits always start at 0) and does not affect the other bits

something like that
actually you could put it into a function
unsigned int getIRinputs(void){
    return (unsigned int)PORTB|((PORTC & 0x04)<<6);
}

Easy done
Even if you had the inputs on 9 separate ports the principle is the same.
Read, Shift, OR

Something like this:
typedef union NUM_9_BITS_t {
    unsigned int U;
    struct NUM_9_BITS_FIELD {
        unsigned int BIT0 : 1;
        unsigned int BIT1 : 1;
        unsigned int BIT2 : 1;
        unsigned int BIT3 : 1;
        unsigned int BIT4 : 1;
        unsigned int BIT5 : 1;
        unsigned int BIT6 : 1;
        unsigned int BIT7 : 1;
        unsigned int BIT8 : 1;
        unsigned int BITO : 23;
    } BITS;
} NUM_9_BITS;

NUM_9_BITS num;

num.BITS.BIT0 = digitalRead(PIN0);
num.BITS.BIT1 = digitalRead(PIN1);
num.BITS.BIT2 = digitalRead(PIN2);
num.BITS.BIT3 = digitalRead(PIN3);
num.BITS.BIT4 = digitalRead(PIN4);
num.BITS.BIT5 = digitalRead(PIN5);
num.BITS.BIT6 = digitalRead(PIN6);
num.BITS.BIT7 = digitalRead(PIN7);
num.BITS.BIT8 = digitalRead(PIN8);

Serial.print(num.U);

+1 for the struct. Could you explain why you use 23 and not 7? As an int is only 16-bits. Is 32-bit the minimum size of a union or something?

Thats a perfectly valid approach but seems like a lot lines for something that just needs basic logic and bit shifting.

As @KiraSan said, You need something larger than a byte for 9 bits. However:
int tally;
tally=0;
for (char pin=1; pin<=9; pin++) {
    if (digitalRead(pin)==HIGH) {
        tally|=1<<(9-pin);
    }
}

This is done from memory and is untested, if anyone spots any errors, let me know.
Explanation: tally is the sum (you should do something with this at the end, obviously, or it has no effect). It is defined and set to 0. Then, for each pin (1-9), read the pin; if the pin is high: take the number '1', and double it (9-pin) times; so if pin=9, it is doubled 0 times; for pin=2, it is doubled once (for a total of 2), and so forth. Set this bit on the tally.
Note that this reads digital pin 1 (which happens to be the second pin, the first being pin 0) - this should be marked as "tx" to set in the first bit, not the one referred to as "pin1" (which might be a constant or a variable, and therefore could point to any given pin). This method also assumes the pins are in order - you could easily change it to start from 0, or 7, but they have to be in order.
If you want arbitrary pins, or variable pins, you might try this:
const PIN_COUNT=9;
char pins[PIN_COUNT]={13,2,5,4,3,6,7,8,9};
int tally;

tally=0;

for (char pin=0; pin<PIN_COUNT; pin++) {
    if (digitalRead(pins[pin])==HIGH) {
        tally|=1<<pin;
    }
}

Changes: add PIN_COUNT as a constant at the start, set the order of the pins (which can include any digital pins, including repeating a given pin if you feel so inclined, even after the start of the code.). You can also change them by doing: pins[0]=1; - note that they are numbered from 0-8 for 9 pins. Since they now start at 0, the line with << is now adjusted accordingly, as is the line that starts with for....

authors: محمد يحيى الجدره